diff --git a/.agents/skills/release/SKILL.md b/.agents/skills/release/SKILL.md new file mode 100644 index 00000000..a55d2fd5 --- /dev/null +++ b/.agents/skills/release/SKILL.md @@ -0,0 +1,251 @@ +--- +name: release +description: Prepare and verify a PwrDisk release, push one release commit directly to main, tag the verified commit, monitor signed publication, and hand off promotion. Use for cutting PwrDisk releases or checking release status; ordinary feature and fix PRs do not use this workflow. +--- + +# PwrDisk release + +Release `pwrdrvr/PwrDisk` using the checked-in GitHub Actions workflow. +Read the applicable `AGENTS.md`, [release runbook](../../../docs/releasing.md), +[release workflow](../../../.github/workflows/release.yml), its adjacent +[design notes](../../../.github/workflows/README.md), and +[xtask](../../../xtask/src/main.rs) before changing release metadata. +Those files are authoritative; PwrRoute and PwrAgent have different publishing +and promotion behavior. + +Match the user's requested scope: preparation ends with a reviewable local +commit; a request to cut a release authorizes pushing that one release commit +directly to `main`, then pushing its tag. Do not open a release-prep PR. +Signing-environment approvals and promotion to Latest belong to the operator. +Resume an existing preparation or run at its current stage rather than +duplicating it. + +## Establish the version and changes + +Inspect the worktree, remotes, existing release commits and published releases. +Push only to the remote pointing at `pwrdrvr/PwrDisk`; upstream and personal +forks are read-only. Examples below assume that remote is `origin`. +Preserve unrelated work, using an isolated worktree when needed. + +```bash +git fetch origin main --tags +gh release list -R pwrdrvr/PwrDisk --limit 10 +git log --oneline vPREV..origin/main +``` + +Substitute the previous release tag for `vPREV` and the intended version for +`X.Y.Z` throughout this skill. Read merged PR descriptions and relevant diffs +since that release, including direct commits. Distinguish fork releases from +upstream tags; do not select the highest local tag blindly. If the request and +context do not establish the version, ask while continuing scope inspection. + +PwrDisk continues upstream's version sequence; its first fork release is +0.12.0. Use suffix-free `vX.Y.Z` for stable releases, `-rc.N` for candidates, +and `-beta.N` or `-alpha.N` for builds off main. Every release is initially a +GitHub Pre-release; only suffix-free tags may be promoted to Latest. + +## Prepare one release commit + +Use a clean checkout of current `origin/main`. An isolated worktree can keep +unrelated edits safe; it does not require a preparation branch or PR. Reuse +existing unpublished preparation after inspecting its diff. Keep all release +preparation in one commit on top of main. The normal preparation is: + +| File | Change | +| --- | --- | +| `Cargo.toml` | Set `[workspace.package].version` to `X.Y.Z`. | +| `Cargo.lock` | Refresh workspace versions without upgrading dependencies. | +| `CHANGELOG.md` | Move Unreleased entries under `## vX.Y.Z`. | +| `THIRD_PARTY_LICENSES` | Regenerate with `cargo xtask licenses` after the version bump. | + +All workspace crates inherit the root version. Refresh the lockfile with +`cargo metadata --format-version 1`, redirecting its large JSON output to a +temporary file. Do not use `--no-deps`, which skips the lockfile refresh. +Inspect the diff: only workspace package versions should change in the +lockfile. Investigate dependency drift rather than bundling it into the bump. +Bundle and desktop-entry versions are generated from the crate version; +do not replace unrelated version strings or change `com.pwrdrvr.pwrdisk`. + +`THIRD_PARTY_LICENSES` embeds all six workspace crate versions +(`disktree-app`, `disktree-core`, `disktree-link`, `disktree-mcp`, +`disktree-scan` and `xtask`), so ordinary version bumps require regeneration +even when dependencies are unchanged. Use the `cargo-about` version pinned +in [CI](../../../.github/workflows/ci.yml), currently `0.9.2`, for both +generation and verification: + +```bash +cargo install --locked cargo-about@0.9.2 --features cli +cargo xtask licenses +``` + +Review the generated diff for the expected workspace-version changes. +Investigate any other changes; do not upgrade dependencies or alter license +policy to make an ordinary bump pass, and do not edit the notices by hand. +Include the generated file in the same release commit as the version, +lockfile and changelog. + +This differs from `licenses/velopack.txt`, the notices for Velopack's native +binaries: regenerate that input only when the pinned Velopack tooling +changes, not for an ordinary PwrDisk version bump. + +Preserve the changelog format, leave Unreleased empty, and reconcile its +existing bullets with the merged changes. If the target section already +exists, review and update it rather than creating a duplicate. Only release +preparation edits this file. + +Write user-facing bullets from the included changes, for example +`- SSH scans - Show progress while scanning remote disks.` +Name the affected feature, describe what users gain or what is fixed, and +include measured results only when supported. Avoid PR-number lists and +internal implementation notes. This section supplies the GitHub release notes +and the notes Velopack displays beside an update. + +## Verify and push main + +Run the repository gates and inspect their actual results. Follow +[remote verification](../../../docs/sandboxer.md) for Linux checks when +Sandboxer is available. Commit preparation locally before transferring it; +if corrections are needed, amend the unpublished release commit and verify +its final tree. + +```bash +cargo xtask release-check --tag vX.Y.Z +cargo xtask licenses --check +cargo xtask lint +cargo xtask test +``` + +The notices check must report `THIRD_PARTY_LICENSES is current`, using the +same CI-pinned `cargo-about` version as regeneration. +The metadata gate must report `release metadata agrees for vX.Y.Z`. Also +inspect workspace package versions in `Cargo.lock`; the gate checks the root +version, tag and nonempty changelog section. Report unavailable or failed +checks; do not claim the release is verified while the lint gate is red. + +Commit the release files together as `chore(release): vX.Y.Z`. For a +preparation-only request, hand off the verified local commit here. + +For a release request, fetch `origin/main` again before pushing. If main +advanced, replay the unpublished release commit onto it without a merge +commit, reconcile the added changes with the release notes, and repeat +affected checks. Confirm the final tree was verified and the only commit +being added is the release preparation: + +```bash +git fetch origin main +git merge-base --is-ancestor origin/main HEAD +git rev-list --count origin/main..HEAD +``` + +The ancestor check must succeed and the count must be exactly `1`. Push that +commit as a normal fast-forward update with `git push origin HEAD:main`. +Do not force-push, add a merge commit, or fall back to a PR if repository +policy rejects the push; report the rejection and stop. Verify remote main +holds the exact release commit before tagging it. + +Report the commit and verification results. Stop the verification sandbox +after checks; this workflow has no PR watch to clean it up automatically. + +## Tag and monitor publication + +Before pushing, confirm the intended commit is on `origin/main` and that both +`apple-signing` and `windows-signing` still require reviewer approval and +allow only `v*` tag deployments. Inspect configuration and secret names, +never secret values; [the runbook](../../../docs/releasing.md) lists them. +Missing configuration is a blocker, not permission to alter signing policy. + +Inspect local and remote tags first. If the tag already exists, inspect its +target and run; never move or overwrite it as routine release preparation. +Create an annotated tag on the exact verified full commit SHA, preserving any +configured signing policy, and push only that tag: + +```bash +git tag -a vX.Y.Z RELEASE_COMMIT_SHA -m "vX.Y.Z" +git push origin refs/tags/vX.Y.Z +git ls-remote origin 'refs/tags/vX.Y.Z*' +gh run list -R pwrdrvr/PwrDisk --workflow release.yml --limit 10 +``` + +Verify the remote tag's peeled commit equals the intended release commit. +Find the workflow run for that tag and commit, not simply the newest run. +Monitor without blocking user updates for long periods. Give the operator +the run link and pending environment when approval is needed, and continue +monitoring after approval. Reaching a signing gate is not publication. + +The current pipeline checks metadata and lints, builds Linux for `x86_64` +and `aarch64`, prepares a universal macOS app and both Windows architectures, +then signs and packs macOS and Windows in separate jobs. Only `macos-sign` +and `windows-sign` use their respective signing environments. They verify +the preparation archives' digests and never check out or build source. +Publication creates one GitHub Pre-release only after all assets are ready; +a failed build leaves no partial GitHub release. + +On failure, inspect the failed job logs, report the cause, and stop publication +progression. Do not bypass approvals, downgrade signing, force-push, move an +existing tag, or dispatch replacement runs as an automatic retry. Recovery +requires explicit direction. For an authorized rebuild of an existing tag, +both the workflow ref and its tag input must name that same tag: + +```bash +gh workflow run release.yml -R pwrdrvr/PwrDisk --ref vX.Y.Z -f tag=vX.Y.Z +``` + +An existing GitHub release causes publication to fail; rebuilding it requires +deleting that release first, which can interrupt update feeds. Report that +condition and obtain explicit authorization for deletion rather than removing +it automatically. Monitor one authorized recovery attempt and stop to diagnose +if it fails again. + +## Verify the published release + +```bash +gh release view vX.Y.Z -R pwrdrvr/PwrDisk \ + --json url,isDraft,isPrerelease,assets,body +gh release view -R pwrdrvr/PwrDisk --json tagName,url +``` + +Check the intended release is a non-draft Pre-release, every required job +succeeded, its body matches the prepared changelog section, and the expected +assets are present. Use the runbook's asset table as the authoritative list: + +| Platform | Required coverage | +| --- | --- | +| Linux | x86_64 and aarch64 tarballs, each with `.sha256`. | +| macOS | Universal DMG, portable zip, full package, osx feeds and checksums. | +| Windows | Setup.exe, MSI, portable zip, full package and feeds for both architectures; shared checksums. | + +Optional delta packages depend on an available previous full package, so do +not require a fixed asset count. Preserve Velopack's channel feeds (`osx`, +`win`, `win-arm64`); installed copies need them for updates. Download assets +to a temporary directory and verify their checksum manifests. Check signing +logs for Developer ID signing, team ID, notarization, staples and Gatekeeper +verification of both app and DMG, and valid timestamped Windows signatures +with the configured publisher, including installers and updater binaries. + +Do not manually create the release ahead of CI or replace its changelog notes +with generated notes. There is no Winget or Homebrew distribution job to run. +Keep the `velopack` crate pin, `VPK_VERSION`, package hash and +`licenses/velopack.txt` aligned if a release includes a Velopack upgrade; +an ordinary version bump leaves those unchanged but still regenerates +`THIRD_PARTY_LICENSES` as described above. + +## Hand off promotion + +Have the operator install from the DMG and Setup.exe and check the result +before promoting a suffix-free tag. Report installation and updater smoke +tests separately from CI signing verification; do not infer a working +installation from successful builds alone. Give the operator this command: + +```bash +gh release edit vX.Y.Z -R pwrdrvr/PwrDisk --latest --prerelease=false +``` + +Do not execute promotion as part of a routine release request. Stable · Latest +is the default update channel and sees the release only after promotion; +before that it is available to Stable · Prerelease and Beta · Prerelease. +After the operator promotes, verify Latest points to the intended tag. +Suffixed tags remain prereleases. + +Report the release URL, exact commit and tag, verification results, signing +and asset status, promotion status, and any remaining blockers. Distinguish a +published prerelease awaiting smoke checks from a promoted stable release. diff --git a/.agents/skills/release/agents/openai.yaml b/.agents/skills/release/agents/openai.yaml new file mode 100644 index 00000000..2b239c66 --- /dev/null +++ b/.agents/skills/release/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "PwrDisk Release" + short_description: "Prepare PwrDisk releases and verify publication" diff --git a/.codex/environments/environment.toml b/.codex/environments/environment.toml new file mode 100644 index 00000000..62b62ded --- /dev/null +++ b/.codex/environments/environment.toml @@ -0,0 +1,27 @@ +version = 1 +name = "PwrDisk" + +[[actions]] +name = "Build" +icon = "build" +command = "cargo build --locked -p disktree-app" + +[[actions]] +name = "Test" +icon = "test" +command = "cargo xtask test" + +[[actions]] +name = "Lint" +icon = "test" +command = "cargo xtask lint" + +[[actions]] +name = "Start - Debug" +icon = "run" +command = "cargo run --locked -p disktree-app" + +[[actions]] +name = "Start - Release" +icon = "run" +command = "cargo run --release --locked -p disktree-app" diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..d7723cd0 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,4 @@ +# The MCP server compiles skills/ in and serves each file with its +# sha256; a CRLF checkout would change the digests and break the +# frontmatter it reads. +skills/** text eol=lf diff --git a/.github/actions/setup-rust/action.yml b/.github/actions/setup-rust/action.yml new file mode 100644 index 00000000..9448e051 --- /dev/null +++ b/.github/actions/setup-rust/action.yml @@ -0,0 +1,75 @@ +name: Set up Rust +description: >- + Install the Rust toolchain rust-toolchain.toml pins, remove every other + one, and restore the Rust cache, saving it only from main unless save-if + says otherwise. + +# One copy of the setup every Rust job needs, so the pin, the prune and +# the cache's save rule cannot drift apart between ci.yml, preview-build.yml +# and release.yml. The reasons are in .github/workflows/README.md, under +# "The Rust cache". A local action, so the job must check out the +# repository first. +inputs: + components: + description: Extra toolchain components, comma-separated. + required: false + default: "" + targets: + description: Extra compilation targets, comma-separated. + required: false + default: "" + cache-bin: + description: Whether rust-cache also caches ~/.cargo/bin. + required: false + default: "true" + save-if: + description: >- + Whether rust-cache saves. Empty, the default, saves only on main. + required: false + default: "" + +outputs: + toolchain: + description: The pinned Rust version, for keys that depend on it. + value: ${{ steps.pin.outputs.channel }} + +runs: + using: composite + steps: + # The checked-out rust-toolchain.toml is the only place the version is + # written, so a release tag builds with the Rust it pinned, not with + # whatever a repository variable says today. Carriage returns are + # dropped because a Windows checkout may convert line endings. + - name: Read the pinned Rust version + id: pin + shell: bash + run: | + channel=$(tr -d '\r' < rust-toolchain.toml \ + | sed -n 's/^channel *= *"\([^"]*\)".*/\1/p') + if [ -z "$channel" ]; then + echo "::error file=rust-toolchain.toml::no channel" + exit 1 + fi + echo "channel=$channel" >> "$GITHUB_OUTPUT" + + # The lint gate denies clippy::all and ::pedantic, and a newer clippy's + # new lints are a change to make on purpose, not by surprise. dtolnay + # installs the minimal profile, so a job that runs clippy or rustfmt + # asks for them. + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: ${{ steps.pin.outputs.channel }} + components: ${{ inputs.components }} + targets: ${{ inputs.targets }} + + # Before rust-cache, whose key hashes every installed toolchain. + - name: Keep only the pinned Rust toolchain + shell: bash + run: ./scripts/ci/prune-rust-toolchains.sh + + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + # Only main saves by default, so PR saves cannot evict the entries + # every PR restores from the 10 GB store. + save-if: ${{ inputs.save-if || github.ref == 'refs/heads/main' }} + cache-bin: ${{ inputs.cache-bin }} diff --git a/.github/workflows/README.md b/.github/workflows/README.md new file mode 100644 index 00000000..7e97bdfd --- /dev/null +++ b/.github/workflows/README.md @@ -0,0 +1,172 @@ +# GitHub Actions + +The release workflows are ported from PwrRoute's, which follow PwrGit's +shape: label-gated previews, and signing in environments whose jobs never +check out source. Every build step is a `cargo xtask` task or a script under +`scripts/release/`, so CI and a local run do the same thing. +`docs/releasing.md` is the procedure; this file is how the workflows do it. + +| Workflow | Trigger | What it does | +|---|---|---| +| `ci.yml` | push to `main`, PRs | Lint and test on Linux, macOS and Windows; tests on the other architectures releases build for; an ad hoc signed bundle and DMG on macOS; check third-party notices when their inputs change. | +| `preview-build.yml` | `build-preview` PR label, manual dispatch | The release's packaging, unsigned: a macOS universal DMG cut from the vpk-packed app, and Windows x64 and ARM64 Setup.exe, MSI and portable zip, as workflow artifacts. | +| `release.yml` | `v*` tag push, manual dispatch with a tag | Checks the tag against `Cargo.toml` and `CHANGELOG.md`, lints, builds every platform in unprivileged jobs, packs and signs macOS and Windows with Velopack in credentialed jobs, then creates a GitHub Pre-release with every asset and the Velopack update feeds. | + +Every job runs on a standard GitHub-hosted runner: free on a public +repository, macOS included, and discarded after the job. PwrRoute builds +macOS on self-hosted lab machines; PwrDisk does not, because it takes pull +requests from forks and those must never reach a persistent machine. Every +Rust job installs the version `rust-toolchain.toml` pins, read from the +checkout, so that file is the only place it is written. + +## ci.yml + +The Linux `licenses` job runs `cargo xtask licenses --check` on every push +to `main` and on PRs changing `Cargo.lock`, any `Cargo.toml`, `licenses/**` +or `THIRD_PARTY_LICENSES`. Changes to `ci.yml`, the `setup-rust` action or +`xtask/src/licenses.rs` also run it so edits to the gate or generator are +checked. It installs +`cargo-about@0.9.2` with `cargo install --locked --features cli` and caches +the binary by OS, architecture, generator version and Rust version. Like +PwrRoute, the generator is pinned and the notice check runs on Linux only. + +The existing changed-file classifier selects this job, including both +paths of renames. Unrelated PRs skip it; a failed classifier or incomplete +file list runs it. The workflow trigger stays unfiltered so the job always +reports a result. A stale file fails with instructions to run +`cargo xtask licenses` and commit `THIRD_PARTY_LICENSES`. + +### The Rust cache + +Every Rust job in `ci.yml`, `preview-build.yml` and `release.yml` sets up +through one local composite action, `.github/actions/setup-rust`, so the +toolchain pin, the prune and the cache's save rule cannot drift apart +between jobs. It reads the `channel` from the checked-out +`rust-toolchain.toml`, installs it with `dtolnay/rust-toolchain`, runs +`scripts/ci/prune-rust-toolchains.sh`, then `Swatinem/rust-cache`, saving +only on `main`. The version is read from the file, not a repository +variable, so a release tag builds with the Rust it pinned however the +variable has moved since. Its inputs are what differ between jobs: +`components` (clippy and rustfmt for the lint jobs), `targets` (both Apple +architectures for the universal macOS build), `cache-bin` (off in the +`licenses` job, whose own cache owns `cargo-about`) and `save-if` (`false` +in `release.yml`, because a cache saved under a tag is readable by that +tag's runs alone). Its `toolchain` output is the version it read, which +keys the `cargo-about` cache. A job must check out the repository before +using it, as with any local action. + +The cache saves only on `main`; a PR restores `main`'s entry for the same +job, by key prefix when its `Cargo.lock` differs. The Actions cache store +holds 10 GB and evicts the least recently used entry first. While PRs saved +too, each wrote about 6 GB across the jobs, `main`'s entries were evicted, +and the next PR compiled from scratch: the macOS job's lint went from under +a minute to six, and its tests from two minutes to eight. As in PwrRoute, +the prune script removes the runner image's own stable toolchain before the +cache step, because rust-cache hashes every installed toolchain and image +rollouts would otherwise change the key. A push to `main` never cancels the +`main` run in progress, since a cancelled job saves nothing. + +Lint and test stay one job per platform. They compile separately anyway +(clippy builds dependencies as metadata, tests as full code), so splitting +them would only trade one runner for two and add a cache entry per +platform to the 10 GB budget. + +## preview-build.yml + +Applying the `build-preview` label starts a run, and later pushes to a +labeled PR re-run it. `workflow_dispatch` packages a branch without a PR, +from the default branch's copy of the workflow. PR builds are versioned +`-pr.`, dispatched builds `-dev.`; the +version reaches `cargo xtask bundle` through `PWRDISK_VERSION` and `vpk` +through `--packVersion`, and `Cargo.toml` is never edited, so `--locked` +holds. + +It runs release.yml's jobs minus credentials, release notes and deltas: +`macos-prepare` and `windows-prepare` build and hand over an archive and its +digest, and `macos-pack` and `windows-pack` check the digest and pack +without a checkout, with the same scripts. So a preview also proves the +hand-off, including the per-architecture outputs of the Windows matrix. +No secrets reach this workflow. + +The macOS DMG is ad hoc signed and not notarized: a downloaded copy needs +**Open Anyway** once. Its app carries Velopack's `UpdateMac`, like a +release. The Windows installers are unsigned, so SmartScreen warns. + +## release.yml + +| Job | Runner | Environment | Does | +|---|---|---|---| +| `check` | ubuntu-24.04 | — | `cargo xtask release-check`, `cargo xtask lint`; hands the changelog section on as the release notes. | +| `linux` | ubuntu-22.04, ubuntu-22.04-arm | — | Tests, `cargo xtask portable`, the tarball and its `.sha256`. The oldest runners, for the oldest glibc floor. | +| `macos-prepare` | macos-26 | — | Tests; `cargo xtask bundle --universal --app-only`, with the Icon Composer catalog checked; archives `PwrDisk.app`, the entitlements, the DMG background, `macos-dmg.sh`, `dmg-layout.py`, `macos-signing.py`, `install-vpk.sh` and the notes. | +| `macos-sign` | macos-26 | `apple-signing` | `vpk pack`, signed, notarized and stapled; the DMG from the packed app, the same; verifies both. | +| `windows-prepare` | windows-2025 (x64), windows-11-arm (ARM64) | — | Tests; `cargo build --release` with the static C runtime; archives `pwrdisk.exe`, README, LICENSE, the Velopack notices, `install-vpk.sh`, `vpk-pack-windows.ps1`, the icon and the notes. | +| `windows-sign` | windows-2025 | `windows-signing` | `vpk pack` for each architecture, signed through Azure Artifact Signing; verifies every signature. | +| `publish` | ubuntu-24.04 | — (`contents: write`) | Creates the Pre-release with every platform's assets. | + +### The hand-off + +A prepare job has the checkout and the toolchain. It uploads one archive +holding everything its sign job needs, and passes the archive's SHA-256 as +a job output. The sign job, the only one in its signing environment, +downloads the archive, checks it against both the job output and the +archive's own `.sha256`, and works from the archive alone: it never checks +out source, runs cargo or restores a cache. The Windows prepare job is a +matrix, whose legs share one outputs map; each leg sets only +`sha256-`, and `windows-sign` refuses an empty digest. + +`macos-sign` follows PwrRoute's isolated signing workspace: it clears only +its own `release-signing` directory, and the vpk tools, .NET, the decoded +certificate and API key and the keychain all live in a private `mktemp` +directory removed at the end. `macos-signing.py` snapshots the keychain +search list and default first and restores them on cleanup, which runs on +success, failure and cancellation; its tests (`macos_packaging_test.py`, +run by `cargo xtask test`) mock `security` and `xcrun`. + +### Signing + +Both environments accept only `v*` tags and wait for a reviewer's approval; +`docs/releasing.md` lists their secrets and variables and the scripts that +upload them from 1Password. PwrRoute packs unsigned, with a warning, when a +credential is missing. PwrDisk does not: each sign job checks its +credentials first and fails, so no release ships unsigned or ad hoc +signed. + +### Velopack + +Each sign job runs `vpk download github --pre` for its channel before +packing, so `vpk` can write a delta against the newest published release; +the first release, or a feed that cannot be read, packs full packages only. +That previous package stays in the release that owns it: the macOS job +copies this version's files by name, and the Windows job skips every +package that was there before packing. + +| Channel | Built for | Feed | +|---|---|---| +| `osx` | macOS, universal | `releases.osx.json` | +| `win` | Windows x64 | `releases.win.json` | +| `win-arm64` | Windows ARM64 | `releases.win-arm64.json` | + +An installed copy reads its own channel from Velopack's manifest, so an x64 +install never takes the ARM64 build, or the reverse. The publish job fails +if two platforms produce the same file name rather than let one replace the +other. + +### Not ported from PwrRoute + +- **Self-hosted macOS runners**, for the fork-safety reason above. The + hosted macos-26 builds both architectures, on Xcode 26 so the Icon + Composer icon compiles; another macos-26 signs, as PwrRoute's does. +- **`--require-icon-catalog`.** The jobs check the bundle for `Assets.car` + and `CFBundleIconName` instead. +- **Winget and Homebrew audit stubs.** There is no package in either yet. +- **The separate `typecheck`/`build`/`test` jobs.** PwrDisk's `ci.yml` + lints and tests in one job per platform; the release lints once and tests + on each platform it builds. PwrRoute's main-only Rust cache is ported. +- **Linux `.deb`.** PwrDisk keeps its tarball and `install.sh`. + +## PR labels + +| Label | Workflow | Effect | +|---|---|---| +| `build-preview` | `preview-build.yml` | Builds the unsigned DMG and Windows installers for the PR. Applying it starts a run; later pushes to a labeled PR re-run it. | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 48079012..382247ef 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,17 +11,192 @@ permissions: concurrency: group: ci-${{ github.ref }} - cancel-in-progress: true + # A new push cancels a PR's stale run, but never main's: only main saves + # the Rust cache every PR starts from, and a cancelled job saves nothing. + # A newer main push waits instead, replacing any run already waiting. + cancel-in-progress: ${{ github.event_name == 'pull_request' }} env: CARGO_TERM_COLOR: always +# The Rust cache: every Rust job sets up through .github/actions/setup-rust, +# which saves the cache only on main, so PR saves cannot evict the entries +# every PR restores from the 10 GB store, and prunes extra toolchains first +# so image updates keep the key. The reasons and numbers are in README.md +# beside this file, under "The Rust cache". jobs: + # The pull_request trigger stays path-unfiltered so every job reports on + # every PR: a skipped job satisfies a required check, a missing one leaves + # it pending. PRs that touch only docs, Markdown, agent skills and + # templates skip the jobs below instead. Ported from PwrRoute, which took + # it from PwrAgent; scripts/ci/classify-changes.test.cjs runs this script + # against fixtures, and the allowlist's reasons are at its top. Should + # branch protection come, note that a skipped matrix job reports one check + # under its unexpanded name, `Test (${{ matrix.name }})`, so require the + # other jobs or an aggregate, not a matrix leg. + changes: + name: Classify Changes + runs-on: ubuntu-24.04 + # pulls.listFiles needs pull-requests: read; no other job gets it. + permissions: + contents: read + pull-requests: read + outputs: + # Only an explicit false from a successful classifier may skip CI. + code_impacting: ${{ steps.classify.outcome != 'success' || steps.classify.outputs.code_impacting != 'false' }} + licenses_impacting: ${{ steps.classify.outcome != 'success' || steps.classify.outputs.licenses_impacting != 'false' }} + steps: + - name: Classify changed files + id: classify + # A script/runtime failure must select full CI, too. + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const fullCi = (reason) => { + core.setOutput("code_impacting", "true"); + core.setOutput("licenses_impacting", "true"); + core.notice(`Running full CI: ${reason}`); + }; + + if (context.eventName !== "pull_request") { + fullCi(`${context.eventName} events always run full CI`); + return; + } + + let files; + try { + files = await github.paginate(github.rest.pulls.listFiles, { + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.issue.number, + per_page: 100, + }); + } catch (error) { + fullCi(`changed-file lookup failed (${error.message})`); + return; + } + + const reportedCount = context.payload.pull_request.changed_files; + if (!Array.isArray(files) || !Number.isSafeInteger(reportedCount) || + reportedCount <= 0 || files.length !== reportedCount) { + fullCi( + `changed-file list was incomplete (received ${files?.length} of ${reportedCount})`, + ); + return; + } + + // Unknown/malformed entries are not evidence for skipping CI. + if (files.some((file) => !file || typeof file.filename !== "string" || + file.filename.length === 0 || + (file.previous_filename !== undefined && + (typeof file.previous_filename !== "string" || file.previous_filename.length === 0)) || + (file.status === "renamed" && !file.previous_filename)) || + new Set(files.map((file) => file.filename)).size !== reportedCount) { + fullCi("changed-file list had invalid or duplicate entries"); + return; + } + + const isNonCodePath = (path) => { + // Read by xtask's release check and its tests. + if (path === "CHANGELOG.md") return false; + // The MCP server compiles these in, and its tests read them. + if (path.startsWith("skills/")) return false; + return path === ".github/dependabot.yml" || + path.startsWith("docs/") || + path.startsWith(".agents/skills/") || + path.startsWith(".github/ISSUE_TEMPLATE/") || + path.startsWith(".github/PULL_REQUEST_TEMPLATE/") || + path.toLowerCase().endsWith(".md"); + }; + const codeImpactingFile = files.find((file) => { + const paths = [file.filename, file.previous_filename].filter(Boolean); + return paths.some((path) => !isNonCodePath(path)); + }); + const nonCodeOnly = codeImpactingFile === undefined; + const isLicensePath = (path) => + path === "Cargo.lock" || path === "Cargo.toml" || + path.endsWith("/Cargo.toml") || path.startsWith("licenses/") || + path === "THIRD_PARTY_LICENSES" || + // Exercise changes to the gate and generator themselves. + path === ".github/workflows/ci.yml" || + path.startsWith(".github/actions/setup-rust/") || + path === "xtask/src/licenses.rs"; + const licensesImpacting = files.some((file) => + [file.filename, file.previous_filename].filter(Boolean) + .some(isLicensePath)); + + core.setOutput("code_impacting", String(!nonCodeOnly)); + core.setOutput("licenses_impacting", String(licensesImpacting)); + await core.summary + .addHeading("Changed-file classification") + .addTable([ + [{data: "Classification", header: true}, {data: "Files", header: true}], + [nonCodeOnly ? "Non-code only" : "Code impacting", String(files.length)], + ]) + .addRaw( + nonCodeOnly + ? "Only documentation, agent skills, PR/issue templates or Dependabot configuration changed; expensive CI jobs are skipped." + : `Full CI runs because \`${codeImpactingFile.filename}\` requires it.`, + ) + .write(); + + # Here rather than in `cargo xtask lint`, which stays Rust-only. After + # the classifier, so a failure turns this check red and, through the + # job's result, still runs full CI. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # The test runs the PR's own script, and this job's token is the + # only one with pull-requests: read; keep it out of .git/config. + persist-credentials: false + - name: Test the classifier + run: node --test scripts/ci/classify-changes.test.cjs + + licenses: + name: Check third-party licenses + runs-on: ubuntu-24.04 + needs: changes + if: >- + !cancelled() && + (needs.changes.result != 'success' || needs.changes.outputs.licenses_impacting != 'false') + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: ./.github/actions/setup-rust + id: rust + with: + # The versioned binary cache below owns cargo-about. + cache-bin: false + + # cargo-about's output changes between releases; keep this pin and + # the binary cache key together, as PwrRoute pins its generator too. + - name: Cache cargo-about + id: cargo-about + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ~/.cargo/bin/cargo-about + # The Rust that built it is part of the key, so a toolchain bump + # rebuilds the binary instead of restoring one it did not build. + key: ${{ runner.os }}-${{ runner.arch }}-cargo-about-0.9.2-rust-${{ steps.rust.outputs.toolchain }} + + - name: Install cargo-about + if: steps.cargo-about.outputs.cache-hit != 'true' + # 0.9.2 requires this feature to install its binary. + run: cargo install --locked cargo-about@0.9.2 --features cli + + - name: Check notices + run: cargo xtask licenses --check + check: name: Lint and test runs-on: ubuntu-24.04 + needs: changes + # Runs unless the classifier succeeded and said non-code only. + if: >- + !cancelled() && + (needs.changes.result != 'success' || needs.changes.outputs.code_impacting != 'false') steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 # What GPUI links against: windowing (Wayland, X11), input, fonts, # and the Vulkan loader. @@ -33,15 +208,11 @@ jobs: libx11-xcb-dev libxcb1-dev libfontconfig-dev libfreetype-dev \ libvulkan-dev libasound2-dev libssl-dev libzstd-dev - # Pinned: the lint gate denies clippy::all and ::pedantic, and a newer - # clippy's new lints are a change to make on purpose, not by surprise. - - uses: dtolnay/rust-toolchain@master + # The lint gate runs clippy and rustfmt. + - uses: ./.github/actions/setup-rust with: - toolchain: "1.97" components: clippy, rustfmt - - uses: Swatinem/rust-cache@v2 - - name: Lint run: cargo xtask lint @@ -54,55 +225,89 @@ jobs: # either: gpui-kit builds GPUI with runtime shader compilation, so the # shaders compile when the app starts, not here. runs-on: macos-15 + needs: changes + # Runs unless the classifier succeeded and said non-code only. + if: >- + !cancelled() && + (needs.changes.result != 'success' || needs.changes.outputs.code_impacting != 'false') steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: dtolnay/rust-toolchain@master + - uses: ./.github/actions/setup-rust with: - toolchain: "1.97" components: clippy, rustfmt - - uses: Swatinem/rust-cache@v2 - - name: Lint run: cargo xtask lint - name: Test run: cargo xtask test - # The app bundle, signed ad hoc: catches a broken Info.plist, icon or - # signature before a release does. + # The app bundle, signed ad hoc, and the DMG release.yml cuts the same + # way: catches a broken Info.plist, icon, signature or DMG layout + # before a release does. This runner's Xcode has no actool 26, so + # this is the bundle without the Icon Composer icon. - name: Bundle run: cargo xtask bundle + bundle-macos-26: + name: Bundle (macOS 26) + # The bundle with the Icon Composer icon: Xcode 26's actool compiles it + # into Assets.car, and the plist names it, which the job checks. + runs-on: macos-26 + needs: changes + # Runs unless the classifier succeeded and said non-code only. + if: >- + !cancelled() && + (needs.changes.result != 'success' || needs.changes.outputs.code_impacting != 'false') + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: ./.github/actions/setup-rust + + - name: Bundle + run: cargo xtask bundle + + - name: Icon catalog + run: | + app=target/bundle/PwrDisk.app + test -f "$app/Contents/Resources/Assets.car" + test -f "$app/Contents/Resources/AppIcon.icns" + test "$(plutil -extract CFBundleIconName raw "$app/Contents/Info.plist")" = Icon + windows: name: Lint and test (Windows) runs-on: windows-2025 + needs: changes + # Runs unless the classifier succeeded and said non-code only. + if: >- + !cancelled() && + (needs.changes.result != 'success' || needs.changes.outputs.code_impacting != 'false') steps: # Check out with the repository's own line endings, as on Linux. - run: git config --global core.autocrlf false - - uses: actions/checkout@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - # Pinned with the Linux job, for the same reason. GPUI needs nothing - # beyond the Windows SDK the runner already has. - - uses: dtolnay/rust-toolchain@master + # GPUI needs nothing beyond the Windows SDK the runner already has. + - uses: ./.github/actions/setup-rust with: - toolchain: "1.97" components: clippy, rustfmt - - uses: Swatinem/rust-cache@v2 - - name: Lint run: cargo xtask lint - name: Test run: cargo xtask test + # A debug build: build.rs embeds the icon in every profile, and Test + # has already compiled everything but the binary. A release build + # (thin LTO, one codegen unit) took over three minutes even with a + # warm cache; preview-build.yml and release.yml build that one. - name: Check embedded executable icon shell: pwsh run: | - cargo build --release --locked -p disktree-app + cargo build --locked -p disktree-app Add-Type @' using System; using System.Runtime.InteropServices; @@ -112,9 +317,9 @@ jobs: string file, int index, IntPtr[] large, IntPtr[] small, uint count); } '@ - $exe = (Resolve-Path target/release/disktree.exe).Path + $exe = (Resolve-Path target/debug/pwrdisk.exe).Path if ([ExecutableIcons]::ExtractIconEx($exe, -1, $null, $null, 0) -lt 1) { - throw "disktree.exe has no embedded icon" + throw "pwrdisk.exe has no embedded icon" } # The other half of each release: the same tests on the architectures @@ -129,11 +334,16 @@ jobs: - { name: macOS x86_64, runner: macos-15-intel } - { name: Windows aarch64, runner: windows-11-arm } runs-on: ${{ matrix.runner }} + needs: changes + # Runs unless the classifier succeeded and said non-code only. + if: >- + !cancelled() && + (needs.changes.result != 'success' || needs.changes.outputs.code_impacting != 'false') steps: - if: runner.os == 'Windows' run: git config --global core.autocrlf false - - uses: actions/checkout@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: System libraries if: runner.os == 'Linux' @@ -144,11 +354,7 @@ jobs: libx11-xcb-dev libxcb1-dev libfontconfig-dev libfreetype-dev \ libvulkan-dev libasound2-dev libssl-dev libzstd-dev - - uses: dtolnay/rust-toolchain@master - with: - toolchain: "1.97" - - - uses: Swatinem/rust-cache@v2 + - uses: ./.github/actions/setup-rust - name: Test run: cargo xtask test diff --git a/.github/workflows/preview-build.yml b/.github/workflows/preview-build.yml new file mode 100644 index 00000000..daf94143 --- /dev/null +++ b/.github/workflows/preview-build.yml @@ -0,0 +1,330 @@ +name: Preview Build + +# The release's packaging, unsigned, for a pull request or a branch: a +# macOS universal DMG cut from the vpk-packed app, and Windows x64 and ARM64 +# Setup.exe, MSI and portable zip. The same jobs and scripts as release.yml, +# minus credentials, release notes and deltas, so a packaging change is seen +# working before a tag. See README.md beside this file. +on: + pull_request: + # `labeled`: the build-preview label was just applied. `synchronize`: + # a later push to a PR that has it; without this the only way to re-run + # after a fix is to remove and re-add the label. + types: [labeled, synchronize] + # Packages a branch without a PR. Only from the default branch's copy of + # this file, as GitHub runs every dispatch. + workflow_dispatch: + +concurrency: + # A new push to a labeled PR cancels the preview it supersedes. Adding + # any other label makes a skipped run, which gets its own group so it + # cannot cancel an active build. Dispatch runs never cancel each other. + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}${{ github.event.action == 'labeled' && github.event.label.name != 'build-preview' && '-unrelated-label' || '' }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +# No secrets are used, and the token only reads. Every runner is +# GitHub-hosted and discarded after the job, so a labeled fork PR reaches +# no persistent machine. +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + # `0.12.0-pr.12` on a PR, `0.12.0-dev.34` on dispatch. xtask and vpk stamp + # packages with it; Cargo.toml is left alone so `--locked` still holds. + PREVIEW_SUFFIX: ${{ github.event.pull_request.number && format('pr.{0}', github.event.pull_request.number) || format('dev.{0}', github.run_number) }} + +jobs: + version: + name: Preview version + if: >- + github.event_name == 'workflow_dispatch' || + (github.event.action == 'labeled' && github.event.label.name == 'build-preview') || + (github.event.action == 'synchronize' && contains(github.event.pull_request.labels.*.name, 'build-preview')) + runs-on: ubuntu-24.04 + timeout-minutes: 5 + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Compute preview version + id: version + run: | + base=$(sed -n 's/^version = "\([0-9]*\.[0-9]*\.[0-9]*\).*"/\1/p' Cargo.toml | head -1) + echo "version=${base}-${PREVIEW_SUFFIX}" >> "$GITHUB_OUTPUT" + echo "Preview version: ${base}-${PREVIEW_SUFFIX}" + + macos-prepare: + name: Build macOS universal + needs: version + # macOS 26 for actool 26 and the Icon Composer icon, as release.yml. + runs-on: macos-26 + timeout-minutes: 60 + outputs: + signing-input-sha256: ${{ steps.archive.outputs.sha256 }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: ./.github/actions/setup-rust + with: + targets: aarch64-apple-darwin, x86_64-apple-darwin + + - name: Build PwrDisk.app (universal) + env: + PWRDISK_VERSION: ${{ needs.version.outputs.version }} + run: cargo xtask bundle --universal --app-only + + # The bundle quietly drops the Icon Composer icon without actool 26; + # nor may a release, which this previews, so a runner image without it stops here. + - name: Check the icon catalog + run: | + app=target/bundle/PwrDisk.app + test -f "$app/Contents/Resources/Assets.car" + test -f "$app/Contents/Resources/AppIcon.icns" + test "$(plutil -extract CFBundleIconName raw \ + "$app/Contents/Info.plist")" = Icon + + - name: Stage and archive pack input + id: archive + run: | + set -euo pipefail + stage="$RUNNER_TEMP/macos-input" + mkdir "$stage" + ditto target/bundle/PwrDisk.app "$stage/PwrDisk.app" + cp packaging/macos/PwrDisk.entitlements packaging/dmg/background.png \ + scripts/release/macos-dmg.sh scripts/release/dmg-layout.py \ + scripts/release/install-vpk.sh "$stage/" + tarball="$RUNNER_TEMP/macos-preview-input.tgz" + tar -czf "$tarball" -C "$stage" . + echo "sha256=$(shasum -a 256 "$tarball" | awk '{print $1}')" >> "$GITHUB_OUTPUT" + + - name: Upload pack input + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: macos-preview-input + path: ${{ runner.temp }}/macos-preview-input.tgz + if-no-files-found: error + retention-days: 3 + + # release.yml's macos-sign, ad hoc: no checkout, the same vpk and DMG + # steps on the same macos-26 image. + macos-pack: + name: Pack macOS DMG (ad hoc signed) + needs: [version, macos-prepare] + runs-on: macos-26 + timeout-minutes: 45 + steps: + - name: Download pack input + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: macos-preview-input + path: .preview-input + + - name: Verify and expand pack input + env: + EXPECTED_SHA256: ${{ needs.macos-prepare.outputs.signing-input-sha256 }} + run: | + set -euo pipefail + actual="$(shasum -a 256 .preview-input/macos-preview-input.tgz | awk '{print $1}')" + if [ -z "$EXPECTED_SHA256" ] || [ "$actual" != "$EXPECTED_SHA256" ]; then + echo "::error::pack input SHA-256 mismatch: expected $EXPECTED_SHA256, got $actual" >&2 + exit 1 + fi + mkdir input + tar -xzf .preview-input/macos-preview-input.tgz -C input + + - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 8.0.x + + - name: Install vpk + run: input/install-vpk.sh + + # Ad hoc (`-`): an app vpk changed but did not sign fails + # `codesign --verify`. + - name: Pack with vpk + env: + VERSION: ${{ needs.version.outputs.version }} + run: | + set -euo pipefail + vpk --skip-updates pack \ + --packId PwrDisk \ + --packVersion "$VERSION" \ + --packDir input/PwrDisk.app \ + --mainExe pwrdisk \ + --packTitle PwrDisk \ + --packAuthors "PwrDrvr LLC" \ + --signEntitlements input/PwrDisk.entitlements \ + --noInst \ + --outputDir releases \ + --signAppIdentity - + ls -l releases + + - name: Put the packed app in a DMG + env: + VERSION: ${{ needs.version.outputs.version }} + run: | + set -euo pipefail + mkdir -p dist packed + ditto -x -k releases/PwrDisk-osx-Portable.zip packed + DMG_VERSION="$VERSION" input/macos-dmg.sh "$PWD/packed/PwrDisk.app" \ + "dist/PwrDisk-$VERSION-universal.dmg" + cp releases/PwrDisk-osx-Portable.zip dist/ + + # What release.yml checks, short of the team signature and Gatekeeper, + # plus the DMG's contents. + - name: Verify + run: | + set -euo pipefail + app="$PWD/packed/PwrDisk.app" + codesign --verify --deep --strict --all-architectures "$app" + lipo "$app/Contents/MacOS/pwrdisk" -verify_arch arm64 x86_64 + test -x "$app/Contents/MacOS/UpdateMac" + mount=$(mktemp -d) + hdiutil attach -nobrowse -readonly -mountpoint "$mount" dist/*.dmg + trap 'hdiutil detach "$mount" -quiet || true' EXIT + test -d "$mount/PwrDisk.app/Contents/MacOS" + test -x "$mount/PwrDisk.app/Contents/MacOS/UpdateMac" + [ "$(readlink "$mount/Applications")" = /Applications ] + test -f "$mount/.DS_Store" + test -f "$mount/.background/background.png" + test -f "$mount/.VolumeIcon.icns" + + - name: Upload macOS preview + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: PwrDisk-${{ needs.version.outputs.version }}-preview-macos + path: dist/* + if-no-files-found: error + retention-days: 14 + + windows-prepare: + name: Build Windows ${{ matrix.arch }} + needs: version + strategy: + matrix: + include: + - { runner: windows-2025, arch: x64 } + - { runner: windows-11-arm, arch: arm64 } + runs-on: ${{ matrix.runner }} + timeout-minutes: 60 + # As in release.yml: one output per architecture, which also proves the + # hand-off the signing job relies on. + outputs: + sha256-x64: ${{ steps.archive.outputs.sha256-x64 }} + sha256-arm64: ${{ steps.archive.outputs.sha256-arm64 }} + env: + RUSTFLAGS: -C target-feature=+crt-static + steps: + - run: git config --global core.autocrlf false + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: ./.github/actions/setup-rust + + - name: Build (unsigned) + run: cargo build --release --locked -p disktree-app + + - name: Stage and archive pack input + id: archive + shell: pwsh + env: + ARCH: ${{ matrix.arch }} + run: | + $stage = Join-Path $env:RUNNER_TEMP "windows-input" + New-Item -ItemType Directory -Force "$stage/app" | Out-Null + Copy-Item target/release/pwrdisk.exe, README.md, LICENSE "$stage/app/" + Copy-Item licenses/velopack.txt "$stage/app/VELOPACK-NOTICES.txt" + Copy-Item scripts/release/install-vpk.sh, scripts/release/vpk-pack-windows.ps1, assets/disktree.ico "$stage/" + $name = "windows-preview-input-$env:ARCH.tgz" + $archive = Join-Path $env:RUNNER_TEMP $name + & tar.exe -czf $archive -C $stage . + if ($LASTEXITCODE -ne 0) { throw "tar failed (exit code $LASTEXITCODE)." } + $sha256 = (Get-FileHash -Algorithm SHA256 $archive).Hash.ToLowerInvariant() + "sha256-$env:ARCH=$sha256" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8 + + - name: Upload pack input + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: windows-preview-input-${{ matrix.arch }} + path: ${{ runner.temp }}/windows-preview-input-${{ matrix.arch }}.tgz + if-no-files-found: error + retention-days: 3 + + # release.yml's windows-sign, unsigned: no checkout, both architectures + # packed by the same script on one x64 runner. + windows-pack: + name: Pack Windows Setup.exe, MSI and zip (unsigned) + needs: [version, windows-prepare] + runs-on: windows-2025 + timeout-minutes: 30 + steps: + - name: Download pack input + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: windows-preview-input-* + path: .preview-input + merge-multiple: true + + - name: Verify and expand pack input + shell: pwsh + env: + SHA256_X64: ${{ needs.windows-prepare.outputs.sha256-x64 }} + SHA256_ARM64: ${{ needs.windows-prepare.outputs.sha256-arm64 }} + run: | + foreach ($arch in "x64", "arm64") { + $expected = [Environment]::GetEnvironmentVariable("SHA256_$($arch.ToUpper())") + $archive = ".preview-input/windows-preview-input-$arch.tgz" + $actual = (Get-FileHash -Algorithm SHA256 $archive).Hash.ToLowerInvariant() + if (-not $expected -or $actual -ne $expected) { + throw "Windows $arch pack input digest mismatch: expected '$expected', got $actual." + } + New-Item -ItemType Directory -Force "input/$arch" | Out-Null + & tar.exe -xzf $archive -C "input/$arch" + if ($LASTEXITCODE -ne 0) { throw "Failed to expand the $arch input (exit code $LASTEXITCODE)." } + } + + - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 8.0.x + + - name: Install vpk + shell: bash + run: input/x64/install-vpk.sh + + - name: Pack with vpk + shell: pwsh + env: + VERSION: ${{ needs.version.outputs.version }} + run: | + New-Item -ItemType Directory -Force dist | Out-Null + foreach ($arch in "x64", "arm64") { + $out = "releases/$arch" + & "./input/$arch/vpk-pack-windows.ps1" -Version $env:VERSION -Arch $arch ` + -PackDir "input/$arch/app" -OutputDir $out -Icon "input/$arch/disktree.ico" + Get-ChildItem $out | Format-Table Name, Length + $channel = if ($arch -eq "x64") { "win" } else { "win-$arch" } + Add-Type -AssemblyName System.IO.Compression.FileSystem + $zip = [IO.Compression.ZipFile]::OpenRead((Resolve-Path "$out/PwrDisk-$channel-Portable.zip").Path) + $names = $zip.Entries | ForEach-Object { $_.FullName } + $zip.Dispose() + foreach ($expected in "Update.exe", "current/pwrdisk.exe", "current/VELOPACK-NOTICES.txt") { + if ($names -notcontains $expected) { throw "$arch portable zip has no $expected" } + } + Copy-Item "$out/PwrDisk-$channel-Setup.exe", "$out/PwrDisk-$channel.msi", "$out/PwrDisk-$channel-Portable.zip" dist/ -ErrorAction Stop + } + + - name: Upload Windows preview + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: PwrDisk-${{ needs.version.outputs.version }}-preview-windows + path: dist/* + if-no-files-found: error + retention-days: 14 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9ca399cd..3f136a40 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,65 +1,95 @@ name: Release -# Push a tag like v0.9.0 to build and publish a release. The tag must match -# the workspace version in Cargo.toml. +# A `vX.Y.Z` tag builds every platform, then publishes one GitHub +# Pre-release with all of them; promote it to Latest by hand once checked. +# Ported from PwrRoute: each signed platform is two jobs. An unprivileged +# prepare job builds from source and hands a signing-input archive, and its +# SHA-256 as a job output, to a credentialed sign job that never checks out +# or builds source. The sign job packs the release with Velopack's `vpk` +# (installers and the update feed). Unlike PwrRoute, a release never ships +# unsigned: a sign job without its credentials fails. See README.md beside +# this file and docs/releasing.md. on: push: - tags: ["v*"] + tags: + - "v*.*.*" + - "v*.*.*-*" # pre-release tags like v0.12.1-rc.1 workflow_dispatch: inputs: tag: - description: "Existing tag to (re)build, e.g. v0.9.0" + description: "Existing tag to build, e.g. v0.12.0" required: true + type: string permissions: - contents: write + contents: read env: CARGO_TERM_COLOR: always + # Through the environment, never spliced into a script: a tag typed into + # the dispatch form is text, not shell. + RELEASE_TAG: ${{ inputs.tag || github.ref_name }} jobs: - release: - name: Check the tag and draft the release + check: + name: Check release metadata and lint runs-on: ubuntu-24.04 - outputs: - tag: ${{ steps.version.outputs.tag }} - version: ${{ steps.version.outputs.version }} + timeout-minutes: 60 steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ inputs.tag || github.ref }} + persist-credentials: false - - name: Version - id: version - # Through the environment, not spliced into the script: a tag typed - # into the dispatch form is text, never shell. + # The signing environments accept only v* tags, so a rebuild + # dispatched from a branch would build everything and then be refused + # at signing. Fail here instead: dispatch it from the tag itself. + # First, before the tag's own setup-rust action is loaded: a tag + # older than that action fails here with this message, not there. + - name: Check the run starts from the tag env: - TAG: ${{ inputs.tag || github.ref_name }} + REF_TYPE: ${{ github.ref_type }} + REF_NAME: ${{ github.ref_name }} run: | - tag="$TAG" - version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1) - if [ "$tag" != "v$version" ]; then - echo "tag $tag does not match Cargo.toml version $version" >&2 + if [ "$REF_TYPE" != tag ] || [ "$REF_NAME" != "$RELEASE_TAG" ]; then + echo "Run this workflow from the tag $RELEASE_TAG (Use workflow from:" \ + "Tags > $RELEASE_TAG), not from $REF_TYPE $REF_NAME" >&2 exit 1 fi - echo "tag=$tag" >> "$GITHUB_OUTPUT" - echo "version=$version" >> "$GITHUB_OUTPUT" - # A draft, so nobody downloads from a release still missing half its - # builds; `publish` below makes it public once every build is in. - - name: Draft - env: - GH_TOKEN: ${{ github.token }} - TAG: ${{ steps.version.outputs.tag }} + - name: System libraries run: | - if ! gh release view "$TAG" >/dev/null 2>&1; then - gh release create "$TAG" --draft --verify-tag \ - --title "disktree ${TAG#v}" --generate-notes - fi + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + pkg-config libxkbcommon-dev libxkbcommon-x11-dev libwayland-dev \ + libx11-xcb-dev libxcb1-dev libfontconfig-dev libfreetype-dev \ + libvulkan-dev libasound2-dev libssl-dev libzstd-dev + + - uses: ./.github/actions/setup-rust + with: + components: clippy, rustfmt + # A cache saved under a tag is readable by that tag's runs alone. + save-if: false + + # The tag, Cargo.toml and CHANGELOG.md agree before anything is + # built; the changelog section becomes the release's notes. + - name: Check release metadata + run: cargo xtask release-check --notes-file RELEASE_NOTES.md + + - name: Lint + run: cargo xtask lint + + - name: Hand over the release notes + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: release-notes + path: RELEASE_NOTES.md + if-no-files-found: error + retention-days: 7 linux: name: Build (Linux ${{ matrix.arch }}) - needs: release + needs: check strategy: matrix: include: @@ -68,10 +98,12 @@ jobs: - { runner: ubuntu-22.04, arch: x86_64 } - { runner: ubuntu-22.04-arm, arch: aarch64 } runs-on: ${{ matrix.runner }} + timeout-minutes: 60 steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ inputs.tag || github.ref }} + persist-credentials: false - name: System libraries run: | @@ -81,154 +113,361 @@ jobs: libx11-xcb-dev libxcb1-dev libfontconfig-dev libfreetype-dev \ libvulkan-dev libasound2-dev libssl-dev libzstd-dev - - uses: dtolnay/rust-toolchain@master + - uses: ./.github/actions/setup-rust with: - toolchain: "1.97" - - - uses: Swatinem/rust-cache@v2 + targets: x86_64-unknown-linux-musl, aarch64-unknown-linux-musl + save-if: false - name: Test run: cargo xtask test - name: Build - run: | - rustup target add x86_64-unknown-linux-musl aarch64-unknown-linux-musl - cargo xtask portable + run: cargo xtask portable + # Velopack is not used on Linux: vpk's Linux output is an AppImage + # only, and its updater runs only from one. Linux packages are not + # signed. - name: Package - id: package env: - VERSION: ${{ needs.release.outputs.version }} ARCH: ${{ matrix.arch }} run: | - name="disktree-$VERSION-$ARCH-linux" + version="${RELEASE_TAG#v}" + name="pwrdisk-$version-$ARCH-linux" mkdir -p "dist/$name" # portable strips before appending; stripping again loses helpers. - cp target/portable/disktree "dist/$name/" - cp packaging/install.sh packaging/disktree.desktop.in \ + cp target/portable/pwrdisk "dist/$name/" + cp packaging/install.sh packaging/pwrdisk.desktop.in \ assets/disktree.svg README.md LICENSE "dist/$name/" - echo "$VERSION" > "dist/$name/VERSION" + echo "$version" > "dist/$name/VERSION" tar -C dist -czf "dist/$name.tar.gz" "$name" (cd dist && sha256sum "$name.tar.gz" > "$name.tar.gz.sha256") - echo "archive=dist/$name.tar.gz" >> "$GITHUB_OUTPUT" + # The same tarball under a name without the version, so the + # README's .../releases/latest/download/ link never goes stale. + cp "dist/$name.tar.gz" "dist/pwrdisk-$ARCH-linux.tar.gz" - - name: Upload - env: - GH_TOKEN: ${{ github.token }} - TAG: ${{ needs.release.outputs.tag }} - ARCHIVE: ${{ steps.package.outputs.archive }} - run: gh release upload "$TAG" "$ARCHIVE" "$ARCHIVE.sha256" --clobber + - name: Upload Linux release assets + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: release-linux-${{ matrix.arch }} + path: | + dist/*.tar.gz + dist/*.tar.gz.sha256 + if-no-files-found: error + retention-days: 90 - macos: - name: Build (macOS ${{ matrix.arch }}) - needs: release - strategy: - matrix: - include: - # `xtask bundle` names the zip after the machine it runs on, so - # each architecture builds on its own. - - { runner: macos-15, arch: aarch64 } - - { runner: macos-15-intel, arch: x86_64 } - runs-on: ${{ matrix.runner }} - env: - # Signing and notarizing happen only when the repository has these - # secrets; without them the app is signed ad hoc, and a downloaded - # copy needs "Open Anyway" in System Settings once. - # MACOS_CERTIFICATE base64 of the Developer ID .p12 - # MACOS_CERTIFICATE_PASSWORD its password - # MACOS_SIGN_IDENTITY "Developer ID Application: Name (TEAMID)" - # NOTARY_KEY_P8 base64 of an App Store Connect API key - # NOTARY_KEY_ID, NOTARY_ISSUER that key's ID and issuer - MACOS_CERTIFICATE: ${{ secrets.MACOS_CERTIFICATE }} - MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }} - MACOS_SIGN_IDENTITY: ${{ secrets.MACOS_SIGN_IDENTITY }} - NOTARY_KEY_P8: ${{ secrets.NOTARY_KEY_P8 }} - NOTARY_KEY_ID: ${{ secrets.NOTARY_KEY_ID }} - NOTARY_ISSUER: ${{ secrets.NOTARY_ISSUER }} + macos-prepare: + name: Build macOS universal and prepare signing input + needs: check + # Apple silicon; the Intel half is cross-compiled and joined with lipo. + # macOS 26, for Xcode 26's actool: it compiles the Icon Composer icon, + # which both halves then carry. Hosted, never a persistent machine: + # this repository takes fork PRs. + runs-on: macos-26 + timeout-minutes: 60 + outputs: + signing-input-sha256: ${{ steps.archive.outputs.sha256 }} steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ inputs.tag || github.ref }} + persist-credentials: false - - uses: dtolnay/rust-toolchain@master + - uses: ./.github/actions/setup-rust with: - toolchain: "1.97" - - - uses: Swatinem/rust-cache@v2 + targets: aarch64-apple-darwin, x86_64-apple-darwin + save-if: false - name: Test run: cargo xtask test - # A keychain of its own for the certificate, deleted with the runner. - - name: Signing certificate - if: env.MACOS_CERTIFICATE != '' + # Ad hoc signed; vpk re-signs it in the sign job. + - name: Build PwrDisk.app (universal) + run: cargo xtask bundle --universal --app-only + + # The bundle quietly drops the Icon Composer icon without actool 26; + # a release must not, so a runner image without it stops here. + - name: Check the icon catalog run: | - keychain="$RUNNER_TEMP/signing.keychain-db" - password=$(uuidgen) - echo "$MACOS_CERTIFICATE" | base64 --decode > "$RUNNER_TEMP/cert.p12" - security create-keychain -p "$password" "$keychain" - security set-keychain-settings -lut 3600 "$keychain" - security unlock-keychain -p "$password" "$keychain" - security import "$RUNNER_TEMP/cert.p12" -k "$keychain" \ - -P "$MACOS_CERTIFICATE_PASSWORD" -T /usr/bin/codesign - security set-key-partition-list -S apple-tool:,apple: \ - -s -k "$password" "$keychain" - security list-keychains -d user -s "$keychain" \ - $(security list-keychains -d user | tr -d '"') - rm "$RUNNER_TEMP/cert.p12" - - - name: Bundle + app=target/bundle/PwrDisk.app + test -f "$app/Contents/Resources/Assets.car" + test -f "$app/Contents/Resources/AppIcon.icns" + test "$(plutil -extract CFBundleIconName raw \ + "$app/Contents/Info.plist")" = Icon + + # Everything the sign job needs, and nothing else: it has no checkout. + - name: Stage signing input run: | - args=() - if [ -n "$MACOS_CERTIFICATE" ]; then - args+=(--sign "$MACOS_SIGN_IDENTITY") - if [ -n "$NOTARY_KEY_P8" ]; then - echo "$NOTARY_KEY_P8" | base64 --decode \ - > "$RUNNER_TEMP/AuthKey.p8" - export NOTARY_KEY="$RUNNER_TEMP/AuthKey.p8" - args+=(--notarize) - fi + set -euo pipefail + stage=$(mktemp -d "$RUNNER_TEMP/pwrdisk-macos-input.XXXXXX") + echo "PWRDISK_MACOS_INPUT=$stage" >> "$GITHUB_ENV" + ditto target/bundle/PwrDisk.app "$stage/PwrDisk.app" + # macos-dmg.sh finds background.png beside itself. + cp packaging/macos/PwrDisk.entitlements packaging/dmg/background.png \ + scripts/release/macos-dmg.sh scripts/release/dmg-layout.py \ + scripts/release/macos-signing.py scripts/release/install-vpk.sh \ + "$stage/" + cargo xtask release-check --notes-file "$stage/RELEASE_NOTES.md" + + - name: Archive signing input + id: archive + run: | + set -euo pipefail + tarball="$RUNNER_TEMP/macos-release-signing-input.tgz" + tar -czf "$tarball" -C "$PWRDISK_MACOS_INPUT" . + sha256="$(shasum -a 256 "$tarball" | awk '{print $1}')" + echo "sha256=$sha256" >> "$GITHUB_OUTPUT" + printf "%s macos-release-signing-input.tgz\n" "$sha256" > "$tarball.sha256" + + - name: Upload signing input + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: macos-release-signing-input + path: | + ${{ runner.temp }}/macos-release-signing-input.tgz + ${{ runner.temp }}/macos-release-signing-input.tgz.sha256 + if-no-files-found: error + retention-days: 7 + + macos-sign: + name: Pack, sign and notarize macOS + # The only macOS job with Apple credentials. It does not check out + # source or run cargo; it packs the verified app from macos-prepare. + needs: macos-prepare + runs-on: macos-26 + timeout-minutes: 90 + # Only v* tags may use this environment, and it waits for a reviewer. + # scripts/release/upload-csc-link-from-1password.sh fills it. + environment: apple-signing + defaults: + run: + working-directory: release-signing + steps: + # As in PwrRoute: no files from an earlier checkout may supply + # signing code. + - name: Initialize isolated signing workspace + working-directory: . + run: | + set -euo pipefail + umask 077 + rm -rf -- release-signing + mkdir release-signing + signing_temp=$(mktemp -d "$RUNNER_TEMP/pwrdisk-signing.XXXXXX") + echo "PWRDISK_SIGNING_TEMP_DIR=$signing_temp" >> "$GITHUB_ENV" + echo "TMPDIR=$signing_temp" >> "$GITHUB_ENV" + + - name: Download signing input + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: macos-release-signing-input + path: release-signing/.release-input + + - name: Verify signing input + env: + EXPECTED_SHA256: ${{ needs.macos-prepare.outputs.signing-input-sha256 }} + run: | + set -euo pipefail + cd .release-input + actual="$(shasum -a 256 macos-release-signing-input.tgz | awk '{print $1}')" + if [ -z "$EXPECTED_SHA256" ] || [ "$actual" != "$EXPECTED_SHA256" ]; then + echo "::error::signing input SHA-256 mismatch: expected $EXPECTED_SHA256, got $actual" >&2 + exit 1 + fi + shasum -a 256 --check macos-release-signing-input.tgz.sha256 + + - name: Expand signing input + run: mkdir input && tar -xzf .release-input/macos-release-signing-input.tgz -C input + + # A release is never quietly ad hoc signed: PwrRoute packs one with a + # warning, PwrDisk fails instead. + - name: Check signing credentials + env: + CSC_LINK: ${{ secrets.CSC_LINK }} + CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }} + APPLE_API_KEY_BASE64: ${{ secrets.APPLE_API_KEY_BASE64 }} + APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }} + APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }} + run: | + missing=() + for name in CSC_LINK CSC_KEY_PASSWORD APPLE_API_KEY_BASE64 \ + APPLE_API_KEY_ID APPLE_API_ISSUER; do + [ -n "${!name}" ] || missing+=("$name") + done + if [ ${#missing[@]} -gt 0 ]; then + echo "::error::apple-signing is missing: ${missing[*]}" >&2 + exit 1 fi - cargo xtask bundle "${args[@]}" - - name: Upload + - name: Install .NET for vpk + env: + DOTNET_INSTALL_DIR: ${{ env.PWRDISK_SIGNING_TEMP_DIR }}/dotnet + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 8.0.x + + # From the signing input: pinned version, SHA-512-verified package. + - name: Install vpk + env: + VPK_TEMP_ROOT: ${{ env.PWRDISK_SIGNING_TEMP_DIR }} + run: input/install-vpk.sh + + # A keychain of its own for the Developer ID certificate and the + # notarytool profile vpk and macos-dmg.sh use. Always cleaned below. + - name: Import Developer ID certificate and notary profile + id: keychain + env: + CSC_LINK: ${{ secrets.CSC_LINK }} + CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }} + APPLE_API_KEY_BASE64: ${{ secrets.APPLE_API_KEY_BASE64 }} + APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }} + APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }} + APPLE_TEAM_ID: T44CNHC4UH + run: python3 input/macos-signing.py prepare + + # The newest published full package, so vpk can write a delta against + # it. The first release, or a feed that cannot be read, packs full only. + - name: Fetch the previous release for deltas env: GH_TOKEN: ${{ github.token }} - TAG: ${{ needs.release.outputs.tag }} - VERSION: ${{ needs.release.outputs.version }} - ARCH: ${{ matrix.arch }} run: | - zip="target/bundle/disktree-$VERSION-$ARCH-macos.zip" - (cd "$(dirname "$zip")" && shasum -a 256 "$(basename "$zip")" \ - > "$(basename "$zip").sha256") - gh release upload "$TAG" "$zip" "$zip.sha256" --clobber - - windows: - name: Build (Windows ${{ matrix.arch }}) - needs: release + if ! vpk --skip-updates download github --repoUrl "https://github.com/$GITHUB_REPOSITORY" \ + --token "$GH_TOKEN" --pre --channel osx --outputDir releases; then + echo "::warning::Could not fetch the previous macOS release; packing without a delta." + fi + + # vpk adds UpdateMac and sq.version to the app and re-signs it with + # PwrDisk.entitlements (none): Developer ID, hardened runtime, + # notarized and stapled. No .pkg installer (--noInst): it needs a + # Developer ID Installer certificate, which apple-signing does not + # hold; the DMG is the installer. --icon is read only when vpk builds + # the .app itself; this one keeps the AppIcon.icns bundle drew. + - name: Pack with vpk + env: + IDENTITY: ${{ steps.keychain.outputs.identity }} + KEYCHAIN: ${{ steps.keychain.outputs.path }} + run: | + set -euo pipefail + vpk --skip-updates pack \ + --packId PwrDisk \ + --packVersion "${RELEASE_TAG#v}" \ + --packDir input/PwrDisk.app \ + --mainExe pwrdisk \ + --packTitle PwrDisk \ + --packAuthors "PwrDrvr LLC" \ + --releaseNotes input/RELEASE_NOTES.md \ + --signEntitlements input/PwrDisk.entitlements \ + --noInst \ + --outputDir releases \ + --signAppIdentity "$IDENTITY" \ + --notaryProfile pwrdisk-notary \ + --keychain "$KEYCHAIN" + + # Cut from the packed app, so the copy dragged to Applications is the + # one that can update itself. The script signs, notarizes and staples + # the DMG with the same identity and profile. + - name: Put the packed app in a DMG + env: + IDENTITY: ${{ steps.keychain.outputs.identity }} + KEYCHAIN: ${{ steps.keychain.outputs.path }} + NOTARY_PROFILE: pwrdisk-notary + run: | + set -euo pipefail + mkdir -p dist packed + ditto -x -k releases/PwrDisk-osx-Portable.zip packed + DMG_VERSION="${RELEASE_TAG#v}" input/macos-dmg.sh "$PWD/packed/PwrDisk.app" \ + "dist/PwrDisk-${RELEASE_TAG#v}-universal.dmg" "$IDENTITY" + + # What a downloaded copy will face: the team's signature, a stapled + # ticket, and Gatekeeper's verdict, for the app and the DMG. + - name: Verify signature and notarization + env: + APPLE_TEAM_ID: T44CNHC4UH + run: | + set -euo pipefail + app="$PWD/packed/PwrDisk.app" + codesign --verify --deep --strict --all-architectures "$app" + details=$(codesign -dv "$app" 2>&1) + if ! grep -qx "TeamIdentifier=$APPLE_TEAM_ID" <<< "$details"; then + echo "::error::PwrDisk.app is not signed by team $APPLE_TEAM_ID." >&2 + exit 1 + fi + lipo "$app/Contents/MacOS/pwrdisk" -verify_arch arm64 x86_64 + test -x "$app/Contents/MacOS/UpdateMac" + xcrun stapler validate "$app" + spctl --assess --type execute -vv "$app" + dmg=$(ls dist/*.dmg) + xcrun stapler validate "$dmg" + spctl --assess --type open --context context:primary-signature -vv "$dmg" + + - name: Remove temporary signing credentials + if: always() + run: | + set -euo pipefail + if [ -n "${PWRDISK_SIGNING_TEMP_DIR:-}" ]; then + # Even a cleanup error must not retain decoded keys or the keychain. + trap 'rm -rf -- "$PWRDISK_SIGNING_TEMP_DIR"' EXIT + if [ -f input/macos-signing.py ]; then + python3 input/macos-signing.py cleanup + fi + fi + + # This version's packages and the osx feed only: the previous + # release's package fetched for the delta stays in the release that + # owns it. + - name: Collect macOS release assets + run: | + set -euo pipefail + version="${RELEASE_TAG#v}" + cp "releases/PwrDisk-$version-osx-full.nupkg" releases/PwrDisk-osx-Portable.zip \ + releases/releases.osx.json releases/assets.osx.json releases/RELEASES-osx dist/ + if [ -f "releases/PwrDisk-$version-osx-delta.nupkg" ]; then + cp "releases/PwrDisk-$version-osx-delta.nupkg" dist/ + fi + # The README links .../releases/latest/download/PwrDisk.dmg; a + # versioned name alone would make that link go stale every release. + cp "dist/PwrDisk-$version-universal.dmg" dist/PwrDisk.dmg + (cd dist && shasum -a 256 -- * > "PwrDisk-$version-macos-SHA256SUMS") + ls -l dist + + - name: Upload macOS release assets + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: release-macos + path: release-signing/dist/* + if-no-files-found: error + retention-days: 90 + + windows-prepare: + name: Build Windows ${{ matrix.arch }} and prepare signing input + needs: check strategy: matrix: include: - - { runner: windows-2025, arch: x86_64 } - - { runner: windows-11-arm, arch: aarch64 } + - { runner: windows-2025, arch: x64 } + - { runner: windows-11-arm, arch: arm64 } runs-on: ${{ matrix.runner }} + timeout-minutes: 60 + # One output per architecture: a matrix job's legs share one outputs + # map, and each leg sets only its own key, so neither overwrites the + # other. windows-sign refuses an empty digest. + outputs: + sha256-x64: ${{ steps.archive.outputs.sha256-x64 }} + sha256-arm64: ${{ steps.archive.outputs.sha256-arm64 }} env: - # The C runtime linked in, so disktree.exe also runs where the Visual + # The C runtime linked in, so pwrdisk.exe also runs where the Visual # C++ runtime was never installed. For the tests too, so both steps # share one build. RUSTFLAGS: -C target-feature=+crt-static steps: - run: git config --global core.autocrlf false - - uses: actions/checkout@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ inputs.tag || github.ref }} + persist-credentials: false - - uses: dtolnay/rust-toolchain@master + - uses: ./.github/actions/setup-rust with: - toolchain: "1.97" - - - uses: Swatinem/rust-cache@v2 + save-if: false - name: Test run: cargo xtask test @@ -236,37 +475,287 @@ jobs: - name: Build run: cargo build --release --locked -p disktree-app - - name: Package - id: package + # `app/` becomes vpk's packDir: what installs under + # %LocalAppData%\PwrDisk\current. Files are copied, never piped + # through a PowerShell redirect, which re-encodes text and would + # mangle the "Lütke" in LICENSE. + - name: Stage signing input + shell: pwsh + run: | + $stage = Join-Path $env:RUNNER_TEMP "windows-release-input" + New-Item -ItemType Directory -Force "$stage/app" | Out-Null + Copy-Item target/release/pwrdisk.exe, README.md, LICENSE "$stage/app/" + Copy-Item licenses/velopack.txt "$stage/app/VELOPACK-NOTICES.txt" + Copy-Item scripts/release/install-vpk.sh, scripts/release/vpk-pack-windows.ps1, assets/disktree.ico "$stage/" + cargo xtask release-check --notes-file "$stage/RELEASE_NOTES.md" + if ($LASTEXITCODE -ne 0) { throw "release-check failed (exit code $LASTEXITCODE)." } + + - name: Archive signing input + id: archive shell: pwsh env: - VERSION: ${{ needs.release.outputs.version }} ARCH: ${{ matrix.arch }} run: | - $name = "disktree-$env:VERSION-$env:ARCH-windows" - New-Item -ItemType Directory -Force "dist/$name" | Out-Null - Copy-Item target/release/disktree.exe, README.md, LICENSE "dist/$name/" - Compress-Archive -Path "dist/$name" -DestinationPath "dist/$name.zip" - $hash = (Get-FileHash "dist/$name.zip" -Algorithm SHA256).Hash.ToLower() - # The format `sha256sum -c` reads, with a Unix line ending. - [IO.File]::WriteAllText("dist/$name.zip.sha256", "$hash $name.zip`n") - "archive=dist/$name.zip" >> $env:GITHUB_OUTPUT - - - name: Upload + $name = "windows-release-signing-input-$env:ARCH.tgz" + $archive = Join-Path $env:RUNNER_TEMP $name + & tar.exe -czf $archive -C (Join-Path $env:RUNNER_TEMP "windows-release-input") . + if ($LASTEXITCODE -ne 0) { throw "Failed to archive Windows signing input (exit code $LASTEXITCODE)." } + $sha256 = (Get-FileHash -Algorithm SHA256 $archive).Hash.ToLowerInvariant() + "sha256-$env:ARCH=$sha256" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8 + "$sha256 $name" | Set-Content -Path "$archive.sha256" -Encoding ascii + + - name: Upload signing input + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: windows-release-signing-input-${{ matrix.arch }} + path: | + ${{ runner.temp }}/windows-release-signing-input-${{ matrix.arch }}.tgz + ${{ runner.temp }}/windows-release-signing-input-${{ matrix.arch }}.tgz.sha256 + if-no-files-found: error + retention-days: 7 + + windows-sign: + name: Pack and sign Windows installers + # The only Windows job with Azure credentials. It does not check out + # source or run cargo; it packs the verified builds from + # windows-prepare. x64 for both architectures: packing and signing read + # the files, they do not run them. + needs: windows-prepare + runs-on: windows-2025 + timeout-minutes: 60 + # Azure Artifact Signing, as in PwrAgent and PwrRoute: the four + # WIN_AZURE_SIGN_* variables and three AZURE_* secrets. Only v* tags, + # after approval. + environment: windows-signing + steps: + - name: Download signing input + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: windows-release-signing-input-* + path: .release-input + merge-multiple: true + + - name: Verify and expand signing input + shell: pwsh + env: + SHA256_X64: ${{ needs.windows-prepare.outputs.sha256-x64 }} + SHA256_ARM64: ${{ needs.windows-prepare.outputs.sha256-arm64 }} + run: | + foreach ($arch in "x64", "arm64") { + $expected = [Environment]::GetEnvironmentVariable("SHA256_$($arch.ToUpper())") + $name = "windows-release-signing-input-$arch.tgz" + $archive = ".release-input/$name" + $actual = (Get-FileHash -Algorithm SHA256 $archive).Hash.ToLowerInvariant() + if (-not $expected -or $actual -ne $expected) { + throw "Windows $arch signing input digest mismatch: expected '$expected', got $actual." + } + $recorded = (Get-Content "$archive.sha256" -Raw).Trim() + if ($recorded -ne "$actual $name") { + throw "Windows $arch signing input checksum file does not match the archive." + } + New-Item -ItemType Directory -Force "input/$arch" | Out-Null + & tar.exe -xzf $archive -C "input/$arch" + if ($LASTEXITCODE -ne 0) { throw "Failed to expand the $arch signing input (exit code $LASTEXITCODE)." } + } + + # A release is never shipped unsigned. + - name: Check signing configuration shell: bash + env: + WIN_AZURE_SIGN_PUBLISHER_NAME: ${{ vars.WIN_AZURE_SIGN_PUBLISHER_NAME }} + WIN_AZURE_SIGN_ENDPOINT: ${{ vars.WIN_AZURE_SIGN_ENDPOINT }} + WIN_AZURE_SIGN_ACCOUNT: ${{ vars.WIN_AZURE_SIGN_ACCOUNT }} + WIN_AZURE_SIGN_PROFILE: ${{ vars.WIN_AZURE_SIGN_PROFILE }} + AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} + AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} + AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + run: | + missing=() + for name in WIN_AZURE_SIGN_PUBLISHER_NAME WIN_AZURE_SIGN_ENDPOINT \ + WIN_AZURE_SIGN_ACCOUNT WIN_AZURE_SIGN_PROFILE \ + AZURE_TENANT_ID AZURE_CLIENT_ID AZURE_CLIENT_SECRET; do + [ -n "${!name}" ] || missing+=("$name") + done + if [ ${#missing[@]} -gt 0 ]; then + echo "::error::windows-signing is missing: ${missing[*]}" >&2 + exit 1 + fi + + # vpk runs on .NET; so does the Azure Artifact Signing dlib it ships. + - name: Install .NET for vpk + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 8.0.x + + # From the signing input: pinned version, SHA-512-verified package. + # Both architectures carry the same script. + - name: Install vpk + shell: bash + run: input/x64/install-vpk.sh + + # The metadata.json the Azure Artifact Signing dlib reads; the + # credentials come from the AZURE_* environment of the pack step. + - name: Write Azure Artifact Signing metadata + shell: pwsh + env: + WIN_AZURE_SIGN_ENDPOINT: ${{ vars.WIN_AZURE_SIGN_ENDPOINT }} + WIN_AZURE_SIGN_ACCOUNT: ${{ vars.WIN_AZURE_SIGN_ACCOUNT }} + WIN_AZURE_SIGN_PROFILE: ${{ vars.WIN_AZURE_SIGN_PROFILE }} + run: | + @{ + Endpoint = $env:WIN_AZURE_SIGN_ENDPOINT + CodeSigningAccountName = $env:WIN_AZURE_SIGN_ACCOUNT + CertificateProfileName = $env:WIN_AZURE_SIGN_PROFILE + } | ConvertTo-Json | Set-Content -Path (Join-Path $env:RUNNER_TEMP "azure-signing.json") -Encoding utf8 + + # Each architecture is its own channel and its own output directory, + # so neither feed nor delta sees the other's packages. The previous + # release's full package lets vpk write a delta; the first release, + # or a feed that cannot be read, packs full only. + - name: Pack with vpk + shell: pwsh env: GH_TOKEN: ${{ github.token }} - TAG: ${{ needs.release.outputs.tag }} - ARCHIVE: ${{ steps.package.outputs.archive }} - run: gh release upload "$TAG" "$ARCHIVE" "$ARCHIVE.sha256" --clobber + AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} + AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} + AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + run: | + foreach ($arch in "x64", "arm64") { + $channel = if ($arch -eq "x64") { "win" } else { "win-$arch" } + $out = "releases/$arch" + & vpk --skip-updates download github --repoUrl "https://github.com/$env:GITHUB_REPOSITORY" ` + --token $env:GH_TOKEN --pre --channel $channel --outputDir $out + if ($LASTEXITCODE -ne 0) { + "::warning::Could not fetch the previous Windows $arch release; packing without a delta." + } + # What was there before packing: the previous release's package, + # which stays in the release that owns it. + New-Item -ItemType Directory -Force $out | Out-Null + Get-ChildItem $out -File -Filter *.nupkg | ForEach-Object { $_.Name } | + Set-Content (Join-Path $env:RUNNER_TEMP "previous-$arch.txt") + & "./input/$arch/vpk-pack-windows.ps1" ` + -Version $env:RELEASE_TAG.TrimStart("v") -Arch $arch ` + -PackDir "input/$arch/app" -OutputDir $out ` + -Icon "input/$arch/disktree.ico" ` + -ReleaseNotes "input/$arch/RELEASE_NOTES.md" ` + -AzureSignFile (Join-Path $env:RUNNER_TEMP "azure-signing.json") + } + + - name: Verify Authenticode signatures + shell: pwsh + env: + EXPECTED_PUBLISHER: ${{ vars.WIN_AZURE_SIGN_PUBLISHER_NAME }} + run: | + foreach ($arch in "x64", "arm64") { + $channel = if ($arch -eq "x64") { "win" } else { "win-$arch" } + $out = "releases/$arch" + $portable = Join-Path $env:RUNNER_TEMP "portable-$arch" + Expand-Archive "$out/PwrDisk-$channel-Portable.zip" -DestinationPath $portable + $targets = @( + "$out/PwrDisk-$channel-Setup.exe", + "$out/PwrDisk-$channel.msi", + (Join-Path $portable "Update.exe"), + (Join-Path $portable "PwrDisk.exe"), + (Join-Path $portable "current/pwrdisk.exe") + ) + foreach ($target in $targets) { + if (-not (Test-Path -LiteralPath $target)) { + throw "Expected signed file is missing: $target" + } + $sig = Get-AuthenticodeSignature (Resolve-Path $target).Path + if ($sig.Status -ne "Valid") { + throw "${target} signature is $($sig.Status): $($sig.StatusMessage)" + } + # The certificate's common name, compared whole: a substring + # of the subject would also accept a lookalike publisher. + $signer = $sig.SignerCertificate.GetNameInfo( + [Security.Cryptography.X509Certificates.X509NameType]::SimpleName, $false) + if ($signer -cne $env:EXPECTED_PUBLISHER) { + throw "${target} is signed by '$signer', not '$env:EXPECTED_PUBLISHER'" + } + if (-not $sig.TimeStamperCertificate) { + throw "${target} has no timestamp, so it stops verifying when the certificate expires" + } + "signed: $target" + } + } + + # Every file vpk wrote for this version, both architectures: the + # installers, the portable zips, the packages and the feeds. + - name: Collect Windows release assets + shell: pwsh + run: | + $version = $env:RELEASE_TAG.TrimStart("v") + New-Item -ItemType Directory -Force dist | Out-Null + foreach ($arch in "x64", "arm64") { + $previous = @(Get-Content (Join-Path $env:RUNNER_TEMP "previous-$arch.txt") -ErrorAction SilentlyContinue) + Get-ChildItem "releases/$arch" -File | + Where-Object { $_.Extension -ne ".nupkg" -or $previous -notcontains $_.Name } | + ForEach-Object { + if (Test-Path -LiteralPath (Join-Path dist $_.Name)) { + throw "Both architectures wrote $($_.Name)" + } + Copy-Item -LiteralPath $_.FullName -Destination dist + } + } + $sums = Get-ChildItem dist -File | Sort-Object Name | ForEach-Object { + "$((Get-FileHash -Algorithm SHA256 $_.FullName).Hash.ToLowerInvariant()) $($_.Name)" + } + [IO.File]::WriteAllText("dist/PwrDisk-$version-windows-SHA256SUMS", ($sums -join "`n") + "`n") + Get-ChildItem dist | Format-Table Name, Length + + - name: Upload Windows release assets + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: release-windows + path: dist/* + if-no-files-found: error + retention-days: 90 publish: - name: Publish - needs: [release, linux, macos, windows] + name: Create the release + needs: [linux, macos-sign, windows-sign] runs-on: ubuntu-24.04 + timeout-minutes: 20 + concurrency: + group: release-${{ inputs.tag || github.ref_name }} + cancel-in-progress: false + permissions: + contents: write steps: - - name: Publish + # One directory per artifact: merging would let a same-named file + # from one platform silently replace another's. + - name: Download platform artifacts + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: release-* + path: release-artifacts + + - name: Check asset names are unique + run: | + set -euo pipefail + mv release-artifacts/release-notes/RELEASE_NOTES.md "$RUNNER_TEMP/" + rmdir release-artifacts/release-notes + dupes=$(find release-artifacts -type f -exec basename {} \; | sort | uniq -d) + if [ -n "$dupes" ]; then + echo "::error::Two platforms produced the same asset name: $dupes" >&2 + exit 1 + fi + mkdir release-assets + find release-artifacts -type f -exec mv {} release-assets/ \; + ls -l release-assets + + # Born a Pre-release: the update channel's Stable · Latest slot + # follows promoted releases only, so a release reaches installed + # copies on that channel when it is promoted to Latest by hand. + - name: Create the pre-release env: GH_TOKEN: ${{ github.token }} - TAG: ${{ needs.release.outputs.tag }} - run: gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=false --latest + run: | + gh release create "$RELEASE_TAG" \ + --repo "$GITHUB_REPOSITORY" \ + --verify-tag \ + --prerelease \ + --title "PwrDisk ${RELEASE_TAG#v}" \ + --notes-file "$RUNNER_TEMP/RELEASE_NOTES.md" \ + release-assets/* diff --git a/.gitignore b/.gitignore index ea8c4bf7..05099244 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /target +/.local/sandboxer/ diff --git a/AGENTS.md b/AGENTS.md index 0342b30c..d7dcccbe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,8 +1,16 @@ -# disktree — agent guide +# PwrDisk — agent guide + +PwrDisk is a maintained fork of [disktree](https://github.com/pwrdrvr/PwrDisk). +The user-facing name is PwrDisk (binary `pwrdisk`, bundle ID +`com.pwrdrvr.pwrdisk`); crate, module and type names and the SSH helper +(`disktree-scan`) keep the upstream names so upstream merges stay clean. A GPUI + gpui-omarchy treemap explorer for disk usage on Omarchy. Read `README.md` for the product; this file is the working contract. +Opening a PR? Read [Pull requests](#pull-requests) first: screenshots are +attached with `gh --attach`, never hosted on a branch. + ## What this is Find what is eating a volume, mark paths for removal, review the list, and @@ -11,37 +19,105 @@ phases after choosing a local/SSH source and root: explore (treemap, breadcrumbs, selection and status) and review (the marked list, the removal mode, the confirmation). Marking is never destructive. +`pwrdisk mcp` is the same thing for an AI agent: an MCP server over stdio +that scans with `disktree-core`, marks, and opens the review screen in a +window over a per-user socket or pipe (`disktree-link`). Removal uses either +human review or an explicit destructive MCP write after a single-use preview +and user confirmation of the exact paths and mode. Computer use must never +approve removal. Both routes enforce the configured per-operation capacity +limit (5% per volume by default), including a fresh measurement on the worker. + ## Commands ```sh make build # release build -make run # build and open the source/root chooser +make run # opens a window: see Testing on a desktop make install # ~/.local: binary, desktop entry, icon make install PREFIX=/usr/local # system-wide (needs root) make uninstall -make bundle # macOS: target/bundle/disktree.app and its zip +make bundle # macOS: target/bundle/PwrDisk.app, zip and DMG +make dock-icons # macOS 26: redraw the Dock icon of an unbundled run make lint # rustfmt --check, then clippy --all-targets -D warnings make test # core and window-harness tests make ci # lint, then test make fmt # format in place +cargo xtask licenses # rewrite THIRD_PARTY_LICENSES after a dependency change ``` `make install` is the supported way to put this on a machine: it installs the -release binary, `packaging/disktree.desktop.in` (rendered with the real install +release binary, `packaging/pwrdisk.desktop.in` (rendered with the real install prefix and the crate version) and `assets/disktree.svg`. Keep the desktop entry's `Categories` to a single main category plus additional ones, or `desktop-file-validate` complains. -On macOS `make install` installs `target/bundle/disktree.app` into +On macOS `make install` installs `target/bundle/PwrDisk.app` into `~/Applications` instead, built by `cargo xtask bundle` from `packaging/macos/` (the `Info.plist` template and the icon's SVG). The bundle identifier there keys every macOS permission grant; do not change it lightly. +The macOS icon has two sources in `packaging/macos/`, and each macOS reads +the one made for it. `AppIcon.svg` is the mark on Apple's legacy 824-in-1024 +tile; the bundle draws `AppIcon.icns` from it, which macOS 15 and earlier +draw literally. `AppIcon.icon` with `AppGlyph.svg` is the Icon Composer +package: when Xcode 26's actool is at hand `cargo xtask bundle` compiles it +into `Assets.car` and names it with `CFBundleIconName`, and macOS 26 draws +that with its own shape, glass edge and Dark, Clear and Tinted looks. Handed +only the `.icns`, macOS 26 normalizes it instead, and 26.6.2 has drawn such a +padded icns on a light plate, so a bundle without the catalog says so. A run +outside the bundle (`make run`, `cargo run`) has no icon for macOS to draw, +so `dock_icon.rs` paints one: `DockIcon.png`, or on macOS 26 +`DockIcon-glass.png`, the shipped icon as that macOS itself draws it, since +Liquid Glass is never applied to an image set at run time. `make dock-icons` +redraws both on a macOS 26 with Xcode 26; run it after either SVG changes. + +Releases are cut by `release.yml` from a `vX.Y.Z` tag that matches the +workspace version and a `## vX.Y.Z` section of `CHANGELOG.md` (`cargo xtask +release-check`); `docs/releasing.md` is the procedure and +`.github/workflows/README.md` the design. macOS ships a DMG and Windows a +Velopack Setup.exe, MSI and portable zip, both of which update themselves +from GitHub Releases. The `velopack` crate pin and `VPK_VERSION` in +`scripts/release/install-vpk.sh` move together. + `cargo xtask lint` is the gate. It must be green before anything is called done, and it must not fix anything: a red local run is the same signal CI gives. On Windows, where there is no make, run `cargo xtask lint`, `cargo xtask test` and `cargo build --release` directly; CI runs the gate on both systems. +When Sandboxer MCP tools are available, run Linux builds, lint, tests, SSH +integration and other Linux-only checks there. Start from +`pwrdisk-base-us-east` in `us-east`; read +[remote verification](docs/sandboxer.md) first. Use local checks when +Sandboxer is unavailable. Sandboxer is Linux only. macOS and Windows changes +are verified on those systems with the headless gate (`cargo xtask lint`, +`cargo xtask test`) and CI; anything that needs a window follows +[Testing on a desktop](#testing-on-a-desktop). + +## Testing on a desktop + +Never launch PwrDisk, or send synthetic input, on the operator's desktop. +Keys and clicks from `osascript` or System Events, `cliclick`, AX actions, +computer use, and moving or resizing windows land wherever the operator is +working; they have landed in another app. That holds for screenshots, +native accessibility checks and every other GUI check, and for `make run` +or `cargo run` to look at a change. The window-harness tests (`make test`, +`cargo xtask test`) are fine: they draw headless. + +* **An on-screen macOS window** (screenshots, VoiceOver, native AX checks) runs + in the PwrSuiteLab headed E2E Tart VM through the PwrSuiteLab Control + MCP. Read [docs/headed-e2e-pwrsuitelab.md](docs/headed-e2e-pwrsuitelab.md) + before the first job. Without that MCP, stop and ask the operator: there + is no local fallback and no script fallback. +* **Any other window**, such as a Linux or Windows GUI the lab cannot show: + ask the operator. Never the local desktop. +* **Files, not the clipboard.** Lab VMs start with clipboard sharing off. + Inputs travel in the committed source a job stages and outputs come back + as collected artifacts; never ask the operator to paste into or copy + from the guest. +* **Keep the lab out of this repository.** PwrDisk is public: no lab + detail goes in code, docs, commits or PRs. The last section of + [docs/headed-e2e-pwrsuitelab.md](docs/headed-e2e-pwrsuitelab.md) lists + what counts. Targets come from `lab_status` at run time. + ## House rules * **Strict lints from omatrack's style.** `clippy::all` and `clippy::pedantic` @@ -63,11 +139,11 @@ and `cargo build --release` directly; CI runs the gate on both systems. ## Invariants 1. **Sizes come from `st_blocks * 512` unless apparent size was asked for.** - That is the number that comes back when a file is deleted. On macOS the - directory listing reports it and `st_size` for a whole buffer of entries: - every fork's allocation, and the data fork's length; see `macos.rs`. On - Windows it is the allocation the directory listing reports; see - `windows.rs`. An + APFS clones can share those blocks; private-byte estimates are reported + separately without changing tile weights. On macOS the directory listing + reports every fork's allocation and the data fork's length in bulk; see + `macos.rs`. On Windows it is the allocation the directory listing reports; + see `windows.rs`. An elevated scan of a whole NTFS drive reads it from the master file table instead, keeping the walk's rules for hidden entries, links, cloud folders and depth; see `mft.rs`. That path counts every stream's @@ -80,15 +156,18 @@ and `cargo build --release` directly; CI runs the gate on both systems. children when asked. Hardlink de-duplication zeroes a duplicate leaf's `bytes` while that pass runs; anything that patches a directory's `bytes` directly will be overwritten. `Node` is paid for tens of millions of - times, so `a_node_stays_small` holds its size. + times, so `a_node_stays_small` in `index.rs` holds its size. 3. **A directory is only built when its own scan *and* every subdirectory task has finished.** That is the `+1` sentinel in `PendingDir::pending`. Building early silently drops whole subtrees — it has happened once. 4. **Only paths under the scanned root may be removed**, and mount points, the root, the home directory, any directory holding it, and symlink targets are - refused. On Windows so is every directory directly in the profiles folder - Windows reports (`FOLDERID_UserProfiles`, usually `C:\Users`); what is - inside a profile stays removable. + refused. So are the profiles folder and every directory directly in it: + on Windows the one Windows reports (`FOLDERID_UserProfiles`, usually + `C:\Users`), on macOS `/Users`, on Linux `/home` (and its real path + when it is a link). What is inside a profile stays + removable. The window asks the guards before a mark is made + (`removal::refusal`), so a refused path is never offered for marking. 5. **Marks are keyed by absolute path**, not tree position, so they survive a re-scan; `Marks::refresh` re-reads their sizes and drops what is gone. 6. **The treemap is painted, not composed of elements.** Thousands of @@ -107,37 +186,135 @@ and `cargo build --release` directly; CI runs the gate on both systems. the tree, which `-X` and the media exception allow, is reported and never added to this volume's free space; see `space::attribution`. The final number comes from `statvfs` before and after. - 10. **Discovery is not a scan.** No implicit home walk at startup. List mounts in the selected machine's namespace without probing them; scans stop at nested mounts, including bind mounts and same-device subvolumes. Switching machines clears marks and identity. The Unix SSH helper streams - records and never retains the tree. + records and never retains the tree. SSH hosts are Unix, so remote paths + are POSIX on every client: join, split and compare them through + `PathStyle`, never `std::path`, which uses `\` on Windows. 11. **A live overview is not an actionable tree.** Keep provisional, bounded display summaries separate from `Disktree::tree` and all path, mark and removal APIs. Only a complete scan may replace the real tree. Counters and sampled paths belong in fixed, monospace progress lanes. +12. **The user confirms removal.** Marking never authorizes deleting. + `review` only opens the review screen; agents must never click its + confirmation or press its approval keys through computer use. MCP removal + is a destructive write: prepare an expiring, single-use preview, show the + exact paths and mode and explain recoverability, then obtain explicit + confirmation for that operation. An expired or changed preview requires + new confirmation. The app validates the intent and rechecks existing + guards and its configured capacity limit for both UI and MCP removals. + Past the limit only the person can go: in the window, through Mark + anyway and then Review's second confirmation (a typed phrase by + default), which names each disk past the limit, with the worker + holding each of those disks to its confirmed share and every other + disk to the limit. An agent's mark past the limit is refused, and + agents keep the default limit when the window's is Off, on the + worker as at the preview: nothing the person confirms in Review + raises an agent's removal. `mark_guard.rs` holds the rule. + Trash never falls back to permanent deletion. No headless or SSH removal. + A cache cleanup is decided per marked path (Skip by default, the + owner's exact command, or Delete files); owner approval never approves + deleting files, which has its own consent, and a failed owner command + never falls back to it. See `docs/owner-cleanup.md`. + A linked window's tree and marks remain the source of truth; `ls` and + `find` read it without navigating. Only an explicit `show` request moves + the view, and guidance requires the user to request that behavior. + `scan` explicitly changes the scan root; linking never does so implicitly. +13. **The link is a same-user socket or pipe, nothing more.** `disktree-link` + binds `0600` in a per-user directory on Unix. On Windows it uses a + named pipe keyed by the user's SID, with a protected DACL granting only + that user access and `PIPE_REJECT_REMOTE_CLIENTS`. Before exchanging + messages the client verifies the connected pipe's owner is that SID. + It has no token: the agent already runs as the user and `pwrdisk mcp` + scans on its own. + Do not add a port. + A window showing an SSH host answers only `hello` and `state`: an + agent's paths are this computer's. +14. **The skills are the agent's safety brief.** `skills/` is compiled + into `pwrdisk mcp` (`disktree-mcp/src/skills.rs` lists every file; + a URI is looked up, never turned into a path). They tell the agent + to agree the list before marking unless the user gave a standing + instruction, and never to delete by other means. A change to what + the guards refuse, what removal does, or what a system hides from a + scan updates the matching `references/.md` in the same PR. + +15. **A tree owns a handful of buffers, by index.** Nodes live in one + vector, each directory's children a contiguous run of it, names in one + string and clone records in side tables, so dropping a tree frees eight + buffers instead of tens of millions of allocations. An allocation record + keeps only what its node does not say (`index/records.rs`): a clone with + one name reads its size from the node, so a placed leaf's `bytes` and + `inode` change only by hardlink de-duplication. A record is never + changed in place, which is what lets the files of a clone group share + one; a change that writes to a record must stop that. A node is read + through a `Node<'_>` cursor from its tree and written through `NodeMut` + or a whole-tree pass. Build with `Tree::build` (a `Draft` for tests and + small trees); a subtree moves to another tree only as a copy. A + finished tree keeps every subtree one contiguous run, which is what + lets `par_bottom_up` split it across workers without `unsafe`: only + the order *within* a block may change after it is built. + +16. **A bug fix states the rule it broke as a property, model or oracle + test, and confirms that test fails on the pre-fix code.** Do the same + for new guard, limit, accounting and path logic, and for state that + changes over time. Example tests alone check only what their author + expected. Here they have asserted the bug as correct, and passed only + because of a bug. + [docs/property-model-oracle-testing.md](docs/property-model-oracle-testing.md) + says what each kind is and how to write one. + ## Where changes belong | change | where | | --- | --- | | bounded Unix SSH traversal | `crates/disktree-core/src/remote_walk.rs` | | SSH protocol, discovery and transport | `crates/disktree-core/src/remote.rs` | +| joining, splitting or comparing a scanned path | `crates/disktree-core/src/path_style.rs` | | measurement, filtering, parallelism | `crates/disktree-core/src/scan.rs` | | what a node is, or a derived total | `crates/disktree-core/src/tree.rs` | +| how a tree is held in memory, its buffers and parallel passes | `crates/disktree-core/src/index.rs` | | tile geometry, nesting, the merged tail | `crates/disktree-core/src/treemap.rs` | | anything that deletes, or refuses to | `crates/disktree-core/src/removal.rs` | | free space and projections | `crates/disktree-core/src/space.rs` | | what macOS lists and measures in bulk | `crates/disktree-core/src/macos.rs` — `unsafe` for `getattrlistbulk` | | what Windows lists, measures and compares differently | `crates/disktree-core/src/windows.rs` — `unsafe` for Win32 | | reading a whole NTFS drive from its file table | `crates/disktree-core/src/mft.rs` | +| APFS clone hints and private-size system calls | `crates/disktree-core/src/macos.rs` — isolated `unsafe` | +| clone sharing totals and conservative savings | `crates/disktree-core/src/sharing.rs` | +| what git is asked about a checkout, when, and how many at once | `crates/disktree-app/src/git.rs` (the probe and its time limit), `crates/disktree-app/src/git_store.rs` (the queue, the bucket, the cache) | | a key, a screen transition, a mark | `crates/disktree-app/src/state.rs` | +| what may be marked, Mark anyway, Review's over-limit confirmation | `crates/disktree-app/src/mark_guard.rs`, the settings in `safety.rs` | +| cache cleanup: owners, proposals, decisions, per-path results | `crates/disktree-core/src/cleanup.rs` (model, allowlist), `crates/disktree-app/src/cleanup.rs` (window state), `cleanup_view.rs` (Review's proposals) | +| Removing and Done: the run's list, its rows, following and running figures; the row anatomy Review shares | `crates/disktree-app/src/run_view.rs`, the model in `run_list.rs`, Review's `mark_row` in `views.rs` | +| what the explore bar folds into ⋮ at each width, and ⋮'s keys | `crates/disktree-app/src/toolbar.rs` | +| the legend as a filter: its chips and what they keep | `crates/disktree-app/src/legend.rs`, the rule in `crates/disktree-core/src/filter.rs` | | spacing, type and size | `crates/disktree-app/src/ui.rs` — tokens only, no `px` in layout | | the mosaic's painting or labels | `crates/disktree-app/src/treemap_view.rs` | | layout of a screen | `crates/disktree-app/src/views.rs` | | colours derived from the theme | `crates/disktree-app/src/palette.rs` | +| the title strip, window controls, the client-side frame | `crates/disktree-app/src/chrome.rs` | +| where the main window opens, and remembering it | `crates/disktree-app/src/window_frame.rs` | +| which display a new window opens on | `crates/disktree-app/src/placement.rs` | +| the menu bar, its shortcuts, the strip's menu off macOS | `crates/disktree-app/src/app_menu.rs`, the dropdown in `views.rs` | +| Help's rows, Copy Diagnostics Info | `crates/disktree-app/src/help.rs`, the report in `diagnostics.rs` | +| Settings (Updates, Safety, Agents (MCP), Diagnostics, About) | `crates/disktree-app/src/settings.rs` | +| Changelog, License, Third-Party Notices, Logs windows | `doc_window.rs`, `logs_window.rs`, framed by `aux_window.rs` | +| what goes in `main.log`, and where it lives | `crates/disktree-app/src/diag_log.rs` — never a scanned path | +| `THIRD_PARTY_LICENSES` | `cargo xtask licenses` (cargo-about), then commit it; non-crate parts in `licenses/bundled.txt` | +| the macOS icon, in any of its looks | `packaging/macos/` — the SVGs and `AppIcon.icon`, then `make dock-icons` | +| checking, downloading and applying updates | `crates/disktree-app/src/updater.rs` | +| what the window says about updates, and its notices: the toasts, the strip's ready chip | `crates/disktree-app/src/toasts.rs`, the chip in `views.rs` | +| the MCP connect commands and the connected agent's status line | `crates/disktree-app/src/agent.rs` | +| which release a release channel picks | `crates/disktree-app/src/update_channel.rs` | +| release packaging, the DMG, `vpk` | `scripts/release/`, `xtask/src/bundle.rs`, `.github/workflows/release.yml` | +| what an agent can ask of the window, and the answer | `crates/disktree-link/src/lib.rs` (messages), `crates/disktree-app/src/agent.rs` (handling) | +| a tool, its parameters or its wording | `crates/disktree-mcp/src/server.rs` (the MCP surface), `crates/disktree-mcp/src/session.rs` (what it does) | +| how a listing or a plan reads to an agent | `crates/disktree-mcp/src/report.rs` | +| what an agent is told to do, and to avoid | `skills/` (each system's cautions in `skills/pwrdisk-free-space/references/`), listed in `crates/disktree-mcp/src/skills.rs` | ## Verification expectations @@ -146,6 +323,77 @@ and `cargo build --release` directly; CI runs the gate on both systems. against real temporary trees. * The screens are covered by window-harness tests that draw frames and press keys, including one that marks a directory, confirms the removal and checks - the files are gone while unmarked neighbours are untouched. -* Rendering was verified by those tests and by running the app against a real - home directory; it has not been eyeballed in every theme and font size. + the files are gone while unmarked neighbours are untouched, and one that + drives the window over the real socket or pipe as `pwrdisk mcp` does. + Initialize them through `tests::init`, which applies a fixed theme without + native filesystem watching. Keep its control bindings aligned with + gpui-omarchy when updating that dependency; its normal `init` starts a + watcher that cannot wake GPUI's deterministic test executor safely. +* `disktree-mcp` tests every tool as a function against a temporary tree, + with a stand-in window on the socket or pipe for the linked cases; + `disktree-link` tests the transport itself. +* Rendering is verified by those tests and, where an on-screen macOS window + is needed, in the PwrSuiteLab VM against a contrived tree (see + [Testing on a desktop](#testing-on-a-desktop)); it has not been eyeballed + in every theme and font size. + +## Pull requests + +* **Screenshots and videos go on the PR with `gh --attach`.** GitHub CLI + 2.99+ uploads them: `gh pr create/edit/comment --attach ./after.png`, with + the same `./after.png` in the Markdown body, rewrites that link to a + `user-attachments` URL. Never push images to a side branch, a gist or the + repository to host them. `gh` exits 0 even when the link does not match, so + check every image link before calling a PR done. The procedure, and the + three ways it fails silently, are in + [docs/pr-screenshots.md](docs/pr-screenshots.md); read it before the first + `--attach`, and before any later body edit. +* **A PR that changes what the window shows has before/after screenshots**, + of a contrived tree rather than a real disk; + [docs/pr-screenshots.md](docs/pr-screenshots.md) says how to make one in + the lab VM, never on the operator's desktop. If nothing can show the + change, say why in the body and ask the operator. +* **Scans are private data.** A real scan shows user names in paths, + project and client names, volume names and sizes, and the chooser lists + mounts and SSH hosts. Show any screenshot that is not 100% contrived to the + operator and wait for approval before attaching it. +* **Titles are Conventional Commits:** `type(scope): what changed`, in the + imperative, as the Pwr family's other repositories do. Scopes follow the + table above: `core`, `scan`, `ssh`, `removal`, `macos`, `windows`, `app`, + `ci`, `release`, `docs`. A port of an upstream PR says so in the title, + `(port of tobi/disktree#N)`, and keeps the upstream commits and their + authorship. +* **Don't edit `CHANGELOG.md` in feature or fix PRs.** Every open PR that + adds a line conflicts with every other one. Put the user-facing summary in + the PR body; one release commit (`chore(release): vX.Y.Z`) writes the + version's section from changes since the last tag and is pushed directly + to `main` as a fast-forward update, without a release-prep PR. Follow + `.agents/skills/release/SKILL.md` when cutting a release. +* **PRs go to the fork, `pwrdrvr/PwrDisk`.** In a checkout with several + remotes, push only to the one pointing there; `tobi/disktree` and personal + forks are read-only from here. + +## PwrAgent threads + +* Before opening or attaching a PR, check that the thread's workspace holds + its head commit. Attaching a PR does not move the workspace. +* Attach the thread's PR and watch it with `notifyOn: ["merged", "closed"]`, + so the thread hears when it lands or is dropped. +* Work worth doing that this change leaves out goes on a PwrAgent to-do card + (`add_todo`, with a `start_thread` action whose prompt stands alone), not a + note in the PR body, a commit message or a code comment. The operator does + not read those notes; a card can be tracked and started. +* A PwrDisk window open on this machine belongs to the operator or another + thread: several checkouts and builds run here at once. Leave it alone, and + do not start another to look at a change; that runs in the lab, as + [Testing on a desktop](#testing-on-a-desktop) says. That includes the + link: do not point a local `pwrdisk mcp` at it to test a change; the + `disktree-mcp` tests use a stand-in window. + +## Agent instruction files + +Agent guidance lives in `AGENTS.md`, not in the README or code comments, and +in the smallest scope that needs it. Long procedures go in `docs/` with a +one-line pointer here that says when to read them. Every `AGENTS.md` has a +sibling `CLAUDE.md` symlink (`ln -s AGENTS.md CLAUDE.md`), so Codex and +Claude read one file. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..7df9ea17 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,239 @@ +# Changelog + +Each release's notes are its `## vX.Y.Z` section here: `cargo xtask +release-check` refuses a tag without one, and release.yml publishes the +section as the GitHub release's notes and as the notes Velopack shows beside +an update. Keep new entries under Unreleased until the version is cut. + +## Unreleased + +## v0.17.0 + +- Artifact assessments - Distinguish Detected artifacts from Suggested for + review cleanup candidates in the inspector and MCP reports, with the + identification evidence and guidance shown before marking. Recognize + more developer dependency and build-cache layouts without treating whole + tool homes or generic build folders as disposable. +- VM and Git data - Identify virtual disks, checkpoints, saved VM memory, + Git metadata and worktrees without recommending their removal. VM and + Git contents also prevent enclosing directories from being suggested as + a whole. Review warns when marked VM data may hold unique work. +- Protected folders - Refuse protected paths before they can be marked. + Protect the profiles folder and each home directory directly beneath it + on macOS, Linux and Windows, including Linux's linked `/home` spelling. + Contents inside a home remain eligible under the other removal guards. +- Removal limits - Require Mark anyway to mark beyond the configured + capacity limit. Review defaults to a second, typed confirmation naming + each affected disk and its share. Each disk is held to its own confirmed + share; growth beyond it is refused. Settings > Safety offers a checkbox + or no second step instead of typing, and an Off choice for the window. +- Agent limits - Agents cannot use the person's over-limit override. They + retain the default 5% limit when the window's limit is Off, both at the + preview and when the removal worker remeasures the selection. +- Removal outcomes - A worker that cannot start now finishes with every + item marked failed. MCP reconciles a preview's exact native-UI removal + outcome before issuing another request, including cancellation or errors + in an outstanding confirmation form. Observed volume changes retain + their sign rather than reporting a decrease in free space as zero. +- Agent planning - Add read-only `pwrdisk_rank` to compare up to 50 explicit + candidates, `pwrdisk_retention` for a bounded macOS Time Machine snapshot + presence check, and `pwrdisk_read_skill` for embedded guidance. Snapshot + presence does not quantify retained bytes or guarantee recovered space. +- Agents settings - Put connection status, copyable MCP setup commands and + the first prompt in Settings > Agents (MCP), also reachable from Help > + Connect an AI Agent (MCP) and the connected-agent indicator. +- Notices - Show transient notices as timed toasts, keep errors until + dismissed, and offer Undo after Unmark all. Copy buttons confirm in place. + Toasts, floating menus and list controls no longer activate content + underneath the pointer. Scan headings no longer clip letter descenders. +- Side panel - Pin section headers while their rows scroll. Short or + zoomed windows fold secondary selection figures and empty sections, + keeping assessments, marking actions and the disk meter accessible. +- Legend - Show each filter chip's size across the whole scan and keep the + legend on one row. Empty, tiny or overflowing kinds move into a +N menu; + active filters remain visible. Rename Reclaimable to Suggested to match + the distinction between identification and cleanup assessment. +- Compatibility - The window link now uses protocol version 7. Update + and restart both the PwrDisk window and MCP process together. + +## v0.16.0 + +- Removal progress - Keep the complete approved list available from the + start of removal through Done. Each row shows whether it is waiting, + being removed, in trash, removed, failed or not reached after Stop, with + failures explained beside the affected item. +- Following removal - Follow the item being processed automatically. + Scroll it out of view to pause following; use Follow the removal or + scroll back to resume. Large lists draw only the rows in view. +- Removal totals - Show running progress, listed bytes, private-byte + estimates, observed free-space change and the disk meter beside the + list. Keep the final results and the ledger of removals since the scan + available on Done; moving to trash explains why space is not yet freed. +- Review rows - Show each item's category or reclaim reason and its parent + folder consistently across Review, Removing and Done. Deep paths shorten + in the middle to fit one line; tooltips and accessible names retain the + complete path. Narrow windows move the progress sidebar below the list. +- Git status - Check selected checkouts promptly and hovered checkouts + only after a pause, with at most two checks at once and a five-second + limit. Keep cached answers while refreshing, cancel checks on a rescan + or source change, and stop periodic refreshes while the window is in the + background. Slow checkouts report too large to check. +- Git inspection - Avoid checkout-defined hooks, filters and network + access when inspecting repositories. Checkouts with their own filters + report changes unknown, and macOS does not prompt to install developer + tools merely because a checkout was selected. +- Responsiveness - Stop rereading checkout metadata and saved Safety + settings on every frame. Run Git checks on separate threads so they do + not occupy the app's shared background workers. + +## v0.15.0 + +- Large scans - Use less memory for file names and allocation records, + classify large trees in parallel, and quit without waiting for every + file record to be freed on the main thread. +- APFS sharing - Show private and shared bytes per entry in the inspector, + hover cards, List view and MCP reports. Reclaim estimates account for + the selected set together, including clones, and distinguish known + savings from uncertain bounds without changing treemap weights. +- Agent estimates - Add read-only `pwrdisk_estimate` for up to 200 paths, + with accepted, covered and refused paths, per-volume reclaim bounds, + and bounded discovery of other clone holders. Estimates do not mark + paths or authorize removal. +- List view - Switch between Treemap and List from the title strip or + Cmd/Ctrl+1 and Cmd/Ctrl+2. Browse the complete file list with paging, + keyboard navigation and accessible names. Less-used toolbar controls + move into an overflow menu when space is tight. +- Legend filters - Cycle category, age and Reclaimable chips through only, + hidden and shown. Filters apply to Treemap, List and search, with partial + folder sizes and an explicit empty result. Marking a partly shown folder + still marks the whole folder; the inspector explains this. +- Marked totals - Keep the combined marked size, reclaim estimate and + Review button visible above the Disk meter, with marked paths first in + the side panel. +- Treemap navigation - A click selects; clicking the selection opens one + level toward it. Double-clicks no longer skip through multiple levels. + Improve tile contrast, strike marked names and underline search matches + without adding prefixes to file names. +- Removal - Keep the scan snapshot by default instead of starting a full + rescan after every removal. Removed entries stay greyed out and cannot + be marked again until a rescan. Choose Move & rescan or Delete & rescan + when a fresh tree is wanted; MCP removal also accepts `rescan`. +- Freed space - Keep a ledger of removals since the scan, separating listed + bytes, private-byte estimates and the measured free-space change. MCP + status exposes the ledger, and listings and searches identify entries + removed since the scan. +- Removal checks - Allow entries inside macOS `/tmp` and `/var/tmp` while + keeping the temporary-directory roots and other system paths protected. + Fix Windows volume-capacity checks for individual files. Confirmation, + capacity limits and the other removal guards still apply. +- Keyboard and accessibility - Improve focus traversal, modal containment, + source and scan status, Review summaries, document reading and Logs + selection. Expose text and search values to native accessibility APIs. + Help, Settings and readers reflow through 200% interface zoom, and + directory navigation honors Reduce motion. +- Window placement - Remember the main window's position and size, + keep restored windows on screen, and open macOS windows on the active + display. Improve Settings organization, About build information and + platform-specific dialog button placement. +- Updates - Show checking and download progress, keep a downloaded update + ready across later checks, and offer Restart from a persistent title-strip + chip. Restart runs once in the background and saves the window position. +- SSH and volumes - Preserve POSIX paths for Unix SSH hosts on Windows, + omit Linux kernel pseudo-filesystems from source discovery, and handle + escaped mount sources consistently. Searches retain matching nested + empty directories. +- Compatibility - The window link now uses protocol version 6. Update + and restart both the PwrDisk window and MCP process together. + +## v0.14.0 + +- Removal safety - Settings > Safety adds a per-operation limit, defaulting + to 5% of each volume's capacity, for both manual and MCP removal. The + complete selection is re-measured before removal; oversized, unreadable + or unknown-capacity selections are refused. +- AI-assisted removal - Preview the marked paths, size and trash/permanent + mode before confirming removal through the MCP client's interactive + form. Confirmation is expiring and single-use; changed marks, mode or + safety settings require a new preview. Clients without form support + use human Review instead. Removal requires a linked local window, and + Trash never falls back to permanent deletion. +- Agent browsing - Listing never moves the window, including requests + from older clients that pass `show`. Navigation uses an explicit + `pwrdisk_show` request when the user asks to follow or open a path. +- Cleanup candidates - Recognize verified pnpm package stores without + classifying the executable, global tools or the whole installation as + disposable. Unknown aggregates retain their own category, and legacy + Google Drive folders are recognized as synced data. +- Scan context - Linked MCP status reports allocated/apparent size, + hidden-entry inclusion and unreadable counts. macOS reports explain + APFS sharing and distinguish listed bytes from potential savings; + cleanup searches explain removal eligibility without adding marks. +- Compatibility - The window link now uses protocol version 3. Update + and restart both the PwrDisk window and MCP process together. + +## v0.13.0 + +- Downloads - Add stable filenames for the universal macOS DMG and both + Linux tarballs so the README's download buttons keep working across + releases. Versioned downloads remain available. +- Documentation - Put downloads, installation and a quick tour first in + the README, with detailed usage and build instructions in separate + guides. +- Third-Party Notices - Include the socket2 attribution required by the + Windows agent-window link and refresh notices for this release. + +## v0.12.0 + +The first PwrDisk release, continuing from disktree 0.11.0 with local and +SSH exploration, AI-assisted review, and signed installers. + +- PwrDisk - The app, binary and bundle are PwrDisk (`pwrdisk`, + `com.pwrdrvr.pwrdisk`), a maintained fork of tobi/disktree. A Power + Efficiency preset saved by disktree is still read until PwrDisk saves one. +- macOS - A drag-to-install DMG with a universal app (Apple silicon and + Intel), signed with a Developer ID, notarized and stapled. +- Windows - `PwrDisk-win-Setup.exe`, a per-user MSI and a portable zip for + x64, and the same for ARM64 (`PwrDisk-win-arm64-*`), signed through Azure + Artifact Signing. Setup installs to your profile without administrator + rights and adds a Start menu shortcut. +- Sources and SSH - Choose a local volume or an SSH host and root before + scanning. Explore remote disks with live scan progress and treemap + previews, then export a cleanup plan; remote scans are read-only. +- AI agents - `pwrdisk mcp` lets an agent inspect disk usage and mark an + agreed cleanup list. Marks appear in the open window on macOS, Linux + and Windows, and the agent can open Review for you. Only a person can + confirm removal. Embedded skills explain each system's storage and + cleanup cautions. +- Scan progress - Whole-drive scans show estimated byte coverage and + average files per second, followed by an explicit finalizing state. + Progress scrolls in short windows while the free-space meter stays + visible. Folder and filtered scans keep counts when no compatible + total is available. +- APFS space estimates - Show clone sharing separately from treemap + sizes and estimate what the marked set can reclaim together. Retained + clones and hardlinks reduce projected savings; the volume meter uses + the conservative estimate and reports measured free space after removal. +- macOS service stores - Show measured Spotlight-index and FSEvents + usage when readable, label partial results, and keep those stores + protected from raw removal. Unreadable service stores do not produce + repeated Full Disk Access hints. +- Explore and Review - Custom window chrome and faster marking, path + lookup and review keep large cleanup queues responsive. +- Updates - Copies installed from the DMG, Setup.exe or the MSI check + GitHub Releases at startup and every six hours, and download a newer + release in the background. Shift-U (or PwrDisk › Check for Updates… on + macOS) opens Settings › Updates; Restart to update installs a download + at once, and otherwise it installs when PwrDisk quits. Pick Stable or + Beta, Latest or Prerelease there; a copy follows the channel its version + implies until you do. +- Settings and Help - Shared menus, separate Updates, Diagnostics and + About panes, and offline Changelog, License and Third-Party Notices + windows make support information easier to find. Copy Diagnostics Info + omits scanned paths, SSH hosts and volume names. +- Logs - A live viewer adds wrapped lines, search with Filter and + Highlight modes, context rows, line selection, and marks for copying + just one action's output. Following pauses while you read, and display + preferences persist. Logs record counts and durations, never scanned + paths. +- Linux - The tarball and `install.sh` are unchanged. Linux copies do not + update themselves; download the next release. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 120000 index 00000000..47dc3e3d --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index dde47dd2..99c7abea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -274,18 +274,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "async-compression" -version = "0.4.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef217a77a86a6e3dab9a5b3c81dc445b603fe743a90c1cb10a2f2144628d8cfa" -dependencies = [ - "compression-codecs", - "compression-core", - "futures-io", - "pin-project-lite", -] - [[package]] name = "async-executor" version = "1.14.0" @@ -483,7 +471,7 @@ dependencies = [ "log", "num-rational", "num-traits", - "pastey", + "pastey 0.1.1", "rayon", "thiserror 2.0.20", "v_frame", @@ -499,7 +487,7 @@ dependencies = [ "anyhow", "arrayvec", "log", - "nom 8.0.0", + "nom", "num-rational", "v_frame", ] @@ -541,48 +529,37 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] -name = "bindgen" -version = "0.72.1" +name = "base64" +version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" -dependencies = [ - "bitflags 2.13.2", - "cexpr", - "clang-sys", - "itertools 0.13.0", - "log", - "prettyplease", - "proc-macro2", - "quote", - "regex", - "rustc-hash 2.1.3", - "shlex 1.3.0", - "syn 2.0.119", -] +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" [[package]] name = "bit-set" -version = "0.8.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +checksum = "34ddef2995421ab6a5c779542c81ee77c115206f4ad9d5a8e05f4ff49716a3dd" dependencies = [ - "bit-vec 0.8.0", + "bit-vec 0.9.1", ] [[package]] name = "bit-set" -version = "0.9.1" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34ddef2995421ab6a5c779542c81ee77c115206f4ad9d5a8e05f4ff49716a3dd" +checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" dependencies = [ "bit-vec 0.9.1", ] [[package]] -name = "bit-vec" -version = "0.8.0" +name = "bit-set" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec 0.10.1", +] [[package]] name = "bit-vec" @@ -590,6 +567,16 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +[[package]] +name = "bit-vec" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269" +dependencies = [ + "borsh", + "serde", +] + [[package]] name = "bit_field" version = "0.10.3" @@ -687,10 +674,24 @@ version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" dependencies = [ + "borsh-derive", "bytes", "cfg_aliases", ] +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.5", +] + [[package]] name = "bstr" version = "1.13.1" @@ -698,6 +699,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" dependencies = [ "memchr", + "regex-automata", "serde_core", ] @@ -751,15 +753,6 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" -[[package]] -name = "bzip2" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c" -dependencies = [ - "libbz2-rs-sys", -] - [[package]] name = "calloop" version = "0.14.4" @@ -821,16 +814,7 @@ dependencies = [ "find-msvc-tools", "jobserver", "libc", - "shlex 2.0.1", -] - -[[package]] -name = "cexpr" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" -dependencies = [ - "nom 7.1.3", + "shlex", ] [[package]] @@ -845,15 +829,6 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" -[[package]] -name = "cgl" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff" -dependencies = [ - "libc", -] - [[package]] name = "chacha20" version = "0.10.2" @@ -890,17 +865,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "clang-sys" -version = "1.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" -dependencies = [ - "glob", - "libc", - "libloading", -] - [[package]] name = "cocoa" version = "0.25.0" @@ -978,23 +942,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" [[package]] -name = "compression-codecs" -version = "0.4.42" +name = "combine" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "257c7085cbb71be72d8fb97edff08b03d86d5d9f2222b9cc34a6bec87093bc10" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" dependencies = [ - "bzip2", - "compression-core", - "flate2", + "bytes", "memchr", ] -[[package]] -name = "compression-core" -version = "0.4.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e8ccc4ea9f6acc32d102c0f6d471d11d913ad15f20c04de743374861fa1d414" - [[package]] name = "concurrent-queue" version = "2.5.0" @@ -1145,19 +1101,6 @@ dependencies = [ "libc", ] -[[package]] -name = "core-graphics2" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4416167a69126e617f8d0a214af0e3c1dbdeffcb100ddf72dcd1a1ac9893c146" -dependencies = [ - "bitflags 2.13.2", - "block", - "cfg-if", - "core-foundation 0.10.1", - "libc", -] - [[package]] name = "core-text" version = "21.0.0" @@ -1170,20 +1113,6 @@ dependencies = [ "libc", ] -[[package]] -name = "core-video" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "139679cc63eb9504bdbe37e37874b0247136177655f0008588781e90863afa62" -dependencies = [ - "block", - "core-foundation 0.10.1", - "core-graphics2", - "io-surface", - "libc", - "metal", -] - [[package]] name = "core_detect" version = "1.0.0" @@ -1319,6 +1248,40 @@ dependencies = [ "linktime-proc-macro", ] +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.5", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.5", +] + [[package]] name = "data-url" version = "0.3.2" @@ -1331,6 +1294,17 @@ version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +[[package]] +name = "derivative" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "derive_more" version = "2.1.1" @@ -1351,7 +1325,6 @@ dependencies = [ "quote", "rustc_version", "syn 2.0.119", - "unicode-xid", ] [[package]] @@ -1420,23 +1393,40 @@ dependencies = [ [[package]] name = "disktree-app" -version = "0.11.0" +version = "0.17.0" dependencies = [ "anyhow", + "async-channel", + "chrono", "disktree-core", + "disktree-link", + "disktree-mcp", "dunce", "gpui-kit", "gpui-omarchy", + "log", + "objc2 0.6.4", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", "rustc-hash 2.1.3", + "rustix", + "rustls", + "semver", + "serde", + "serde_json", "tempfile", + "ureq", + "velopack", "windows-sys 0.61.2", ] [[package]] name = "disktree-core" -version = "0.11.0" +version = "0.17.0" dependencies = [ "chrono", + "libc", + "proptest", "rayon", "rustc-hash 2.1.3", "rustix", @@ -1450,9 +1440,37 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "disktree-link" +version = "0.17.0" +dependencies = [ + "disktree-core", + "serde", + "serde_json", + "tempfile", + "tokio", + "windows-sys 0.61.2", +] + +[[package]] +name = "disktree-mcp" +version = "0.17.0" +dependencies = [ + "anyhow", + "disktree-core", + "disktree-link", + "rmcp", + "schemars", + "serde", + "serde_json", + "sha2 0.10.9", + "tempfile", + "tokio", +] + [[package]] name = "disktree-scan" -version = "0.11.0" +version = "0.17.0" dependencies = [ "disktree-core", "rustix", @@ -1474,7 +1492,6 @@ checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" dependencies = [ "bitflags 2.13.2", "block2 0.6.2", - "libc", "objc2 0.6.4", ] @@ -1656,17 +1673,6 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" -[[package]] -name = "erased-serde" -version = "0.4.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec" -dependencies = [ - "serde", - "serde_core", - "typeid", -] - [[package]] name = "errno" version = "0.3.14" @@ -1738,9 +1744,6 @@ name = "fastrand" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" -dependencies = [ - "getrandom 0.4.3", -] [[package]] name = "fax" @@ -1834,7 +1837,6 @@ version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be" dependencies = [ - "fastrand", "futures-core", "futures-sink", "spin 0.9.9", @@ -2264,9 +2266,9 @@ dependencies = [ [[package]] name = "gpui-base" -version = "0.6.6" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9e904ee0d351f4e85b967e26ae986d3aa195a8d9d35fcd18184a2c40989694e" +checksum = "2e9955b6f4b048fd50ca15fc8e225d80bb00ba9ebc8fecdddde5ad26dbef9270" dependencies = [ "aho-corasick", "anyhow", @@ -2275,14 +2277,17 @@ dependencies = [ "chrono", "data-url", "futures", + "gpui-fast", "gpui-pre", "gpui-pre-macros", "gpui-pre-sum-tree", "html5ever", "instant", + "itertools 0.13.0", "lsp-types", "markdown", "markup5ever_rcdom", + "num-traits", "objc2 0.6.4", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", @@ -2295,6 +2300,7 @@ dependencies = [ "smallvec", "smol", "tracing", + "unicode-linebreak", "unicode-segmentation", "web-time", "windows 0.58.0", @@ -2302,9 +2308,9 @@ dependencies = [ [[package]] name = "gpui-component" -version = "0.6.6" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0cf6c72516b44bb2e66a1bd2ccf77a122ecd1b54a75559ac299bb296bfcb5bb7" +checksum = "465a363235cd4062ef5f0953fc096fc764ed6f53dfbd9f409f669f93ea3b1ff9" dependencies = [ "anyhow", "chrono", @@ -2312,6 +2318,7 @@ dependencies = [ "enum-iterator", "gpui-base", "gpui-component-macros", + "gpui-fast", "gpui-kit-assets", "gpui-pre", "gpui-pre-macros", @@ -2321,7 +2328,7 @@ dependencies = [ "log", "lsp-types", "markdown", - "notify", + "notify 8.2.1", "num-traits", "objc2 0.6.4", "objc2-app-kit 0.3.2", @@ -2337,18 +2344,21 @@ dependencies = [ "serde", "serde_json", "serde_repr", + "similar", "smallvec", "smol", "tracing", + "unicode-segmentation", + "unicode-width", "uuid", "windows 0.58.0", ] [[package]] name = "gpui-component-macros" -version = "0.6.6" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3867545508c7cf6a5f6da586f60d894a3f8e7cce94b7fe82df7fad5f868ec20e" +checksum = "5c0c9398aaf99e595d450e38eb44ff0c500df8c332b4783d5b72022e69525359" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2357,62 +2367,18 @@ dependencies = [ ] [[package]] -name = "gpui-kit" -version = "0.6.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42732dc20f50926278b2abf7a99d427a7741ab28bca6bfb49685f9ce3a53a1c7" -dependencies = [ - "gpui-base", - "gpui-component", - "gpui-kit-assets", - "gpui-pre", - "gpui-pre-platform", - "gpui-pre-web", -] - -[[package]] -name = "gpui-kit-assets" -version = "0.6.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "111d3d03a68454318a193f137419864ccebdc7d3dc0194b0b0b3f818a6bc3d55" -dependencies = [ - "anyhow", - "gpui-pre", - "gpui-pre-reqwest", - "log", - "rust-embed", - "wasm-bindgen", - "wasm-bindgen-futures", -] - -[[package]] -name = "gpui-omarchy" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e0cebe18129f1d98eede90b13f4766f7cec5486458833523696629b6acbf9f2" -dependencies = [ - "async-channel", - "chrono", - "gpui-kit", - "notify", - "toml 0.8.23", -] - -[[package]] -name = "gpui-pre" -version = "0.3.6" +name = "gpui-fast" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0437c0b83e636a92bd1a39fa1d05fb632ae671289537497b35871ffbe231b84" +checksum = "895ff4c92ead42ca7e7f70213373f122f1482194b56d481eed5c768c85cc793b" dependencies = [ "accesskit", "anyhow", "async-channel", "async-task", "backtrace", - "bindgen", "bitflags 2.13.2", "chrono", - "core-video", "ctor", "derive_more", "embed-resource", @@ -2420,19 +2386,19 @@ dependencies = [ "futures", "futures-concurrency", "getrandom 0.3.4", + "gpui-fast-macros", "gpui-pre-collections", "gpui-pre-http-client", - "gpui-pre-macros", "gpui-pre-refineable", "gpui-pre-scheduler", "gpui-pre-shared-string", "gpui-pre-sum-tree", "gpui-pre-util", - "gpui-pre-util-macros", "heapless", "image", "inventory", "itertools 0.14.0", + "libc", "log", "lyon", "num_cpus", @@ -2457,7 +2423,7 @@ dependencies = [ "smallvec", "spin 0.10.1", "strum", - "taffy", + "taffy 0.15.0", "thiserror 2.0.20", "ttf-parser", "url", @@ -2466,39 +2432,415 @@ dependencies = [ "waker-fn", "web-time", "windows 0.62.2", - "zed-font-kit", "zed-scap", ] [[package]] -name = "gpui-pre-apple" -version = "0.3.6" +name = "gpui-fast-apple" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3af534f0746eb9e014114bcc0ee00dc250c4b8d75df2e437180c403aa65649c1" +checksum = "bd9051d4ff1f981c8d11d536551dca5189446221dcfdeb0110c62af3a93da676" dependencies = [ "anyhow", - "block", + "async-task", + "block2 0.6.2", "cbindgen", - "cocoa 0.26.1", "core-foundation 0.10.1", - "core-video", + "core-foundation-sys", + "core-graphics 0.24.0", + "core-text", "derive_more", + "dispatch2", "etagere", "foreign-types", - "gpui-pre", + "futures", + "gpui-fast", + "gpui-pre-collections", + "gpui-pre-util", "image", + "libc", "log", + "mach2", "metal", - "objc", "objc2 0.6.4", + "objc2-core-foundation", + "objc2-core-text", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "objc2-security", + "parking_lot", + "pathfinder_geometry", + "smallvec", + "thiserror 2.0.20", + "zed-font-kit", +] + +[[package]] +name = "gpui-fast-linux" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f20d5697fb19b0e447750ed61b96c030ba2224b01e51240166543e88fdb5536c" +dependencies = [ + "accesskit", + "accesskit_unix", + "anyhow", + "as-raw-xcb-connection", + "ashpd", + "bytemuck", + "calloop", + "calloop-wayland-source", + "filedescriptor", + "futures", + "gpui-fast", + "gpui-fast-wgpu", + "gpui-pre-collections", + "gpui-pre-http-client", + "gpui-pre-util", + "libc", + "log", + "notify-rust", + "oo7", + "open", + "parking_lot", + "raw-window-handle", + "smallvec", + "smol", + "strum", + "url", + "uuid", + "wayland-backend", + "wayland-client", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-plasma", + "wayland-protocols-wlr", + "x11rb", + "xkbcommon", + "zed-scap", + "zed-xim", +] + +[[package]] +name = "gpui-fast-macos" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1ba7c34a1549412fb33fff3c35330bd8462f16f4a8f77e1f9804a15eae8a098" +dependencies = [ + "accesskit", + "accesskit_macos", + "anyhow", + "block2 0.6.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "core-graphics 0.24.0", + "ctor", + "dispatch2", + "foreign-types", + "futures", + "gpui-fast", + "gpui-fast-apple", + "gpui-pre-collections", + "gpui-pre-scheduler", + "gpui-pre-util", + "image", + "itertools 0.14.0", + "log", + "objc2 0.6.4", + "objc2-app-kit 0.3.2", + "objc2-core-graphics", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-user-notifications", + "parking_lot", + "raw-window-handle", + "semver", + "smallvec", + "strum", + "uuid", +] + +[[package]] +name = "gpui-fast-macros" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e07e9e22196a84bb8cb06c19fc6e5d2218fa11d6b573f914f423970a1b38c97e" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "gpui-fast-platform" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2868731e97d39c951031bb98994f0813b27d7f2a9344cb4b3e62f343e1db3e1a" +dependencies = [ + "anyhow", + "console_error_panic_hook", + "gpui-fast", + "gpui-fast-linux", + "gpui-fast-macos", + "gpui-fast-web", + "gpui-fast-wgpu", + "gpui-fast-windows", + "gpui-pre-ios", +] + +[[package]] +name = "gpui-fast-web" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fe935ac901a3c9f679b2e15f6e7ef1414a35870603694b47709b660ae0e56a5" +dependencies = [ + "anyhow", + "async-channel", + "console_error_panic_hook", + "futures", + "gpui-fast", + "gpui-fast-wgpu", + "gpui-pre-http-client", + "gpui-pre-scheduler", + "js-sys", + "log", "parking_lot", + "raw-window-handle", + "smallvec", + "unicode-properties", + "unicode-script", + "unicode-segmentation", + "uuid", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm_thread", + "web-sys", + "web-time", +] + +[[package]] +name = "gpui-fast-wgpu" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1557220ba04513682d8f08f3c0289ee098d42fc68b4349ddb5786af93e9a24d5" +dependencies = [ + "anyhow", + "bytemuck", + "cosmic-text", + "etagere", + "gpui-fast", + "gpui-pre-collections", + "gpui-pre-util", + "image", + "itertools 0.14.0", + "log", + "parking_lot", + "profiling", + "raw-window-handle", + "smallvec", + "swash", + "unicode-bidi", + "unicode-segmentation", + "web-sys", + "wgpu 30.0.1", + "zed-font-kit", +] + +[[package]] +name = "gpui-fast-windows" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca29f9d7985f6e5021eba769c853ab5776e45ddf041d9905db2a25e2c6d6cfff" +dependencies = [ + "accesskit", + "accesskit_windows", + "anyhow", + "dunce", + "etagere", + "futures", + "gpui-fast", + "gpui-pre-collections", + "gpui-pre-scheduler", + "gpui-pre-util", + "image", + "itertools 0.14.0", + "log", + "parking_lot", + "rand 0.9.5", + "raw-window-handle", + "smallvec", + "uuid", + "windows 0.62.2", + "windows-core 0.62.2", + "windows-numerics 0.3.1", + "windows-registry 0.6.1", +] + +[[package]] +name = "gpui-kit" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fac401f6b149bf33794da0942510240afd29b7b18556574e4cf17196b647066" +dependencies = [ + "gpui-base", + "gpui-component", + "gpui-fast", + "gpui-fast-platform", + "gpui-kit-assets", + "gpui-pre", + "gpui-pre-macros", + "gpui-pre-platform", + "gpui-pre-web", +] + +[[package]] +name = "gpui-kit-assets" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7abc281dcbfe51c16a7e73189521a3a771168c31e3ab0db99e21e481d1b1b9a" +dependencies = [ + "anyhow", + "gpui-pre", + "gpui-pre-reqwest", + "log", + "rust-embed", + "wasm-bindgen", + "wasm-bindgen-futures", +] + +[[package]] +name = "gpui-omarchy" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41462d5f3aa1056cdce799d6b4dfb1c04b47a3649d1a4eb5e2e29d8ca3434eed" +dependencies = [ + "async-channel", + "chrono", + "gpui-kit", + "itertools 0.13.0", + "notify 7.0.0", + "num-traits", + "toml 0.8.23", +] + +[[package]] +name = "gpui-pre" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34f61c1cfd36fc9c436af09308c963822ae27a45a84feb21a77ba5c9e051f1c0" +dependencies = [ + "accesskit", + "anyhow", + "async-channel", + "async-task", + "backtrace", + "bitflags 2.13.2", + "chrono", + "ctor", + "derive_more", + "embed-resource", + "etagere", + "futures", + "futures-concurrency", + "getrandom 0.3.4", + "gpui-pre-collections", + "gpui-pre-http-client", + "gpui-pre-macros", + "gpui-pre-refineable", + "gpui-pre-scheduler", + "gpui-pre-shared-string", + "gpui-pre-sum-tree", + "gpui-pre-util", + "heapless", + "image", + "inventory", + "itertools 0.14.0", + "libc", + "log", + "lyon", + "num_cpus", + "objc2-core-foundation", + "objc2-core-video", + "parking", + "parking_lot", + "pin-project", + "pollster 0.4.0", + "postage", + "profiling", + "proptest", + "rand 0.9.5", + "raw-window-handle", + "regex", + "resvg 0.46.0", + "schemars", + "seahash", + "serde", + "serde_json", + "slotmap", + "smallvec", + "spin 0.10.1", + "strum", + "taffy 0.13.0", + "thiserror 2.0.20", + "ttf-parser", + "url", + "usvg 0.46.0", + "uuid", + "waker-fn", + "web-time", + "windows 0.62.2", + "zed-scap", +] + +[[package]] +name = "gpui-pre-apple" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52f58893fe1a0836464428dfad2b5eaf42c9c303a9638f4c2aced5a69072a15" +dependencies = [ + "anyhow", + "async-task", + "block2 0.6.2", + "cbindgen", + "core-foundation 0.10.1", + "core-foundation-sys", + "core-graphics 0.24.0", + "core-text", + "derive_more", + "dispatch2", + "etagere", + "foreign-types", + "futures", + "gpui-pre", + "gpui-pre-collections", + "gpui-pre-util", + "image", + "libc", + "log", + "mach2", + "metal", + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-core-text", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "objc2-security", + "parking_lot", + "pathfinder_geometry", + "smallvec", + "thiserror 2.0.20", + "zed-font-kit", ] [[package]] name = "gpui-pre-collections" -version = "0.3.6" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15e7a65204039187d1f4b3d4c2e0233eeac54d4acb0b13f9dc1a3b5adad26c1f" +checksum = "920c2f5b2f1a7813114d89f4841f26f6060d9c35d7c8a852a4205d1a767a7ce0" dependencies = [ "gpui-pre-util", "indexmap", @@ -2507,9 +2849,9 @@ dependencies = [ [[package]] name = "gpui-pre-derive-refineable" -version = "0.3.6" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79dfb4a05f3cd9893d7768dbf5dba1bbbe99cab7394e89b360ccb3b2bcb6b34e" +checksum = "947395f26228296c0c79fb889d3687b205e552c25bbcdece216fb2394ea9bcd1" dependencies = [ "proc-macro2", "quote", @@ -2518,14 +2860,12 @@ dependencies = [ [[package]] name = "gpui-pre-http-client" -version = "0.3.6" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfd5a7542c77887a5aff997d78c95884119c8463409569b63fcf060956da1682" +checksum = "c56cdaa3f1a271162b7fede1d4557879eedb056e293cedbb82743600650b755e" dependencies = [ "anyhow", - "async-compression", "bytes", - "derive_more", "futures", "http", "http-body", @@ -2537,18 +2877,39 @@ dependencies = [ "url", ] +[[package]] +name = "gpui-pre-ios" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13e735b73ae85ed188764287df4d24837045d71a122c51c2264aed8c38ffd51b" +dependencies = [ + "anyhow", + "block2 0.6.2", + "futures", + "gpui-pre", + "gpui-pre-apple", + "log", + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", + "objc2-ui-kit", + "parking_lot", + "raw-window-handle", + "uuid", +] + [[package]] name = "gpui-pre-linux" -version = "0.3.6" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aab655cda1d6dcd549ac869e8678babc84cf573ab6794a1fe1a39c6c70c60b48" +checksum = "e28213c3fde6f13e91ba0b74b90cbaadec9373e36a031eda98561d31059870f3" dependencies = [ "accesskit", "accesskit_unix", "anyhow", "as-raw-xcb-connection", "ashpd", - "bitflags 2.13.2", "bytemuck", "calloop", "calloop-wayland-source", @@ -2577,7 +2938,6 @@ dependencies = [ "wayland-protocols", "wayland-protocols-plasma", "wayland-protocols-wlr", - "x11-clipboard", "x11rb", "xkbcommon", "zed-scap", @@ -2586,20 +2946,18 @@ dependencies = [ [[package]] name = "gpui-pre-macos" -version = "0.3.6" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "951d17e41a72067ad2d35c60e08a62e8ad7fa9400b41c802e26cfb459f6c05da" +checksum = "c7c988b7e49775cc8542dbe48d5a10e073d8e898a023ef3ff3d24f33363e9863" dependencies = [ "accesskit", "accesskit_macos", "anyhow", - "async-task", "block2 0.6.2", "cocoa 0.26.1", "core-foundation 0.10.1", "core-foundation-sys", "core-graphics 0.24.0", - "core-text", "ctor", "dispatch2", "foreign-types", @@ -2607,35 +2965,30 @@ dependencies = [ "gpui-pre", "gpui-pre-apple", "gpui-pre-collections", + "gpui-pre-scheduler", "gpui-pre-util", "image", "itertools 0.14.0", - "libc", "log", - "mach2", "objc", "objc2 0.6.4", "objc2-app-kit 0.3.2", - "objc2-core-graphics", - "objc2-core-media", + "objc2-core-video", "objc2-foundation 0.3.2", - "objc2-screen-capture-kit", "objc2-user-notifications", "parking_lot", - "pathfinder_geometry", "raw-window-handle", "semver", "smallvec", "strum", "uuid", - "zed-font-kit", ] [[package]] name = "gpui-pre-macros" -version = "0.3.6" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6324092b40ea8ec7c327a4a28427e366a489b4d5d23b5d1bd0243fc2f4ca7a9e" +checksum = "0bb80dac5e1f6b8cde1d2740389e77dfc0071bfcc81fba5526d5dc90f68171cc" dependencies = [ "heck 0.5.0", "proc-macro-crate", @@ -2644,36 +2997,27 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "gpui-pre-perf" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b94bff26ccd8105f6206144f8dab16a2dc02e7a68f39dada02cdf492f0afd940" -dependencies = [ - "gpui-pre-collections", - "serde", - "serde_json", -] - [[package]] name = "gpui-pre-platform" -version = "0.3.6" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8423d1e0a693d2f9f16c0326bb01b5e81ec0531854d596a18476934ac6880478" +checksum = "bbdbdac421178313fed8929fe95b42634a266a735079fcf03ff231bc2ccb2c5e" dependencies = [ + "anyhow", "console_error_panic_hook", "gpui-pre", "gpui-pre-linux", "gpui-pre-macos", "gpui-pre-web", + "gpui-pre-wgpu", "gpui-pre-windows", ] [[package]] name = "gpui-pre-refineable" -version = "0.3.6" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93b4b0a8d296a3ee5beb1136bc48f8167a6028eb1e243b56851dcd8c9fc6d7a1" +checksum = "237703b3b219d11adb50dd33bb0fcca3d34fc001623b3143e72cb051d0fb3777" dependencies = [ "gpui-pre-derive-refineable", ] @@ -2684,7 +3028,7 @@ version = "0.12.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05be23908e707966824f8c51a609904b7f30739e8d915e120a53c1b995ba964c" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "encoding_rs", "futures-core", @@ -2730,9 +3074,9 @@ dependencies = [ [[package]] name = "gpui-pre-scheduler" -version = "0.3.6" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff7b10b3d2fc3fda24847a04436eca9531612c8414874a37ddc005f20e521e12" +checksum = "83f342555282a59ed8dd58dd7e0a920524fa8ef6aa8c8f30e2edb7019a8f72cb" dependencies = [ "async-task", "backtrace", @@ -2747,9 +3091,9 @@ dependencies = [ [[package]] name = "gpui-pre-shared-string" -version = "0.3.6" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe17f81bd98a0253140ea79f7f76442d7499bd8d17db302861af8e46c11d38df" +checksum = "71f488bf4780735f6b2dad24f8db1e3d9e2593de0ec298e3574c788f571b81c4" dependencies = [ "schemars", "serde", @@ -2758,46 +3102,35 @@ dependencies = [ [[package]] name = "gpui-pre-sum-tree" -version = "0.3.6" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a6d35e998a51d24248dad731de1f09d386cbbf46a04edde3b67f469b2ce3f16" +checksum = "aadb3bd3da22617e2158b1842f5a9c29c1626c926ad0686163ced1a009963ff3" dependencies = [ "gpui-pre-ztracing", "heapless", - "log", "rayon", "tracing", ] [[package]] name = "gpui-pre-util" -version = "0.3.6" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a026a30c578930d20974fd8c3d77de36223ac7ba193bd4259e7238929bc8806" +checksum = "a04ec9abd7a87ac05a221f4629403831c44c17123bc33cb5d271a6303259b340" dependencies = [ "anyhow", "log", "which", ] -[[package]] -name = "gpui-pre-util-macros" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cbf79627a6afc626d4e887dad9d2d92bb069413e8cc692ba3e90bff219eb7a9" -dependencies = [ - "gpui-pre-perf", - "quote", - "syn 2.0.119", -] - [[package]] name = "gpui-pre-web" -version = "0.3.6" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34be433b9fcb370b1fe9a1c7fe911f0eb6058791ef8167dcf6c5a5deb624975c" +checksum = "aedd55b99dc77e28df8202b0ea868aa5c90fda4aefff539ea21087d7c2ff4bfb" dependencies = [ "anyhow", + "async-channel", "console_error_panic_hook", "futures", "gpui-pre", @@ -2822,9 +3155,9 @@ dependencies = [ [[package]] name = "gpui-pre-wgpu" -version = "0.3.6" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05515b32799b1767d69300921c1b562cd53104965211a0e8905acdc7aa18e693" +checksum = "5b1cdb26c1503bf9662ee8fbc5ab0b44b2deeee4b5c12dc67491ba6fb5fc544b" dependencies = [ "anyhow", "bytemuck", @@ -2833,6 +3166,7 @@ dependencies = [ "gpui-pre", "gpui-pre-collections", "gpui-pre-util", + "image", "itertools 0.14.0", "log", "parking_lot", @@ -2843,15 +3177,15 @@ dependencies = [ "unicode-bidi", "unicode-segmentation", "web-sys", - "wgpu", + "wgpu 29.0.4", "zed-font-kit", ] [[package]] name = "gpui-pre-windows" -version = "0.3.6" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27662e65bfcf4445d2cccfad91f1570ec07f4b1b5de98400a9f207fd19c464cf" +checksum = "513d4f0fc7d596d3bdef2a73a524ffb83dabc95bf484f2855a698e7f431290a9" dependencies = [ "accesskit", "accesskit_windows", @@ -2861,6 +3195,7 @@ dependencies = [ "futures", "gpui-pre", "gpui-pre-collections", + "gpui-pre-scheduler", "gpui-pre-util", "image", "itertools 0.14.0", @@ -2876,35 +3211,21 @@ dependencies = [ "windows-registry 0.6.1", ] -[[package]] -name = "gpui-pre-zlog" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3a5af0b734a391a84872eb770b3ee9830091ec2487b79d06371fe14eefb2b5d" -dependencies = [ - "anyhow", - "chrono", - "gpui-pre-collections", - "log", -] - [[package]] name = "gpui-pre-ztracing" -version = "0.3.6" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a24cb19f78c5bc3aab8ddf1e8e0bd6b402fbcb9c7f112f64ddbedef8f8768a59" +checksum = "f17bfd6bd1f77ba5c58181fa6f82fc7a63015a1c58bef94a76e5acb9f8e42572" dependencies = [ - "gpui-pre-zlog", "gpui-pre-ztracing-macro", "tracing", - "tracing-subscriber", ] [[package]] name = "gpui-pre-ztracing-macro" -version = "0.3.6" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1bb25850ad31b88bbdef454afb93ec4cdb81f5e200ba5b3f1a0368111780d2c" +checksum = "4b0d73e1bc02eef886a5947f41b8512708792e9e5d3053d181843311a487f96f" [[package]] name = "h2" @@ -2990,6 +3311,9 @@ name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash 0.2.0", +] [[package]] name = "heapless" @@ -3275,6 +3599,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "idna" version = "1.1.0" @@ -3386,6 +3716,17 @@ dependencies = [ "libc", ] +[[package]] +name = "inotify" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592" +dependencies = [ + "bitflags 2.13.2", + "inotify-sys", + "libc", +] + [[package]] name = "inotify-sys" version = "0.1.8" @@ -3437,18 +3778,6 @@ dependencies = [ "rustversion", ] -[[package]] -name = "io-surface" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "554b8c5d64ec09a3a520fe58e4d48a73e00ff32899cdcbe32a4877afd4968b8e" -dependencies = [ - "cgl", - "core-foundation 0.10.1", - "core-foundation-sys", - "leaky-cow", -] - [[package]] name = "ipnet" version = "2.12.2" @@ -3507,6 +3836,36 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.20", + "walkdir", + "windows-link 0.2.1", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + [[package]] name = "jni-sys" version = "0.3.1" @@ -3622,33 +3981,12 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" -[[package]] -name = "leak" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd100e01f1154f2908dfa7d02219aeab25d0b9c7fa955164192e3245255a0c73" - -[[package]] -name = "leaky-cow" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40a8225d44241fd324a8af2806ba635fc7c8a7e9a7de4d5cf3ef54e71f5926fc" -dependencies = [ - "leak", -] - [[package]] name = "lebe" version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" -[[package]] -name = "libbz2-rs-sys" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c" - [[package]] name = "libc" version = "0.2.189" @@ -3742,7 +4080,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" dependencies = [ "serde_core", - "value-bag", ] [[package]] @@ -3847,12 +4184,9 @@ dependencies = [ [[package]] name = "mach2" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a1b95cd5421ec55b445b5ae102f5ea0e768de1f82bd3001e11f426c269c3aea" -dependencies = [ - "libc", -] +checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b" [[package]] name = "malloc_buf" @@ -3974,12 +4308,6 @@ dependencies = [ "unicase", ] -[[package]] -name = "minimal-lexical" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" - [[package]] name = "miniz_oxide" version = "0.8.9" @@ -4075,6 +4403,44 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "naga" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130" +dependencies = [ + "arrayvec", + "bit-set 0.10.0", + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.17.1", + "indexmap", + "libm", + "log", + "naga-types", + "num-traits", + "once_cell", + "rustc-hash 1.1.0", + "spirv", + "thiserror 2.0.20", + "unicode-ident", +] + +[[package]] +name = "naga-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49" +dependencies = [ + "hashbrown 0.17.1", + "indexmap", + "rustc-hash 1.1.0", + "thiserror 2.0.20", +] + [[package]] name = "ndk-sys" version = "0.6.0+11769913" @@ -4099,16 +4465,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "nom" -version = "7.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" -dependencies = [ - "memchr", - "minimal-lexical", -] - [[package]] name = "nom" version = "8.0.0" @@ -4142,16 +4498,35 @@ dependencies = [ "bitflags 2.13.2", "filetime", "fsevent-sys", - "inotify", + "inotify 0.10.2", "kqueue", "libc", "log", "mio", - "notify-types", + "notify-types 1.0.1", "walkdir", "windows-sys 0.52.0", ] +[[package]] +name = "notify" +version = "8.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f812702fbc75d35416d3f884e04925be7e9498f4eceea2e24ba34559284674" +dependencies = [ + "bitflags 2.13.2", + "inotify 0.11.5", + "kqueue", + "libc", + "log", + "mio", + "notify-types 2.2.0", + "objc2-core-foundation", + "objc2-core-services", + "walkdir", + "windows-sys 0.61.2", +] + [[package]] name = "notify-rust" version = "4.18.0" @@ -4176,21 +4551,21 @@ dependencies = [ ] [[package]] -name = "ntapi" -version = "0.4.3" +name = "notify-types" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +checksum = "0a437a9308232ce794b1e7fdf540d38ea37efc3c73492640c13b4c8568b8f108" dependencies = [ - "winapi", + "bitflags 2.13.2", ] [[package]] -name = "nu-ansi-term" -version = "0.50.3" +name = "ntapi" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" dependencies = [ - "windows-sys 0.61.2", + "winapi", ] [[package]] @@ -4386,45 +4761,23 @@ dependencies = [ "objc2-cloud-kit", "objc2-core-data 0.3.2", "objc2-core-foundation", - "objc2-core-graphics", - "objc2-core-image 0.3.2", - "objc2-core-text", - "objc2-core-video", - "objc2-foundation 0.3.2", - "objc2-quartz-core 0.3.2", -] - -[[package]] -name = "objc2-cloud-kit" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" -dependencies = [ - "bitflags 2.13.2", - "objc2 0.6.4", - "objc2-foundation 0.3.2", -] - -[[package]] -name = "objc2-core-audio" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2" -dependencies = [ - "dispatch2", - "objc2 0.6.4", - "objc2-core-audio-types", - "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image 0.3.2", + "objc2-core-text", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", ] [[package]] -name = "objc2-core-audio-types" +name = "objc2-cloud-kit" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" dependencies = [ "bitflags 2.13.2", "objc2 0.6.4", + "objc2-foundation 0.3.2", ] [[package]] @@ -4457,7 +4810,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", "dispatch2", + "libc", "objc2 0.6.4", ] @@ -4497,28 +4852,13 @@ dependencies = [ ] [[package]] -name = "objc2-core-location" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009" -dependencies = [ - "objc2 0.6.4", - "objc2-foundation 0.3.2", -] - -[[package]] -name = "objc2-core-media" +name = "objc2-core-services" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05ec576860167a15dd9fce7fbee7512beb4e31f532159d3482d1f9c6caedf31d" +checksum = "583300ad934cba24ff5292aee751ecc070f7ca6b39a574cc21b7b5e588e06a0b" dependencies = [ - "bitflags 2.13.2", - "dispatch2", - "objc2 0.6.4", - "objc2-core-audio", - "objc2-core-audio-types", + "libc", "objc2-core-foundation", - "objc2-core-video", ] [[package]] @@ -4544,6 +4884,7 @@ dependencies = [ "objc2-core-foundation", "objc2-core-graphics", "objc2-io-surface", + "objc2-metal 0.3.2", ] [[package]] @@ -4634,22 +4975,32 @@ dependencies = [ "bitflags 2.13.2", "objc2 0.6.4", "objc2-core-foundation", + "objc2-core-graphics", "objc2-foundation 0.3.2", "objc2-metal 0.3.2", ] [[package]] -name = "objc2-screen-capture-kit" +name = "objc2-security" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe137109bd1e8b5a99390f77a7d8b2961dafc1a1c5db8f2e60329ad6d895a" +dependencies = [ + "objc2-core-foundation", +] + +[[package]] +name = "objc2-ui-kit" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74b7c5390f477482f001bc354d6571a70db7e4f8d5288e860c45521fbce11394" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" dependencies = [ + "bitflags 2.13.2", "block2 0.6.2", - "dispatch2", "objc2 0.6.4", - "objc2-core-graphics", - "objc2-core-media", + "objc2-core-foundation", "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", ] [[package]] @@ -4661,7 +5012,6 @@ dependencies = [ "bitflags 2.13.2", "block2 0.6.2", "objc2 0.6.4", - "objc2-core-location", "objc2-foundation 0.3.2", ] @@ -4815,6 +5165,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + [[package]] name = "pathfinder_geometry" version = "0.5.1" @@ -5064,8 +5420,6 @@ checksum = "af3fb618632874fb76937c2361a7f22afd393c982a2165595407edc75b06d3c1" dependencies = [ "atomic", "crossbeam-queue", - "futures", - "log", "parking_lot", "pin-project", "pollster 0.2.5", @@ -5109,16 +5463,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" -[[package]] -name = "prettyplease" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" -dependencies = [ - "proc-macro2", - "syn 2.0.119", -] - [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -5158,17 +5502,18 @@ dependencies = [ [[package]] name = "proptest" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" dependencies = [ - "bit-set 0.8.0", - "bit-vec 0.8.0", + "bit-set 0.11.1", + "bit-vec 0.10.1", "bitflags 2.13.2", + "chacha20", + "core_detect", "num-traits", "proptest-macro", - "rand 0.9.5", - "rand_chacha 0.9.0", + "rand 0.10.2", "rand_xorshift", "regex-syntax", "rusty-fork", @@ -5178,14 +5523,14 @@ dependencies = [ [[package]] name = "proptest-macro" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "efaa288b896cb2b345da7b7f2110ab19e51565b83495b56fcec98a62f8b1f33e" +checksum = "e99782ea31698c2206c6887c1220d2f594b291c26cb9ec5b6d7cf175320bc212" dependencies = [ "convert_case 0.11.0", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.5", ] [[package]] @@ -5411,11 +5756,11 @@ dependencies = [ [[package]] name = "rand_xorshift" -version = "0.4.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" dependencies = [ - "rand_core 0.9.5", + "rand_core 0.10.1", ] [[package]] @@ -5698,6 +6043,42 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rmcp" +version = "3.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab5023804cbe0304cbe06197ac16e645a0a0d0ffa2953bf735c15c2fa0213350" +dependencies = [ + "chrono", + "futures", + "indexmap", + "pastey 0.2.3", + "pin-project-lite", + "rmcp-macros", + "schemars", + "serde", + "serde_json", + "thiserror 2.0.20", + "tokio", + "tokio-util", + "tracing", + "url", + "uuid", +] + +[[package]] +name = "rmcp-macros" +version = "3.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1da498700030856ba63114bceefa30ba21f5e278cb975e5b9de3529fe842b40" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "serde_json", + "syn 3.0.5", +] + [[package]] name = "ropey" version = "2.0.0-beta.1" @@ -5853,6 +6234,7 @@ version = "0.23.45" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" dependencies = [ + "log", "once_cell", "ring", "rustls-pki-types", @@ -5892,6 +6274,33 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + [[package]] name = "rustls-webpki" version = "0.103.15" @@ -5969,6 +6378,7 @@ version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a" dependencies = [ + "chrono", "dyn-clone", "indexmap", "ref-cast", @@ -6120,15 +6530,6 @@ dependencies = [ "syn 3.0.5", ] -[[package]] -name = "serde_fmt" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e497af288b3b95d067a23a4f749f2861121ffcb2f6d8379310dcda040c345ed" -dependencies = [ - "serde_core", -] - [[package]] name = "serde_json" version = "1.0.151" @@ -6197,6 +6598,17 @@ dependencies = [ "unsafe-libyaml", ] +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + [[package]] name = "sha1_smol" version = "1.0.1" @@ -6225,15 +6637,6 @@ dependencies = [ "digest 0.11.3", ] -[[package]] -name = "sharded-slab" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" -dependencies = [ - "lazy_static", -] - [[package]] name = "shellexpand" version = "3.1.2" @@ -6243,12 +6646,6 @@ dependencies = [ "dirs 6.0.0", ] -[[package]] -name = "shlex" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" - [[package]] name = "shlex" version = "2.0.1" @@ -6271,6 +6668,16 @@ version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + [[package]] name = "simd_helpers" version = "0.1.0" @@ -6286,6 +6693,16 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" +dependencies = [ + "bstr", + "unicode-segmentation", +] + [[package]] name = "simplecss" version = "0.2.2" @@ -6365,7 +6782,6 @@ version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4aaa7368fcf4852a4c2dd92df0cace6a71f2091ca0a23391ce7f3a31833f1523" dependencies = [ - "borsh", "serde_core", ] @@ -6458,6 +6874,12 @@ dependencies = [ "quote", ] +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "strum" version = "0.28.0" @@ -6485,85 +6907,6 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" -[[package]] -name = "sval" -version = "2.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b81b254da21fe1fcc4e3a74fe39b46e25e3a863078f8b71c954d47f84889dbc6" - -[[package]] -name = "sval_buffer" -version = "2.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50be352d2822ffafb59e3e2ddac9d5ee60f2eeadbb7b5a2a951b9f3651e87a6f" -dependencies = [ - "sval", - "sval_ref", - "zerocopy", -] - -[[package]] -name = "sval_dynamic" -version = "2.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b048ca293b998d9a45659159f94a64063791e74cdc670164943dbb434405573d" -dependencies = [ - "sval", -] - -[[package]] -name = "sval_fmt" -version = "2.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6b5888e40f80568733217f27b7317b845f463400ced36c424b1a804730e53b2" -dependencies = [ - "itoa", - "ryu", - "sval", -] - -[[package]] -name = "sval_json" -version = "2.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e17664d6bb6b74947afaab9d7c991caa9bf5638d4dee16fcbef637f440796049" -dependencies = [ - "itoa", - "ryu", - "sval", -] - -[[package]] -name = "sval_nested" -version = "2.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07c059969ca5ca163ea7fef6c9661758973d17691aba92abdcf5c428f4ec122c" -dependencies = [ - "sval", - "sval_buffer", - "sval_ref", -] - -[[package]] -name = "sval_ref" -version = "2.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42d6b29ff568c85c87561807f51d2adfff4b6016c6363133f7cd1652a12548f3" -dependencies = [ - "sval", -] - -[[package]] -name = "sval_serde" -version = "2.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f33ec9edc42b12764d5c90ca0a1d84189c6bde81ed27507f1e661c6e4e05853" -dependencies = [ - "serde_core", - "sval", - "sval_nested", -] - [[package]] name = "svg_fmt" version = "0.4.5" @@ -6601,6 +6944,17 @@ dependencies = [ "zeno", ] +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "2.0.119" @@ -6699,6 +7053,17 @@ dependencies = [ "smallvec", ] +[[package]] +name = "taffy" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c8480887e8803986d96a7173729565520d4bbb721ad6b7ad6941a22897207aa" +dependencies = [ + "serde", + "slotmap", + "smallvec", +] + [[package]] name = "tao-core-video-sys" version = "0.2.0" @@ -6795,15 +7160,6 @@ dependencies = [ "syn 3.0.5", ] -[[package]] -name = "thread_local" -version = "1.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" -dependencies = [ - "cfg-if", -] - [[package]] name = "tiff" version = "0.11.3" @@ -6898,10 +7254,23 @@ dependencies = [ "libc", "mio", "pin-project-lite", + "signal-hook-registry", "socket2", + "tokio-macros", "windows-sys 0.61.2", ] +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + [[package]] name = "tokio-rustls" version = "0.26.5" @@ -7087,32 +7456,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", - "valuable", -] - -[[package]] -name = "tracing-log" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" -dependencies = [ - "log", - "once_cell", - "tracing-core", -] - -[[package]] -name = "tracing-subscriber" -version = "0.3.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" -dependencies = [ - "nu-ansi-term", - "sharded-slab", - "smallvec", - "thread_local", - "tracing-core", - "tracing-log", ] [[package]] @@ -7159,10 +7502,10 @@ dependencies = [ ] [[package]] -name = "typeid" -version = "1.0.3" +name = "typed-path" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" +checksum = "54ec2755506471f54baf5e4bb5499d8e510cc1caf271270e778a736bd2d7336c" [[package]] name = "typenum" @@ -7231,9 +7574,9 @@ checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" [[package]] name = "unicode-properties" -version = "0.1.4" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" +checksum = "e70f2a8b45122e719eb623c01822704c4e0907e7e426a05927e1a1cfff5b75d0" [[package]] name = "unicode-script" @@ -7259,12 +7602,6 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - [[package]] name = "unsafe-libyaml" version = "0.2.11" @@ -7277,6 +7614,36 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" +[[package]] +name = "ureq" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc" +dependencies = [ + "base64 0.23.1", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + [[package]] name = "url" version = "2.5.8" @@ -7301,7 +7668,7 @@ version = "0.45.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef" dependencies = [ - "base64", + "base64 0.22.1", "data-url", "flate2", "fontdb", @@ -7328,7 +7695,7 @@ version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e419dff010bb12512b0ae9e3d2f318dfbdf0167fde7eb05465134d4e8756076f" dependencies = [ - "base64", + "base64 0.22.1", "data-url", "flate2", "fontdb", @@ -7355,6 +7722,12 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "utf8_iter" version = "1.0.4" @@ -7369,6 +7742,7 @@ checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" dependencies = [ "getrandom 0.4.3", "js-sys", + "rand 0.10.2", "serde_core", "sha1_smol", "wasm-bindgen", @@ -7386,45 +7760,35 @@ dependencies = [ ] [[package]] -name = "valuable" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" - -[[package]] -name = "value-bag" -version = "1.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2799ffb329a792ecfd902b71306c8a815a6ef1c0470fa9953a6aa4d4cecbe511" -dependencies = [ - "value-bag-serde1", - "value-bag-sval2", -] - -[[package]] -name = "value-bag-serde1" -version = "1.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0941feceafbe7a8f59ea1096d45b97002884a41306315ad797b3684b63a81d8c" -dependencies = [ - "erased-serde", - "serde_core", - "serde_fmt", -] - -[[package]] -name = "value-bag-sval2" -version = "1.14.1" +name = "velopack" +version = "1.2.161" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "839752af8179287d27eb2b94164641b1ede9e60ab7424163388dc21ebd0508cd" +checksum = "4295172ffaad78f9adbab35f7ffefa97e4ceefee9d2c38bda37fdce4d6c66e5a" dependencies = [ - "sval", - "sval_buffer", - "sval_dynamic", - "sval_fmt", - "sval_json", - "sval_ref", - "sval_serde", + "anyhow", + "bitflags 2.13.2", + "derivative", + "glob", + "lazy_static", + "libc", + "log", + "normpath", + "rand 0.10.2", + "regex", + "semver", + "serde", + "serde_json", + "sha1", + "sha2 0.11.0", + "thiserror 2.0.20", + "ureq", + "url", + "uuid", + "wait-timeout", + "waitpid-any", + "windows 0.62.2", + "xml", + "zip", ] [[package]] @@ -7462,6 +7826,16 @@ dependencies = [ "libc", ] +[[package]] +name = "waitpid-any" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18aa3ce681e189f125c4c1e1388c03285e2fd434ef52c7203084012ac29c5e4a" +dependencies = [ + "rustix", + "windows-sys 0.59.0", +] + [[package]] name = "waker-fn" version = "1.2.0" @@ -7701,6 +8075,24 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -7722,7 +8114,37 @@ dependencies = [ "hashbrown 0.16.1", "js-sys", "log", - "naga", + "naga 29.0.4", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "smallvec", + "static_assertions", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "wgpu-core 29.0.4", + "wgpu-hal 29.0.4", + "wgpu-types 29.0.4", +] + +[[package]] +name = "wgpu" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527ccdf43dd5b2e8676eed9984ce00e2bbb0a1b85b70c1969dcb6cd2eb55ab9e" +dependencies = [ + "arrayvec", + "bitflags 2.13.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "js-sys", + "log", + "naga 30.0.1", "parking_lot", "portable-atomic", "profiling", @@ -7732,9 +8154,9 @@ dependencies = [ "wasm-bindgen", "wasm-bindgen-futures", "web-sys", - "wgpu-core", - "wgpu-hal", - "wgpu-types", + "wgpu-core 30.0.1", + "wgpu-hal 30.0.1", + "wgpu-types 30.0.1", ] [[package]] @@ -7753,7 +8175,42 @@ dependencies = [ "hashbrown 0.16.1", "indexmap", "log", - "naga", + "naga 29.0.4", + "once_cell", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "rustc-hash 1.1.0", + "smallvec", + "thiserror 2.0.20", + "wgpu-core-deps-apple 29.0.4", + "wgpu-core-deps-emscripten 29.0.4", + "wgpu-core-deps-wasm 29.0.4", + "wgpu-core-deps-windows-linux-android 29.0.4", + "wgpu-hal 29.0.4", + "wgpu-naga-bridge 29.0.4", + "wgpu-types 29.0.4", +] + +[[package]] +name = "wgpu-core" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14" +dependencies = [ + "arrayvec", + "bit-set 0.10.0", + "bit-vec 0.9.1", + "bitflags 2.13.2", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "indexmap", + "log", + "naga 30.0.1", + "naga-types", "once_cell", "parking_lot", "portable-atomic", @@ -7762,13 +8219,13 @@ dependencies = [ "rustc-hash 1.1.0", "smallvec", "thiserror 2.0.20", - "wgpu-core-deps-apple", - "wgpu-core-deps-emscripten", - "wgpu-core-deps-wasm", - "wgpu-core-deps-windows-linux-android", - "wgpu-hal", - "wgpu-naga-bridge", - "wgpu-types", + "wgpu-core-deps-apple 30.0.1", + "wgpu-core-deps-emscripten 30.0.1", + "wgpu-core-deps-wasm 30.0.1", + "wgpu-core-deps-windows-linux-android 30.0.1", + "wgpu-hal 30.0.1", + "wgpu-naga-bridge 30.0.1", + "wgpu-types 30.0.1", ] [[package]] @@ -7777,7 +8234,16 @@ version = "29.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f5e39e26c4c0e07589e67d18546cf79ff45383659fc72fca4dd293358a0347f3" dependencies = [ - "wgpu-hal", + "wgpu-hal 29.0.4", +] + +[[package]] +name = "wgpu-core-deps-apple" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "061f3d319a40d39d00b1ecc2c33b89fe21d4e6fe01859df3500a3a8ecccd6b68" +dependencies = [ + "wgpu-hal 30.0.1", ] [[package]] @@ -7786,7 +8252,16 @@ version = "29.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "01e09be551dc939498bdd5f6b2c66e55ab275dad25825267a08605a80fc9f0af" dependencies = [ - "wgpu-hal", + "wgpu-hal 29.0.4", +] + +[[package]] +name = "wgpu-core-deps-emscripten" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98b86cf4abf524a902dd35f18ca6a3f08fc2ae9847c8f10b48e30491b1f0b86" +dependencies = [ + "wgpu-hal 30.0.1", ] [[package]] @@ -7795,7 +8270,16 @@ version = "29.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af1fb1798be2a912497d4c224f72d39bb0cb34af50e8bcc29865bc339c943059" dependencies = [ - "wgpu-hal", + "wgpu-hal 29.0.4", +] + +[[package]] +name = "wgpu-core-deps-wasm" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d260ca2ca8adc654f513a869bf3cac0b47f5b8d3f87803d6942015f8de597aae" +dependencies = [ + "wgpu-hal 30.0.1", ] [[package]] @@ -7804,7 +8288,16 @@ version = "29.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e592c1bbef6ad047647ae6e666ebd8cee7a32bb4544d9700ec96cbf73230257" dependencies = [ - "wgpu-hal", + "wgpu-hal 29.0.4", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7586165fd5f6d881cb9ce4bb71f40d6caab2c0f1837e3fc1d9788a197fb6004f" +dependencies = [ + "wgpu-hal 30.0.1", ] [[package]] @@ -7832,10 +8325,65 @@ dependencies = [ "libc", "libloading", "log", - "naga", + "naga 29.0.4", + "ndk-sys", + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "once_cell", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", + "profiling", + "range-alloc", + "raw-window-handle", + "raw-window-metal", + "renderdoc-sys", + "smallvec", + "thiserror 2.0.20", + "wasm-bindgen", + "wayland-sys", + "web-sys", + "wgpu-naga-bridge 29.0.4", + "wgpu-types 29.0.4", + "windows 0.62.2", + "windows-core 0.62.2", + "windows-result 0.4.1", +] + +[[package]] +name = "wgpu-hal" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set 0.10.0", + "bitflags 2.13.2", + "block2 0.6.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "glow", + "glutin_wgl_sys", + "gpu-allocator", + "hashbrown 0.17.1", + "js-sys", + "khronos-egl", + "libc", + "libloading", + "log", + "naga 30.0.1", + "naga-types", "ndk-sys", "objc2 0.6.4", "objc2-core-foundation", + "objc2-core-graphics", "objc2-foundation 0.3.2", "objc2-metal 0.3.2", "objc2-quartz-core 0.3.2", @@ -7850,12 +8398,13 @@ dependencies = [ "raw-window-metal", "renderdoc-sys", "smallvec", + "static_assertions", "thiserror 2.0.20", "wasm-bindgen", "wayland-sys", "web-sys", - "wgpu-naga-bridge", - "wgpu-types", + "wgpu-naga-bridge 30.0.1", + "wgpu-types 30.0.1", "windows 0.62.2", "windows-core 0.62.2", "windows-result 0.4.1", @@ -7867,8 +8416,18 @@ version = "29.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95226013f547544b223281cd16a4fb549aa9dcb562adbda0faae4c73ffbbc161" dependencies = [ - "naga", - "wgpu-types", + "naga 29.0.4", + "wgpu-types 29.0.4", +] + +[[package]] +name = "wgpu-naga-bridge" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f62e73117bb7a62bfd9c5a5841438a823f6566c6442a808ee269d2d055c081" +dependencies = [ + "naga 30.0.1", + "wgpu-types 30.0.1", ] [[package]] @@ -7885,6 +8444,22 @@ dependencies = [ "web-sys", ] +[[package]] +name = "wgpu-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99dad6f1fbdbbdb4c278a6508b059d44688f5cebddf78d005a46a31340269286" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "js-sys", + "log", + "naga-types", + "raw-window-handle", + "static_assertions", + "web-sys", +] + [[package]] name = "which" version = "8.0.6" @@ -8575,16 +9150,6 @@ dependencies = [ "pkg-config", ] -[[package]] -name = "x11-clipboard" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "662d74b3d77e396b8e5beb00b9cad6a9eccf40b2ef68cc858784b14c41d535a3" -dependencies = [ - "libc", - "x11rb", -] - [[package]] name = "x11rb" version = "0.13.2" @@ -8659,6 +9224,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" +[[package]] +name = "xml" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f45bb2c13fec6a6cb4c0f76a7e94839e110a14ec803ec2940777a94c347bc52" + [[package]] name = "xml-rs" version = "0.8.29" @@ -8684,7 +9255,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "xtask" -version = "0.11.0" +version = "0.17.0" dependencies = [ "disktree-core", ] @@ -9002,6 +9573,20 @@ dependencies = [ "syn 3.0.5", ] +[[package]] +name = "zip" +version = "8.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +dependencies = [ + "crc32fast", + "flate2", + "indexmap", + "memchr", + "typed-path", + "zopfli", +] + [[package]] name = "zlib-rs" version = "0.6.7" @@ -9014,6 +9599,18 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + [[package]] name = "zune-core" version = "0.4.12" diff --git a/Cargo.toml b/Cargo.toml index 19d0d6ec..921a9d7c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,16 +1,25 @@ [workspace] resolver = "3" -members = ["crates/disktree-app", "crates/disktree-core", "crates/disktree-scan", "xtask"] +members = [ + "crates/disktree-app", + "crates/disktree-core", + "crates/disktree-link", + "crates/disktree-mcp", + "crates/disktree-scan", + "xtask", +] [workspace.package] -version = "0.11.0" +version = "0.17.0" edition = "2024" rust-version = "1.97" license = "MIT" -repository = "https://github.com/tobi/disktree" +repository = "https://github.com/pwrdrvr/PwrDisk" [workspace.dependencies] disktree-core = { path = "crates/disktree-core" } +disktree-link = { path = "crates/disktree-link" } +disktree-mcp = { path = "crates/disktree-mcp" } anyhow = "1" rayon = "1" rustc-hash = "2" @@ -80,7 +89,3 @@ lto = "thin" codegen-units = 1 overflow-checks = true -# gpui-pre-macros leaves a helper ungated in release builds while its module is -# gated on debug_assertions; enable it for the host proc-macro only. -[profile.release.package.gpui-pre-macros] -debug-assertions = true diff --git a/LICENSE b/LICENSE index 55611cc5..330df541 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,7 @@ MIT License Copyright (c) 2026 Tobi Lütke +Copyright (c) 2026 PwrDisk contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/Makefile b/Makefile index 75fc361b..e8c9bc13 100644 --- a/Makefile +++ b/Makefile @@ -1,14 +1,14 @@ -# disktree: build, check, and install. +# PwrDisk: build, check, and install. # # `make install` puts the binary, a desktop entry and an icon under PREFIX -# (default: ~/.local), so disktree shows up in the Omarchy launcher and in +# (default: ~/.local), so PwrDisk shows up in the Omarchy launcher and in # "Open with" for directories. The default needs no root: # -# make install # ~/.local/bin/disktree +# make install # ~/.local/bin/pwrdisk # sudo make install PREFIX=/usr/local # system-wide # -# On macOS it installs disktree.app into ~/Applications instead (APPS to -# change that), plus a `disktree` command in BINDIR that runs the app's +# On macOS it installs PwrDisk.app into ~/Applications instead (APPS to +# change that), plus a `pwrdisk` command in BINDIR that runs the app's # binary, so both Spotlight and a terminal find it. PREFIX ?= $(HOME)/.local @@ -17,17 +17,17 @@ APPDIR ?= $(PREFIX)/share/applications ICONDIR ?= $(PREFIX)/share/icons/hicolor/scalable/apps APPS ?= $(HOME)/Applications -BUNDLE = target/bundle/disktree.app +BUNDLE = target/bundle/PwrDisk.app UNAME := $(shell uname -s) MANIFEST = Cargo.toml CARGO ?= cargo -TARGET = target/release/disktree +TARGET = target/release/pwrdisk ifeq ($(UNAME),Linux) -TARGET = target/portable/disktree +TARGET = target/portable/pwrdisk endif ICON = assets/disktree.svg -DESKTOP = packaging/disktree.desktop.in +DESKTOP = packaging/pwrdisk.desktop.in # Being on PATH is not enough: an older package can win earlier in it. define check_install_path @@ -47,17 +47,18 @@ define check_install_path fi endef -.PHONY: help build run install install-scan uninstall bundle lint test test-ssh ci fmt clean +.PHONY: help build run install install-scan uninstall bundle dock-icons lint test test-ssh ci fmt clean help: - @echo "disktree" + @echo "PwrDisk" @echo @echo " make build release build" @echo " make run build and open the source/root chooser" @echo " make install-scan build/install the headless SSH helper only" @echo " make install install to $(PREFIX): binary, desktop entry, icon" - @echo " (macOS: disktree.app into $(APPS))" - @echo " make bundle macOS: build target/bundle/disktree.app and its zip" + @echo " (macOS: PwrDisk.app into $(APPS))" + @echo " make bundle macOS: build target/bundle/PwrDisk.app, zip and DMG" + @echo " make dock-icons macOS 26: redraw the Dock icon of an unbundled run" @echo " make uninstall remove what install put there" @echo " make lint rustfmt --check and clippy -D warnings" @echo " make test core and window-harness tests" @@ -103,47 +104,48 @@ fmt: ifeq ($(UNAME),Darwin) # Replaced whole rather than copied over: a stale file left inside a signed -# bundle breaks its signature. +# bundle breaks its signature. Only the app: the zip and DMG are for +# handing it to another Mac. install: - $(CARGO) xtask bundle + $(CARGO) xtask bundle --app-only install -d "$(APPS)" "$(BINDIR)" - rm -rf "$(APPS)/disktree.app" - ditto "$(BUNDLE)" "$(APPS)/disktree.app" - ln -sf "$(APPS)/disktree.app/Contents/MacOS/disktree" "$(BINDIR)/disktree" + rm -rf "$(APPS)/PwrDisk.app" + ditto "$(BUNDLE)" "$(APPS)/PwrDisk.app" + ln -sf "$(APPS)/PwrDisk.app/Contents/MacOS/pwrdisk" "$(BINDIR)/pwrdisk" @echo @echo "installed:" - @echo " $(APPS)/disktree.app" - @echo " $(BINDIR)/disktree -> the app's binary" - $(call check_install_path,disktree) + @echo " $(APPS)/PwrDisk.app" + @echo " $(BINDIR)/pwrdisk -> the app's binary" + $(call check_install_path,pwrdisk) uninstall: - rm -rf "$(APPS)/disktree.app" - @if [ -L "$(BINDIR)/disktree" ]; then rm -f "$(BINDIR)/disktree"; fi + rm -rf "$(APPS)/PwrDisk.app" + @if [ -L "$(BINDIR)/pwrdisk" ]; then rm -f "$(BINDIR)/pwrdisk"; fi @echo "removed" else install: build install -d $(BINDIR) $(APPDIR) $(ICONDIR) - install -m755 $(TARGET) $(BINDIR)/disktree - install -m644 $(ICON) $(ICONDIR)/disktree.svg + install -m755 $(TARGET) $(BINDIR)/pwrdisk + install -m644 $(ICON) $(ICONDIR)/pwrdisk.svg VERSION=$$(sed -n 's/^version = "\(.*\)"/\1/p' $(MANIFEST) | head -1) && \ sed -e 's|@BINDIR@|$(BINDIR)|' -e "s|@VERSION@|$$VERSION|" \ - $(DESKTOP) > $(APPDIR)/disktree.desktop && \ - chmod 644 $(APPDIR)/disktree.desktop + $(DESKTOP) > $(APPDIR)/pwrdisk.desktop && \ + chmod 644 $(APPDIR)/pwrdisk.desktop @if command -v update-desktop-database >/dev/null 2>&1; then \ update-desktop-database $(APPDIR) 2>/dev/null || true; \ fi @echo @echo "installed:" - @echo " $(BINDIR)/disktree" - @echo " $(APPDIR)/disktree.desktop" - @echo " $(ICONDIR)/disktree.svg" + @echo " $(BINDIR)/pwrdisk" + @echo " $(APPDIR)/pwrdisk.desktop" + @echo " $(ICONDIR)/pwrdisk.svg" @if command -v desktop-file-validate >/dev/null 2>&1; then \ - desktop-file-validate $(APPDIR)/disktree.desktop || true; \ + desktop-file-validate $(APPDIR)/pwrdisk.desktop || true; \ fi - $(call check_install_path,disktree) + $(call check_install_path,pwrdisk) uninstall: - rm -f $(BINDIR)/disktree $(APPDIR)/disktree.desktop $(ICONDIR)/disktree.svg + rm -f $(BINDIR)/pwrdisk $(APPDIR)/pwrdisk.desktop $(ICONDIR)/pwrdisk.svg @if command -v update-desktop-database >/dev/null 2>&1; then \ update-desktop-database $(APPDIR) 2>/dev/null || true; \ fi @@ -153,5 +155,11 @@ endif bundle: $(CARGO) xtask bundle +# The Dock icon a run outside the bundle shows, in the flat look of macOS 15 +# and the Liquid Glass of macOS 26, which only that macOS can draw: needs +# macOS 26 and Xcode 26. Run after either SVG in packaging/macos changes. +dock-icons: + swift packaging/macos/render-dock-icons.swift + clean: $(CARGO) clean diff --git a/README.md b/README.md index bf9bc21f..4b639205 100644 --- a/README.md +++ b/README.md @@ -1,589 +1,236 @@ -# disktree - -![disktree: a home directory as a treemap, coloured by kind of data, with reclaimable space hatched and the selection, findings and free space in the side panel](assets/screenshot.png) - -Find what is filling a disk, mark what should go, and remove it — with the -volume's free space in view the whole time. - -disktree is a treemap for Omarchy. Choose a local or SSH source, then a -mounted volume or directory; no scan starts until you explicitly accept. -It draws every directory as a nested mosaic sized by its real disk cost, -and lets you walk into it with the keyboard or the mouse. Mark as much as you -like; nothing happens until you review the list and commit, and the permanent -path always asks first. - -Built with [GPUI](https://gpui-kit.com/) through -[gpui-omarchy](https://github.com/huacnlee/gpui-omarchy), so it follows your -Omarchy theme and behaves like the rest of the desktop. +
+ + + +

PwrDisk

+ +See what is filling your disk. Get the space back safely. + +

Your whole drive as one map, every folder drawn to its real size.
+Mark what should go, review the list, and watch the free space come back.
+macOS, Windows and Linux.

+ +

+ Download for Mac — Universal, Intel and Apple Silicon + Download for Windows — x64 installer + Download for Windows — ARM64 installer +

+ +

+ Download for Linux — x86-64 tarball + Download for Linux — ARM64 tarball +

+ +macOS 11 Big Sur or newer · Windows 10 or newer, x64 and ARM64 · Linux x86-64 and ARM64 · MIT
+Signed and notarized for macOS, signed for Windows, and both keep themselves up to date. No account, no telemetry. + +

+ +PwrDisk scanning a home folder on a 1 TiB disk with 21 GiB free. Each folder is a tile sized by its space and coloured by kind: Projects with its Rust target folders and node_modules, agent worktrees, movies, local AI models, photos, Dropbox, caches and toolchains. Reclaimable space is hatched. The side panel shows the selected Projects folder at 185 GiB, a Worth a look list led by .cache at 69 GiB, and the disk meter. + +
+ +## Why PwrDisk + +Disks fill up slowly and then all at once. PwrDisk shows you where the space +went in one picture, and gets it back without the "wait, what did I just +delete?" moment. + +- **The whole drive at a glance.** Every folder is a tile sized by what it + really costs on disk, coloured by what it holds: code, caches, toolchains, + synced files, media, documents. Space you can safely get back — caches, + build output, package stores — is hatched. +- **Worth a look.** The side panel lists the biggest things that could + plausibly go, so you don't have to go hunting. +- **Free space, live.** The meter shows the drive's free space now and after + what you have marked, and only counts what would actually come back to + that drive. +- **Marking is never deleting.** Mark as much as you like and change your + mind as often as you like. Nothing happens until you open the review list + and confirm. The default is the Trash or Recycle Bin; deleting permanently + always asks first. +- **Guard rails you don't have to think about.** PwrDisk refuses to remove + system folders, your home folder, mount points or anything outside what you + scanned. Select a git checkout and it tells you about uncommitted changes, + stashes and unpushed commits before you mark it. +- **Fast.** A home directory takes seconds. On Windows, run it as + administrator and it reads a whole NTFS drive straight from the file + table — about 3.4 seconds for 4 million files. +- **Servers too.** Scan a Linux server over SSH, read-only. PwrDisk never + deletes over SSH; it hands you the list, or a delete script that checks it + is on the right machine first. +- **Let an AI agent do the digging.** Claude Code, Codex or any MCP client + can scan, explain and mark for you. You confirm every removal. ## Install -Download `disktree-*-x86_64-linux.tar.gz` (`aarch64-linux` on ARM) from the -[latest release](https://github.com/tobi/disktree/releases/latest), unpack -it, and run `./install.sh` inside (or just copy `disktree` onto your -`PATH`). Or build it: - -```sh -git clone https://github.com/tobi/disktree -cd disktree -make install -``` - -`make install` builds a release binary and puts three things under `~/.local` -(no root needed): - -- `~/.local/bin/disktree` -- a desktop entry, so disktree is in the launcher and in a file manager's - **Open with** for a directory (it adds a handler; it never becomes the - default) -- an icon - -`sudo make install PREFIX=/usr/local` installs system-wide; `make uninstall` -removes exactly what was installed. - -On Arch, including Omarchy, disktree is in the AUR: -[`disktree`](https://aur.archlinux.org/packages/disktree) builds each release -from source, and -[`disktree-bin`](https://aur.archlinux.org/packages/disktree-bin) installs -the release binary: - -```sh -yay -S disktree-bin -``` - -If another installed version wins on `PATH`, the installer warns which one. -Run `export PATH="$HOME/.local/bin:$PATH"` and add that setting to your shell -configuration so the locally installed build takes precedence. - -For Linux builds with embedded SSH helpers, also install the two Rust -standard-library targets (no external C cross-compiler is needed): - -```sh -rustup target add x86_64-unknown-linux-musl aarch64-unknown-linux-musl -``` - -You need Rust 1.97 or newer and a Wayland or X11 session with a GPU that GPUI -can drive (Vulkan). Distributions often package an older Rust; -[rustup](https://rustup.rs) installs a current one. The repo pins 1.97 in -`rust-toolchain.toml`, so with rustup the right toolchain is fetched on the -first build even if `rustup default` points at something older. - -### macOS - -Download `disktree-*-aarch64-macos.zip` (`x86_64-macos` for an Intel Mac) -from the [latest release](https://github.com/tobi/disktree/releases/latest), -unzip it, and drag `disktree.app` into Applications. macOS 11 or newer. - -A release that was not signed and notarized is stopped by Gatekeeper: macOS -says it "is damaged and can't be opened" or "cannot be verified". The app is -fine; the browser marked the download as quarantined. Clear the mark once: - -```sh -xattr -dr com.apple.quarantine /Applications/disktree.app -``` - -(Or open it once, then choose **Open Anyway** in System Settings › Privacy & -Security.) - -Or build it, with Rust 1.97 or newer and Xcode or its Command Line Tools. -macOS does not come with Rust; install it with [rustup](https://rustup.rs). +| Platform | Download | Notes | +| --- | --- | --- | +| macOS 11 or newer | [PwrDisk.dmg](https://github.com/pwrdrvr/PwrDisk/releases/latest/download/PwrDisk.dmg) | Universal: Apple Silicon and Intel. Open it and drag PwrDisk to Applications. | +| Windows 10 / 11, x64 | [PwrDisk-win-Setup.exe](https://github.com/pwrdrvr/PwrDisk/releases/latest/download/PwrDisk-win-Setup.exe) | Installs for you alone, no administrator prompt. | +| Windows 10 / 11, ARM64 | [PwrDisk-win-arm64-Setup.exe](https://github.com/pwrdrvr/PwrDisk/releases/latest/download/PwrDisk-win-arm64-Setup.exe) | The same, for ARM PCs. | +| Windows, for deployment tools | [x64 .msi](https://github.com/pwrdrvr/PwrDisk/releases/latest/download/PwrDisk-win.msi) · [ARM64 .msi](https://github.com/pwrdrvr/PwrDisk/releases/latest/download/PwrDisk-win-arm64.msi) | Installs the same way as Setup.exe. | +| Windows, portable | [x64 .zip](https://github.com/pwrdrvr/PwrDisk/releases/latest/download/PwrDisk-win-Portable.zip) · [ARM64 .zip](https://github.com/pwrdrvr/PwrDisk/releases/latest/download/PwrDisk-win-arm64-Portable.zip) | Runs from wherever you unpack it. | +| Linux, x86-64 | [pwrdisk-x86_64-linux.tar.gz](https://github.com/pwrdrvr/PwrDisk/releases/latest/download/pwrdisk-x86_64-linux.tar.gz) | Unpack and run `./install.sh`. | +| Linux, ARM64 | [pwrdisk-aarch64-linux.tar.gz](https://github.com/pwrdrvr/PwrDisk/releases/latest/download/pwrdisk-aarch64-linux.tar.gz) | The same, for ARM. | + +Every release, with checksums, is on the +[releases page](https://github.com/pwrdrvr/PwrDisk/releases). + +**macOS.** The app is signed with a Developer ID and notarized by Apple, so it +opens like any other download. To measure everything, give PwrDisk **Full +Disk Access** in System Settings › Privacy & Security (the side panel offers +a button when it is missing), then reopen it. Without it macOS hides Mail, +Messages, Safari, other apps' data and the Trash, and PwrDisk shows them as +unreadable rather than guessing. + +**Windows.** Installers are signed by PwrDrvr LLC and land in the Start menu; +uninstall from Settings › Apps. When PwrDisk would be faster or see more as +administrator, the side panel offers **Restart as Administrator**. + +**Linux.** No root needed; this installs into `~/.local` with a launcher +entry and an icon. Use `aarch64` in place of `x86_64` on ARM: ```sh -make install # ~/Applications/disktree.app, and ~/.local/bin/disktree -make uninstall +curl -fL https://github.com/pwrdrvr/PwrDisk/releases/latest/download/pwrdisk-x86_64-linux.tar.gz | tar xz +cd pwrdisk-*-x86_64-linux && ./install.sh ``` -To see everything, give disktree **Full Disk Access** in System Settings › -Privacy & Security (the panel offers a button when it is missing), then -reopen it. Without it macOS hides Mail, Messages, Safari, other apps' data -and the Trash, and disktree counts them as unreadable. Started from a -terminal, it is the terminal that needs the access. macOS also asks once -each for Desktop, Documents and Downloads. - -What is different from Linux: +You need a Wayland or X11 session with a GPU that does Vulkan. On Omarchy +PwrDisk follows your theme; on Hyprland, see +[the window rules](docs/guide.md#on-hyprland). + +**Updates.** The Mac app and Windows installs check for a new release when +they start and every six hours, download it in the background, and install +it when you quit (or right away from **Restart to update**). **Shift-U** +shows the version and lets you pick a release channel. The Linux tarball +does not update itself; download the next release. + +## Using it + +1. **Pick what to scan.** Choose **This computer** or an SSH host, then a + drive or folder. Nothing is scanned until you choose. +2. **Look around.** Click a tile, or use the arrow keys. Scroll to zoom into + a folder and keep scrolling to go inside; scroll back to come out. + **Enter** opens the selected folder, **Backspace** goes up. +3. **Mark what should go.** **Space** marks the tile under the pointer; press + it again to unmark. The side panel shows how much free space you would + have afterwards. +4. **Review.** Press **c** to see the list. Unmark anything you are unsure + of, then **Enter** moves the rest to the Trash or Recycle Bin. **p** + deletes permanently instead, after asking. +5. **See the result.** PwrDisk shows how much space you actually got + back, without scanning again: what went stays in the treemap, greyed + out, until you rescan. **Move & rescan** (shift-Enter) scans afterwards + instead. -- **Free space** is what `df` reports. Finder's figure is larger: it counts - purgeable space (caches and local snapshots macOS will clear on its own). -- **Cloned files** (copies APFS shares blocks between, as Finder's Duplicate - makes) are each counted in full, so a total can exceed what deleting them - frees. -- **Time Machine's local snapshots** are not files and do not appear; they - are part of the gap between the scan and the disk's used space. -- **Cloud-only folders** (iCloud Drive, Dropbox and the like, evicted to the - server) are not opened, so a scan never downloads them. +| key | does | +| --- | --- | +| `space` | mark or unmark | +| `enter` / `⌫` | open the folder / go up | +| scroll | zoom in, then go inside | +| `/` | filter by name | +| `c` | review what is marked | +| `t` | colour by size, file count or age | +| `g` | scan the whole disk | +| `o` | show in Finder, File Explorer or the file manager | +| `?` | every key | -To sign and notarize a build for others, with a Developer ID certificate in -the keychain and credentials saved by `xcrun notarytool store-credentials`: +From a terminal: ```sh -NOTARY_PROFILE= cargo xtask bundle \ - --sign "Developer ID Application: Name (TEAMID)" --notarize +pwrdisk # choose a source and a folder +pwrdisk ~/src # scan a folder straight away +pwrdisk --disk # the whole disk +pwrdisk ssh myserver /var # a server over SSH, read-only ``` -### Windows +The [user guide](docs/guide.md) covers every screen and key, how sizes are +measured, SSH, and what differs on macOS and Windows. -On Windows 10 or 11, download `disktree-*-x86_64-windows.zip` -(`aarch64-windows` on ARM) from the same release, unpack it anywhere and run -`disktree.exe`. Or build it with Rust 1.97 or newer, from -[rustup](https://rustup.rs), and the MSVC toolchain (Visual Studio Build -Tools, C++ workload): - -```powershell -git clone https://github.com/tobi/disktree -cd disktree -cargo build --release # target\release\disktree.exe -``` - -See [On Windows](#on-windows) for what differs there. - -## Use - -```sh -disktree # choose a local/SSH source and root -disktree ~ # explicitly scan home -disktree --disk # the whole disk it lives on -disktree ~/src # or any directory -disktree --help # options: apparent size, follow links, skip hidden, … -``` +## With an AI agent -### Servers over SSH (read-only) +PwrDisk is also an [MCP](https://modelcontextprotocol.io) server. Connect it +once and ask your agent what is eating your disk: ```sh -disktree ssh dev # connect and choose a remote root -disktree ssh user@server /var # an explicit remote path -disktree ssh dev --disk # the disk containing the remote home -disktree ssh dev -a /srv # apparent size instead of allocated blocks +claude mcp add --scope user pwrdisk -- pwrdisk mcp # Claude Code +codex mcp add pwrdisk -- pwrdisk mcp # Codex ``` -Linux builds made with `make build` / `cargo xtask portable` include static -**x86-64 and ARM64 Linux scanners appended to the executable**. SSH detects -the server's OS/CPU and uploads the matching scanner only when its checked -cache is missing or damaged. The cache is private and content-addressed under -`~/.cache/disktree/ssh//` (or the server's `XDG_CACHE_HOME`). -Uploads are checksum-verified and atomically installed; there is no sudo, -system-package change or dependency on the server's glibc version. +On macOS the command lives inside the app. **Settings › Agents (MCP)** +shows the command line and each client's command with the full path and a +Copy button; **Help › Connect an AI Agent (MCP)…** and the line under the +disk open it. -This uses stable Rust's musl targets rather than Cosmopolitan: the existing -Rust/rayon/rustix scanner has no supported stable Cosmopolitan target. These -are Linux binaries, not a single executable for every OS; ARM64 is built and -ELF-validated, while x86-64 was also executed against a real server. +The agent walks the tree, lists every cache and build directory, and +proposes what can go. You can confirm in PwrDisk's review screen yourself, +or explicitly approve an exact removal preview for the destructive MCP +removal tool. Approval to mark never authorizes removal. Agents must never +approve through computer use. Trash may be recoverable until emptied; +permanent deletion cannot be undone through PwrDisk. Settings > Safety +limits each operation to 5% of each volume's capacity by default. If a PwrDisk window is open, you both look at the +same map and its marks show up as the agent makes them. More in +[the guide](docs/guide.md#with-an-ai-agent). -You can extract a helper without opening a window, or test the entire -SSH/deployment/scan path headlessly: +## What PwrDisk will not delete -```sh -disktree extract-scanner x86_64 ./disktree-scan -disktree extract-scanner aarch64 ./disktree-scan-arm64 -disktree ssh dev --check /var/log -``` +Only things inside the folder you scanned can be removed, and never: -The appended manifest stores architecture, byte ranges and SHA-256 hashes. -Do not run `strip` after packaging: it discards the trailer. The Linux release -pipeline strips first, embeds last, and ships that single file. Appending to -signed macOS/Windows executables needs platform-specific signature handling; -those builds do not yet embed helpers. +- the scanned folder itself, your home folder, or a folder that holds it; +- `/Users` on macOS, `/home` on Linux or `C:\Users` on Windows, or any + account's folder in it (what is inside one can still be marked); +- system folders (`/usr`, `/etc`, `C:\Windows`, Program Files, Homebrew's + prefix and the like), even where permissions would allow it; +- a mount point, or anything with another disk mounted inside it; +- what a symlink points to (the link is removed, not its target). -For a development or non-Linux desktop build without the trailer, install -the small **disktree-scan** helper on the server first: +Each rule is [tested](crates/disktree-core/src/removal.rs). The full list is +in [the guide](docs/guide.md#what-it-refuses-to-do). These are checked +before you mark, so Mark is never offered for them. -```sh -# On the server, inside the checkout: -make install-scan # ~/.local/bin/disktree-scan; no GUI deps -# Or: -cargo install --path crates/disktree-scan --locked -``` +One removal may also take only 5% of a disk by default. Past that, Mark +becomes **Over 5% limit** with a ▾ that holds **Mark anyway**, and Review +asks you to type what you are doing ("delete 20% of my disk") before it +removes anything. Settings › Safety changes the limit, turns it off, or +swaps the typing for a checkbox or nothing; agents are always held to it. -The helper can be on the server's **non-interactive SSH PATH** or at -`~/.local/bin/disktree-scan` (the default install location); disktree tries -both. A binary copied from another machine must match the server's OS, -architecture and runtime. The manually built native helper may need the -server's libc; the embedded Linux helpers are static. Disktree never runs -sudo or changes the server's configuration. -SSH keeps your normal authentication settings. When launched from a -terminal, it can ask for a password or key passphrase there; GUI launches -need key/agent access or a working SSH askpass helper. Connect once with -`ssh dev` to verify access and accept its host key. - -The protocol also supports lightweight root discovery, separate from a scan: -it reads the target's mount namespace without walking or probing the listed -paths. Same-device mounts remain distinct choices; capacity is unknown -until a root is explicitly selected. Discovery requests omit scan fields, -so outdated helpers reject them instead of silently scanning their home. - -The Linux/macOS helper streams a depth-first walk directly to stdout. It -never constructs a tree or retains a directory's children: memory scales -with open ancestors, not file count. Deep directories are not rejected -at an arbitrary depth; filesystem errors are reported as unreadable. -Hardlink identities are sent to the desktop, which uses the local scanner's -compact identity index to count each inode once. The helper keeps no -per-file identity table in negotiated desktop-de-duplication mode; links -outside the chosen root cannot fill one. Older clients retain bounded -helper-side accounting for wire compatibility. A resource limit fails -explicitly instead of returning a partial tree. Symlinks are not followed, -and every nested mount is skipped, even a bind mount or same-device -subvolume. Select those as separate roots. - -While indexing, a quiet sidebar shows live files, directories, measured -bytes, read errors and elapsed time. Counters and paths use monospace type -in fixed lanes; changing values do not re-center or reflow the screen. -Narrow windows use a compact progress footer instead. - -Ordinary local walks and current SSH helpers paint a **live top-level -overview** before the full tree arrives. These are measured contributions, -not complete directory sizes. Updates are limited to once a second, in -arrival order, with at most 128 named buckets plus an overflow bucket. The -preview is kept separate from the real tree: it cannot be navigated, -marked or removed. On completion the full, actionable treemap replaces it; -on error or cancellation the preview is discarded. The Windows file-table -fast path still waits for its complete tree. Remote scans also show a -sampled recent directory and connection / helper setup / indexing / treemap -stages. Progress uses a single replaceable snapshot, not a growing event -queue; path updates are throttled to five per second. There is no guessed -percentage: the total is unknown until the walk finishes. Older helpers -still provide counters from their streamed records, without path samples. - -One compressed SSH connection carries a bounded JSON request on stdin and -compact postorder records on stdout. The client keeps stdin open so the -helper exits on disconnect, including while scanning or blocked on output. -Linux helpers also enforce a 1 GiB address-space ceiling, disable core dumps, -and stop after five minutes. File contents never cross the connection and -paths are never interpolated into remote shell commands. Only the desktop -retains the complete tree for offline navigation; its memory still scales -with entry count. The native Windows helper currently retains the original -tree-building scan path. - -Remote mode is **export-only**. Mark with Space, open review with `c`, then: - -- **Copy as prompt** (`a`): includes the SSH host, remote OS, scan root, - selected paths, sizes and cleanup precautions. It requires verifying the - actual scanned hostname and machine ID before any destructive operation, - and stopping if either check fails or cannot be performed. -- **Save list…** (`s`): remote paths, one per line, saved locally. -- **Copy delete script** (`y`), or **Save delete script…** (`e`): a - GNU/Linux shell script, copied to the clipboard or saved locally. - Running it without arguments only previews the selection. After reviewing - it, `sh disktree-delete.sh --delete` connects to the named SSH host and - runs the exported commands there, never against the local paths. - -There are no trash/delete buttons or removal-mode choices in remote review. -Deletion shortcuts and removal entry points are disabled too. Git inspection, -local folder selection and file-manager reveal are disabled so remote names -cannot accidentally act on this computer. Free space is sampled when the -scan starts, **not live**; press `r` to refresh. - -Before deleting, scripts compare the server's actual kernel hostname and -machine ID against the identity captured in the scan—not the SSH alias. -Missing identity or any mismatch aborts. The check runs on the SSH target, -not the computer launching the wrapper. Pasting the script previews it by -default and runs in a subshell, so its exit cannot close your terminal. - -Exports are not an automatic cleanup recommendation. Scripts refuse system -paths, the scan root, home or its ancestors, symlinked/changed canonical paths, -and paths containing mount points. Control-character names are omitted. -These checks do not eliminate filesystem races or tell you whether git work -is backed up; review the script and prefer a tool's own cleanup command for -tool-owned data. The remote helper itself has no delete operation. - -### The screen - -- **Top:** the trail from `/`, then what is measured — **Size**, **Files** or - **Age**, **Hidden files**, **Apparent size**, and the depth drawn. In the - tree a crumb goes there, and its ▾ lists its siblings, largest first with - their share and size, to jump sideways (arrows and Enter work too). Above - the scanned root a crumb is dimmer, and clicking it widens the scan to - there (see below). -- **Under it:** the scan totals, the filter when one is typed, and the legend. -- **Mosaic:** colour is the *kind* of data — code, agent scratch, - toolchains, synced files, git, media, documents, caches — at one muted - level, lighter with depth. A diagonal hatch is space that can be had back - (caches, sync history, package stores, build output), independent of - colour. Top-level directories carry a strip of their colour and a name - band; deeper open directories a slim label row. In **Age** mode colour is - the last write instead, from this week to older. -- **Panel:** the selection (its size set large, share of the scan, files, - last write, and for a checkout what git says — changes, stashes, unpushed - commits); *Worth a look*, the largest things that could plausibly go; - what is marked; and the disk, free now and after the marks, with the way - to the review screen. Drag its left edge to resize it; double-click the - edge to reset. - -One colour is kept apart: amber marks the selection, the main action, and -what can be had back. - -The kinds come from directory names and a few shapes (a bare git repository, -`target` beside a `Cargo.toml`). Some of the names are specific to one -machine; see `crates/disktree-core/src/classify.rs`. - -### Marking - -Space, X, Enter and the arrows act on the tile under the mouse if the mouse -moved last, and on the keyboard selection after you use an arrow or Tab. - -A marked tile takes the danger colour, and so does everything inside it: -removing a directory takes its contents with it. Marking a directory absorbs -any marks already inside it, and something inside a marked directory cannot be -marked or kept on its own; its panel offers to unmark the directory instead. -Marking is reversible — press it again — and the saving is never counted twice. - -### Zooming and going in - -Scroll to magnify toward the pointer. The wheel magnifies until the directory -under the pointer fills the view, and the next notch goes into it — one -continuous motion, with the directory's contents growing into place. Scroll the -other way to come back out. Enter goes into the selected directory at any -depth, and Backspace or Escape goes up one level. `<` and `>`, beside the -Size / Files / Age switch, go back and forward through the directories visited, -as do `alt ←` `alt →` (also `⌘[` `⌘]` on macOS) and the mouse's side -buttons. `+` and `-` magnify without going in; `0` resets. - -### Removing - -`c` (or **Review…**) opens the list of everything marked. Unmark anything -there, then choose: - -- **Move to trash** — the default when a trash is available. On macOS that is - the system Trash, the same move as Finder's (on another disk, that disk's - own Trash; network shares often have none). Elsewhere it is `trash-put` - from trash-cli, then `gio trash`, then a built-in XDG trash. Recoverable - until the trash is emptied, so it commits directly. -- **Delete permanently** — `rm -rf` semantics. It always asks first, in a dialog - that names what goes and how much comes back. - -When it finishes, disktree scans again so the numbers on screen match the disk, -and shows how much free space was actually gained. - -## Keys +## Thanks, Tobi -| key | does | -| --- | --- | -| `space` / `x` | mark or unmark the tile you point at | -| `ctrl`-click (`⌘`-click on macOS) | mark without moving the selection | -| `enter` | open that directory, at any depth | -| `⌫` / `esc` | go up one directory | -| `alt ←` `alt →` | back and forward through where you have been | -| `←` `↑` `↓` `→` | move between tiles at this level | -| `tab` | next largest sibling | -| scroll | zoom toward a directory, then go into it | -| `shift`-scroll | pan the magnified view | -| `[` `]` | draw fewer or more levels at once | -| `-` `=` `0` | magnify, shrink, reset the view | -| `ctrl =` `ctrl -` `ctrl 0` (`⌘` on macOS) | interface zoom | -| `/` | filter by name: only matches keep their colour; `enter` shows only them, `esc` clears | -| `c` | review the marked list | -| `t` | size, files or age: what areas and colours say | -| `d` | disk usage or apparent size | -| `i` | include or skip hidden entries | -| `r` | scan again | -| `esc` while scanning | stop the scan | -| `v` | choose a local/SSH source and root | -| `ctrl o` (`⌘O` on macOS) | choose another directory to scan | -| `g` | the whole disk | -| `p` | show or hide the selection line | -| `o` | show it in Finder, File Explorer or the file manager | -| right-click | show that tile in Finder, File Explorer or the file manager | -| `?` | every key | -| `q` | quit | - -On macOS the menu bar also has ⌘⇧R to show the selection in Finder, ⌘R to -rescan, ⌘[ and ⌘] for back and forward, and ⌘Q, ⌘H and ⌘W (closing the -window quits); other ⌘ chords are left to the system. On Linux and Windows -the same work with ctrl, with F5 to rescan too. - -On the review screen: `m` trash, `p` permanent, `!` unmark all, `enter` -commits, `esc` goes back. Or hand the list on instead of acting on it: `s` -saves it as a text file, one path per line, and `a` copies a prompt for a -coding agent: free the space by removing what you picked, checking each path -first (git work that exists nowhere else, a tool's own clean command) and -touching nothing else. A name holding a newline is left out of the list and -escaped in the prompt, so it cannot pass for another path. - -## What it measures - -- **Disk usage** by default: `st_blocks × 512`, the number `du` reports and the - space that actually comes back when a file is deleted. Apparent size (what - `ls -l` shows) is one toggle away. -- **Hardlinks once.** Two names for one inode cost one file. -- **Hidden entries included**, because `~/.cache` is often the biggest thing in - a home directory. Symlinks are not followed. -- **The projection counts one volume.** The meter shows the scanned volume's - free space, so it adds up only the marks whose bytes come back to that - volume, by the same rule the scan bounds the volume with. With `-X`, a mark - on a disk mounted inside the tree, on a network share or in a snapshot - subvolume is left out of the projection — removing it gives its space back - somewhere else, or, in a snapshot, shares its blocks with the live files — - and the panel and the review screen say what was left out. A mark whose - volume cannot be told is not claimed either. - -The scan follows [dust](https://github.com/bootandy/dust)'s approach: one rayon -scope per root, a completion counter per directory so no directory is built -before its last subdirectory lands, and one bottom-up pass that aggregates sizes -and removes duplicate hardlinks. - -## Choosing sources and roots - -Launch without a path to choose **This computer** or enter an SSH alias / -`user@host` and press **Connect SSH**. Discovery reads that machine's mount -namespace, not file contents. It never starts a scan or probes mounted -network filesystems just to fill the list. - -Select a mount and choose **Scan selected root**, or enter an absolute -directory path and choose **Scan directory**. Enter acts on the focused -host/path field or the highlighted mount. Escape cancels discovery and -returns to the current scan, or the idle welcome screen at startup. - -During exploration, press `v`, click **Source…** beside the disk name, -or click the disktree logo to reopen the same chooser. The source being -browsed is shown explicitly, and connecting never retargets an existing -scan. Changing machines on acceptance clears the old machine's marks, -identity and navigation history; an absolute path is not an identity -across hosts. A rescan that detects a changed or lost remote machine -identity also clears marks, even if the SSH alias is unchanged. - -Pseudo-filesystems, snapshots and automount triggers are filtered out. -Linux bind mounts and btrfs subvolumes remain individually selectable, -even when they share a device. Free space is measured only after choosing -a root. Explicit command-line paths and `--disk` still start directly; -`ssh HOST --check [PATH]` remains the headless scan command. - -## The whole disk - -Click `/` (or any directory above the scanned root) in the trail, press -`g`, run `disktree --disk`, or use the launcher's *Scan the whole disk* -action. `g` and `--disk` scan the disk your home directory lives on — `/` -on Omarchy and on macOS. On macOS the Data volume's second mount, -`/System/Volumes/Data`, is skipped: it is `/Users`, `/Applications` and the -rest again under other names. - -Widening is memoized: the tree already measured is handed to the wider walk -and reused where it is reached, so going from `~` to `/` reads only what is -outside `~` (on this machine, seconds instead of a full rescan). The current -view stays on screen until the wider tree lands, which then opens with the -directory you came from selected. Going back down is just navigation. - -By default a scan stops at **every nested mount point**, including bind -mounts and same-device btrfs subvolumes. Boundaries are checked by path, -before metadata or directory reads, so an automounted NAS is not activated -just to measure its parent. Choose `/home`, `/var/log`, or another mount as -its own root rather than implicitly traversing it from `/`. - -Local `-X` explicitly crosses mounts; remote streaming scans reject it. -A local mark on another volume is still removed, but is not added to the -metered volume's free-space projection. - -Without root, some system directories cannot be read; they are counted as -unreadable in the top bar rather than guessed at. - -## On Windows - -The same program, with Windows' answers to the questions above: - -- **Disk usage** is the allocation NTFS reports for each file: whole - clusters, less for a compressed or sparse file, nothing for one small - enough to live in its file record. It arrives with the directory listing - itself (`FileIdExtdDirectoryInfo`), so it costs no more than the walk. - Hardlinks count once on NTFS. -- **The whole disk** is the drive your profile is on, usually `C:\`. A - folder another volume is mounted on is a link, like a junction, and is - not entered, so a scan stays on one volume; `-l` follows links, and with - them mounted folders. -- **Run as administrator** and the whole disk is read from NTFS's master - file table instead of walked, as WizTree does: one pass over the table in - large reads. On a 4-million-file `C:\` that took about 3.4 s against 11.2 - s for WizTree and about 20 s for the walk. It also sees what the walk is - refused, such as System Volume Information. It is used only for a whole - NTFS drive, since a folder would still cost the whole table, and not with - `-l`, whose links the table does not follow. disktree flushes the volume - after its own removals so the rescan shows them; changes other programs - made seconds before may not show yet. - Started without admin rights, disktree walks as before. On a whole NTFS - drive without `-l`, or once Windows refuses the walk a folder, the side - panel offers **Restart as Administrator**, which reopens the same folder - and options through the UAC prompt; during a widening scan, the wider - folder being scanned. -- **Move to trash** is the Recycle Bin, through the shell, which asks - before destroying anything it cannot recycle. -- **Refused besides the rules below:** Windows, Program Files and - ProgramData, what Windows keeps at the top of its drive (System Volume - Information, Recovery, Boot, and the page and hibernation files, which - Settings turns off), any folder holding your profile, such as - `C:\Users`, and every profile in the folder Windows keeps them in - (`C:\Users\*`, `Public` and `Default` included), since an elevated - disktree may run as another account and can reach them all. What is - inside a profile can still be removed, as under your own. Names compare - without regard to case, as Windows compares them. -- **Hidden** means a name starting with a dot, or the hidden attribute, so - `-H` drops `AppData` as Explorer hides it. -- **The theme** follows Windows' light or dark setting, since there is no - Omarchy theme to follow. It does on macOS too, and on GNOME and KDE. - -## What it refuses to do - -The removal rules live in `crates/disktree-core/src/removal.rs`, and each one is -tested: - -- only paths under the scanned root can be removed; -- the filesystem root, the scanned root and your home directory are refused; -- a mount point is refused, and so is anything with a mount point inside it, - since removing it would reach into another filesystem; permanent deletion - also stops at a mount boundary rather than descending into one (a btrfs - subvolume that is not mounted goes with its directory, as the scan shows - it); -- a directory holding your home directory or a system tree is refused (on - macOS `/Users` is on the same volume as `/`, and `/opt` holds - `/opt/homebrew`); -- system trees (`/usr`, `/etc`, `/boot`, `/var/lib`, `/nix/store`, - `/gnu/store`, Homebrew's prefix on macOS and Linux, …) are - refused even where permissions would allow it: packages own them, and - pacman, paccache or `journalctl --vacuum` are the tools; -- a symlink is unlinked, never followed; -- nothing is passed through a shell — a file called `-rf` is just a file; -- selecting a checkout never runs a program it names: git is asked with its - fsmonitor, hooks and pager off, and a checkout that defines its own filter - drivers is not asked for its status at all ("changes unknown"). - -## On Hyprland - -Hyprland tiles new windows, so disktree opens into whatever tile it is given. -It is designed for a roomy window; float it, or give it a rule. The window -class is `disktree`. +PwrDisk began as [disktree](https://github.com/tobi/disktree), written by +[Tobi Lütke](https://github.com/tobi). The idea, the design and most of the +code are his and disktree's contributors', and they deserve the credit. -``` -windowrule = float, class:^(disktree)$ -windowrule = size 1400 900, class:^(disktree)$ -``` +Tobi also has a day job running Shopify, which we hear keeps him fairly +busy. So we picked disktree up to keep it fed: signed installers that update +themselves, macOS and Windows builds, and the AI agent link. Fixes that make +sense upstream go back to disktree as pull requests. -## Develop +## Build it yourself ```sh -make run # release build, opening the source/root chooser -make lint # rustfmt --check, then clippy with every warning an error -make test # scanner, layout and removal tests, plus window-harness tests -make test-ssh # real localhost SSH scans/errors; Linux, bun + openssh required -make ci # lint, then test +git clone https://github.com/pwrdrvr/PwrDisk +cd PwrDisk +make install ``` -The lint gate is strict on purpose: `clippy::all` and `clippy::pedantic` are -errors, and every exception is written down with its reason in `Cargo.toml`. -The window-harness tests draw real frames and press real keys — including one -that marks a directory, confirms the deletion and checks that the files are -gone while their neighbours are not. - -| path | what lives there | -| --- | --- | -| `crates/disktree-core` | scanning, the tree, the squarified layout, free space and removal — no UI | -| `crates/disktree-app/src/state.rs` | every action the interface can take, and the key map | -| `crates/disktree-app/src/views.rs` | the screens | -| `crates/disktree-app/src/treemap_view.rs` | painting the mosaic and its labels | -| `crates/disktree-app/src/ui.rs` | the spacing, type and size scale, in `rem` | -| `crates/disktree-app/src/tests.rs` | end-to-end tests through a real window | -| `packaging/`, `assets/`, `Makefile` | the desktop entry, the icon, and install | - -The interface follows the -[GPUI Kit design guides](https://gpui-kit.com/versions/main/docs/design-guides/): -every size is on one `rem` scale so interface zoom keeps its proportions, -primary is reserved for what Enter does, and the only question the app asks is -the one it cannot take back. +[docs/building.md](docs/building.md) has what each system needs, signing +your own Mac build, and how to work on the code. ## License -MIT +MIT. See [LICENSE](LICENSE) and +[THIRD_PARTY_LICENSES](THIRD_PARTY_LICENSES). + +### Cache cleanup + +Marked caches go to **Cache cleanup** in Review, or MCP's +`pwrdisk_removal_preview` with `mode: "owner_cleanup"`. Check owners shows, +for each marked path, the installed owner's exact command, version and +whole-cache scope, or why there is none. You then choose per path: skip it, +run that command, or deliberately delete the files, which has its own +disclosure and its own confirmation. Missing, unsupported, failed or +cancelled owner commands never fall back to deleting files, and unknown +runtime caches are never called disposable. Each path gets its own result; +listed allocation is separate from measured free-space change. See +[supported owners, versions and scope limitations](docs/owner-cleanup.md). diff --git a/THIRD_PARTY_LICENSES b/THIRD_PARTY_LICENSES new file mode 100644 index 00000000..27451016 --- /dev/null +++ b/THIRD_PARTY_LICENSES @@ -0,0 +1,24695 @@ +PwrDisk Third-Party Licenses +============================ + +Generated by `cargo xtask licenses` from Cargo.lock (cargo-about), +licenses/bundled.txt and licenses/velopack.txt. Do not edit this +file by hand. + +PwrDisk's own license, which carries disktree's, is in LICENSE. + +Bundled Non-Cargo Components +---------------------------- + +These ship inside PwrDisk but are not crates, so cargo-about cannot list +them. Edit licenses/bundled.txt when one changes. + +- disktree, by Tobi Lütke, which PwrDisk is a fork of. MIT; its notice is + PwrDisk's own, in LICENSE. +- Velopack's native binaries, added to release packages by `vpk pack` + 1.2.161: Update.exe, Setup.exe and the launcher stub (Windows), the MSI's + velopack_wix custom-action DLL, and UpdateMac (macOS). MIT, Copyright (c) + 2021 Caelan Sayler, Copyright (c) 2024 Velopack Ltd. | https://github.com/velopack/velopack + The Rust crates compiled into them, with their license texts, are under + "Velopack's Native Binaries" below (licenses/velopack.txt, written by + scripts/release/velopack-notices.sh). + +DiskHound artifact classification rules and test corpus +----------------------------------------------------- +https://github.com/huntharo/diskhound + +MIT License + +Copyright (c) 2026 Thomas Zarebczan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +Velopack's Native Binaries +-------------------------- + +The Rust crates compiled into Velopack 1.2.161's Update.exe, Setup.exe, +launcher stub and velopack_wix DLL (Windows x64 and ARM64) and UpdateMac +(macOS), which `vpk pack` adds to PwrDisk's release packages. +Velopack's own crates (velopack, velopack_bins, velopack_l18n, +velopack_wix) are listed too. +Generated by scripts/release/velopack-notices.sh from Velopack's Cargo.lock at +tag 1.2.161; do not edit by hand. + +Dependency Summary +~~~~~~~~~~~~~~~~~~ + +Apache License 2.0 (175) +- num_threads@0.1.7 | https://github.com/jhpratt/num_threads +- powerfmt@0.2.0 | https://github.com/jhpratt/powerfmt +- deranged@0.5.8 | https://github.com/jhpratt/deranged +- ureq-proto@0.6.4 | https://github.com/algesten/ureq-proto +- utf8_iter@1.0.4 | https://github.com/hsivonen/utf8_iter +- zeroize@1.9.0 | https://github.com/RustCrypto/utils +- rustix@1.1.5 | https://github.com/bytecodealliance/rustix +- ring@0.17.14 | https://github.com/briansmith/ring +- fast_image_resize@6.1.0 | https://github.com/cykooz/fast_image_resize +- windows-collections@0.3.2 | https://github.com/microsoft/windows-rs +- windows-core@0.62.2 | https://github.com/microsoft/windows-rs +- windows-future@0.3.2 | https://github.com/microsoft/windows-rs +- windows-implement@0.60.2 | https://github.com/microsoft/windows-rs +- windows-interface@0.59.3 | https://github.com/microsoft/windows-rs +- windows-link@0.2.1 | https://github.com/microsoft/windows-rs +- windows-numerics@0.3.1 | https://github.com/microsoft/windows-rs +- windows-result@0.4.1 | https://github.com/microsoft/windows-rs +- windows-strings@0.5.1 | https://github.com/microsoft/windows-rs +- windows-sys@0.52.0 | https://github.com/microsoft/windows-rs +- windows-sys@0.59.0 | https://github.com/microsoft/windows-rs +- windows-sys@0.61.2 | https://github.com/microsoft/windows-rs +- windows-targets@0.52.6 | https://github.com/microsoft/windows-rs +- windows-threading@0.2.1 | https://github.com/microsoft/windows-rs +- windows@0.62.2 | https://github.com/microsoft/windows-rs +- windows_aarch64_msvc@0.52.6 | https://github.com/microsoft/windows-rs +- windows_x86_64_msvc@0.52.6 | https://github.com/microsoft/windows-rs +- zopfli@0.8.3 | https://github.com/zopfli-rs/zopfli +- web-time@1.1.0 | https://github.com/daxpedda/web-time +- moxcms@0.8.1 | https://github.com/awxkee/moxcms.git +- pxfm@0.1.30 | https://github.com/awxkee/pxfm +- cvt@0.1.2 | https://github.com/marmistrz/cvt +- pretty-bytes-rust@0.3.0 | https://github.com/MrDesjardins/pretty-bytes +- self_cell@1.3.0 | https://github.com/Voultapher/self_cell +- sys-locale@0.3.2 | https://github.com/1Password/sys-locale +- ureq@3.4.2 | https://github.com/algesten/ureq +- zune-core@0.5.3 | https://github.com/etemesi254/zune-image +- zune-jpeg@0.5.15 | https://github.com/etemesi254/zune-image/tree/dev/crates/zune-jpeg +- fluent-bundle@0.16.0 | https://github.com/projectfluent/fluent-rs +- fluent-syntax@0.12.0 | https://github.com/projectfluent/fluent-rs +- fluent@0.17.0 | https://github.com/projectfluent/fluent-rs +- intl-memoizer@0.5.3 | https://github.com/projectfluent/fluent-rs +- clap@4.6.7 | https://github.com/clap-rs/clap +- clap_builder@4.6.7 | https://github.com/clap-rs/clap +- clap_derive@4.6.7 | https://github.com/clap-rs/clap +- clap_lex@1.1.1 | https://github.com/clap-rs/clap +- winapi@0.3.9 | https://github.com/retep998/winapi-rs +- anstream@1.0.0 | https://github.com/rust-cli/anstyle.git +- anstyle-parse@1.0.0 | https://github.com/rust-cli/anstyle.git +- anstyle-query@1.1.5 | https://github.com/rust-cli/anstyle.git +- anstyle-wincon@3.0.11 | https://github.com/rust-cli/anstyle.git +- anstyle@1.0.14 | https://github.com/rust-cli/anstyle.git +- colorchoice@1.0.5 | https://github.com/rust-cli/anstyle.git +- crc32fast@1.5.2 | https://github.com/srijs/rust-crc32fast +- is_terminal_polyfill@1.70.2 | https://github.com/polyfill-rs/is_terminal_polyfill +- log-panics@2.1.0 | https://github.com/sfackler/rust-log-panics +- once_cell_polyfill@1.70.2 | https://github.com/polyfill-rs/once_cell_polyfill +- typenum@1.20.1 | https://github.com/paholg/typenum +- http@1.5.0 | https://github.com/hyperium/http +- iana-time-zone@0.1.65 | https://github.com/strawlab/iana-time-zone +- rustls-pki-types@1.15.1 | https://github.com/rustls/pki-types +- memmap2@0.9.11 | https://github.com/RazrFalcon/memmap2-rs +- gif@0.14.2 | https://github.com/image-rs/image-gif +- weezl@0.1.12 | https://github.com/image-rs/weezl +- aligned@0.4.3 | https://github.com/rust-embedded-community/aligned +- as-slice@0.2.1 | https://github.com/japaric/as-slice +- base64@0.23.1 | https://github.com/marshallpierce/rust-base64 +- bitflags@2.13.2 | https://github.com/bitflags/bitflags +- bumpalo@3.20.3 | https://github.com/fitzgen/bumpalo +- cfg-if@1.0.5 | https://github.com/rust-lang/cfg-if +- core-foundation-sys@0.8.7 | https://github.com/servo/core-foundation-rs +- crossbeam-deque@0.8.8 | https://github.com/crossbeam-rs/crossbeam +- crossbeam-epoch@0.9.21 | https://github.com/crossbeam-rs/crossbeam +- crossbeam-utils@0.8.23 | https://github.com/crossbeam-rs/crossbeam +- derivative@2.2.0 | https://github.com/mcarton/rust-derivative +- displaydoc@0.2.7 | https://github.com/yaahc/displaydoc +- either@1.18.0 | https://github.com/rayon-rs/either +- equivalent@1.0.2 | https://github.com/indexmap-rs/equivalent +- errno@0.3.14 | https://github.com/lambda-fairy/rust-errno +- flate2@1.1.10 | https://github.com/rust-lang/flate2-rs +- fnv@1.0.7 | https://github.com/servo/rust-fnv +- form_urlencoded@1.2.2 | https://github.com/servo/rust-url +- glob@0.3.4 | https://github.com/rust-lang/glob +- hashbrown@0.17.1 | https://github.com/rust-lang/hashbrown +- heck@0.5.0 | https://github.com/withoutboats/heck +- httparse@1.10.1 | https://github.com/seanmonstar/httparse +- idna@1.1.0 | https://github.com/servo/rust-url/ +- idna_adapter@1.2.2 | https://github.com/hsivonen/idna_adapter +- indexmap@2.14.2 | https://github.com/indexmap-rs/indexmap +- lazy_static@1.5.0 | https://github.com/rust-lang-nursery/lazy-static.rs +- log@0.4.34 | https://github.com/rust-lang/log +- num-traits@0.2.19 | https://github.com/rust-num/num-traits +- once_cell@1.21.4 | https://github.com/matklad/once_cell +- percent-encoding@2.3.2 | https://github.com/servo/rust-url/ +- png@0.18.1 | https://github.com/image-rs/image-png +- rayon-core@1.13.0 | https://github.com/rayon-rs/rayon +- rayon@1.12.0 | https://github.com/rayon-rs/rayon +- regex-automata@0.4.18 | https://github.com/rust-lang/regex +- regex-syntax@0.8.11 | https://github.com/rust-lang/regex +- regex@1.13.1 | https://github.com/rust-lang/regex +- ring@0.17.14 | https://github.com/briansmith/ring +- rustix@1.1.5 | https://github.com/bytecodealliance/rustix +- rustls@0.23.45 | https://github.com/rustls/rustls +- smallvec@1.16.1 | https://github.com/servo/rust-smallvec +- stable_deref_trait@1.2.1 | https://github.com/storyyeller/stable_deref_trait +- syn@1.0.109 | https://github.com/dtolnay/syn +- time@0.1.45 | https://github.com/time-rs/time +- unic-langid-impl@0.9.6 | https://github.com/zbraniecki/unic-locale +- unic-langid@0.9.6 | https://github.com/zbraniecki/unic-locale +- url@2.5.8 | https://github.com/servo/rust-url +- uuid@1.26.1 | https://github.com/uuid-rs/uuid +- wait-timeout@0.2.1 | https://github.com/alexcrichton/wait-timeout +- waitpid-any@0.3.0 | https://github.com/oxalica/waitpid-any +- block-buffer@0.12.1 | https://github.com/RustCrypto/utils +- chacha20@0.10.2 | https://github.com/RustCrypto/stream-ciphers +- const-oid@0.10.2 | https://github.com/RustCrypto/formats +- cpufeatures@0.3.1 | https://github.com/RustCrypto/utils +- crypto-common@0.2.2 | https://github.com/RustCrypto/traits +- digest@0.11.3 | https://github.com/RustCrypto/traits +- hybrid-array@0.4.15 | https://github.com/RustCrypto/hybrid-array +- sha1@0.11.0 | https://github.com/RustCrypto/hashes +- sha2@0.11.0 | https://github.com/RustCrypto/hashes +- remove_dir_all@1.0.0 | https://github.com/XAMPPRocky/remove_dir_all.git +- rand_core@0.10.1 | https://github.com/rust-random/rand_core +- getrandom@0.2.17 | https://github.com/rust-random/getrandom +- getrandom@0.4.3 | https://github.com/rust-random/getrandom +- bytemuck@1.25.2 | https://github.com/Lokathor/bytemuck +- simplelog@0.12.2 | https://github.com/drakulix/simplelog.rs +- anyhow@1.0.104 | https://github.com/dtolnay/anyhow +- document-features@0.2.12 | https://github.com/slint-ui/document-features +- fdeflate@0.3.7 | https://github.com/image-rs/fdeflate +- fluent-langneg@0.13.1 | https://github.com/projectfluent/fluent-langneg-rs +- fluent-langneg@0.14.2 | https://github.com/projectfluent/fluent-langneg-rs +- fs_at@0.2.1 | https://github.com/rbtcollins/fs_at.git +- image@0.25.10 | https://github.com/image-rs/image +- intl_pluralrules@7.0.2 | https://github.com/zbraniecki/pluralrules +- itoa@1.0.18 | https://github.com/dtolnay/itoa +- libc@0.2.189 | https://github.com/rust-lang/libc +- litrs@1.0.0 | https://github.com/LukasKalbertodt/litrs +- miniz_oxide@0.8.9 | https://github.com/Frommi/miniz_oxide/tree/master/miniz_oxide +- miniz_oxide@0.9.1 | https://github.com/Frommi/miniz_oxide/tree/master/miniz_oxide +- normpath@1.5.2 | https://github.com/dylni/normpath +- num-conv@0.2.2 | https://github.com/jhpratt/num-conv +- objc2-app-kit@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-cloud-kit@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-core-data@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-core-foundation@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-core-graphics@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-core-image@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-core-text@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-core-video@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-quartz-core@0.3.2 | https://github.com/madsmtm/objc2 +- oneshot@0.2.1 | https://github.com/faern/oneshot +- proc-macro2@1.0.107 | https://github.com/dtolnay/proc-macro2 +- quote@1.0.47 | https://github.com/dtolnay/quote +- rand@0.10.3 | https://github.com/rust-random/rand +- rustc-hash@2.1.3 | https://github.com/rust-lang/rustc-hash +- semver@1.0.28 | https://github.com/dtolnay/semver +- serde@1.0.229 | https://github.com/serde-rs/serde +- serde_core@1.0.229 | https://github.com/serde-rs/serde +- serde_derive@1.0.229 | https://github.com/serde-rs/serde +- serde_json@1.0.151 | https://github.com/serde-rs/json +- syn@2.0.119 | https://github.com/dtolnay/syn +- syn@3.0.6 | https://github.com/dtolnay/syn +- thiserror-impl@2.0.20 | https://github.com/dtolnay/thiserror +- thiserror@2.0.20 | https://github.com/dtolnay/thiserror +- time-core@0.1.9 | https://github.com/time-rs/time +- time-macros@0.2.32 | https://github.com/time-rs/time +- time@0.3.55 | https://github.com/time-rs/time +- type-map@0.5.1 | https://github.com/kardeiz/type-map +- typed-path@0.12.3 | https://github.com/chipsenkbeil/typed-path +- unicode-ident@1.0.26 | https://github.com/dtolnay/unicode-ident +- utf8-zero@0.8.1 | https://github.com/algesten/utf8-zero +- utf8parse@0.2.2 | https://github.com/alacritty/vte +- widestring@1.2.1 | https://github.com/VoidStarKat/widestring-rs +- chrono@0.4.45 | https://github.com/chronotope/chrono + +MIT License (36) +- winreg@0.56.0 | https://github.com/gentoo90/winreg-rs +- bytes@1.12.1 | https://github.com/tokio-rs/bytes +- synstructure@0.13.2 | https://github.com/mystor/synstructure +- synstructure@0.14.0 | https://github.com/mystor/synstructure +- velopack_bins@0.0.0-local | https://github.com/velopack/velopack +- velopack_l18n@0.0.0-local +- velopack@0.0.0-local | https://github.com/velopack/velopack +- velopack_wix@0.0.0-local | https://github.com/velopack/velopack +- xdialog@3.1.9 | https://github.com/velopack/xdialog +- fs_extra@1.3.0 | https://github.com/webdesus/fs_extra +- cfb@0.15.0 | https://github.com/mdsteele/rust-cfb +- simple-stopwatch@0.1.4 | https://github.com/huwb/rust-simple-stopwatch +- progress-streams@1.1.0 | https://github.com/pop-os/progress-streams +- strum@0.28.0 | https://github.com/Peternator7/strum +- strum_macros@0.28.0 | https://github.com/Peternator7/strum +- block2@0.6.2 | https://github.com/madsmtm/objc2 +- objc2-encode@4.1.0 | https://github.com/madsmtm/objc2 +- objc2-foundation@0.3.2 | https://github.com/madsmtm/objc2 +- objc2@0.6.4 | https://github.com/madsmtm/objc2 +- webview2-com-sys@0.39.1 | https://github.com/wravery/webview2-rs +- simd-adler32@0.3.10 | https://github.com/mcountryman/simd-adler32 +- zmij@1.0.23 | https://github.com/dtolnay/zmij +- zip@8.6.0 | https://github.com/zip-rs/zip2 +- xml@1.4.0 | https://github.com/kornelski/xml-rs +- aho-corasick@1.1.5 | https://github.com/BurntSushi/aho-corasick +- byteorder-lite@0.1.0 | https://github.com/image-rs/byteorder-lite +- memchr@2.8.3 | https://github.com/BurntSushi/memchr +- termcolor@1.4.1 | https://github.com/BurntSushi/termcolor +- walkdir@2.5.0 | https://github.com/BurntSushi/walkdir +- nix@0.29.0 | https://github.com/nix-rust/nix +- nix@0.31.3 | https://github.com/nix-rust/nix +- strsim@0.11.1 | https://github.com/rapidfuzz/strsim-rs +- color_quant@1.1.0 | https://github.com/image-rs/color_quant.git +- same-file@1.0.6 | https://github.com/BurntSushi/same-file +- winapi-util@0.1.11 | https://github.com/BurntSushi/winapi-util +- os_info@3.15.0 | https://github.com/stanislav-tkach/os_info + +Unicode License v3 (31) +- unicode-ident@1.0.26 | https://github.com/dtolnay/unicode-ident +- icu_collections@2.3.0 | https://github.com/unicode-org/icu4x +- icu_locale_core@2.3.0 | https://github.com/unicode-org/icu4x +- icu_locid@1.5.0 | https://github.com/unicode-org/icu4x +- icu_locid_transform@1.5.0 | https://github.com/unicode-org/icu4x +- icu_locid_transform_data@1.5.1 | https://github.com/unicode-org/icu4x +- icu_normalizer@2.3.0 | https://github.com/unicode-org/icu4x +- icu_normalizer_data@2.3.0 | https://github.com/unicode-org/icu4x +- icu_properties@2.3.0 | https://github.com/unicode-org/icu4x +- icu_properties_data@2.3.0 | https://github.com/unicode-org/icu4x +- icu_provider@1.5.0 | https://github.com/unicode-org/icu4x +- icu_provider@2.3.1 | https://github.com/unicode-org/icu4x +- icu_provider_macros@1.5.0 | https://github.com/unicode-org/icu4x +- litemap@0.7.5 | https://github.com/unicode-org/icu4x +- litemap@0.8.3 | https://github.com/unicode-org/icu4x +- potential_utf@0.1.6 | https://github.com/unicode-org/icu4x +- tinystr@0.7.6 | https://github.com/unicode-org/icu4x +- tinystr@0.8.4 | https://github.com/unicode-org/icu4x +- writeable@0.5.5 | https://github.com/unicode-org/icu4x +- writeable@0.6.4 | https://github.com/unicode-org/icu4x +- yoke-derive@0.7.5 | https://github.com/unicode-org/icu4x +- yoke-derive@0.8.3 | https://github.com/unicode-org/icu4x +- yoke@0.7.5 | https://github.com/unicode-org/icu4x +- yoke@0.8.3 | https://github.com/unicode-org/icu4x +- zerofrom-derive@0.1.8 | https://github.com/unicode-org/icu4x +- zerofrom@0.1.8 | https://github.com/unicode-org/icu4x +- zerotrie@0.2.5 | https://github.com/unicode-org/icu4x +- zerovec-derive@0.10.4 | https://github.com/unicode-org/icu4x +- zerovec-derive@0.11.6 | https://github.com/unicode-org/icu4x +- zerovec@0.10.4 | https://github.com/unicode-org/icu4x +- zerovec@0.11.8 | https://github.com/unicode-org/icu4x + +ISC License (19) +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- untrusted@0.9.0 | https://github.com/briansmith/untrusted +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- libloading@0.9.0 | https://github.com/nagisa/rust_libloading/ +- rustls-webpki@0.103.15 | https://github.com/rustls/webpki + +BSD 3-Clause "New" or "Revised" License (7) +- zstd-safe@8.0.0 | https://github.com/gyscos/zstd-rs +- zstd-sys@2.1.0+zstd.1.5.7 | https://github.com/gyscos/zstd-rs +- zstd@0.14.0 | https://github.com/gyscos/zstd-rs +- zstd-sys@2.1.0+zstd.1.5.7 | https://github.com/gyscos/zstd-rs +- subtle@2.6.1 | https://github.com/dalek-cryptography/subtle +- sha1_smol@1.0.1 | https://github.com/mitsuhiko/sha1-smol +- zstd-sys@2.1.0+zstd.1.5.7 | https://github.com/gyscos/zstd-rs + +BSD Zero Clause License (1) +- adler2@2.0.1 | https://github.com/oyvindln/adler2 + +Community Data License Agreement Permissive 2.0 (1) +- webpki-roots@1.0.9 | https://github.com/rustls/webpki-roots + +zlib License (1) +- zlib-rs@0.6.8 | https://github.com/trifectatechfoundation/zlib-rs + +License Texts +~~~~~~~~~~~~~ + +BSD Zero Clause License (0BSD) +----------------------------------------------------------- + +Applies to: +- adler2@2.0.1 + +Copyright (C) Jonas Schievink + +Permission to use, copy, modify, and/or distribute this software for +any purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN +AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- num_threads@0.1.7 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2021 Jacob Pratt + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- powerfmt@0.2.0 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023 Jacob Pratt et al. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- deranged@0.5.8 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 Jacob Pratt et al. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- ureq-proto@0.6.4 +- utf8_iter@1.0.4 +- zeroize@1.9.0 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- rustix@1.1.5 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +--- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Licenses for support code +------------------------- + +Parts of the TLS test suite are under the Go license. This code is not included +in BoringSSL (i.e. libcrypto and libssl) when compiled, however, so +distributing code linked against BoringSSL does not trigger this license: + +Copyright (c) 2009 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BoringSSL uses the Chromium test infrastructure to run a continuous build, +trybots etc. The scripts which manage this, and the script for generating build +metadata, are under the Chromium license. Distributing code linked against +BoringSSL does not trigger this license. + +Copyright 2015 The Chromium Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- fast_image_resize@6.1.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright (c) 2021 Kirill Kuzminykh + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- windows-collections@0.3.2 +- windows-core@0.62.2 +- windows-future@0.3.2 +- windows-implement@0.60.2 +- windows-interface@0.59.3 +- windows-link@0.2.1 +- windows-numerics@0.3.1 +- windows-result@0.4.1 +- windows-strings@0.5.1 +- windows-sys@0.52.0 +- windows-sys@0.59.0 +- windows-sys@0.61.2 +- windows-targets@0.52.6 +- windows-threading@0.2.1 +- windows@0.62.2 +- windows_aarch64_msvc@0.52.6 +- windows_x86_64_msvc@0.52.6 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright (c) Microsoft Corporation. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- zopfli@0.8.3 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2011 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- web-time@1.1.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023 dAxpeDDa + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- moxcms@0.8.1 +- pxfm@0.1.30 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 Radzivon Bartoshyk + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- cvt@0.1.2 +- pretty-bytes-rust@0.3.0 +- self_cell@1.3.0 +- sys-locale@0.3.2 +- ureq@3.4.2 +- zune-core@0.5.3 +- zune-jpeg@0.5.15 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- fluent-bundle@0.16.0 +- fluent-syntax@0.12.0 +- fluent@0.17.0 +- intl-memoizer@0.5.3 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017 Mozilla + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- clap@4.6.7 +- clap_builder@4.6.7 +- clap_derive@4.6.7 +- clap_lex@1.1.1 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright Individual contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- winapi@0.3.9 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- anstream@1.0.0 +- anstyle-parse@1.0.0 +- anstyle-query@1.1.5 +- anstyle-wincon@3.0.11 +- anstyle@1.0.14 +- colorchoice@1.0.5 +- crc32fast@1.5.2 +- is_terminal_polyfill@1.70.2 +- log-panics@2.1.0 +- once_cell_polyfill@1.70.2 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- typenum@1.20.1 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2014 Paho Lurie-Gregg + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- http@1.5.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2017 http-rs authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- iana-time-zone@0.1.65 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2020 Andrew Straw + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- rustls-pki-types@1.15.1 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2023 Dirkjan Ochtman + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- memmap2@0.9.11 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [2015] [Dan Burkert] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- gif@0.14.2 +- weezl@0.1.12 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- aligned@0.4.3 +- as-slice@0.2.1 +- base64@0.23.1 +- bitflags@2.13.2 +- bumpalo@3.20.3 +- cfg-if@1.0.5 +- core-foundation-sys@0.8.7 +- crossbeam-deque@0.8.8 +- crossbeam-epoch@0.9.21 +- crossbeam-utils@0.8.23 +- derivative@2.2.0 +- displaydoc@0.2.7 +- either@1.18.0 +- equivalent@1.0.2 +- errno@0.3.14 +- flate2@1.1.10 +- fnv@1.0.7 +- form_urlencoded@1.2.2 +- glob@0.3.4 +- hashbrown@0.17.1 +- heck@0.5.0 +- httparse@1.10.1 +- idna@1.1.0 +- idna_adapter@1.2.2 +- indexmap@2.14.2 +- lazy_static@1.5.0 +- log@0.4.34 +- num-traits@0.2.19 +- once_cell@1.21.4 +- percent-encoding@2.3.2 +- png@0.18.1 +- rayon-core@1.13.0 +- rayon@1.12.0 +- regex-automata@0.4.18 +- regex-syntax@0.8.11 +- regex@1.13.1 +- ring@0.17.14 +- rustix@1.1.5 +- rustls@0.23.45 +- smallvec@1.16.1 +- stable_deref_trait@1.2.1 +- syn@1.0.109 +- time@0.1.45 +- unic-langid-impl@0.9.6 +- unic-langid@0.9.6 +- url@2.5.8 +- uuid@1.26.1 +- wait-timeout@0.2.1 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- waitpid-any@0.3.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- block-buffer@0.12.1 +- chacha20@0.10.2 +- const-oid@0.10.2 +- cpufeatures@0.3.1 +- crypto-common@0.2.2 +- digest@0.11.3 +- hybrid-array@0.4.15 +- sha1@0.11.0 +- sha2@0.11.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- remove_dir_all@1.0.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +Copyright 2017 Aaron Power + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- rand_core@0.10.1 + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- getrandom@0.2.17 +- getrandom@0.4.3 + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- bytemuck@1.25.2 + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + + "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- simplelog@0.12.2 + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, +and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by +the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all +other entities that control, are controlled by, or are under common +control with that entity. For the purposes of this definition, +"control" means (i) the power, direct or indirect, to cause the +direction or management of such entity, whether by contract or +otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity +exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, +including but not limited to software source code, documentation +source, and configuration files. + +"Object" form shall mean any form resulting from mechanical +transformation or translation of a Source form, including but +not limited to compiled object code, generated documentation, +and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or +Object form, made available under the License, as indicated by a +copyright notice that is included in or attached to the work +(an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object +form, that is based on (or derived from) the Work and for which the +editorial revisions, annotations, elaborations, or other modifications +represent, as a whole, an original work of authorship. For the purposes +of this License, Derivative Works shall not include works that remain +separable from, or merely link (or bind by name) to the interfaces of, +the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including +the original version of the Work and any modifications or additions +to that Work or Derivative Works thereof, that is intentionally +submitted to Licensor for inclusion in the Work by the copyright owner +or by an individual or Legal Entity authorized to submit on behalf of +the copyright owner. For the purposes of this definition, "submitted" +means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, +and issue tracking systems that are managed by, or on behalf of, the +Licensor for the purpose of discussing and improving the Work, but +excluding communication that is conspicuously marked or otherwise +designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity +on behalf of whom a Contribution has been received by Licensor and +subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the +Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +(except as stated in this section) patent license to make, have made, +use, offer to sell, sell, import, and otherwise transfer the Work, +where such license applies only to those patent claims licensable +by such Contributor that are necessarily infringed by their +Contribution(s) alone or by combination of their Contribution(s) +with the Work to which such Contribution(s) was submitted. If You +institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work +or a Contribution incorporated within the Work constitutes direct +or contributory patent infringement, then any patent licenses +granted to You under this License for that Work shall terminate +as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the +Work or Derivative Works thereof in any medium, with or without +modifications, and in Source or Object form, provided that You +meet the following conditions: + +(a) You must give any other recipients of the Work or +Derivative Works a copy of this License; and + +(b) You must cause any modified files to carry prominent notices +stating that You changed the files; and + +(c) You must retain, in the Source form of any Derivative Works +that You distribute, all copyright, patent, trademark, and +attribution notices from the Source form of the Work, +excluding those notices that do not pertain to any part of +the Derivative Works; and + +(d) If the Work includes a "NOTICE" text file as part of its +distribution, then any Derivative Works that You distribute must +include a readable copy of the attribution notices contained +within such NOTICE file, excluding those notices that do not +pertain to any part of the Derivative Works, in at least one +of the following places: within a NOTICE text file distributed +as part of the Derivative Works; within the Source form or +documentation, if provided along with the Derivative Works; or, +within a display generated by the Derivative Works, if and +wherever such third-party notices normally appear. The contents +of the NOTICE file are for informational purposes only and +do not modify the License. You may add Your own attribution +notices within Derivative Works that You distribute, alongside +or as an addendum to the NOTICE text from the Work, provided +that such additional attribution notices cannot be construed +as modifying the License. + +You may add Your own copyright statement to Your modifications and +may provide additional or different license terms and conditions +for use, reproduction, or distribution of Your modifications, or +for any such Derivative Works as a whole, provided Your use, +reproduction, and distribution of the Work otherwise complies with +the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, +any Contribution intentionally submitted for inclusion in the Work +by You to the Licensor shall be under the terms and conditions of +this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify +the terms of any separate license agreement you may have executed +with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade +names, trademarks, service marks, or product names of the Licensor, +except as required for reasonable and customary use in describing the +origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or +agreed to in writing, Licensor provides the Work (and each +Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +implied, including, without limitation, any warranties or conditions +of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A +PARTICULAR PURPOSE. You are solely responsible for determining the +appropriateness of using or redistributing the Work and assume any +risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, +whether in tort (including negligence), contract, or otherwise, +unless required by applicable law (such as deliberate and grossly +negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, +incidental, or consequential damages of any character arising as a +result of this License or out of the use or inability to use the +Work (including but not limited to damages for loss of goodwill, +work stoppage, computer failure or malfunction, or any and all +other commercial damages or losses), even if such Contributor +has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing +the Work or Derivative Works thereof, You may choose to offer, +and charge a fee for, acceptance of support, warranty, indemnity, +or other liability obligations and/or rights consistent with this +License. However, in accepting such obligations, You may act only +on Your own behalf and on Your sole responsibility, not on behalf +of any other Contributor, and only if You agree to indemnify, +defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason +of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following +boilerplate notice, with the fields enclosed by brackets "{}" +replaced with your own identifying information. (Don't include +the brackets!) The text should be enclosed in the appropriate +comment syntax for the file format. We also recommend that a +file or class name and description of purpose be included on the +same "printed page" as the copyright notice for easier +identification within third-party archives. + +Copyright {yyyy} {name of copyright owner} + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- anyhow@1.0.104 +- document-features@0.2.12 +- fdeflate@0.3.7 +- fluent-langneg@0.13.1 +- fluent-langneg@0.14.2 +- fs_at@0.2.1 +- image@0.25.10 +- intl_pluralrules@7.0.2 +- itoa@1.0.18 +- libc@0.2.189 +- litrs@1.0.0 +- miniz_oxide@0.8.9 +- miniz_oxide@0.9.1 +- normpath@1.5.2 +- num-conv@0.2.2 +- objc2-app-kit@0.3.2 +- objc2-cloud-kit@0.3.2 +- objc2-core-data@0.3.2 +- objc2-core-foundation@0.3.2 +- objc2-core-graphics@0.3.2 +- objc2-core-image@0.3.2 +- objc2-core-text@0.3.2 +- objc2-core-video@0.3.2 +- objc2-quartz-core@0.3.2 +- oneshot@0.2.1 +- proc-macro2@1.0.107 +- quote@1.0.47 +- rand@0.10.3 +- rustc-hash@2.1.3 +- semver@1.0.28 +- serde@1.0.229 +- serde_core@1.0.229 +- serde_derive@1.0.229 +- serde_json@1.0.151 +- syn@2.0.119 +- syn@3.0.6 +- thiserror-impl@2.0.20 +- thiserror@2.0.20 +- time-core@0.1.9 +- time-macros@0.2.32 +- time@0.3.55 +- type-map@0.5.1 +- typed-path@0.12.3 +- unicode-ident@1.0.26 +- utf8-zero@0.8.1 +- utf8parse@0.2.2 +- widestring@1.2.1 + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- chrono@0.4.45 + +Rust-chrono is dual-licensed under The MIT License [1] and +Apache 2.0 License [2]. Copyright (c) 2014--2026, Kang Seonghoon and +contributors. + +Nota Bene: This is same as the Rust Project's own license. + + +[1]: , which is reproduced below: + +~~~~ +The MIT License (MIT) + +Copyright (c) 2014, Kang Seonghoon. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +~~~~ + + +[2]: , which is reproduced below: + +~~~~ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +~~~~ + + + +BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) +----------------------------------------------------------- + +Applies to: +- zstd-safe@8.0.0 +- zstd-sys@2.1.0+zstd.1.5.7 +- zstd@0.14.0 + +BSD 3-Clause License + +Copyright (c) 2026, Alexandre Bury + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) +----------------------------------------------------------- + +Applies to: +- zstd-sys@2.1.0+zstd.1.5.7 + +BSD License + +For Zstandard software + +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook, nor Meta, nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) +----------------------------------------------------------- + +Applies to: +- subtle@2.6.1 + +Copyright (c) 2016-2017 Isis Agora Lovecruft, Henry de Valence. All rights reserved. +Copyright (c) 2016-2024 Isis Agora Lovecruft. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) +----------------------------------------------------------- + +Applies to: +- sha1_smol@1.0.1 + +Copyright (c) . + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) +----------------------------------------------------------- + +Applies to: +- zstd-sys@2.1.0+zstd.1.5.7 + +The auto-generated bindings are under the 3-clause BSD license: + +BSD License + +For Zstandard software + +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook, nor Meta, nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +Community Data License Agreement Permissive 2.0 (CDLA-Permissive-2.0) +----------------------------------------------------------- + +Applies to: +- webpki-roots@1.0.9 + +# Community Data License Agreement - Permissive - Version 2.0 + +This is the Community Data License Agreement - Permissive, Version +2.0 (the "agreement"). Data Provider(s) and Data Recipient(s) agree +as follows: + +## 1. Provision of the Data + +1.1. A Data Recipient may use, modify, and share the Data made +available by Data Provider(s) under this agreement if that Data +Recipient follows the terms of this agreement. + +1.2. This agreement does not impose any restriction on a Data +Recipient's use, modification, or sharing of any portions of the +Data that are in the public domain or that may be used, modified, +or shared under any other legal exception or limitation. + +## 2. Conditions for Sharing Data + +2.1. A Data Recipient may share Data, with or without modifications, so +long as the Data Recipient makes available the text of this agreement +with the shared Data. + +## 3. No Restrictions on Results + +3.1. This agreement does not impose any restriction or obligations +with respect to the use, modification, or sharing of Results. + +## 4. No Warranty; Limitation of Liability + +4.1. All Data Recipients receive the Data subject to the following +terms: + +THE DATA IS PROVIDED ON AN "AS IS" BASIS, WITHOUT REPRESENTATIONS, +WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED +INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, +NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +NO DATA PROVIDER SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING +WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE DATA OR RESULTS, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +## 5. Definitions + +5.1. "Data" means the material received by a Data Recipient under +this agreement. + +5.2. "Data Provider" means any person who is the source of Data +provided under this agreement and in reliance on a Data Recipient's +agreement to its terms. + +5.3. "Data Recipient" means any person who receives Data directly +or indirectly from a Data Provider and agrees to the terms of this +agreement. + +5.4. "Results" means any outcome obtained by computational analysis +of Data, including for example machine learning models and models' +insights. + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +/* Copyright (c) 2014, Intel Corporation. + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION + * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ + +#ifndef OPENSSL_HEADER_EC_ECP_NISTZ384_H +#define OPENSSL_HEADER_EC_ECP_NISTZ384_H + +#include "../../limbs/limbs.h" + +#define P384_LIMBS (384u / LIMB_BITS) + +typedef struct { + Limb X[P384_LIMBS]; + Limb Y[P384_LIMBS]; + Limb Z[P384_LIMBS]; +} P384_POINT; + +typedef struct { + Limb X[P384_LIMBS]; + Limb Y[P384_LIMBS]; +} P384_POINT_AFFINE; + + +#endif // OPENSSL_HEADER_EC_ECP_NISTZ384_H + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2015-2016 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +//! EdDSA Signatures. + +use super::ops::ELEM_LEN; +use crate::digest; + +pub mod signing; +pub mod verification; + +/// The length of an Ed25519 public key. +pub const ED25519_PUBLIC_KEY_LEN: usize = ELEM_LEN; + +pub fn eddsa_digest(signature_r: &[u8], public_key: &[u8], msg: &[u8]) -> digest::Digest { + let mut ctx = digest::Context::new(&digest::SHA512); + ctx.update(signature_r); + ctx.update(public_key); + ctx.update(msg); + ctx.finish() +} + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- untrusted@0.9.0 + +// Copyright 2015-2016 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2015-2022 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +use crate::limb::Limb; + +#[derive(Clone, Copy)] +#[repr(transparent)] +pub struct N0([Limb; 2]); + +impl N0 { + #[cfg(feature = "alloc")] + pub(super) const LIMBS_USED: usize = 64 / crate::limb::LIMB_BITS; + + #[inline] + pub const fn precalculated(n0: u64) -> Self { + #[cfg(target_pointer_width = "64")] + { + Self([n0, 0]) + } + + #[cfg(target_pointer_width = "32")] + { + Self([n0 as Limb, (n0 >> crate::limb::LIMB_BITS) as Limb]) + } + } +} + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2015-2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +use crate::{bb, error}; + +#[deprecated( + note = "To be removed. Internal function not intended for external use with no promises regarding side channels." +)] +pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> { + bb::verify_slices_are_equal(a, b) +} + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2016 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +//! Elliptic curve operations and schemes using Curve25519. + +pub mod ed25519; + +pub mod x25519; + +mod ops; +mod scalar; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2016-2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +use crate::error::{KeyRejected, Unspecified}; + +impl From for Unspecified { + fn from(source: untrusted::EndOfInput) -> Self { + super::erase(source) + } +} + +impl From for Unspecified { + fn from(source: core::array::TryFromSliceError) -> Self { + super::erase(source) + } +} + +impl From for Unspecified { + fn from(source: KeyRejected) -> Self { + super::erase(source) + } +} + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2018 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +//! Serialization and deserialization. + +#[doc(hidden)] +pub mod der; + +#[cfg(feature = "alloc")] +mod writer; + +#[cfg(feature = "alloc")] +pub(crate) mod der_writer; + +pub(crate) mod positive; + +pub use self::positive::Positive; + +#[cfg(feature = "alloc")] +pub(crate) use self::writer::TooLongError; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2019-2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +use super::BlockLen; + +pub(super) use self::{ + sha2_32::{block_data_order_32, State32, SHA256_BLOCK_LEN}, + sha2_64::{block_data_order_64, State64, SHA512_BLOCK_LEN}, +}; + +pub(super) const CHAINING_WORDS: usize = 8; + +#[cfg(any( + all(target_arch = "aarch64", target_endian = "little"), + all(target_arch = "arm", target_endian = "little"), + target_arch = "x86_64" +))] +#[macro_use] +mod ffi; + +pub(super) mod fallback; +mod sha2_32; +mod sha2_64; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// TODO(MSRV 1.76): Replace with `core::ptr::from_mut`. +#[allow(dead_code)] +#[inline(always)] +pub fn from_mut(r: &mut T) -> *mut T { + r +} + +// TODO(MSRV 1.76): Replace with `core::ptr::from_ref`. +#[allow(dead_code)] +#[inline(always)] +pub const fn from_ref(r: &T) -> *const T { + r +} + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +//! Integration tests for non-public APIs. + +mod bits_tests; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +pub use self::{ + array::Array, + base::{IndexError, Overlapping}, + partial_block::PartialBlock, +}; + +mod array; +mod base; +mod partial_block; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +#![cfg(all(target_arch = "aarch64", target_endian = "little"))] + +pub(in super::super) mod mont; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +#![cfg(target_arch = "x86_64")] + +pub(in super::super::super) mod mont; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +mod storage; + +pub(super) use self::storage::{AlignedStorage, LIMBS_PER_CHUNK}; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +pub(super) mod aarch64; +pub(super) mod x86_64; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +Copyright 2015-2025 Brian Smith. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- libloading@0.9.0 + +Copyright © 2015, Simonas Kazlauskas + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without +fee is hereby granted, provided that the above copyright notice and this permission notice appear +in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE +AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, +NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- rustls-webpki@0.103.15 + +Except as otherwise noted, this project is licensed under the following +(ISC-style) terms: + +Copyright 2015 Brian Smith. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +The files under third-party/chromium are licensed as described in +third-party/chromium/LICENSE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- winreg@0.56.0 + +Copyright (c) 2015 Igor Shaula + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- bytes@1.12.1 + +Copyright (c) 2018 Carl Lerche + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- synstructure@0.13.2 +- synstructure@0.14.0 + +Copyright 2016 Nika Layzell + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- velopack_bins@0.0.0-local +- velopack_l18n@0.0.0-local +- velopack@0.0.0-local +- velopack_wix@0.0.0-local + +Copyright © 2021 Caelan Sayler +Copyright © 2024 Velopack Ltd. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- xdialog@3.1.9 + +Copyright © 2024 Caelan Sayler, Velopack Ltd. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- fs_extra@1.3.0 + +MIT License + +Copyright (c) 2017 Denis Kurilenko + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- cfb@0.15.0 + +MIT License + +Copyright (c) 2017 Matthew D. Steele + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- simple-stopwatch@0.1.4 + +MIT License + +Copyright (c) 2018 Huw Bowles + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- progress-streams@1.1.0 + +MIT License + +Copyright (c) 2018 System76 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- strum@0.28.0 +- strum_macros@0.28.0 + +MIT License + +Copyright (c) 2019 Peter Glotfelty + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- block2@0.6.2 +- objc2-encode@4.1.0 +- objc2-foundation@0.3.2 +- objc2@0.6.4 +- webview2-com-sys@0.39.1 + +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- simd-adler32@0.3.10 + +MIT License + +Copyright (c) [2021] [Marvin Countryman] + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- zmij@1.0.23 + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- zip@8.6.0 + +The MIT License (MIT) + +Copyright (c) 2014 Mathijs van de Nes + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- xml@1.4.0 + +The MIT License (MIT) + +Copyright (c) 2014 Vladimir Matveev + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- aho-corasick@1.1.5 +- byteorder-lite@0.1.0 +- memchr@2.8.3 +- termcolor@1.4.1 +- walkdir@2.5.0 + +The MIT License (MIT) + +Copyright (c) 2015 Andrew Gallant + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- nix@0.29.0 +- nix@0.31.3 + +The MIT License (MIT) + +Copyright (c) 2015 Carl Lerche + nix-rust Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- strsim@0.11.1 + +The MIT License (MIT) + +Copyright (c) 2015 Danny Guo +Copyright (c) 2016 Titus Wormer +Copyright (c) 2018 Akash Kurdekar + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- color_quant@1.1.0 + +The MIT License (MIT) + +Copyright (c) 2016 PistonDevelopers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- same-file@1.0.6 +- winapi-util@0.1.11 + +The MIT License (MIT) + +Copyright (c) 2017 Andrew Gallant + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- os_info@3.15.0 + +The MIT License (MIT) + +Copyright (c) 2017 Stanislav Tkach + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +Unicode License v3 (Unicode-3.0) +----------------------------------------------------------- + +Applies to: +- unicode-ident@1.0.26 + +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2023 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. + + +Unicode License v3 (Unicode-3.0) +----------------------------------------------------------- + +Applies to: +- icu_collections@2.3.0 +- icu_locale_core@2.3.0 +- icu_locid@1.5.0 +- icu_locid_transform@1.5.0 +- icu_locid_transform_data@1.5.1 +- icu_normalizer@2.3.0 +- icu_normalizer_data@2.3.0 +- icu_properties@2.3.0 +- icu_properties_data@2.3.0 +- icu_provider@1.5.0 +- icu_provider@2.3.1 +- icu_provider_macros@1.5.0 +- litemap@0.7.5 +- litemap@0.8.3 +- potential_utf@0.1.6 +- tinystr@0.7.6 +- tinystr@0.8.4 +- writeable@0.5.5 +- writeable@0.6.4 +- yoke-derive@0.7.5 +- yoke-derive@0.8.3 +- yoke@0.7.5 +- yoke@0.8.3 +- zerofrom-derive@0.1.8 +- zerofrom@0.1.8 +- zerotrie@0.2.5 +- zerovec-derive@0.10.4 +- zerovec-derive@0.11.6 +- zerovec@0.10.4 +- zerovec@0.11.8 + +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 2020-2024 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. + +SPDX-License-Identifier: Unicode-3.0 + +— + +Portions of ICU4X may have been adapted from ICU4C and/or ICU4J. +ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others. + + +zlib License (Zlib) +----------------------------------------------------------- + +Applies to: +- zlib-rs@0.6.8 + +(C) 2024 Trifecta Tech Foundation + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + +3. This notice may not be removed or altered from any source distribution. + + +Crates +------ + +The Rust crates compiled into PwrDisk, for the platforms releases are built +for. Workspace crates (PwrDisk's own, MIT) are not listed. + +Dependency Summary +~~~~~~~~~~~~~~~~~~ + +Apache License 2.0 (468) +- xkeysym@0.2.1 | https://github.com/notgull/xkeysym +- powerfmt@0.2.0 | https://github.com/jhpratt/powerfmt +- deranged@0.5.8 | https://github.com/jhpratt/deranged +- as-raw-xcb-connection@1.0.1 | https://github.com/psychon/as-raw-xcb-connection +- encoding_rs@0.8.41 | https://github.com/hsivonen/encoding_rs +- kurbo@0.13.1 | https://github.com/linebender/kurbo +- multiversion-macros@0.9.0 | https://github.com/calebzulawski/multiversion +- multiversion@0.9.0 | https://github.com/calebzulawski/multiversion +- multiversion_no_op@1.0.0 | https://github.com/hsivonen/multiversion_no_op +- polycool@0.4.0 | https://github.com/linebender/kurbo +- raw-window-metal@1.1.0 | https://github.com/rust-windowing/raw-window-metal +- static_assertions@1.1.0 | https://github.com/nvzqz/static-assertions-rs +- tinyvec@1.13.3 | https://github.com/Lokathor/tinyvec +- ureq-proto@0.6.5 | https://github.com/algesten/ureq-proto +- utf8_iter@1.0.4 | https://github.com/hsivonen/utf8_iter +- x11rb-protocol@0.13.2 | https://github.com/psychon/x11rb +- x11rb@0.13.2 | https://github.com/psychon/x11rb +- zeroize@1.9.0 | https://github.com/RustCrypto/utils +- zeroize_derive@1.5.0 | https://github.com/RustCrypto/utils +- linux-raw-sys@0.12.1 | https://github.com/sunfishcode/linux-raw-sys +- rustix@1.1.4 | https://github.com/bytecodealliance/rustix +- ring@0.17.14 | https://github.com/briansmith/ring +- rangemap@1.8.0 | https://github.com/jeffparsons/rangemap +- windows-collections@0.2.0 | https://github.com/microsoft/windows-rs +- windows-collections@0.3.2 | https://github.com/microsoft/windows-rs +- windows-core@0.57.0 | https://github.com/microsoft/windows-rs +- windows-core@0.58.0 | https://github.com/microsoft/windows-rs +- windows-core@0.61.2 | https://github.com/microsoft/windows-rs +- windows-core@0.62.2 | https://github.com/microsoft/windows-rs +- windows-future@0.2.1 | https://github.com/microsoft/windows-rs +- windows-future@0.3.2 | https://github.com/microsoft/windows-rs +- windows-implement@0.57.0 | https://github.com/microsoft/windows-rs +- windows-implement@0.58.0 | https://github.com/microsoft/windows-rs +- windows-implement@0.60.2 | https://github.com/microsoft/windows-rs +- windows-interface@0.57.0 | https://github.com/microsoft/windows-rs +- windows-interface@0.58.0 | https://github.com/microsoft/windows-rs +- windows-interface@0.59.3 | https://github.com/microsoft/windows-rs +- windows-link@0.1.3 | https://github.com/microsoft/windows-rs +- windows-link@0.2.1 | https://github.com/microsoft/windows-rs +- windows-numerics@0.2.0 | https://github.com/microsoft/windows-rs +- windows-numerics@0.3.1 | https://github.com/microsoft/windows-rs +- windows-registry@0.6.1 | https://github.com/microsoft/windows-rs +- windows-result@0.1.2 | https://github.com/microsoft/windows-rs +- windows-result@0.2.0 | https://github.com/microsoft/windows-rs +- windows-result@0.3.4 | https://github.com/microsoft/windows-rs +- windows-result@0.4.1 | https://github.com/microsoft/windows-rs +- windows-strings@0.1.0 | https://github.com/microsoft/windows-rs +- windows-strings@0.4.2 | https://github.com/microsoft/windows-rs +- windows-strings@0.5.1 | https://github.com/microsoft/windows-rs +- windows-sys@0.48.0 | https://github.com/microsoft/windows-rs +- windows-sys@0.52.0 | https://github.com/microsoft/windows-rs +- windows-sys@0.59.0 | https://github.com/microsoft/windows-rs +- windows-sys@0.61.2 | https://github.com/microsoft/windows-rs +- windows-targets@0.48.5 | https://github.com/microsoft/windows-rs +- windows-targets@0.52.6 | https://github.com/microsoft/windows-rs +- windows-threading@0.1.0 | https://github.com/microsoft/windows-rs +- windows-threading@0.2.1 | https://github.com/microsoft/windows-rs +- windows-version@0.1.7 | https://github.com/microsoft/windows-rs +- windows@0.57.0 | https://github.com/microsoft/windows-rs +- windows@0.58.0 | https://github.com/microsoft/windows-rs +- windows@0.61.3 | https://github.com/microsoft/windows-rs +- windows@0.62.2 | https://github.com/microsoft/windows-rs +- windows_aarch64_msvc@0.48.5 | https://github.com/microsoft/windows-rs +- windows_aarch64_msvc@0.52.6 | https://github.com/microsoft/windows-rs +- windows_x86_64_gnu@0.48.5 | https://github.com/microsoft/windows-rs +- windows_x86_64_gnu@0.52.6 | https://github.com/microsoft/windows-rs +- windows_x86_64_msvc@0.48.5 | https://github.com/microsoft/windows-rs +- windows_x86_64_msvc@0.52.6 | https://github.com/microsoft/windows-rs +- zopfli@0.8.4 | https://github.com/zopfli-rs/zopfli +- zerocopy-derive@0.8.57 | https://github.com/google/zerocopy +- zerocopy@0.8.57 | https://github.com/google/zerocopy +- web-time@1.1.0 | https://github.com/daxpedda/web-time +- moxcms@0.8.1 | https://github.com/awxkee/moxcms.git +- pxfm@0.1.30 | https://github.com/awxkee/pxfm +- codespan-reporting@0.13.1 | https://github.com/brendanzab/codespan +- rustls-platform-verifier@0.7.1 | https://github.com/rustls/rustls-platform-verifier +- self_cell@1.3.0 | https://github.com/Voultapher/self_cell +- sys-locale@0.3.2 | https://github.com/1Password/sys-locale +- unicode-linebreak@0.1.5 | https://github.com/axelf4/unicode-linebreak +- ureq@3.4.2 | https://github.com/algesten/ureq +- zune-core@0.5.3 | https://github.com/etemesi254/zune-image +- zune-jpeg@0.5.15 | https://github.com/etemesi254/zune-image/tree/dev/crates/zune-jpeg +- ntapi@0.4.3 | https://github.com/MSxDOS/ntapi +- cosmic-text@0.19.0 | https://github.com/pop-os/cosmic-text +- bit_field@0.10.3 | https://github.com/phil-opp/rust-bit-field +- notify-rust@4.18.0 | https://github.com/hoodie/notify-rust +- winapi@0.3.9 | https://github.com/retep998/winapi-rs +- wio@0.2.2 | https://github.com/retep998/wio-rs +- crc32fast@1.5.2 | https://github.com/srijs/rust-crc32fast +- float-ord@0.3.2 | https://github.com/notriddle/rust-float-ord +- foreign-types-macros@0.2.4 | https://github.com/sfackler/foreign-types +- foreign-types-shared@0.3.1 | https://github.com/sfackler/foreign-types +- foreign-types@0.5.0 | https://github.com/sfackler/foreign-types +- hex@0.4.3 | https://github.com/KokaKiwi/rust-hex +- quick-error@2.0.1 | http://github.com/tailhook/quick-error +- serde_spanned@0.6.9 | https://github.com/toml-rs/toml +- toml@0.8.23 | https://github.com/toml-rs/toml +- toml_datetime@0.6.11 | https://github.com/toml-rs/toml +- toml_datetime@1.1.1+spec-1.1.0 | https://github.com/toml-rs/toml +- toml_edit@0.22.27 | https://github.com/toml-rs/toml +- toml_edit@0.25.15+spec-1.1.0 | https://github.com/toml-rs/toml +- toml_parser@1.1.3+spec-1.1.0 | https://github.com/toml-rs/toml +- toml_write@0.1.2 | https://github.com/toml-rs/toml +- async-broadcast@0.7.2 | https://github.com/smol-rs/async-broadcast +- futures-channel@0.3.34 | https://github.com/rust-lang/futures-rs +- futures-core@0.3.34 | https://github.com/rust-lang/futures-rs +- futures-executor@0.3.34 | https://github.com/rust-lang/futures-rs +- futures-io@0.3.34 | https://github.com/rust-lang/futures-rs +- futures-macro@0.3.34 | https://github.com/rust-lang/futures-rs +- futures-sink@0.3.34 | https://github.com/rust-lang/futures-rs +- futures-task@0.3.34 | https://github.com/rust-lang/futures-rs +- futures-util@0.3.34 | https://github.com/rust-lang/futures-rs +- futures@0.3.34 | https://github.com/rust-lang/futures-rs +- typenum@1.20.1 | https://github.com/paholg/typenum +- http@1.5.0 | https://github.com/hyperium/http +- ppv-lite86@0.2.21 | https://github.com/cryptocorrosion/cryptocorrosion +- iana-time-zone@0.1.65 | https://github.com/strawlab/iana-time-zone +- gpu-allocator@0.28.0 | https://github.com/Traverse-Research/gpu-allocator +- rustls-pki-types@1.15.1 | https://github.com/rustls/pki-types +- notify-types@1.0.1 | https://github.com/notify-rs/notify.git +- memmap2@0.9.11 | https://github.com/RazrFalcon/memmap2-rs +- async-recursion@1.1.1 | https://github.com/dcchut/async-recursion +- core_detect@1.0.0 | https://github.com/thomcc/core_detect +- gif@0.14.2 | https://github.com/image-rs/image-gif +- weezl@0.1.12 | https://github.com/image-rs/weezl +- addr2line@0.25.1 | https://github.com/gimli-rs/addr2line +- ahash@0.8.12 | https://github.com/tkaitchuck/ahash +- arrayvec@0.7.8 | https://github.com/bluss/arrayvec +- async-channel@2.5.0 | https://github.com/smol-rs/async-channel +- async-executor@1.14.0 | https://github.com/smol-rs/async-executor +- async-fs@2.2.0 | https://github.com/smol-rs/async-fs +- async-io@2.6.0 | https://github.com/smol-rs/async-io +- async-lock@3.4.2 | https://github.com/smol-rs/async-lock +- async-net@2.0.0 | https://github.com/smol-rs/async-net +- async-process@2.5.0 | https://github.com/smol-rs/async-process +- async-signal@0.2.14 | https://github.com/smol-rs/async-signal +- async-task@4.7.1 | https://github.com/smol-rs/async-task +- atomic-waker@1.1.2 | https://github.com/smol-rs/atomic-waker +- backtrace@0.3.76 | https://github.com/rust-lang/backtrace-rs +- base64@0.22.1 | https://github.com/marshallpierce/rust-base64 +- base64@0.23.1 | https://github.com/marshallpierce/rust-base64 +- bitflags@1.3.2 | https://github.com/bitflags/bitflags +- bitflags@2.13.2 | https://github.com/bitflags/bitflags +- blocking@1.7.0 | https://github.com/smol-rs/blocking +- bstr@1.13.1 | https://github.com/BurntSushi/bstr +- bumpalo@3.20.3 | https://github.com/fitzgen/bumpalo +- cfg-if@1.0.4 | https://github.com/rust-lang/cfg-if +- cocoa-foundation@0.2.1 | https://github.com/servo/core-foundation-rs +- cocoa@0.26.1 | https://github.com/servo/core-foundation-rs +- concurrent-queue@2.5.0 | https://github.com/smol-rs/concurrent-queue +- const-random-macro@0.1.16 | https://github.com/tkaitchuck/constrandom +- const-random@0.1.18 | https://github.com/tkaitchuck/constrandom +- core-foundation-sys@0.8.7 | https://github.com/servo/core-foundation-rs +- core-foundation@0.10.1 | https://github.com/servo/core-foundation-rs +- core-graphics-types@0.2.0 | https://github.com/servo/core-foundation-rs +- core-graphics@0.24.0 | https://github.com/servo/core-foundation-rs +- core-text@21.0.0 | https://github.com/servo/core-foundation-rs +- crossbeam-deque@0.8.8 | https://github.com/crossbeam-rs/crossbeam +- crossbeam-epoch@0.9.21 | https://github.com/crossbeam-rs/crossbeam +- crossbeam-utils@0.8.23 | https://github.com/crossbeam-rs/crossbeam +- data-url@0.3.2 | https://github.com/servo/rust-url +- derivative@2.2.0 | https://github.com/mcarton/rust-derivative +- displaydoc@0.2.7 | https://github.com/yaahc/displaydoc +- either@1.18.0 | https://github.com/rayon-rs/either +- equivalent@1.0.2 | https://github.com/indexmap-rs/equivalent +- errno@0.3.14 | https://github.com/lambda-fairy/rust-errno +- euclid@0.22.14 | https://github.com/servo/euclid +- event-listener-strategy@0.5.4 | https://github.com/smol-rs/event-listener-strategy +- event-listener@5.4.2 | https://github.com/smol-rs/event-listener +- fastrand@2.5.0 | https://github.com/smol-rs/fastrand +- filetime@0.2.29 | https://github.com/alexcrichton/filetime +- flate2@1.1.10 | https://github.com/rust-lang/flate2-rs +- form_urlencoded@1.2.2 | https://github.com/servo/rust-url +- futf@0.1.5 | https://github.com/servo/futf +- futures-lite@2.6.1 | https://github.com/smol-rs/futures-lite +- gethostname@1.1.0 | https://codeberg.org/swsnr/gethostname.rs.git +- gimli@0.32.3 | https://github.com/gimli-rs/gimli +- glob@0.3.4 | https://github.com/rust-lang/glob +- hash32@0.3.1 | https://github.com/japaric/hash32 +- hashbrown@0.14.5 | https://github.com/rust-lang/hashbrown +- hashbrown@0.15.5 | https://github.com/rust-lang/hashbrown +- hashbrown@0.16.1 | https://github.com/rust-lang/hashbrown +- hashbrown@0.17.1 | https://github.com/rust-lang/hashbrown +- heapless@0.9.3 | https://github.com/rust-embedded/heapless +- heck@0.5.0 | https://github.com/withoutboats/heck +- html5ever@0.27.0 | https://github.com/servo/html5ever +- httparse@1.10.1 | https://github.com/seanmonstar/httparse +- idna@1.1.0 | https://github.com/servo/rust-url/ +- idna_adapter@1.2.2 | https://github.com/hsivonen/idna_adapter +- indexmap@2.14.2 | https://github.com/indexmap-rs/indexmap +- itertools@0.13.0 | https://github.com/rust-itertools/itertools +- itertools@0.14.0 | https://github.com/rust-itertools/itertools +- khronos-egl@6.0.0 | https://github.com/timothee-haudebourg/khronos-egl +- lazy_static@1.5.0 | https://github.com/rust-lang-nursery/lazy-static.rs +- linux-raw-sys@0.12.1 | https://github.com/sunfishcode/linux-raw-sys +- lock_api@0.4.14 | https://github.com/Amanieu/parking_lot +- log@0.4.34 | https://github.com/rust-lang/log +- markup5ever@0.12.1 | https://github.com/servo/html5ever +- markup5ever_rcdom@0.3.0 | https://github.com/servo/html5ever +- metal@0.33.0 | https://github.com/gfx-rs/metal-rs +- mime@0.3.17 | https://github.com/hyperium/mime +- num-bigint-dig@0.9.1 | https://github.com/dignifiedquire/num-bigint +- num-bigint@0.4.8 | https://github.com/rust-num/num-bigint +- num-complex@0.4.6 | https://github.com/rust-num/num-complex +- num-integer@0.1.47 | https://github.com/rust-num/num-integer +- num-iter@0.1.46 | https://github.com/rust-num/num-iter +- num-rational@0.4.2 | https://github.com/rust-num/num-rational +- num-traits@0.2.19 | https://github.com/rust-num/num-traits +- num@0.4.3 | https://github.com/rust-num/num +- num_cpus@1.17.0 | https://github.com/seanmonstar/num_cpus +- object@0.37.3 | https://github.com/gimli-rs/object +- once_cell@1.21.4 | https://github.com/matklad/once_cell +- openssl-probe@0.2.1 | https://github.com/rustls/openssl-probe +- ordered-stream@0.2.0 | https://github.com/danieldg/ordered-stream +- parking@2.2.1 | https://github.com/smol-rs/parking +- parking_lot@0.12.5 | https://github.com/Amanieu/parking_lot +- parking_lot_core@0.9.12 | https://github.com/Amanieu/parking_lot +- percent-encoding@2.3.2 | https://github.com/servo/rust-url/ +- piper@0.2.5 | https://github.com/smol-rs/piper +- png@0.17.16 | https://github.com/image-rs/image-png +- png@0.18.1 | https://github.com/image-rs/image-png +- polling@3.11.0 | https://github.com/smol-rs/polling +- pollster@0.4.0 | https://github.com/zesterer/pollster +- rayon-core@1.13.0 | https://github.com/rayon-rs/rayon +- rayon@1.12.0 | https://github.com/rayon-rs/rayon +- regex-automata@0.4.18 | https://github.com/rust-lang/regex +- regex-syntax@0.8.11 | https://github.com/rust-lang/regex +- regex@1.13.1 | https://github.com/rust-lang/regex +- renderdoc-sys@1.1.0 | https://github.com/ebkalderon/renderdoc-rs +- ring@0.17.14 | https://github.com/briansmith/ring +- roxmltree@0.20.0 | https://github.com/RazrFalcon/roxmltree +- roxmltree@0.21.1 | https://github.com/RazrFalcon/roxmltree +- rustc-demangle@0.1.28 | https://github.com/rust-lang/rustc-demangle +- rustc-hash@1.1.0 | https://github.com/rust-lang-nursery/rustc-hash +- rustix@1.1.4 | https://github.com/bytecodealliance/rustix +- rustls-native-certs@0.8.4 | https://github.com/rustls/rustls-native-certs +- rustls@0.23.45 | https://github.com/rustls/rustls +- scoped-tls@1.0.1 | https://github.com/alexcrichton/scoped-tls +- scopeguard@1.2.0 | https://github.com/bluss/scopeguard +- security-framework-sys@2.17.0 | https://github.com/kornelski/rust-security-framework +- security-framework@3.7.0 | https://github.com/kornelski/rust-security-framework +- shellexpand@3.1.2 | https://gitlab.com/ijackson/rust-shellexpand +- signal-hook-registry@1.4.8 | https://github.com/vorner/signal-hook +- simplecss@0.2.2 | https://github.com/linebender/simplecss +- smallvec@1.16.1 | https://github.com/servo/rust-smallvec +- smol@2.0.2 | https://github.com/smol-rs/smol +- smol_str@0.3.6 | https://github.com/rust-lang/rust-analyzer/tree/master/lib/smol_str +- socket2@0.6.5 | https://github.com/rust-lang/socket2 +- stable_deref_trait@1.2.1 | https://github.com/storyyeller/stable_deref_trait +- string_cache@0.8.9 | https://github.com/servo/string-cache +- svgtypes@0.16.1 | https://github.com/linebender/svgtypes +- swash@0.2.10 | https://github.com/dfrg/swash +- syn@1.0.109 | https://github.com/dtolnay/syn +- tempfile@3.27.0 | https://github.com/Stebalien/tempfile +- tendril@0.4.3 | https://github.com/servo/tendril +- ttf-parser@0.25.1 | https://github.com/harfbuzz/ttf-parser +- unicase@2.9.0 | https://github.com/seanmonstar/unicase +- unicode-bidi-mirroring@0.4.0 | https://github.com/RazrFalcon/unicode-bidi-mirroring +- unicode-bidi@0.3.18 | https://github.com/servo/unicode-bidi +- unicode-ccc@0.4.0 | https://github.com/RazrFalcon/unicode-ccc +- unicode-id@0.3.6 | https://github.com/Boshen/unicode-id +- unicode-properties@0.1.3 | https://github.com/unicode-rs/unicode-properties +- unicode-segmentation@1.13.3 | https://github.com/unicode-rs/unicode-segmentation +- unicode-vo@0.1.0 | https://github.com/RazrFalcon/unicode-vo +- unicode-width@0.2.2 | https://github.com/unicode-rs/unicode-width +- url@2.5.8 | https://github.com/servo/rust-url +- uuid@1.26.1 | https://github.com/uuid-rs/uuid +- wait-timeout@0.2.1 | https://github.com/alexcrichton/wait-timeout +- waker-fn@1.2.0 | https://github.com/smol-rs/waker-fn +- xml5ever@0.18.1 | https://github.com/servo/html5ever +- zed-font-kit@0.14.1-zed | https://github.com/servo/font-kit +- bit-set@0.9.1 | https://github.com/contain-rs/bit-set +- bit-vec@0.9.1 | https://github.com/contain-rs/bit-vec +- downcast-rs@1.2.1 | https://github.com/marcianx/downcast-rs +- presser@0.3.1 | https://github.com/EmbarkStudios/presser +- qoi@0.4.1 | https://github.com/aldanor/qoi-rust +- waitpid-any@0.3.0 | https://github.com/oxalica/waitpid-any +- hkdf@0.12.4 | https://github.com/RustCrypto/KDFs/ +- aes@0.8.4 | https://github.com/RustCrypto/block-ciphers +- block-buffer@0.10.4 | https://github.com/RustCrypto/utils +- block-buffer@0.12.1 | https://github.com/RustCrypto/utils +- block-padding@0.3.3 | https://github.com/RustCrypto/utils +- cbc@0.1.2 | https://github.com/RustCrypto/block-modes +- chacha20@0.10.2 | https://github.com/RustCrypto/stream-ciphers +- cipher@0.4.4 | https://github.com/RustCrypto/traits +- const-oid@0.10.2 | https://github.com/RustCrypto/formats +- cpufeatures@0.2.17 | https://github.com/RustCrypto/utils +- cpufeatures@0.3.1 | https://github.com/RustCrypto/utils +- crypto-common@0.1.7 | https://github.com/RustCrypto/traits +- crypto-common@0.2.2 | https://github.com/RustCrypto/traits +- digest@0.10.7 | https://github.com/RustCrypto/traits +- digest@0.11.3 | https://github.com/RustCrypto/traits +- hmac@0.12.1 | https://github.com/RustCrypto/MACs +- hybrid-array@0.4.15 | https://github.com/RustCrypto/hybrid-array +- inout@0.1.4 | https://github.com/RustCrypto/utils +- md-5@0.10.6 | https://github.com/RustCrypto/hashes +- pbkdf2@0.12.2 | https://github.com/RustCrypto/password-hashes/tree/master/pbkdf2 +- sha1@0.11.0 | https://github.com/RustCrypto/hashes +- sha2@0.10.9 | https://github.com/RustCrypto/hashes +- sha2@0.11.0 | https://github.com/RustCrypto/hashes +- rand_core@0.10.1 | https://github.com/rust-random/rand_core +- rand_core@0.9.5 | https://github.com/rust-random/rand +- getrandom@0.2.17 | https://github.com/rust-random/getrandom +- getrandom@0.3.4 | https://github.com/rust-random/getrandom +- getrandom@0.4.3 | https://github.com/rust-random/getrandom +- ropey@2.0.0-beta.1 | https://github.com/cessen/ropey +- str_indices@0.4.4 | https://github.com/cessen/str_indices +- proc-macro-crate@3.5.0 | https://github.com/bkchr/proc-macro-crate +- unicode-script@0.5.8 | https://github.com/unicode-rs/unicode-script +- glow@0.17.0 | https://github.com/grovesNL/glow +- yazi@0.2.1 | https://github.com/dfrg/yazi +- zeno@0.3.3 | https://github.com/dfrg/zeno +- flume@0.12.0 | https://github.com/zesterer/flume +- font-types@0.12.5 | https://github.com/googlefonts/fontations +- read-fonts@0.41.0 | https://github.com/googlefonts/fontations +- skrifa@0.44.0 | https://github.com/googlefonts/fontations +- enumflags2@0.7.12 | https://github.com/meithecatte/enumflags2 +- enumflags2_derive@0.7.12 | https://github.com/meithecatte/enumflags2 +- ash@0.38.0+1.3.281 | https://github.com/ash-rs/ash +- font-types@0.11.3 | https://github.com/googlefonts/fontations +- read-fonts@0.37.0 | https://github.com/googlefonts/fontations +- skrifa@0.40.0 | https://github.com/googlefonts/fontations +- atspi-common@0.13.0 | https://github.com/odilia-app/atspi +- atspi-proxies@0.13.0 | https://github.com/odilia-app/atspi +- atspi@0.29.0 | https://github.com/odilia-app/atspi +- glutin_wgl_sys@0.6.1 | https://github.com/rust-windowing/glutin +- ctor@1.0.13 | https://github.com/mmastrac/linktime +- link-section@0.19.3 | https://github.com/mmastrac/linktime +- linktime-proc-macro@0.2.3 | https://github.com/mmastrac/linktime +- bytemuck@1.25.2 | https://github.com/Lokathor/bytemuck +- bytemuck_derive@1.12.1 | https://github.com/Lokathor/bytemuck +- accesskit@0.24.1 | https://github.com/AccessKit/accesskit +- accesskit_atspi_common@0.19.1 | https://github.com/AccessKit/accesskit +- accesskit_consumer@0.38.0 | https://github.com/AccessKit/accesskit +- accesskit_macos@0.26.3 | https://github.com/AccessKit/accesskit +- accesskit_unix@0.22.1 | https://github.com/AccessKit/accesskit +- accesskit_windows@0.34.0 | https://github.com/AccessKit/accesskit +- allocator-api2@0.2.21 | https://github.com/zakarumych/allocator-api2 +- anyhow@1.0.104 | https://github.com/dtolnay/anyhow +- async-trait@0.1.92 | https://github.com/dtolnay/async-trait +- dirs-sys@0.4.1 | https://github.com/dirs-dev/dirs-sys-rs +- dirs-sys@0.5.0 | https://github.com/dirs-dev/dirs-sys-rs +- dirs@5.0.1 | https://github.com/soc/dirs-rs +- dirs@6.0.0 | https://github.com/soc/dirs-rs +- dispatch2@0.3.1 | https://github.com/madsmtm/objc2 +- document-features@0.2.12 | https://github.com/slint-ui/document-features +- dunce@1.0.5 | https://gitlab.com/kornelski/dunce +- dyn-clone@1.0.20 | https://github.com/dtolnay/dyn-clone +- enumn@0.1.14 | https://github.com/dtolnay/enumn +- etagere@0.2.15 | https://github.com/nical/etagere +- fdeflate@0.3.7 | https://github.com/image-rs/fdeflate +- gpu-descriptor-types@0.2.0 | https://github.com/zakarumych/gpu-descriptor +- gpu-descriptor@0.3.2 | https://github.com/zakarumych/gpu-descriptor +- gpui-kit-assets@0.7.3 | https://github.com/longbridge/gpui-kit +- gpui-kit@0.7.3 | https://github.com/longbridge/gpui-kit +- half@2.7.1 | https://github.com/VoidStarKat/half-rs +- ident_case@1.0.1 | https://github.com/TedDriggs/ident_case +- image-webp@0.2.4 | https://github.com/image-rs/image-webp +- image@0.25.10 | https://github.com/image-rs/image +- inventory@0.3.24 | https://github.com/dtolnay/inventory +- itoa@1.0.18 | https://github.com/dtolnay/itoa +- libc@0.2.189 | https://github.com/rust-lang/libc +- linebender_resource_handle@0.1.1 | https://github.com/linebender/raw_resource_handle +- litrs@1.0.0 | https://github.com/LukasKalbertodt/litrs +- lyon@1.0.19 | https://github.com/nical/lyon +- lyon_algorithms@1.0.21 | https://github.com/nical/lyon +- lyon_geom@1.0.19 | https://github.com/nical/lyon +- lyon_path@1.0.19 | https://github.com/nical/lyon +- lyon_tessellation@1.0.22 | https://github.com/nical/lyon +- mac-notification-sys@0.6.15 | https://github.com/h4llow3En/mac-notification-sys +- mac@0.1.1 | https://github.com/reem/rust-mac.git +- mach2@0.6.0 | https://github.com/JohnTitor/mach2 +- miniz_oxide@0.8.9 | https://github.com/Frommi/miniz_oxide/tree/master/miniz_oxide +- miniz_oxide@0.9.1 | https://github.com/Frommi/miniz_oxide/tree/master/miniz_oxide +- naga@29.0.4 | https://github.com/gfx-rs/wgpu +- normpath@1.5.1 | https://github.com/dylni/normpath +- num-conv@0.2.2 | https://github.com/jhpratt/num-conv +- objc2-app-kit@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-cloud-kit@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-core-data@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-core-foundation@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-core-graphics@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-core-image@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-core-text@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-core-video@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-metal@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-quartz-core@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-security@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-user-notifications@0.3.2 | https://github.com/madsmtm/objc2 +- paste@1.0.15 | https://github.com/dtolnay/paste +- pastey@0.2.3 | https://github.com/as1100k/pastey +- pathfinder_geometry@0.5.1 | https://github.com/servo/pathfinder +- pathfinder_simd@0.5.6 | https://github.com/servo/pathfinder +- pin-project-internal@1.1.13 | https://github.com/taiki-e/pin-project +- pin-project-lite@0.2.17 | https://github.com/taiki-e/pin-project-lite +- pin-project@1.1.13 | https://github.com/taiki-e/pin-project +- proc-macro2@1.0.107 | https://github.com/dtolnay/proc-macro2 +- profiling-procmacros@1.0.18 | https://github.com/aclysma/profiling +- profiling@1.0.18 | https://github.com/aclysma/profiling +- quote@1.0.47 | https://github.com/dtolnay/quote +- rand@0.10.2 | https://github.com/rust-random/rand +- rand@0.9.5 | https://github.com/rust-random/rand +- rand_chacha@0.9.0 | https://github.com/rust-random/rand +- range-alloc@0.1.5 | https://github.com/gfx-rs/range-alloc +- raw-window-handle@0.6.2 | https://github.com/rust-windowing/raw-window-handle +- ref-cast-impl@1.0.27 | https://github.com/dtolnay/ref-cast +- ref-cast@1.0.27 | https://github.com/dtolnay/ref-cast +- resvg@0.46.0 | https://github.com/linebender/resvg +- rmcp-macros@3.5.1 | https://github.com/modelcontextprotocol/rust-sdk/ +- rmcp@3.5.1 | https://github.com/modelcontextprotocol/rust-sdk/ +- rustc-hash@2.1.3 | https://github.com/rust-lang/rustc-hash +- rustversion@1.0.23 | https://github.com/dtolnay/rustversion +- ryu@1.0.23 | https://github.com/dtolnay/ryu +- semver@1.0.28 | https://github.com/dtolnay/semver +- serde@1.0.229 | https://github.com/serde-rs/serde +- serde_bytes@0.11.19 | https://github.com/serde-rs/bytes +- serde_core@1.0.229 | https://github.com/serde-rs/serde +- serde_derive@1.0.229 | https://github.com/serde-rs/serde +- serde_derive_internals@0.30.0 | https://github.com/serde-rs/serde +- serde_json@1.0.151 | https://github.com/serde-rs/json +- serde_repr@0.1.21 | https://github.com/dtolnay/serde-repr +- serde_urlencoded@0.7.1 | https://github.com/nox/serde_urlencoded +- simdutf8@0.1.5 | https://github.com/rusticstuff/simdutf8 +- siphasher@1.0.3 | https://github.com/jedisct1/rust-siphash +- spirv@0.4.0+sdk-1.4.341.0 | https://github.com/gfx-rs/rspirv +- svg_fmt@0.4.5 | https://github.com/nical/rust_debug +- syn@2.0.119 | https://github.com/dtolnay/syn +- syn@3.0.5 | https://github.com/dtolnay/syn +- tauri-winrt-notification@0.7.3 | https://github.com/tauri-apps/winrt-notification +- thiserror-impl@1.0.69 | https://github.com/dtolnay/thiserror +- thiserror-impl@2.0.20 | https://github.com/dtolnay/thiserror +- thiserror@1.0.69 | https://github.com/dtolnay/thiserror +- thiserror@2.0.20 | https://github.com/dtolnay/thiserror +- time-core@0.1.9 | https://github.com/time-rs/time +- time@0.3.55 | https://github.com/time-rs/time +- typed-path@0.12.4 | https://github.com/chipsenkbeil/typed-path +- unicode-ident@1.0.24 | https://github.com/dtolnay/unicode-ident +- usvg@0.46.0 | https://github.com/linebender/resvg +- utf-8@0.7.6 | https://github.com/SimonSapin/rust-utf8 +- utf8-zero@0.8.1 | https://github.com/algesten/utf8-zero +- wgpu-core-deps-apple@29.0.4 | https://github.com/gfx-rs/wgpu +- wgpu-core-deps-windows-linux-android@29.0.4 | https://github.com/gfx-rs/wgpu +- wgpu-core@29.0.4 | https://github.com/gfx-rs/wgpu +- wgpu-hal@29.0.4 | https://github.com/gfx-rs/wgpu +- wgpu-naga-bridge@29.0.4 | https://github.com/gfx-rs/wgpu +- wgpu-types@29.0.4 | https://github.com/gfx-rs/wgpu +- wgpu@29.0.4 | https://github.com/gfx-rs/wgpu +- zune-inflate@0.2.54 +- gpui-pre-apple@0.3.9 | https://github.com/zed-industries/zed +- gpui-pre-collections@0.3.9 | https://github.com/zed-industries/zed +- gpui-pre-derive-refineable@0.3.9 | https://github.com/zed-industries/zed +- gpui-pre-http-client@0.3.9 | https://github.com/zed-industries/zed +- gpui-pre-linux@0.3.9 | https://github.com/zed-industries/zed +- gpui-pre-macos@0.3.9 | https://github.com/zed-industries/zed +- gpui-pre-macros@0.3.9 | https://github.com/zed-industries/zed +- gpui-pre-platform@0.3.9 | https://github.com/zed-industries/zed +- gpui-pre-refineable@0.3.9 | https://github.com/zed-industries/zed +- gpui-pre-scheduler@0.3.9 | https://github.com/zed-industries/zed +- gpui-pre-shared-string@0.3.9 | https://github.com/zed-industries/zed +- gpui-pre-sum-tree@0.3.9 | https://github.com/zed-industries/zed +- gpui-pre-util@0.3.9 | https://github.com/zed-industries/zed +- gpui-pre-wgpu@0.3.9 | https://github.com/zed-industries/zed +- gpui-pre-windows@0.3.9 | https://github.com/zed-industries/zed +- gpui-pre-ztracing-macro@0.3.9 | https://github.com/zed-industries/zed +- gpui-pre-ztracing@0.3.9 | https://github.com/zed-industries/zed +- gpui-pre@0.3.9 | https://github.com/zed-industries/zed +- gpui-base@0.7.3 | https://github.com/longbridge/gpui-kit +- chrono@0.4.45 | https://github.com/chronotope/chrono + +MIT License (155) +- rustybuzz@0.20.1 | https://github.com/harfbuzz/rustybuzz +- uds_windows@1.2.1 | https://github.com/haraldh/rust_uds_windows +- freetype-sys@0.20.1 | https://github.com/PistonDevelopers/freetype-sys.git +- freetype-sys@0.20.1 | https://github.com/PistonDevelopers/freetype-sys.git +- schemars@1.2.2 | https://github.com/GREsau/schemars +- markdown@1.0.0 | https://github.com/wooorm/markdown-rs +- freetype-sys@0.20.1 | https://github.com/PistonDevelopers/freetype-sys.git +- freetype-sys@0.20.1 | https://github.com/PistonDevelopers/freetype-sys.git +- freetype-sys@0.20.1 | https://github.com/PistonDevelopers/freetype-sys.git +- freetype-sys@0.20.1 | https://github.com/PistonDevelopers/freetype-sys.git +- freetype-sys@0.20.1 | https://github.com/PistonDevelopers/freetype-sys.git +- freetype-sys@0.20.1 | https://github.com/PistonDevelopers/freetype-sys.git +- freetype-sys@0.20.1 | https://github.com/PistonDevelopers/freetype-sys.git +- mio@1.2.3 | https://github.com/tokio-rs/mio +- float-cmp@0.9.0 | https://github.com/mikedilger/float-cmp +- wayland-backend@0.3.17 | https://github.com/smithay/wayland-rs +- wayland-client@0.31.15 | https://github.com/smithay/wayland-rs +- wayland-cursor@0.31.14 | https://github.com/smithay/wayland-rs +- wayland-protocols-plasma@0.3.12 | https://github.com/smithay/wayland-rs +- wayland-protocols-wlr@0.3.12 | https://github.com/smithay/wayland-rs +- wayland-protocols@0.32.13 | https://github.com/smithay/wayland-rs +- wayland-scanner@0.31.11 | https://github.com/smithay/wayland-rs +- wayland-sys@0.31.11 | https://github.com/smithay/wayland-rs +- new_debug_unreachable@1.0.6 | https://github.com/mbrubeck/rust-debug-unreachable +- ordered-float@5.5.0 | https://github.com/reem/rust-ordered-float +- dlib@0.5.3 | https://github.com/elinorbgr/dlib +- which@8.0.6 | https://github.com/harryfei/which-rs.git +- schannel@0.1.29 | https://github.com/steffengy/schannel-rs +- xkbcommon@0.8.0 | https://github.com/rust-x-bindings/xkbcommon-rs +- memoffset@0.9.1 | https://github.com/Gilnaa/memoffset +- bytes@1.12.1 | https://github.com/tokio-rs/bytes +- calloop@0.14.4 | https://github.com/Smithay/calloop +- slab@0.4.12 | https://github.com/tokio-rs/slab +- tracing-attributes@0.1.31 | https://github.com/tokio-rs/tracing +- tracing-core@0.1.36 | https://github.com/tokio-rs/tracing +- tracing@0.1.44 | https://github.com/tokio-rs/tracing +- pico-args@0.5.0 | https://github.com/RazrFalcon/pico-args +- http-body@1.1.0 | https://github.com/hyperium/http-body +- strict-num@0.1.1 | https://github.com/RazrFalcon/strict-num +- calloop-wayland-source@0.4.1 | https://github.com/smithay/calloop-wayland-source +- zbus@5.19.0 | https://github.com/z-galaxy/zbus/ +- zbus_macros@5.19.0 | https://github.com/z-galaxy/zbus/ +- zbus_names@4.3.4 | https://github.com/z-galaxy/zbus/ +- zbus_xml@5.2.1 | https://github.com/z-galaxy/zbus/ +- zvariant@5.15.0 | https://github.com/z-galaxy/zbus/ +- zvariant_derive@5.15.0 | https://github.com/z-galaxy/zbus/ +- zcheapstr@1.1.0 | https://github.com/z-galaxy/zcheapstr/ +- synstructure@0.13.2 | https://github.com/mystor/synstructure +- trash@5.2.9 | https://github.com/ArturKovacs/trash +- wayland-protocols@0.32.13 | https://github.com/smithay/wayland-rs +- fax@0.2.7 | https://github.com/pdf-rs/fax +- precomputed-hash@0.1.1 | https://github.com/emilio/precomputed-hash +- darling@0.24.1 | https://github.com/TedDriggs/darling +- darling_core@0.24.1 | https://github.com/TedDriggs/darling +- darling_macro@0.24.1 | https://github.com/TedDriggs/darling +- tiff@0.11.3 | https://github.com/image-rs/image-tiff +- filedescriptor@0.8.3 | https://github.com/wezterm/wezterm +- schemars@1.2.2 | https://github.com/GREsau/schemars +- schemars_derive@1.2.2 | https://github.com/GREsau/schemars +- rgb@0.8.53 | https://github.com/kornelski/rust-rgb +- strum@0.28.0 | https://github.com/Peternator7/strum +- strum_macros@0.28.0 | https://github.com/Peternator7/strum +- tokio-macros@2.7.2 | https://github.com/tokio-rs/tokio +- ashpd@0.13.13 | https://github.com/bilelmoussaoui/ashpd +- zed-xim@0.4.0-zed | https://github.com/Riey/xim-rs +- xcursor@0.3.11 | https://github.com/esposm03/xcursor-rs +- float_next_after@1.0.0 | https://gitlab.com/bronsonbdevost/next_afterf +- pulp@0.22.3 | https://github.com/sarah-quinones/pulp/ +- oo7@0.6.0 | https://github.com/linux-credentials/oo7 +- reborrow@0.5.5 | https://github.com/sarah-ek/reborrow/ +- is-docker@0.2.0 | https://github.com/TheLarkInn/is-docker +- is-wsl@0.4.0 | https://github.com/TheLarkInn/is-wsl +- core_maths@0.1.1 | https://github.com/robertbastian/core_maths +- convert_case@0.10.0 | https://github.com/rutrum/convert-case +- gpui-omarchy@0.2.1 | https://github.com/huacnlee/gpui-omarchy +- disktree-app@0.17.0 | https://github.com/pwrdrvr/PwrDisk +- disktree-core@0.17.0 +- disktree-link@0.17.0 +- disktree-mcp@0.17.0 +- disktree-scan@0.17.0 +- xtask@0.17.0 +- block2@0.6.2 | https://github.com/madsmtm/objc2 +- block@0.1.6 | http://github.com/SSheldon/rust-block +- harfrust@0.5.2 | https://github.com/harfbuzz/harfrust +- libm@0.2.16 | https://github.com/rust-lang/compiler-builtins +- malloc_buf@0.0.6 | https://github.com/SSheldon/malloc_buf +- objc-sys@0.3.5 | https://github.com/madsmtm/objc2 +- objc2-app-kit@0.2.2 | https://github.com/madsmtm/objc2 +- objc2-encode@4.1.0 | https://github.com/madsmtm/objc2 +- objc2-foundation@0.2.2 | https://github.com/madsmtm/objc2 +- objc2-foundation@0.3.2 | https://github.com/madsmtm/objc2 +- objc2@0.5.2 | https://github.com/madsmtm/objc2 +- objc2@0.6.4 | https://github.com/madsmtm/objc2 +- pulp-wasm-simd-flag@0.1.1 | https://github.com/sarah-quinones/pulp/ +- seahash@4.1.0 | https://gitlab.redox-os.org/redox-os/seahash +- taffy@0.13.0 | https://github.com/DioxusLabs/taffy +- velopack@1.2.161 | https://github.com/velopack/velopack +- xim-ctext@0.3.0 | https://github.com/Riey/xim-rs +- xim-parser@0.2.2 | https://github.com/Riey/xim-rs +- objc@0.2.7 | http://github.com/SSheldon/rust-objc +- tokio-util@0.7.19 | https://github.com/tokio-rs/tokio +- tokio@1.53.1 | https://github.com/tokio-rs/tokio +- simd-adler32@0.3.10 | https://github.com/mcountryman/simd-adler32 +- imagesize@0.14.0 | https://github.com/Roughsketch/imagesize +- fontconfig-parser@0.5.8 | https://github.com/Riey/fontconfig-parser +- fluent-uri@0.1.4 | https://github.com/yescallop/fluent-uri-rs +- wayland-protocols-plasma@0.3.12 | https://github.com/smithay/wayland-rs +- endi@1.1.1 | https://github.com/zeenix/endi +- zbus-lockstep-macros@0.5.2 | https://github.com/luukvanderduim/zbus-lockstep +- zbus-lockstep@0.5.2 | https://github.com/luukvanderduim/zbus-lockstep +- zmij@1.0.23 | https://github.com/dtolnay/zmij +- zvariant_utils@4.2.0 | https://github.com/z-galaxy/zbus/ +- winnow@0.7.15 | https://github.com/winnow-rs/winnow +- winnow@1.0.4 | https://github.com/winnow-rs/winnow +- spin@0.10.1 | https://github.com/mvdnes/spin-rs.git +- spin@0.9.9 | https://github.com/mvdnes/spin-rs.git +- tracing-core@0.1.36 | https://github.com/tokio-rs/tracing +- zip@8.6.0 | https://github.com/zip-rs/zip2 +- freetype-sys@0.20.1 | https://github.com/PistonDevelopers/freetype-sys.git +- xml@1.4.0 | https://github.com/kornelski/xml-rs +- phf@0.11.3 | https://github.com/rust-phf/rust-phf +- phf@0.13.1 | https://github.com/rust-phf/rust-phf +- phf_generator@0.13.1 | https://github.com/rust-phf/rust-phf +- phf_macros@0.13.1 | https://github.com/rust-phf/rust-phf +- phf_shared@0.11.3 | https://github.com/rust-phf/rust-phf +- phf_shared@0.13.1 | https://github.com/rust-phf/rust-phf +- aho-corasick@1.1.5 | https://github.com/BurntSushi/aho-corasick +- byteorder-lite@0.1.0 | https://github.com/image-rs/byteorder-lite +- byteorder@1.5.0 | https://github.com/BurntSushi/byteorder +- globset@0.4.20 | https://github.com/BurntSushi/ripgrep/tree/master/crates/globset +- memchr@2.8.3 | https://github.com/BurntSushi/memchr +- walkdir@2.5.0 | https://github.com/BurntSushi/walkdir +- strsim@0.11.1 | https://github.com/rapidfuzz/strsim-rs +- raw-cpuid@11.6.0 | https://github.com/gz/rust-cpuid +- sysinfo@0.31.4 | https://github.com/GuillaumeGomez/sysinfo +- fsevent-sys@4.1.0 | https://github.com/octplane/fsevent-rust/tree/master/fsevent-sys +- derive_more-impl@2.1.1 | https://github.com/JelteF/derive_more +- derive_more@2.1.1 | https://github.com/JelteF/derive_more +- lsp-types@0.97.0 | https://github.com/gluon-lang/lsp-types +- color_quant@1.1.0 | https://github.com/image-rs/color_quant.git +- same-file@1.0.6 | https://github.com/BurntSushi/same-file +- winapi-util@0.1.11 | https://github.com/BurntSushi/winapi-util +- rust-embed-impl@8.12.0 | https://pyrossh.dev/repos/rust-embed +- rust-embed-utils@8.12.0 | https://pyrossh.dev/repos/rust-embed +- rust-embed@8.12.0 | https://pyrossh.dev/repos/rust-embed +- xmlwriter@0.1.0 | https://github.com/RazrFalcon/xmlwriter +- fontdb@0.23.0 | https://github.com/RazrFalcon/fontdb +- rustybuzz@0.20.1 | https://github.com/harfbuzz/rustybuzz +- crunchy@0.2.4 | https://github.com/eira-fransham/crunchy +- yeslogic-fontconfig-sys@6.0.1 | https://github.com/yeslogic/fontconfig-rs +- open@5.4.4 | https://github.com/Byron/open-rs +- mime_guess@2.0.5 | https://github.com/abonander/mime_guess +- generic-array@0.14.7 | https://github.com/fizyk20/generic-array.git +- quick-xml@0.41.0 | https://github.com/tafia/quick-xml +- urlencoding@2.1.3 | https://github.com/kornelski/rust_urlencoding + +ISC License (21) +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- untrusted@0.9.0 | https://github.com/briansmith/untrusted +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- inotify-sys@0.1.8 | https://github.com/hannobraun/inotify-sys +- inotify@0.10.2 | https://github.com/hannobraun/inotify +- ring@0.17.14 | https://github.com/briansmith/ring +- libloading@0.8.9 | https://github.com/nagisa/rust_libloading/ +- rustls-webpki@0.103.15 | https://github.com/rustls/webpki + +Unicode License v3 (19) +- unicode-ident@1.0.24 | https://github.com/dtolnay/unicode-ident +- icu_collections@2.3.0 | https://github.com/unicode-org/icu4x +- icu_locale_core@2.3.0 | https://github.com/unicode-org/icu4x +- icu_normalizer@2.3.0 | https://github.com/unicode-org/icu4x +- icu_normalizer_data@2.3.0 | https://github.com/unicode-org/icu4x +- icu_properties@2.3.0 | https://github.com/unicode-org/icu4x +- icu_properties_data@2.3.0 | https://github.com/unicode-org/icu4x +- icu_provider@2.3.1 | https://github.com/unicode-org/icu4x +- litemap@0.8.3 | https://github.com/unicode-org/icu4x +- potential_utf@0.1.6 | https://github.com/unicode-org/icu4x +- tinystr@0.8.4 | https://github.com/unicode-org/icu4x +- writeable@0.6.4 | https://github.com/unicode-org/icu4x +- yoke-derive@0.8.2 | https://github.com/unicode-org/icu4x +- yoke@0.8.3 | https://github.com/unicode-org/icu4x +- zerofrom-derive@0.1.7 | https://github.com/unicode-org/icu4x +- zerofrom@0.1.8 | https://github.com/unicode-org/icu4x +- zerotrie@0.2.5 | https://github.com/unicode-org/icu4x +- zerovec-derive@0.11.6 | https://github.com/unicode-org/icu4x +- zerovec@0.11.8 | https://github.com/unicode-org/icu4x + +BSD 3-Clause "New" or "Revised" License (9) +- encoding_rs@0.8.41 | https://github.com/hsivonen/encoding_rs +- tiny-skia-path@0.11.4 | https://github.com/RazrFalcon/tiny-skia/tree/master/path +- tiny-skia@0.11.4 | https://github.com/RazrFalcon/tiny-skia +- subtle@2.6.1 | https://github.com/dalek-cryptography/subtle +- instant@0.1.13 | https://github.com/sebcrozet/instant +- lebe@0.5.3 | https://github.com/johannesvollmer/lebe +- exr@1.74.2 | https://github.com/johannesvollmer/exrs +- sha1_smol@1.0.1 | https://github.com/mitsuhiko/sha1-smol +- encoding_rs@0.8.41 | https://github.com/hsivonen/encoding_rs + +zlib License (4) +- zlib-rs@0.6.7 | https://github.com/trifectatechfoundation/zlib-rs +- slotmap@1.1.1 | https://github.com/orlp/slotmap +- foldhash@0.1.5 | https://github.com/orlp/foldhash +- foldhash@0.2.0 | https://github.com/orlp/foldhash + +Creative Commons Zero v1.0 Universal (3) +- notify@7.0.0 | https://github.com/notify-rs/notify.git +- hexf-parse@0.2.1 | https://github.com/lifthrasiir/hexf +- tiny-keccak@2.0.2 + +Mozilla Public License 2.0 (2) +- dwrote@0.11.5 | https://github.com/servo/dwrote-rs +- option-ext@0.2.0 | https://github.com/soc/option-ext.git + +BSD Zero Clause License (1) +- adler2@2.0.1 | https://github.com/oyvindln/adler2 + +BSD 2-Clause "Simplified" License (1) +- arrayref@0.3.9 | https://github.com/droundy/arrayref + +Community Data License Agreement Permissive 2.0 (1) +- webpki-roots@1.0.11 | https://github.com/rustls/webpki-roots + +License Texts +~~~~~~~~~~~~~ + +BSD Zero Clause License (0BSD) +----------------------------------------------------------- + +Applies to: +- adler2@2.0.1 + +Copyright (C) Jonas Schievink + +Permission to use, copy, modify, and/or distribute this software for +any purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN +AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- xkeysym@0.2.1 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2022-2023 John Nunley + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- powerfmt@0.2.0 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023 Jacob Pratt et al. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- deranged@0.5.8 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 Jacob Pratt et al. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- as-raw-xcb-connection@1.0.1 +- encoding_rs@0.8.41 +- kurbo@0.13.1 +- multiversion-macros@0.9.0 +- multiversion@0.9.0 +- multiversion_no_op@1.0.0 +- polycool@0.4.0 +- raw-window-metal@1.1.0 +- static_assertions@1.1.0 +- tinyvec@1.13.3 +- ureq-proto@0.6.5 +- utf8_iter@1.0.4 +- x11rb-protocol@0.13.2 +- x11rb@0.13.2 +- zeroize@1.9.0 +- zeroize_derive@1.5.0 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- linux-raw-sys@0.12.1 +- rustix@1.1.4 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +--- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Licenses for support code +------------------------- + +Parts of the TLS test suite are under the Go license. This code is not included +in BoringSSL (i.e. libcrypto and libssl) when compiled, however, so +distributing code linked against BoringSSL does not trigger this license: + +Copyright (c) 2009 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BoringSSL uses the Chromium test infrastructure to run a continuous build, +trybots etc. The scripts which manage this, and the script for generating build +metadata, are under the Chromium license. Distributing code linked against +BoringSSL does not trigger this license. + +Copyright 2015 The Chromium Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- rangemap@1.8.0 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2019-2022 Jeff Parsons, and [contributors](https://github.com/jeffparsons/rangemap/contributors) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- windows-collections@0.2.0 +- windows-collections@0.3.2 +- windows-core@0.57.0 +- windows-core@0.58.0 +- windows-core@0.61.2 +- windows-core@0.62.2 +- windows-future@0.2.1 +- windows-future@0.3.2 +- windows-implement@0.57.0 +- windows-implement@0.58.0 +- windows-implement@0.60.2 +- windows-interface@0.57.0 +- windows-interface@0.58.0 +- windows-interface@0.59.3 +- windows-link@0.1.3 +- windows-link@0.2.1 +- windows-numerics@0.2.0 +- windows-numerics@0.3.1 +- windows-registry@0.6.1 +- windows-result@0.1.2 +- windows-result@0.2.0 +- windows-result@0.3.4 +- windows-result@0.4.1 +- windows-strings@0.1.0 +- windows-strings@0.4.2 +- windows-strings@0.5.1 +- windows-sys@0.48.0 +- windows-sys@0.52.0 +- windows-sys@0.59.0 +- windows-sys@0.61.2 +- windows-targets@0.48.5 +- windows-targets@0.52.6 +- windows-threading@0.1.0 +- windows-threading@0.2.1 +- windows-version@0.1.7 +- windows@0.57.0 +- windows@0.58.0 +- windows@0.61.3 +- windows@0.62.2 +- windows_aarch64_msvc@0.48.5 +- windows_aarch64_msvc@0.52.6 +- windows_x86_64_gnu@0.48.5 +- windows_x86_64_gnu@0.52.6 +- windows_x86_64_msvc@0.48.5 +- windows_x86_64_msvc@0.52.6 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright (c) Microsoft Corporation. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- zopfli@0.8.4 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2011 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- zerocopy-derive@0.8.57 +- zerocopy@0.8.57 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023 The Fuchsia Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- web-time@1.1.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023 dAxpeDDa + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- moxcms@0.8.1 +- pxfm@0.1.30 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 Radzivon Bartoshyk + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- codespan-reporting@0.13.1 +- rustls-platform-verifier@0.7.1 +- self_cell@1.3.0 +- sys-locale@0.3.2 +- unicode-linebreak@0.1.5 +- ureq@3.4.2 +- zune-core@0.5.3 +- zune-jpeg@0.5.15 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- ntapi@0.4.3 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- cosmic-text@0.19.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- bit_field@0.10.3 +- notify-rust@4.18.0 +- winapi@0.3.9 +- wio@0.2.2 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- crc32fast@1.5.2 +- float-ord@0.3.2 +- foreign-types-macros@0.2.4 +- foreign-types-shared@0.3.1 +- foreign-types@0.5.0 +- hex@0.4.3 +- quick-error@2.0.1 +- serde_spanned@0.6.9 +- toml@0.8.23 +- toml_datetime@0.6.11 +- toml_datetime@1.1.1+spec-1.1.0 +- toml_edit@0.22.27 +- toml_edit@0.25.15+spec-1.1.0 +- toml_parser@1.1.3+spec-1.1.0 +- toml_write@0.1.2 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- async-broadcast@0.7.2 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2020 Yoshua Wuyts + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- futures-channel@0.3.34 +- futures-core@0.3.34 +- futures-executor@0.3.34 +- futures-io@0.3.34 +- futures-macro@0.3.34 +- futures-sink@0.3.34 +- futures-task@0.3.34 +- futures-util@0.3.34 +- futures@0.3.34 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright (c) 2016 Alex Crichton +Copyright (c) 2017 The Tokio Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- typenum@1.20.1 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2014 Paho Lurie-Gregg + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- http@1.5.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2017 http-rs authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- ppv-lite86@0.2.21 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2019 The CryptoCorrosion Contributors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- iana-time-zone@0.1.65 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2020 Andrew Straw + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- gpu-allocator@0.28.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2021 Traverse Research B.V. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- rustls-pki-types@1.15.1 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2023 Dirkjan Ochtman + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- notify-types@1.0.1 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2023 Notify Contributors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- memmap2@0.9.11 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [2015] [Dan Burkert] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- async-recursion@1.1.1 +- core_detect@1.0.0 +- gif@0.14.2 +- weezl@0.1.12 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- addr2line@0.25.1 +- ahash@0.8.12 +- arrayvec@0.7.8 +- async-channel@2.5.0 +- async-executor@1.14.0 +- async-fs@2.2.0 +- async-io@2.6.0 +- async-lock@3.4.2 +- async-net@2.0.0 +- async-process@2.5.0 +- async-signal@0.2.14 +- async-task@4.7.1 +- atomic-waker@1.1.2 +- backtrace@0.3.76 +- base64@0.22.1 +- base64@0.23.1 +- bitflags@1.3.2 +- bitflags@2.13.2 +- blocking@1.7.0 +- bstr@1.13.1 +- bumpalo@3.20.3 +- cfg-if@1.0.4 +- cocoa-foundation@0.2.1 +- cocoa@0.26.1 +- concurrent-queue@2.5.0 +- const-random-macro@0.1.16 +- const-random@0.1.18 +- core-foundation-sys@0.8.7 +- core-foundation@0.10.1 +- core-graphics-types@0.2.0 +- core-graphics@0.24.0 +- core-text@21.0.0 +- crossbeam-deque@0.8.8 +- crossbeam-epoch@0.9.21 +- crossbeam-utils@0.8.23 +- data-url@0.3.2 +- derivative@2.2.0 +- displaydoc@0.2.7 +- either@1.18.0 +- equivalent@1.0.2 +- errno@0.3.14 +- euclid@0.22.14 +- event-listener-strategy@0.5.4 +- event-listener@5.4.2 +- fastrand@2.5.0 +- filetime@0.2.29 +- flate2@1.1.10 +- form_urlencoded@1.2.2 +- futf@0.1.5 +- futures-lite@2.6.1 +- gethostname@1.1.0 +- gimli@0.32.3 +- glob@0.3.4 +- hash32@0.3.1 +- hashbrown@0.14.5 +- hashbrown@0.15.5 +- hashbrown@0.16.1 +- hashbrown@0.17.1 +- heapless@0.9.3 +- heck@0.5.0 +- html5ever@0.27.0 +- httparse@1.10.1 +- idna@1.1.0 +- idna_adapter@1.2.2 +- indexmap@2.14.2 +- itertools@0.13.0 +- itertools@0.14.0 +- khronos-egl@6.0.0 +- lazy_static@1.5.0 +- linux-raw-sys@0.12.1 +- lock_api@0.4.14 +- log@0.4.34 +- markup5ever@0.12.1 +- markup5ever_rcdom@0.3.0 +- metal@0.33.0 +- mime@0.3.17 +- num-bigint-dig@0.9.1 +- num-bigint@0.4.8 +- num-complex@0.4.6 +- num-integer@0.1.47 +- num-iter@0.1.46 +- num-rational@0.4.2 +- num-traits@0.2.19 +- num@0.4.3 +- num_cpus@1.17.0 +- object@0.37.3 +- once_cell@1.21.4 +- openssl-probe@0.2.1 +- ordered-stream@0.2.0 +- parking@2.2.1 +- parking_lot@0.12.5 +- parking_lot_core@0.9.12 +- percent-encoding@2.3.2 +- piper@0.2.5 +- png@0.17.16 +- png@0.18.1 +- polling@3.11.0 +- pollster@0.4.0 +- rayon-core@1.13.0 +- rayon@1.12.0 +- regex-automata@0.4.18 +- regex-syntax@0.8.11 +- regex@1.13.1 +- renderdoc-sys@1.1.0 +- ring@0.17.14 +- roxmltree@0.20.0 +- roxmltree@0.21.1 +- rustc-demangle@0.1.28 +- rustc-hash@1.1.0 +- rustix@1.1.4 +- rustls-native-certs@0.8.4 +- rustls@0.23.45 +- scoped-tls@1.0.1 +- scopeguard@1.2.0 +- security-framework-sys@2.17.0 +- security-framework@3.7.0 +- shellexpand@3.1.2 +- signal-hook-registry@1.4.8 +- simplecss@0.2.2 +- smallvec@1.16.1 +- smol@2.0.2 +- smol_str@0.3.6 +- socket2@0.6.5 +- stable_deref_trait@1.2.1 +- string_cache@0.8.9 +- svgtypes@0.16.1 +- swash@0.2.10 +- syn@1.0.109 +- tempfile@3.27.0 +- tendril@0.4.3 +- ttf-parser@0.25.1 +- unicase@2.9.0 +- unicode-bidi-mirroring@0.4.0 +- unicode-bidi@0.3.18 +- unicode-ccc@0.4.0 +- unicode-id@0.3.6 +- unicode-properties@0.1.3 +- unicode-segmentation@1.13.3 +- unicode-vo@0.1.0 +- unicode-width@0.2.2 +- url@2.5.8 +- uuid@1.26.1 +- wait-timeout@0.2.1 +- waker-fn@1.2.0 +- xml5ever@0.18.1 +- zed-font-kit@0.14.1-zed + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- bit-set@0.9.1 +- bit-vec@0.9.1 +- downcast-rs@1.2.1 +- presser@0.3.1 +- qoi@0.4.1 +- waitpid-any@0.3.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- hkdf@0.12.4 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- aes@0.8.4 +- block-buffer@0.10.4 +- block-buffer@0.12.1 +- block-padding@0.3.3 +- cbc@0.1.2 +- chacha20@0.10.2 +- cipher@0.4.4 +- const-oid@0.10.2 +- cpufeatures@0.2.17 +- cpufeatures@0.3.1 +- crypto-common@0.1.7 +- crypto-common@0.2.2 +- digest@0.10.7 +- digest@0.11.3 +- hmac@0.12.1 +- hybrid-array@0.4.15 +- inout@0.1.4 +- md-5@0.10.6 +- pbkdf2@0.12.2 +- sha1@0.11.0 +- sha2@0.10.9 +- sha2@0.11.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- rand_core@0.10.1 +- rand_core@0.9.5 + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- getrandom@0.2.17 +- getrandom@0.3.4 +- getrandom@0.4.3 + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- ropey@2.0.0-beta.1 +- str_indices@0.4.4 + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- proc-macro-crate@3.5.0 + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/LICENSE-2.0 + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- unicode-script@0.5.8 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2021 The Unicode-rs Developers + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- glow@0.17.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- yazi@0.2.1 +- zeno@0.3.3 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- flume@0.12.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- font-types@0.12.5 +- read-fonts@0.41.0 +- skrifa@0.44.0 + +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and +You must cause any modified files to carry prominent notices stating that You changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +Copyright 2019 Fontations Developers + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- enumflags2@0.7.12 + +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and +You must cause any modified files to carry prominent notices stating that You changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + + +Copyright 2017-2023 Maik Klein, Maja Kądziołka + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- enumflags2_derive@0.7.12 + +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and +You must cause any modified files to carry prominent notices stating that You changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + + +Copyright [2017] [Maik Klein] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- ash@0.38.0+1.3.281 + +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and +You must cause any modified files to carry prominent notices stating that You changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +Copyright 2016 Maik Klein + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- font-types@0.11.3 +- read-fonts@0.37.0 +- skrifa@0.40.0 + +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and +You must cause any modified files to carry prominent notices stating that You changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +Copyright 2019 Colin Rothfels + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- atspi-common@0.13.0 +- atspi-proxies@0.13.0 +- atspi@0.29.0 + +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- glutin_wgl_sys@0.6.1 + +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2022 Kirill Chibisov + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- ctor@1.0.13 +- link-section@0.19.3 +- linktime-proc-macro@0.2.3 + +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- bytemuck@1.25.2 +- bytemuck_derive@1.12.1 + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + + "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- accesskit@0.24.1 +- accesskit_atspi_common@0.19.1 +- accesskit_consumer@0.38.0 +- accesskit_macos@0.26.3 +- accesskit_unix@0.22.1 +- accesskit_windows@0.34.0 +- allocator-api2@0.2.21 +- anyhow@1.0.104 +- async-trait@0.1.92 +- dirs-sys@0.4.1 +- dirs-sys@0.5.0 +- dirs@5.0.1 +- dirs@6.0.0 +- dispatch2@0.3.1 +- document-features@0.2.12 +- dunce@1.0.5 +- dyn-clone@1.0.20 +- enumn@0.1.14 +- etagere@0.2.15 +- fdeflate@0.3.7 +- gpu-descriptor-types@0.2.0 +- gpu-descriptor@0.3.2 +- gpui-kit-assets@0.7.3 +- gpui-kit@0.7.3 +- half@2.7.1 +- ident_case@1.0.1 +- image-webp@0.2.4 +- image@0.25.10 +- inventory@0.3.24 +- itoa@1.0.18 +- libc@0.2.189 +- linebender_resource_handle@0.1.1 +- litrs@1.0.0 +- lyon@1.0.19 +- lyon_algorithms@1.0.21 +- lyon_geom@1.0.19 +- lyon_path@1.0.19 +- lyon_tessellation@1.0.22 +- mac-notification-sys@0.6.15 +- mac@0.1.1 +- mach2@0.6.0 +- miniz_oxide@0.8.9 +- miniz_oxide@0.9.1 +- naga@29.0.4 +- normpath@1.5.1 +- num-conv@0.2.2 +- objc2-app-kit@0.3.2 +- objc2-cloud-kit@0.3.2 +- objc2-core-data@0.3.2 +- objc2-core-foundation@0.3.2 +- objc2-core-graphics@0.3.2 +- objc2-core-image@0.3.2 +- objc2-core-text@0.3.2 +- objc2-core-video@0.3.2 +- objc2-metal@0.3.2 +- objc2-quartz-core@0.3.2 +- objc2-security@0.3.2 +- objc2-user-notifications@0.3.2 +- paste@1.0.15 +- pastey@0.2.3 +- pathfinder_geometry@0.5.1 +- pathfinder_simd@0.5.6 +- pin-project-internal@1.1.13 +- pin-project-lite@0.2.17 +- pin-project@1.1.13 +- proc-macro2@1.0.107 +- profiling-procmacros@1.0.18 +- profiling@1.0.18 +- quote@1.0.47 +- rand@0.10.2 +- rand@0.9.5 +- rand_chacha@0.9.0 +- range-alloc@0.1.5 +- raw-window-handle@0.6.2 +- ref-cast-impl@1.0.27 +- ref-cast@1.0.27 +- resvg@0.46.0 +- rmcp-macros@3.5.1 +- rmcp@3.5.1 +- rustc-hash@2.1.3 +- rustversion@1.0.23 +- ryu@1.0.23 +- semver@1.0.28 +- serde@1.0.229 +- serde_bytes@0.11.19 +- serde_core@1.0.229 +- serde_derive@1.0.229 +- serde_derive_internals@0.30.0 +- serde_json@1.0.151 +- serde_repr@0.1.21 +- serde_urlencoded@0.7.1 +- simdutf8@0.1.5 +- siphasher@1.0.3 +- spirv@0.4.0+sdk-1.4.341.0 +- svg_fmt@0.4.5 +- syn@2.0.119 +- syn@3.0.5 +- tauri-winrt-notification@0.7.3 +- thiserror-impl@1.0.69 +- thiserror-impl@2.0.20 +- thiserror@1.0.69 +- thiserror@2.0.20 +- time-core@0.1.9 +- time@0.3.55 +- typed-path@0.12.4 +- unicode-ident@1.0.24 +- usvg@0.46.0 +- utf-8@0.7.6 +- utf8-zero@0.8.1 +- wgpu-core-deps-apple@29.0.4 +- wgpu-core-deps-windows-linux-android@29.0.4 +- wgpu-core@29.0.4 +- wgpu-hal@29.0.4 +- wgpu-naga-bridge@29.0.4 +- wgpu-types@29.0.4 +- wgpu@29.0.4 +- zune-inflate@0.2.54 + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- gpui-pre-apple@0.3.9 +- gpui-pre-collections@0.3.9 +- gpui-pre-derive-refineable@0.3.9 +- gpui-pre-http-client@0.3.9 +- gpui-pre-linux@0.3.9 +- gpui-pre-macos@0.3.9 +- gpui-pre-macros@0.3.9 +- gpui-pre-platform@0.3.9 +- gpui-pre-refineable@0.3.9 +- gpui-pre-scheduler@0.3.9 +- gpui-pre-shared-string@0.3.9 +- gpui-pre-sum-tree@0.3.9 +- gpui-pre-util@0.3.9 +- gpui-pre-wgpu@0.3.9 +- gpui-pre-windows@0.3.9 +- gpui-pre-ztracing-macro@0.3.9 +- gpui-pre-ztracing@0.3.9 +- gpui-pre@0.3.9 + +Copyright 2022 - 2025 Zed Industries, Inc. + + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + + http://www.apache.org/licenses/LICENSE-2.0 + + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + + 1. Definitions. + + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + + END OF TERMS AND CONDITIONS + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- gpui-base@0.7.3 + +Copyright 2024 - 2026 Longbridge + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- chrono@0.4.45 + +Rust-chrono is dual-licensed under The MIT License [1] and +Apache 2.0 License [2]. Copyright (c) 2014--2026, Kang Seonghoon and +contributors. + +Nota Bene: This is same as the Rust Project's own license. + + +[1]: , which is reproduced below: + +~~~~ +The MIT License (MIT) + +Copyright (c) 2014, Kang Seonghoon. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +~~~~ + + +[2]: , which is reproduced below: + +~~~~ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +~~~~ + + + +BSD 2-Clause "Simplified" License (BSD-2-Clause) +----------------------------------------------------------- + +Applies to: +- arrayref@0.3.9 + +Copyright (c) 2015 David Roundy +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) +----------------------------------------------------------- + +Applies to: +- encoding_rs@0.8.41 + +// Copyright © WHATWG (Apple, Google, Mozilla, Microsoft). +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +/// The PUA code points special-cased in the GB18030 encoder. +pub(crate) static GB18030_2022_OVERRIDE_PUA: [u16; 18] = [ + 0xE78D, 0xE78E, 0xE78F, 0xE790, 0xE791, 0xE792, 0xE793, 0xE794, 0xE795, 0xE796, 0xE81E, 0xE826, + 0xE82B, 0xE82C, 0xE832, 0xE843, 0xE854, 0xE864, +]; + +/// The bytes corresponding to the PUA code points special-cased in the GB18030 encoder. +pub(crate) static GB18030_2022_OVERRIDE_BYTES: [[u8; 2]; 18] = [ + [0xA6, 0xD9], + [0xA6, 0xDA], + [0xA6, 0xDB], + [0xA6, 0xDC], + [0xA6, 0xDD], + [0xA6, 0xDE], + [0xA6, 0xDF], + [0xA6, 0xEC], + [0xA6, 0xED], + [0xA6, 0xF3], + [0xFE, 0x59], + [0xFE, 0x61], + [0xFE, 0x66], + [0xFE, 0x67], + [0xFE, 0x6D], + [0xFE, 0x7E], + [0xFE, 0x90], + [0xFE, 0xA0], +]; + + +BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) +----------------------------------------------------------- + +Applies to: +- tiny-skia-path@0.11.4 +- tiny-skia@0.11.4 + +Copyright (c) 2011 Google Inc. All rights reserved. +Copyright (c) 2020 Yevhenii Reizner All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + * Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) +----------------------------------------------------------- + +Applies to: +- subtle@2.6.1 + +Copyright (c) 2016-2017 Isis Agora Lovecruft, Henry de Valence. All rights reserved. +Copyright (c) 2016-2024 Isis Agora Lovecruft. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) +----------------------------------------------------------- + +Applies to: +- instant@0.1.13 + +Copyright (c) 2019, Sébastien Crozet +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the author nor the names of its contributors may be used + to endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) +----------------------------------------------------------- + +Applies to: +- lebe@0.5.3 + +Copyright (c) 2022 Contributors to the lebe Project. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors +may be used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) +----------------------------------------------------------- + +Applies to: +- exr@1.74.2 +- sha1_smol@1.0.1 + +Copyright (c) . + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) +----------------------------------------------------------- + +Applies to: +- encoding_rs@0.8.41 + +Copyright © WHATWG (Apple, Google, Mozilla, Microsoft). + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +Creative Commons Zero v1.0 Universal (CC0-1.0) +----------------------------------------------------------- + +Applies to: +- notify@7.0.0 + +Creative Commons CC0 1.0 Universal + +<> CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER. <> + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; + + ii. moral rights retained by the original author(s) and/or performer(s); + + iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; + + iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; + + v. rights protecting the extraction, dissemination, use and reuse of data in a Work; + + vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and + + vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. + + b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. + + c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. + + d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. + +Creative Commons Zero v1.0 Universal (CC0-1.0) +----------------------------------------------------------- + +Applies to: +- hexf-parse@0.2.1 +- tiny-keccak@2.0.2 + +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. + + +Community Data License Agreement Permissive 2.0 (CDLA-Permissive-2.0) +----------------------------------------------------------- + +Applies to: +- webpki-roots@1.0.11 + +# Community Data License Agreement - Permissive - Version 2.0 + +This is the Community Data License Agreement - Permissive, Version +2.0 (the "agreement"). Data Provider(s) and Data Recipient(s) agree +as follows: + +## 1. Provision of the Data + +1.1. A Data Recipient may use, modify, and share the Data made +available by Data Provider(s) under this agreement if that Data +Recipient follows the terms of this agreement. + +1.2. This agreement does not impose any restriction on a Data +Recipient's use, modification, or sharing of any portions of the +Data that are in the public domain or that may be used, modified, +or shared under any other legal exception or limitation. + +## 2. Conditions for Sharing Data + +2.1. A Data Recipient may share Data, with or without modifications, so +long as the Data Recipient makes available the text of this agreement +with the shared Data. + +## 3. No Restrictions on Results + +3.1. This agreement does not impose any restriction or obligations +with respect to the use, modification, or sharing of Results. + +## 4. No Warranty; Limitation of Liability + +4.1. All Data Recipients receive the Data subject to the following +terms: + +THE DATA IS PROVIDED ON AN "AS IS" BASIS, WITHOUT REPRESENTATIONS, +WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED +INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, +NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +NO DATA PROVIDER SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING +WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE DATA OR RESULTS, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +## 5. Definitions + +5.1. "Data" means the material received by a Data Recipient under +this agreement. + +5.2. "Data Provider" means any person who is the source of Data +provided under this agreement and in reliance on a Data Recipient's +agreement to its terms. + +5.3. "Data Recipient" means any person who receives Data directly +or indirectly from a Data Provider and agrees to the terms of this +agreement. + +5.4. "Results" means any outcome obtained by computational analysis +of Data, including for example machine learning models and models' +insights. + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +/* Copyright (c) 2014, Intel Corporation. + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION + * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ + +#ifndef OPENSSL_HEADER_EC_ECP_NISTZ384_H +#define OPENSSL_HEADER_EC_ECP_NISTZ384_H + +#include "../../limbs/limbs.h" + +#define P384_LIMBS (384u / LIMB_BITS) + +typedef struct { + Limb X[P384_LIMBS]; + Limb Y[P384_LIMBS]; + Limb Z[P384_LIMBS]; +} P384_POINT; + +typedef struct { + Limb X[P384_LIMBS]; + Limb Y[P384_LIMBS]; +} P384_POINT_AFFINE; + + +#endif // OPENSSL_HEADER_EC_ECP_NISTZ384_H + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2015-2016 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +//! EdDSA Signatures. + +use super::ops::ELEM_LEN; +use crate::digest; + +pub mod signing; +pub mod verification; + +/// The length of an Ed25519 public key. +pub const ED25519_PUBLIC_KEY_LEN: usize = ELEM_LEN; + +pub fn eddsa_digest(signature_r: &[u8], public_key: &[u8], msg: &[u8]) -> digest::Digest { + let mut ctx = digest::Context::new(&digest::SHA512); + ctx.update(signature_r); + ctx.update(public_key); + ctx.update(msg); + ctx.finish() +} + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- untrusted@0.9.0 + +// Copyright 2015-2016 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2015-2022 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +use crate::limb::Limb; + +#[derive(Clone, Copy)] +#[repr(transparent)] +pub struct N0([Limb; 2]); + +impl N0 { + #[cfg(feature = "alloc")] + pub(super) const LIMBS_USED: usize = 64 / crate::limb::LIMB_BITS; + + #[inline] + pub const fn precalculated(n0: u64) -> Self { + #[cfg(target_pointer_width = "64")] + { + Self([n0, 0]) + } + + #[cfg(target_pointer_width = "32")] + { + Self([n0 as Limb, (n0 >> crate::limb::LIMB_BITS) as Limb]) + } + } +} + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2015-2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +use crate::{bb, error}; + +#[deprecated( + note = "To be removed. Internal function not intended for external use with no promises regarding side channels." +)] +pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> { + bb::verify_slices_are_equal(a, b) +} + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2016 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +//! Elliptic curve operations and schemes using Curve25519. + +pub mod ed25519; + +pub mod x25519; + +mod ops; +mod scalar; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2016-2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +use crate::error::{KeyRejected, Unspecified}; + +impl From for Unspecified { + fn from(source: untrusted::EndOfInput) -> Self { + super::erase(source) + } +} + +impl From for Unspecified { + fn from(source: core::array::TryFromSliceError) -> Self { + super::erase(source) + } +} + +impl From for Unspecified { + fn from(source: KeyRejected) -> Self { + super::erase(source) + } +} + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2018 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +//! Serialization and deserialization. + +#[doc(hidden)] +pub mod der; + +#[cfg(feature = "alloc")] +mod writer; + +#[cfg(feature = "alloc")] +pub(crate) mod der_writer; + +pub(crate) mod positive; + +pub use self::positive::Positive; + +#[cfg(feature = "alloc")] +pub(crate) use self::writer::TooLongError; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2019-2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +use super::BlockLen; + +pub(super) use self::{ + sha2_32::{block_data_order_32, State32, SHA256_BLOCK_LEN}, + sha2_64::{block_data_order_64, State64, SHA512_BLOCK_LEN}, +}; + +pub(super) const CHAINING_WORDS: usize = 8; + +#[cfg(any( + all(target_arch = "aarch64", target_endian = "little"), + all(target_arch = "arm", target_endian = "little"), + target_arch = "x86_64" +))] +#[macro_use] +mod ffi; + +pub(super) mod fallback; +mod sha2_32; +mod sha2_64; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// TODO(MSRV 1.76): Replace with `core::ptr::from_mut`. +#[allow(dead_code)] +#[inline(always)] +pub fn from_mut(r: &mut T) -> *mut T { + r +} + +// TODO(MSRV 1.76): Replace with `core::ptr::from_ref`. +#[allow(dead_code)] +#[inline(always)] +pub const fn from_ref(r: &T) -> *const T { + r +} + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +//! Integration tests for non-public APIs. + +mod bits_tests; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +pub use self::{ + array::Array, + base::{IndexError, Overlapping}, + partial_block::PartialBlock, +}; + +mod array; +mod base; +mod partial_block; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +#![cfg(all(target_arch = "aarch64", target_endian = "little"))] + +pub(in super::super) mod mont; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +#![cfg(target_arch = "x86_64")] + +pub(in super::super::super) mod mont; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +mod storage; + +pub(super) use self::storage::{AlignedStorage, LIMBS_PER_CHUNK}; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +pub(super) mod aarch64; +pub(super) mod x86_64; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- inotify-sys@0.1.8 + +Copyright (c) Hanno Braun and contributors + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- inotify@0.10.2 + +Copyright (c) Hanno Braun and contributors + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +Copyright 2015-2025 Brian Smith. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- libloading@0.8.9 + +Copyright © 2015, Simonas Kazlauskas + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without +fee is hereby granted, provided that the above copyright notice and this permission notice appear +in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE +AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, +NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- rustls-webpki@0.103.15 + +Except as otherwise noted, this project is licensed under the following +(ISC-style) terms: + +Copyright 2015 Brian Smith. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +The files under third-party/chromium are licensed as described in +third-party/chromium/LICENSE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- rustybuzz@0.20.1 + + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- uds_windows@1.2.1 + + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- freetype-sys@0.20.1 + +# +# FreeType 2 BDF module definition +# + +# Copyright 2001, 2002, 2006 by +# Francesco Zappa Nardelli +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + + +FTMODULE_H_COMMANDS += BDF_DRIVER + +define BDF_DRIVER +$(OPEN_DRIVER) FT_Driver_ClassRec, bdf_driver_class $(CLOSE_DRIVER) +$(ECHO_DRIVER)bdf $(ECHO_DRIVER_DESC)bdf bitmap fonts$(ECHO_DRIVER_DONE) +endef + +# EOF + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- freetype-sys@0.20.1 + +# +# FreeType 2 PCF module definition +# + +# Copyright 2000, 2006 by +# Francesco Zappa Nardelli +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + + +FTMODULE_H_COMMANDS += PCF_DRIVER + +define PCF_DRIVER +$(OPEN_DRIVER) FT_Driver_ClassRec, pcf_driver_class $(CLOSE_DRIVER) +$(ECHO_DRIVER)pcf $(ECHO_DRIVER_DESC)pcf bitmap fonts$(ECHO_DRIVER_DONE) +endef + +# EOF + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- schemars@1.2.2 + +#![allow(clippy::all)] +use crate::_alloc_prelude::*; +// Copied from regex_syntax crate to avoid pulling in the whole crate just for a utility function +// https://github.com/rust-lang/regex/blob/431c4e4867e1eb33eb39b23ed47c9934b2672f8f/regex-syntax/src/lib.rs +// +// Copyright (c) 2014 The Rust Project Developers +// +// Permission is hereby granted, free of charge, to any +// person obtaining a copy of this software and associated +// documentation files (the "Software"), to deal in the +// Software without restriction, including without +// limitation the rights to use, copy, modify, merge, +// publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software +// is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice +// shall be included in all copies or substantial portions +// of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +// DEALINGS IN THE SOFTWARE. + +pub fn escape(text: &str) -> String { + let mut quoted = String::new(); + escape_into(text, &mut quoted); + quoted +} + +fn escape_into(text: &str, buf: &mut String) { + buf.reserve(text.len()); + for c in text.chars() { + if is_meta_character(c) { + buf.push('\\'); + } + buf.push(c); + } +} + +fn is_meta_character(c: char) -> bool { + match c { + '\\' | '.' | '+' | '*' | '?' | '(' | ')' | '|' | '[' | ']' | '{' | '}' | '^' | '$' + | '#' | '&' | '-' | '~' => true, + _ => false, + } +} + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- markdown@1.0.0 + +(The MIT License) + +Copyright (c) 2022 Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- freetype-sys@0.20.1 + +/* + * Copyright 2001, 2002, 2012 Francesco Zappa Nardelli + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COMPUTING RESEARCH LAB OR NEW MEXICO STATE UNIVERSITY BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT + * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR + * THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + /************************************************************************** + * + * This file is used to define the BDF error enumeration constants. + * + */ + +#ifndef BDFERROR_H_ +#define BDFERROR_H_ + +#include + +#undef FTERRORS_H_ + +#undef FT_ERR_PREFIX +#define FT_ERR_PREFIX BDF_Err_ +#define FT_ERR_BASE FT_Mod_Err_BDF + +#include + +#endif /* BDFERROR_H_ */ + + +/* END */ + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- freetype-sys@0.20.1 + +/* bdf.c + + FreeType font driver for bdf files + + Copyright (C) 2001, 2002 by + Francesco Zappa Nardelli + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + + +#define FT_MAKE_OPTION_SINGLE_OBJECT + +#include "bdflib.c" +#include "bdfdrivr.c" + + +/* END */ + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- freetype-sys@0.20.1 + +/* bdfdrivr.h + + FreeType font driver for bdf fonts + + Copyright (C) 2001, 2002, 2003, 2004 by + Francesco Zappa Nardelli + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + + +#ifndef BDFDRIVR_H_ +#define BDFDRIVR_H_ + +#include + +#include "bdf.h" + + +FT_BEGIN_HEADER + + + typedef struct BDF_encoding_el_ + { + FT_ULong enc; + FT_UShort glyph; + + } BDF_encoding_el; + + + typedef struct BDF_FaceRec_ + { + FT_FaceRec root; + + char* charset_encoding; + char* charset_registry; + + bdf_font_t* bdffont; + + BDF_encoding_el* en_table; + + FT_UInt default_glyph; + + } BDF_FaceRec, *BDF_Face; + + + FT_EXPORT_VAR( const FT_Driver_ClassRec ) bdf_driver_class; + + +FT_END_HEADER + + +#endif /* BDFDRIVR_H_ */ + + +/* END */ + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- freetype-sys@0.20.1 + +/* pcf.c + + FreeType font driver for pcf fonts + + Copyright 2000-2001, 2003 by + Francesco Zappa Nardelli + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + + +#define FT_MAKE_OPTION_SINGLE_OBJECT + +#include "pcfdrivr.c" +#include "pcfread.c" +#include "pcfutil.c" + + +/* END */ + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- freetype-sys@0.20.1 + +/* pcfdrivr.h + + FreeType font driver for pcf fonts + + Copyright 2000-2001, 2002 by + Francesco Zappa Nardelli + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + + +#ifndef PCFDRIVR_H_ +#define PCFDRIVR_H_ + +#include + + +FT_BEGIN_HEADER + + FT_EXPORT_VAR( const FT_Driver_ClassRec ) pcf_driver_class; + +FT_END_HEADER + + +#endif /* PCFDRIVR_H_ */ + + +/* END */ + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- freetype-sys@0.20.1 + +/* pcfread.h + + FreeType font driver for pcf fonts + + Copyright 2003 by + Francesco Zappa Nardelli + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + + +#ifndef PCFREAD_H_ +#define PCFREAD_H_ + + + +FT_BEGIN_HEADER + + FT_LOCAL( PCF_Property ) + pcf_find_property( PCF_Face face, + const FT_String* prop ); + +FT_END_HEADER + +#endif /* PCFREAD_H_ */ + + +/* END */ + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- freetype-sys@0.20.1 + +/* pcfutil.h + + FreeType font driver for pcf fonts + + Copyright 2000, 2001, 2004 by + Francesco Zappa Nardelli + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + + +#ifndef PCFUTIL_H_ +#define PCFUTIL_H_ + + +#include +#include FT_CONFIG_CONFIG_H +#include + +FT_BEGIN_HEADER + + FT_LOCAL( void ) + BitOrderInvert( unsigned char* buf, + size_t nbytes ); + + FT_LOCAL( void ) + TwoByteSwap( unsigned char* buf, + size_t nbytes ); + + FT_LOCAL( void ) + FourByteSwap( unsigned char* buf, + size_t nbytes ); + +FT_END_HEADER + +#endif /* PCFUTIL_H_ */ + + +/* END */ + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- mio@1.2.3 + +Copyright (c) 2014 Carl Lerche and other MIO contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- float-cmp@0.9.0 + +Copyright (c) 2014-2020 Optimal Computing (NZ) Ltd + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- wayland-backend@0.3.17 +- wayland-client@0.31.15 +- wayland-cursor@0.31.14 +- wayland-protocols-plasma@0.3.12 +- wayland-protocols-wlr@0.3.12 +- wayland-protocols@0.32.13 +- wayland-scanner@0.31.11 +- wayland-sys@0.31.11 + +Copyright (c) 2015 Elinor Berger + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- new_debug_unreachable@1.0.6 +- ordered-float@5.5.0 + +Copyright (c) 2015 Jonathan Reem + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- dlib@0.5.3 + +Copyright (c) 2015 Victor Berger + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- which@8.0.6 + +Copyright (c) 2015 fangyuanziti + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- schannel@0.1.29 + +Copyright (c) 2015 steffengy + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- xkbcommon@0.8.0 + +Copyright (c) 2016 Remi Thebault + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- memoffset@0.9.1 + +Copyright (c) 2017 Gilad Naaman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- bytes@1.12.1 + +Copyright (c) 2018 Carl Lerche + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- calloop@0.14.4 + +Copyright (c) 2018 Victor Berger + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- slab@0.4.12 + +Copyright (c) 2019 Carl Lerche + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- tracing-attributes@0.1.31 +- tracing-core@0.1.36 +- tracing@0.1.44 + +Copyright (c) 2019 Tokio Contributors + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- pico-args@0.5.0 + +Copyright (c) 2019 Yevhenii Reizner + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- http-body@1.1.0 + +Copyright (c) 2019-2026 Sean McArthur & Hyper Contributors + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- strict-num@0.1.1 + +Copyright (c) 2022 Yevhenii Reizner + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- calloop-wayland-source@0.4.1 + +Copyright (c) 2023 Kirill Chibisov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- zbus@5.19.0 +- zbus_macros@5.19.0 +- zbus_names@4.3.4 +- zbus_xml@5.2.1 +- zvariant@5.15.0 +- zvariant_derive@5.15.0 + +Copyright (c) 2024 Zeeshan Ali Khan & zbus contributors + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- zcheapstr@1.1.0 + +Copyright (c) 2026 Zeeshan Ali Khan & zcheapstr contributors + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- synstructure@0.13.2 + +Copyright 2016 Nika Layzell + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- trash@5.2.9 + +Copyright 2019 Artúr Barnabás Kovács + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- wayland-protocols@0.32.13 + +Copyright © 2008-2013 Kristian Høgsberg +Copyright © 2010-2013 Intel Corporation +Copyright © 2013 Rafael Antognolli +Copyright © 2013 Jasper St. Pierre +Copyright © 2014 Jonas Ådahl +Copyright © 2014 Jason Ekstrand +Copyright © 2014-2015 Collabora, Ltd. +Copyright © 2015 Red Hat Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice (including the next +paragraph) shall be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + +--- + +The above is the version of the MIT "Expat" License used by X.org: + + http://cgit.freedesktop.org/xorg/xserver/tree/COPYING + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- fax@0.2.7 + +Copyright © 2021 The pdf-rs contributers. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- precomputed-hash@0.1.1 + +MIT License + +Copyright (c) 2017 Emilio Cobos Álvarez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- darling@0.24.1 +- darling_core@0.24.1 +- darling_macro@0.24.1 + +MIT License + +Copyright (c) 2017 Ted Driggs + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- tiff@0.11.3 + +MIT License + +Copyright (c) 2018 PistonDevelopers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- filedescriptor@0.8.3 + +MIT License + +Copyright (c) 2018 Wez Furlong + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- schemars@1.2.2 +- schemars_derive@1.2.2 + +MIT License + +Copyright (c) 2019 Graham Esau + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- rgb@0.8.53 + +MIT License + +Copyright (c) 2019 Kornel + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- strum@0.28.0 +- strum_macros@0.28.0 + +MIT License + +Copyright (c) 2019 Peter Glotfelty + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- tokio-macros@2.7.2 + +MIT License + +Copyright (c) 2019 Yoshua Wuyts +Copyright (c) Tokio Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- ashpd@0.13.13 + +MIT License + +Copyright (c) 2020 Bilal Elmoussaoui + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- zed-xim@0.4.0-zed + +MIT License + +Copyright (c) 2020 Riey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- xcursor@0.3.11 + +MIT License + +Copyright (c) 2020 Samuele Esposito + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- float_next_after@1.0.0 + +MIT License + +Copyright (c) 2020 Scripta Qumranica Electronica + +Created by Bronson Brown-deVost + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- pulp@0.22.3 + +MIT License + +Copyright (c) 2021 sarah + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- oo7@0.6.0 + +MIT License + +Copyright (c) 2022 Bilal Elmoussaoui, Sophie Herold, Maximiliano Sandoval, Dhanuka Warusadura + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- reborrow@0.5.5 + +MIT License + +Copyright (c) 2022 sarah + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- is-docker@0.2.0 +- is-wsl@0.4.0 + +MIT License + +Copyright (c) 2023 Sean Larkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- core_maths@0.1.1 + +MIT License + +Copyright (c) 2024 Robert Bastian + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- convert_case@0.10.0 + +MIT License + +Copyright (c) 2025 rutrum + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- gpui-omarchy@0.2.1 + +MIT License + +Copyright (c) 2026 Jason Lee (huacnlee) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- disktree-app@0.17.0 +- disktree-core@0.17.0 +- disktree-link@0.17.0 +- disktree-mcp@0.17.0 +- disktree-scan@0.17.0 +- xtask@0.17.0 +- block2@0.6.2 +- block@0.1.6 +- harfrust@0.5.2 +- libm@0.2.16 +- malloc_buf@0.0.6 +- objc-sys@0.3.5 +- objc2-app-kit@0.2.2 +- objc2-encode@4.1.0 +- objc2-foundation@0.2.2 +- objc2-foundation@0.3.2 +- objc2@0.5.2 +- objc2@0.6.4 +- pulp-wasm-simd-flag@0.1.1 +- seahash@4.1.0 +- taffy@0.13.0 +- velopack@1.2.161 +- xim-ctext@0.3.0 +- xim-parser@0.2.2 + +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- objc@0.2.7 + +MIT License + +Copyright (c) Steven Sheldon + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- tokio-util@0.7.19 +- tokio@1.53.1 + +MIT License + +Copyright (c) Tokio Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- simd-adler32@0.3.10 + +MIT License + +Copyright (c) [2021] [Marvin Countryman] + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- imagesize@0.14.0 + +MIT License + +Copyright (c) 2017 Maiddog + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- fontconfig-parser@0.5.8 + +MIT License + +Copyright (c) 2021 Riey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- fluent-uri@0.1.4 + +MIT License + +Copyright (c) 2021 Scallop Ye + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- wayland-protocols-plasma@0.3.12 + +MIT License Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice (including the next +paragraph) shall be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS +OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF +OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- endi@1.1.1 +- zbus-lockstep-macros@0.5.2 +- zbus-lockstep@0.5.2 +- zmij@1.0.23 +- zvariant_utils@4.2.0 + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- winnow@0.7.15 +- winnow@1.0.4 + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- spin@0.10.1 +- spin@0.9.9 + +The MIT License (MIT) + +Copyright (c) 2014 Mathijs van de Nes + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- tracing-core@0.1.36 +- zip@8.6.0 + +The MIT License (MIT) + +Copyright (c) 2014 Mathijs van de Nes + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- freetype-sys@0.20.1 + +The MIT License (MIT) + +Copyright (c) 2014 PistonDevelopers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- xml@1.4.0 + +The MIT License (MIT) + +Copyright (c) 2014 Vladimir Matveev + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- phf@0.11.3 +- phf@0.13.1 +- phf_generator@0.13.1 +- phf_macros@0.13.1 +- phf_shared@0.11.3 +- phf_shared@0.13.1 + +The MIT License (MIT) + +Copyright (c) 2014-2022 Steven Fackler, Yuki Okushi + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- aho-corasick@1.1.5 +- byteorder-lite@0.1.0 +- byteorder@1.5.0 +- globset@0.4.20 +- memchr@2.8.3 +- walkdir@2.5.0 + +The MIT License (MIT) + +Copyright (c) 2015 Andrew Gallant + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- strsim@0.11.1 + +The MIT License (MIT) + +Copyright (c) 2015 Danny Guo +Copyright (c) 2016 Titus Wormer +Copyright (c) 2018 Akash Kurdekar + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- raw-cpuid@11.6.0 + +The MIT License (MIT) + +Copyright (c) 2015 Gerd Zellweger + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- sysinfo@0.31.4 + +The MIT License (MIT) + +Copyright (c) 2015 Guillaume Gomez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- fsevent-sys@4.1.0 + +The MIT License (MIT) + +Copyright (c) 2015 Pierre Baillet + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- derive_more-impl@2.1.1 +- derive_more@2.1.1 + +The MIT License (MIT) + +Copyright (c) 2016 Jelte Fennema + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- lsp-types@0.97.0 + +The MIT License (MIT) + +Copyright (c) 2016 Markus Westerlind + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- color_quant@1.1.0 + +The MIT License (MIT) + +Copyright (c) 2016 PistonDevelopers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- same-file@1.0.6 +- winapi-util@0.1.11 + +The MIT License (MIT) + +Copyright (c) 2017 Andrew Gallant + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- rust-embed-impl@8.12.0 +- rust-embed-utils@8.12.0 +- rust-embed@8.12.0 + +The MIT License (MIT) + +Copyright (c) 2018 pyros2097 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- xmlwriter@0.1.0 + +The MIT License (MIT) + +Copyright (c) 2019 Reizner Evgeniy + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- fontdb@0.23.0 + +The MIT License (MIT) + +Copyright (c) 2020 Yevhenii Reizner + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- rustybuzz@0.20.1 + +The MIT License (MIT) + +Copyright (c) HarfBuzz developers +Copyright (c) 2020 Yevhenii Reizner + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- crunchy@0.2.4 + +The MIT License (MIT) + +Copyright 2017-2023 Eira Fransham. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- yeslogic-fontconfig-sys@6.0.1 + +The MIT License (MIT) + +Copyright 2019 YesLogic Pty. Ltd. +Copyright 2016 Manuel Reinhardt +Copyright 2014 Austin Bonander +Copyright 2013 The Servo Project Developers. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- open@5.4.4 + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- mime_guess@2.0.5 + +The MIT License (MIT) + +Copyright (c) 2015 Austin Bonander + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- generic-array@0.14.7 + +The MIT License (MIT) + +Copyright (c) 2015 Bartłomiej Kamiński + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- quick-xml@0.41.0 + +The MIT License (MIT) + +Copyright (c) 2016 Johann Tuffe + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- urlencoding@2.1.3 + +© 2016 Bertram Truong +© 2021 Kornel Lesiński + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +Mozilla Public License 2.0 (MPL-2.0) +----------------------------------------------------------- + +Applies to: +- dwrote@0.11.5 +- option-ext@0.2.0 + +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. + + +Unicode License v3 (Unicode-3.0) +----------------------------------------------------------- + +Applies to: +- unicode-ident@1.0.24 + +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2023 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. + + +Unicode License v3 (Unicode-3.0) +----------------------------------------------------------- + +Applies to: +- icu_collections@2.3.0 +- icu_locale_core@2.3.0 +- icu_normalizer@2.3.0 +- icu_normalizer_data@2.3.0 +- icu_properties@2.3.0 +- icu_properties_data@2.3.0 +- icu_provider@2.3.1 +- litemap@0.8.3 +- potential_utf@0.1.6 +- tinystr@0.8.4 +- writeable@0.6.4 +- yoke-derive@0.8.2 +- yoke@0.8.3 +- zerofrom-derive@0.1.7 +- zerofrom@0.1.8 +- zerotrie@0.2.5 +- zerovec-derive@0.11.6 +- zerovec@0.11.8 + +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 2020-2024 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. + +SPDX-License-Identifier: Unicode-3.0 + +— + +Portions of ICU4X may have been adapted from ICU4C and/or ICU4J. +ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others. + + +zlib License (Zlib) +----------------------------------------------------------- + +Applies to: +- zlib-rs@0.6.7 + +(C) 2024 Trifecta Tech Foundation + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + +3. This notice may not be removed or altered from any source distribution. + + +zlib License (Zlib) +----------------------------------------------------------- + +Applies to: +- slotmap@1.1.1 + +Copyright (c) 2021 Orson Peters + +This software is provided 'as-is', without any express or implied warranty. In +no event will the authors be held liable for any damages arising from the use of +this software. + +Permission is granted to anyone to use this software for any purpose, including +commercial applications, and to alter it and redistribute it freely, subject to +the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not claim + that you wrote the original software. If you use this software in a product, + an acknowledgment in the product documentation would be appreciated but is + not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source distribution. + + +zlib License (Zlib) +----------------------------------------------------------- + +Applies to: +- foldhash@0.1.5 +- foldhash@0.2.0 + +Copyright (c) 2024 Orson Peters + +This software is provided 'as-is', without any express or implied warranty. In +no event will the authors be held liable for any damages arising from the use of +this software. + +Permission is granted to anyone to use this software for any purpose, including +commercial applications, and to alter it and redistribute it freely, subject to +the following restrictions: + +1. The origin of this software must not be misrepresented; you must not claim + that you wrote the original software. If you use this software in a product, + an acknowledgment in the product documentation would be appreciated but is + not required. + +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + +3. This notice may not be removed or altered from any source distribution. diff --git a/assets/screenshot.png b/assets/screenshot.png index b3ba0610..085a2862 100644 Binary files a/assets/screenshot.png and b/assets/screenshot.png differ diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 00000000..a27d7d7c --- /dev/null +++ b/clippy.toml @@ -0,0 +1,12 @@ +# The product's name and its family's, so doc comments can say them without +# backticks. ".." keeps clippy's own list. +doc-valid-idents = [ + "PwrDisk", + "PwrRoute", + "PwrGit", + "PwrAgnt", + "PwrAgent", + "PwrSnap", + "PwrSuite", + "..", +] diff --git a/crates/disktree-app/Cargo.toml b/crates/disktree-app/Cargo.toml index 4bc758a2..484ac2c7 100644 --- a/crates/disktree-app/Cargo.toml +++ b/crates/disktree-app/Cargo.toml @@ -4,30 +4,89 @@ version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true +repository.workspace = true description = "GPUI treemap explorer for disk usage, in Omarchy's visual language" [[bin]] -name = "disktree" +name = "pwrdisk" path = "src/main.rs" [lints] workspace = true [dependencies] -gpui-kit = { version = "=0.6.6", default-features = false, features = ["assets"] } -gpui-omarchy = "0.1.3" +gpui-kit = { version = "=0.7.3", default-features = false, features = ["assets"] } +gpui-omarchy = "0.2.1" disktree-core = { workspace = true } +disktree-link = { workspace = true } +disktree-mcp = { workspace = true } anyhow = { workspace = true } dunce = "1.0.5" rustc-hash = { workspace = true } tempfile = "3" +# Installer and auto-updater. Pinned with `=` because the `vpk` CLI that +# packs releases must be the same version: VPK_VERSION (and its SHA-512) in +# scripts/release/install-vpk.sh. Upgrade them together. +velopack = "=1.2.161" +# Velopack logs through `log`; the updater's own lines go there too, and +# diag_log.rs writes them all to main.log. +log = "0.4" +# The log's and the diagnostics' local times. Already in the tree. +chrono = { version = "0.4", default-features = false, features = ["clock"] } +# Wakes the window when a background update check changes what it shows. +# Already in the tree through GPUI. +async-channel = "2" +# The release channel: SemVer precedence for picking each slot's release. +# Already in the tree through Velopack. +semver = "1" +# The release channel setting and the held download, as JSON, and the +# release list GitHub's API returns. +serde = { version = "1", features = ["derive"] } +serde_json = "1" +# Reads the published release list from GitHub's API, as PwrRoute does. +ureq = { version = "3", default-features = false, features = ["rustls-no-provider", "platform-verifier"] } +rustls = { version = "0.23.45", default-features = false, features = ["ring", "std", "tls12"] } + +[target.'cfg(unix)'.dependencies] +# Stops a timed-out git probe's whole process group, children included +# (git.rs), without `unsafe`. Already in the tree through tempfile. +rustix = { version = "1.1", features = ["process"] } + +[target.'cfg(target_os = "macos")'.dependencies] +# AppKit for the Dock icon of a run outside the app bundle (dock_icon.rs) +# and the screen under the pointer (placement.rs): the crates and versions +# GPUI already builds, with only the classes used. +objc2 = "0.6" +# The kernel release, which says which macOS this is whatever SDK linked it. +rustix = { version = "1.1", features = ["system"] } +objc2-app-kit = { version = "0.3", default-features = false, features = [ + "std", + "NSApplication", + "NSEvent", + "NSGraphics", + "NSImage", + "NSResponder", + "NSScreen", +] } +objc2-foundation = { version = "0.3", default-features = false, features = [ + "std", + "NSArray", + "NSBundle", + "NSData", + "NSDictionary", + "NSEnumerator", + "NSGeometry", + "NSProcessInfo", + "NSString", + "NSValue", +] } [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61", features = ["Win32_System_Console"] } [dev-dependencies] # The window harness: it lets the tests draw a real frame and press real keys. -gpui-kit = { version = "=0.6.6", default-features = false, features = [ +gpui-kit = { version = "=0.7.3", default-features = false, features = [ "assets", "test-support", ] } diff --git a/crates/disktree-app/build.rs b/crates/disktree-app/build.rs index b3e6868e..37a82818 100644 --- a/crates/disktree-app/build.rs +++ b/crates/disktree-app/build.rs @@ -1,5 +1,231 @@ -#[cfg(windows)] +//! Captures where this binary was built from, for Settings › About and +//! Diagnostics (`src/build_info.rs`): the checkout, branch, commit +//! and whether it had uncommitted changes. Read from `git` here, once per +//! build; the app never looks at a checkout while it runs. +//! +//! Every value is an environment variable for `env!`, empty when unknown +//! (no `git`, or a source tree that is not a checkout). On Windows it also +//! embeds the app icon. + +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::{SystemTime, UNIX_EPOCH}; + fn main() { + build_identity(); + #[cfg(windows)] + windows_icon(); +} + +/// The checkout, branch, commit and state, for `src/build_info.rs`. +fn build_identity() { + let manifest = PathBuf::from( + std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default(), + ); + let on_ci = std::env::var_os("GITHUB_ACTIONS").is_some(); + + // One call for HEAD, the checkout and the git dirs `watch` needs. + let parsed = git( + &manifest, + &[ + "rev-parse", + "HEAD", + "--show-toplevel", + "--git-dir", + "--git-common-dir", + ], + ) + .map(|out| out.lines().map(str::to_owned).collect::>()) + .unwrap_or_default(); + let head = parsed.first().cloned(); + let toplevel = parsed.get(1).cloned(); + // A pull request's CI checkout is GitHub's merge commit, on no branch: + // the workflow names the PR's head instead (preview-build.yml). + let commit = std::env::var("PWRDISK_SOURCE_SHA") + .ok() + .map(|sha| sha.trim().to_owned()) + .filter(|sha| !sha.is_empty()) + .or(head); + // The subject and time of that commit; a shallow checkout may not + // have the PR's head, and then neither is known. + let (subject, commit_time) = commit + .as_deref() + .and_then(|commit| { + git(&manifest, &["log", "-1", "--format=%ct%n%s", commit]) + }) + .and_then(|out| { + let (time, subject) = out.split_once('\n')?; + Some((Some(subject.to_owned()), Some(time.to_owned()))) + }) + .unwrap_or((None, None)); + // `--no-optional-locks`: a build never rewrites the index. + let dirty = git( + &manifest, + &[ + "--no-optional-locks", + "status", + "--porcelain", + "--untracked-files=normal", + ], + ) + .is_some_and(|status| !status.is_empty()); + let branch = + git(&manifest, &["symbolic-ref", "--quiet", "--short", "HEAD"]) + .or_else(|| ci_branch(on_ci)); + // HEAD may carry more than one tag; this version's is the one that + // makes it a release. + let release_tag = format!( + "v{}", + std::env::var("CARGO_PKG_VERSION").unwrap_or_default() + ); + let tags = + git(&manifest, &["tag", "--points-at", "HEAD"]).unwrap_or_default(); + let tag = tags + .lines() + .find(|tag| *tag == release_tag) + .or_else(|| tags.lines().next()) + .map(str::to_owned) + .or_else(|| ci_tag(on_ci)); + // A runner's path says nothing about the build, so CI leaves it out. + let checkout = if on_ci { None } else { toplevel }; + // The time only means something when the tree had changes: otherwise + // the commit says it all, and a time would set two identical builds + // apart. SOURCE_DATE_EPOCH wins, for reproducible builds. + let built_at = dirty.then(|| { + std::env::var("SOURCE_DATE_EPOCH").ok().unwrap_or_else(|| { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|elapsed| elapsed.as_secs().to_string()) + .unwrap_or_default() + }) + }); + + emit("PWRDISK_BUILD_COMMIT", commit.as_deref()); + emit("PWRDISK_BUILD_SUBJECT", subject.as_deref()); + emit("PWRDISK_BUILD_COMMIT_TIME", commit_time.as_deref()); + emit("PWRDISK_BUILD_BRANCH", branch.as_deref()); + emit("PWRDISK_BUILD_TAG", tag.as_deref()); + emit("PWRDISK_BUILD_DIRTY", dirty.then_some("1")); + emit("PWRDISK_BUILD_CHECKOUT", checkout.as_deref()); + emit("PWRDISK_BUILD_TIME", built_at.as_deref()); + + watch(&manifest, parsed.get(2), parsed.get(3)); +} + +fn emit(name: &str, value: Option<&str>) { + // One line per value: a newline would end the directive. + let value = value.unwrap_or_default().replace(['\r', '\n'], " "); + println!("cargo:rustc-env={name}={value}"); +} + +/// Trimmed stdout of `git -C dir args`, or `None` when git fails or says +/// nothing. +fn git(dir: &Path, args: &[&str]) -> Option { + let output = Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .output() + .ok()?; + if !output.status.success() { + return None; + } + let text = String::from_utf8(output.stdout).ok()?; + let text = text.trim(); + (!text.is_empty()).then(|| text.to_owned()) +} + +/// A pull request's checkout is a detached merge commit; the branch it +/// builds is the PR's head. +fn ci_branch(on_ci: bool) -> Option { + if !on_ci { + return None; + } + let head = std::env::var("GITHUB_HEAD_REF") + .ok() + .filter(|v| !v.is_empty()); + head.or_else(|| { + (std::env::var("GITHUB_REF_TYPE").ok().as_deref() == Some("branch")) + .then(|| std::env::var("GITHUB_REF_NAME").ok()) + .flatten() + .filter(|v| !v.is_empty()) + }) +} + +/// A tag push's shallow checkout may not carry the tag object. +fn ci_tag(on_ci: bool) -> Option { + if !on_ci || std::env::var("GITHUB_REF_TYPE").ok().as_deref() != Some("tag") + { + return None; + } + std::env::var("GITHUB_REF_NAME") + .ok() + .filter(|v| !v.is_empty()) +} + +/// Run again when HEAD moves (a checkout, a commit on a detached HEAD), a +/// branch or tag changes (a commit) or anything compiled in does (an edit +/// under `crates/` or to a document, which makes or clears uncommitted +/// changes). Not on the index: tools that only refresh it would rebuild +/// the app for nothing. +fn watch( + manifest: &Path, + git_dir: Option<&String>, + common_dir: Option<&String>, +) { + for var in [ + "GITHUB_ACTIONS", + "GITHUB_HEAD_REF", + "GITHUB_REF_NAME", + "GITHUB_REF_TYPE", + "PWRDISK_SOURCE_SHA", + "SOURCE_DATE_EPOCH", + ] { + println!("cargo:rerun-if-env-changed={var}"); + } + println!("cargo:rerun-if-changed=build.rs"); + if let Some(crates) = manifest.parent() { + println!("cargo:rerun-if-changed={}", crates.display()); + if let Some(root) = crates.parent() { + // The documents the app compiles in (`doc_window.rs`) live + // outside `crates/`, and an edit to one makes the build more + // than its commit too. + for file in [ + "Cargo.toml", + "Cargo.lock", + "CHANGELOG.md", + "LICENSE", + "THIRD_PARTY_LICENSES", + ] { + println!( + "cargo:rerun-if-changed={}", + root.join(file).display() + ); + } + } + } + let absolute = |path: &String| { + let path = PathBuf::from(path); + if path.is_absolute() { + path + } else { + manifest.join(path) + } + }; + if let Some(git_dir) = git_dir.map(absolute) { + println!("cargo:rerun-if-changed={}", git_dir.join("HEAD").display()); + } + if let Some(common) = common_dir.map(absolute) { + for path in ["refs/heads", "refs/tags", "packed-refs"] { + println!("cargo:rerun-if-changed={}", common.join(path).display()); + } + } +} + +/// The icon Explorer, the taskbar and Alt-Tab show, as a resource linked +/// into `pwrdisk.exe`. +#[cfg(windows)] +fn windows_icon() { use std::{env, fs, path::PathBuf, process::Command}; let icon = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()) @@ -58,8 +284,5 @@ fn main() { ); println!("cargo:rerun-if-changed={}", icon.display()); - println!("cargo:rustc-link-arg-bin=disktree={}", res.display()); + println!("cargo:rustc-link-arg-bin=pwrdisk={}", res.display()); } - -#[cfg(not(windows))] -fn main() {} diff --git a/crates/disktree-app/src/agent.rs b/crates/disktree-app/src/agent.rs new file mode 100644 index 00000000..9ae0a2ee --- /dev/null +++ b/crates/disktree-app/src/agent.rs @@ -0,0 +1,897 @@ +//! The window's end of the agent link. +//! +//! `pwrdisk mcp` scans and marks on its own; this is how an open window +//! follows along. A listener on the per-user socket queues what an agent +//! asks, the UI thread answers between frames, and every answer carries the +//! window's state, so the agent's view of the marks is always the window's. +//! +//! While a window is open it is the agent's source of truth: `ls`, `find` +//! and `scan` are answered from the tree on screen, and a mark is measured +//! from it too, so the agent and the person read the same numbers. +//! +//! An agent can look, mark and open review. Destructive requests require a +//! single-use intent matching an explicitly confirmed preview. UI and MCP +//! removal share the same guards and configured capacity limit. + +use disktree_core::path_style::PathStyle; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use disktree_core::query; +use disktree_core::removal::{Plan, RemovalMode, Target}; +use disktree_core::tree::{Node, path_of}; +use disktree_link::{ + FindRequest, FoundList, Incoming, Insight, Listener, Listing, Mark, + MarkRequest, Refused, Removal, Request, Response, ScanOptionsRequest, + SelectionEstimate, Space, State, TreeSummary, VERSION, +}; +use gpui_kit::Context; + +use crate::marks::{display_path, is_hidden}; +use crate::state::{Disktree, Screen, now_seconds}; + +/// How often the UI thread looks for agent requests. Short enough that a +/// mark lands in the mosaic before the agent's next sentence. +const POLL: Duration = Duration::from_millis(50); + +/// Who is connected and what they last did, for the header and the panel. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Presence { + pub client: String, + pub action: String, + pub at: Instant, +} + +/// The listener and what has come over it. +#[derive(Debug)] +pub struct AgentLink { + listener: Listener, + pub presence: Option, + /// A path to show once the scan an agent asked for lands. + pending_show: Option, + /// The last removal, for an agent that asks what was freed. + pub last_removal: Option, + pub(crate) removal_preview: Option, + pub(crate) raw_inspection: Option, + pub(crate) removal_operation: Option, + pub(crate) removal_operation_epoch: u64, +} + +impl AgentLink { + pub const fn new(listener: Listener) -> Self { + Self { + listener, + presence: None, + pending_show: None, + last_removal: None, + removal_preview: None, + raw_inspection: None, + removal_operation: None, + removal_operation_epoch: 0, + } + } +} + +/// The screen as the protocol names it. +const fn screen_name(screen: Screen) -> &'static str { + match screen { + Screen::Explore => "explore", + Screen::Review => "review", + Screen::Running => "running", + Screen::Done => "done", + } +} + +/// One way to connect a client: an id for its Copy button, what it is +/// called, and the text to paste. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Connect { + pub id: &'static str, + pub label: &'static str, + pub text: String, +} + +/// The ways to connect a client, with the binary where it is: the bare +/// command line first, for any client that asks for a command, then the +/// one-liners for the clients that have one. The executable's own path, so +/// the command works from a bundle, a symlink on `PATH`, or a build +/// directory alike. +pub fn connect_commands(exe: &Path) -> Vec { + let exe = exe.display(); + vec![ + Connect { + id: "agents-copy-command", + label: "Command line", + text: format!("\"{exe}\" mcp"), + }, + Connect { + id: "agents-copy-claude", + label: "Claude Code", + text: format!( + "claude mcp add --scope user pwrdisk -- \"{exe}\" mcp" + ), + }, + Connect { + id: "agents-copy-codex", + label: "Codex", + text: format!("codex mcp add pwrdisk -- \"{exe}\" mcp"), + }, + Connect { + id: "agents-copy-json", + label: "Other MCP clients (JSON)", + text: format!( + "{{\"mcpServers\": {{\"pwrdisk\": {{\"command\": \"{exe}\", \ + \"args\": [\"mcp\"]}}}}}}" + ), + }, + ] +} + +/// What to ask an agent once it is connected. It asks for a proposal, not +/// a standing instruction: the skill marks without asking only when told +/// to. +pub const FIRST_PROMPT: &str = "What is eating my disk? Use PwrDisk to \ +find out, and show me what could go before you mark anything."; + +fn presence_line(presence: Option<&Presence>) -> String { + presence.map_or_else( + || "No agent is connected to this window.".to_owned(), + |presence| { + format!( + "{} is connected \u{00b7} {}", + presence.client, presence.action + ) + }, + ) +} + +impl Disktree { + /// Start answering agents on `listener`. + pub fn attach_agent(&mut self, listener: Listener, cx: &Context<'_, Self>) { + self.agent = Some(AgentLink::new(listener)); + Self::poll_agent(cx); + } + + fn poll_agent(cx: &Context<'_, Self>) { + cx.spawn(async move |this, cx| { + loop { + cx.background_executor().timer(POLL).await; + let keep_going = + this.update(cx, Self::poll_agent_once).unwrap_or(false); + if !keep_going { + break; + } + } + }) + .detach(); + } + + /// Answer everything that arrived. Returns whether there is a listener + /// to keep polling. Driven by the timer above, and by the tests. + pub(crate) fn poll_agent_once( + &mut self, + cx: &mut Context<'_, Self>, + ) -> bool { + let Some(agent) = &self.agent else { + return false; + }; + // Every noted action stamps the presence, so its time says whether + // what Settings shows can have changed, without formatting it. + let before = agent.presence.as_ref().map(|presence| presence.at); + let incoming = agent.listener.drain(); + if incoming.is_empty() { + self.forget_departed_agent(cx); + self.tell_settings(before, cx); + return true; + } + for item in incoming { + match item { + Incoming::Request { request, reply, .. } => { + let response = self.answer_agent(&request, cx); + reply.send(response); + } + Incoming::Closed { .. } => {} + } + } + self.forget_departed_agent(cx); + self.tell_settings(before, cx); + cx.notify(); + true + } + + /// Settings › Agents (MCP) shows who is connected: redraw it when that + /// line changes, and only then, since this runs every [`POLL`]. + fn tell_settings( + &self, + before: Option, + cx: &mut Context<'_, Self>, + ) { + let now = self + .agent + .as_ref() + .and_then(|agent| agent.presence.as_ref()) + .map(|presence| presence.at); + if now != before { + cx.defer(crate::settings::agents_changed); + } + } + + /// Whether an agent is connected, and who it is and what it last did, + /// as Settings says it. + pub fn agent_status(&self) -> (bool, String) { + match &self.agent { + Some(agent) => ( + agent.presence.is_some(), + presence_line(agent.presence.as_ref()), + ), + None => ( + false, + "This window cannot be driven here; an agent still scans \ + and marks on its own." + .to_owned(), + ), + } + } + + /// Once the last connection is gone, so is the presence. + fn forget_departed_agent(&mut self, cx: &mut Context<'_, Self>) { + if let Some(agent) = &mut self.agent + && agent.presence.is_some() + && agent.listener.connections() == 0 + { + agent.presence = None; + cx.notify(); + } + } + + pub(crate) fn note_agent(&mut self, client: Option<&str>, action: String) { + let Some(agent) = &mut self.agent else { + return; + }; + let client = client + .map(str::to_owned) + .or_else(|| agent.presence.as_ref().map(|p| p.client.clone())) + .unwrap_or_else(|| "an agent".to_string()); + agent.presence = Some(Presence { + client, + action, + at: Instant::now(), + }); + } + + pub(crate) fn answer_agent( + &mut self, + request: &Request, + cx: &mut Context<'_, Self>, + ) -> Response { + // A window on an SSH host holds that host's paths. An agent's paths + // are this computer's, and a mark or a scan would be read against + // the wrong machine; it only learns where the window is. + if let Some(host) = &self.remote + && !matches!(request, Request::Hello { .. } | Request::State) + { + return Response::error(disktree_link::remote_refusal(host)); + } + match request { + Request::Hello { client, version } => { + if *version != VERSION { + return Response::error(format!( + "PwrDisk GUI {}: {}", + env!("CARGO_PKG_VERSION"), + disktree_link::protocol_mismatch(VERSION, *version), + )); + } + if let Some(agent) = &mut self.agent { + agent.removal_preview = None; + agent.raw_inspection = None; + } + self.note_agent(Some(client), "connected".to_string()); + Response::State(self.agent_state()) + } + Request::State => Response::State(self.agent_state()), + Request::PrepareRemoval { + mode, + decisions, + files, + } => self.agent_prepare_removal( + *mode, + decisions.as_deref(), + *files, + cx, + ), + Request::Remove(request) => self.agent_remove(request, cx), + Request::Show { root, path } => self.agent_show(root, path, cx), + Request::Scan { root, options } => { + self.agent_scan(root, options, cx) + } + Request::Ls { path, limit } => self.agent_ls(path, *limit), + Request::Find(request) => self.agent_find(request), + Request::Estimate { + paths, + peer_scope, + peer_limit, + } => self.agent_estimate(paths, peer_scope.as_deref(), *peer_limit), + Request::Mark { root, targets } => { + self.agent_marks(root, targets, cx) + } + Request::Unmark { paths } => { + if self.screen == Screen::Running { + return Response::error("a removal is running"); + } + if paths.is_empty() { + self.clear_marks(cx); + } else { + for path in paths { + self.unmark(path, cx); + } + } + self.leave_review_if_empty(); + self.note_agent(None, "unmarked".to_string()); + Response::State(self.agent_state()) + } + Request::Review => { + if self.screen == Screen::Running { + return Response::error("a removal is running"); + } + if self.marks.is_empty() { + return Response::error("nothing is marked"); + } + self.open_review(cx); + self.confirm_open = false; + self.note_agent(None, "opened the review screen".to_string()); + cx.notify(); + Response::Ok + } + } + } + + /// Scan `root` with the options the agent gave, or rescan it. Answered + /// at once; the agent polls the state until `scanning` turns false. + fn agent_scan( + &mut self, + root: &Path, + options: &ScanOptionsRequest, + cx: &mut Context<'_, Self>, + ) -> Response { + if self.screen == Screen::Running { + return Response::error("a removal is running"); + } + if let Some(apparent) = options.apparent_size { + self.options.apparent_size = apparent; + } + if let Some(hidden) = options.include_hidden { + self.options.include_hidden = hidden; + } + if let Some(one) = options.one_filesystem { + self.options.one_filesystem = one; + } + if let Some(depth) = options.max_depth { + self.options.max_depth = depth; + } + self.note_agent( + None, + format!( + "scanning {}", + display_path(root, self.home.as_deref(), PathStyle::Native) + ), + ); + if root == self.root_path { + self.screen = Screen::Explore; + self.start_scan(cx); + } else { + self.agent_set_root(root, cx); + } + cx.notify(); + Response::State(self.agent_state()) + } + + /// Scan `root` for an agent. A window still on the source chooser + /// leaves it first: the agent's request names the root explicitly, + /// and `start_scan` would otherwise only reopen the chooser. + fn agent_set_root(&mut self, root: &Path, cx: &mut Context<'_, Self>) { + if self.awaiting_root { + self.awaiting_root = false; + self.close_volumes(cx); + } + self.set_root(root.to_path_buf(), cx); + } + + /// The node at `path` in the tree on screen, or why there is none. + fn agent_node(&self, path: &Path) -> Result, String> { + let tree = self.tree.as_deref().ok_or_else(|| { + if self.scan.is_some() { + "the window is still scanning; ask again when the state \ + says scanning is false" + } else { + "the window has no tree" + } + .to_string() + })?; + let relative = path.strip_prefix(&self.root_path).map_err(|_| { + format!( + "{} is outside the window's tree, rooted at {}", + display_path(path, self.home.as_deref(), PathStyle::Native), + display_path( + &self.root_path, + self.home.as_deref(), + PathStyle::Native + ) + ) + })?; + tree.root() + .descend(relative) + .map(|(_, node)| node) + .ok_or_else(|| { + format!( + "{} is not in the window's tree: it may be new, hidden, \ + below the depth limit, or on another filesystem", + display_path(path, self.home.as_deref(), PathStyle::Native) + ) + }) + } + + /// Estimate from the complete window tree without changing any state. + fn agent_estimate( + &self, + paths: &[PathBuf], + peer_scope: Option<&Path>, + peer_limit: usize, + ) -> Response { + if self.scan.is_some() || self.screen == Screen::Running { + return Response::error( + "Wait for the scan or removal to finish before estimating.", + ); + } + let Some(tree) = self.tree.as_deref() else { + return Response::error("The window has no completed scan."); + }; + // The tree still holds what was removed since the scan, at the + // scan's sizes: an estimate over it would price space already + // gone. + if let Some(path) = paths.iter().find(|path| { + self.was_removed(path) + || self.removed.below(path, PathStyle::Native) > 0 + }) { + return Response::error(format!( + "{} {} since the scan; rescan before estimating it.", + display_path(path, self.home.as_deref(), PathStyle::Native), + if self.was_removed(path) { + "was removed" + } else { + "lost part of itself to a removal" + }, + )); + } + let summary = self.agent_state().tree; + let context = disktree_core::planning::Context::of( + &self.root_path, + &self.options, + summary.as_ref().map_or(0, |tree| tree.scanned_at), + summary.as_ref().map_or(0, |tree| tree.unreadable), + ); + match disktree_core::planning::estimate( + tree, context, paths, peer_scope, peer_limit, + ) { + Ok(report) => Response::Estimate(report), + Err(message) => Response::error(message), + } + } + + /// What is in a directory of the tree on screen. + fn agent_ls(&mut self, path: &Path, limit: usize) -> Response { + let mut listing = match self.agent_node(path) { + Ok(node) => Listing::of( + &self.root_path, + self.tree.as_ref().map_or(0, |tree| tree.root().bytes), + path, + node, + limit, + ), + Err(message) => return Response::error(message), + }; + self.note_removal(&mut listing.entry, path); + for child in &mut listing.children { + let path = path.join(&child.name); + self.note_removal(child, &path); + } + self.note_agent( + None, + format!( + "reading {}", + display_path(path, self.home.as_deref(), PathStyle::Native) + ), + ); + Response::Listing(listing) + } + + /// The largest entries of the tree on screen matching a description. + fn agent_find(&mut self, request: &FindRequest) -> Response { + let filter = match request.filter() { + Ok(filter) => filter, + Err(message) => return Response::error(message), + }; + let from = request + .path + .clone() + .unwrap_or_else(|| self.root_path.clone()); + let mut found = match self.agent_node(&from) { + Ok(node) => { + FoundList::of(&query::find(&from, node, &filter, request.limit)) + } + Err(message) => return Response::error(message), + }; + for item in &mut found.matches { + self.note_removal(&mut item.entry, &item.path); + } + self.note_agent(None, "searching the tree".to_string()); + Response::Found(found) + } + + /// Say what a removal since the scan took of `path`: the tree keeps + /// it until a rescan, and its size is still the scan's. + fn note_removal(&self, entry: &mut disktree_link::Entry, path: &Path) { + if self.removed.is_empty() { + return; + } + entry.removed = self.was_removed(path); + if !entry.removed { + entry.removed_bytes = self.removed.below(path, PathStyle::Native); + } + } + + /// Mark what the agent asks, measured from the tree on screen. A path + /// the tree does not have is refused, not guessed at. + fn agent_marks( + &mut self, + root: &Path, + targets: &[MarkRequest], + cx: &mut Context<'_, Self>, + ) -> Response { + if self.screen == Screen::Running { + return Response::error("a removal is running"); + } + if root != self.root_path { + self.agent_set_root(root, cx); + } + let mut marked = 0_usize; + let mut refused = Vec::new(); + for target in targets { + // Without a tree yet, the agent's own measurement stands in; + // `Marks::refresh` corrects it when the scan lands. + if self.was_removed(&target.path) { + refused.push(Refused { + path: target.path.clone(), + reason: "removed since the scan; it is still listed \ + until a rescan" + .into(), + }); + continue; + } + let measured = if self.tree.is_some() { + match self.agent_node(&target.path) { + // A directory part of which was removed frees only + // the rest. + Ok(node) => ( + node.bytes.saturating_sub( + self.removed.below(&target.path, PathStyle::Native), + ), + node.is_dir(), + ), + Err(reason) => { + refused.push(Refused { + path: target.path.clone(), + reason, + }); + continue; + } + } + } else { + (target.bytes, target.is_dir) + }; + match self.agent_mark(Target { + hidden: is_hidden(&target.path, PathStyle::Native), + path: target.path.clone(), + bytes: measured.0, + is_dir: measured.1, + }) { + Ok(()) => marked += 1, + Err(reason) => refused.push(Refused { + path: target.path.clone(), + reason, + }), + } + } + self.leave_review_if_empty(); + self.note_agent( + None, + format!( + "marked {marked} path{}", + if marked == 1 { "" } else { "s" } + ), + ); + cx.notify(); + Response::Marked { + state: self.agent_state(), + refused, + } + } + + /// A review screen over nothing is an empty list; go back to the tree. + fn leave_review_if_empty(&mut self) { + if self.screen == Screen::Review && self.marks.is_empty() { + self.screen = Screen::Explore; + } + } + + /// Mark `target` for an agent: like a press of Space, except it never + /// unmarks, and a path inside a marked directory is left alone rather + /// than toggled. Err with the reason when it is not marked afterwards: + /// the guards refuse it, or it would take the list past the limit, + /// which only the person can go past. + fn agent_mark(&mut self, target: Target) -> Result<(), String> { + if self.marks.contains(&target.path, PathStyle::Native) { + return Ok(()); + } + if !target.path.starts_with(&self.root_path) + || target.path == self.root_path + { + return Err("the scanned root itself, or outside it".into()); + } + if self.marked_ancestor(&target.path).is_some() { + return Ok(()); + } + self.refusal_cache.replace(None); + if let Some(reason) = self.agent_mark_refusal(&target) { + return Err(reason); + } + self.space_baseline = self.space_baseline.or(self.space); + let path = target.path.clone(); + self.marks.toggle(target, PathStyle::Native); + // A directory's mark absorbs the marks inside it, as Space does. + let inside: Vec = self + .marks + .items() + .iter() + .filter(|item| item.path != path && item.path.starts_with(&path)) + .map(|item| item.path.clone()) + .collect(); + for inner in &inside { + self.marks.remove(inner, PathStyle::Native); + } + Ok(()) + } + + /// Show `path`, rescanning from `root` first when the window is + /// elsewhere. A directory is opened; a file is selected in its own. + fn agent_show( + &mut self, + root: &Path, + path: &Path, + cx: &mut Context<'_, Self>, + ) -> Response { + if self.screen == Screen::Running { + return Response::error("a removal is running"); + } + self.note_agent( + None, + format!( + "looking at {}", + display_path(path, self.home.as_deref(), PathStyle::Native) + ), + ); + if root != self.root_path { + self.agent_set_root(root, cx); + } + if self.scan.is_some() || self.tree.is_none() { + // The tree is on its way; show the path when it lands. + if let Some(agent) = &mut self.agent { + agent.pending_show = Some(path.to_path_buf()); + } + return Response::Ok; + } + if self.show_path(path, cx) { + Response::Ok + } else { + Response::error(format!( + "{} is not in the window's tree", + display_path(path, self.home.as_deref(), PathStyle::Native) + )) + } + } + + /// Put `path` on screen. Returns whether it was found. + fn show_path(&mut self, path: &Path, cx: &mut Context<'_, Self>) -> bool { + let Some(crumbs) = self.crumbs_for_path(path) else { + return false; + }; + if matches!(self.screen, Screen::Review | Screen::Done) { + self.screen = Screen::Explore; + } + let is_dir = self.node_at(&crumbs).is_some_and(Node::is_dir); + if is_dir { + self.go_to(crumbs, cx); + } else { + self.reveal(crumbs, cx); + } + true + } + + /// Called when a scan lands: show what an agent asked for meanwhile. + pub(crate) fn finish_pending_show(&mut self, cx: &mut Context<'_, Self>) { + let pending = self + .agent + .as_mut() + .and_then(|agent| agent.pending_show.take()); + if let Some(path) = pending { + self.show_path(&path, cx); + } + } + + /// Called when a removal finishes: keep what it did for the agent. + pub(crate) fn record_removal(&mut self) { + let Some(agent) = &mut self.agent else { + return; + }; + let totals = self.run_list.totals(); + // Use the same measurement and per-run baseline as the ledger. + let observed = self + .ledger + .cohorts() + .last() + .and_then(crate::ledger::Cohort::observed); + agent.last_removal = Some(Removal { + mode: match self.removal_mode { + RemovalMode::Trash => "trash".to_string(), + RemovalMode::Permanent => "permanent".to_string(), + RemovalMode::OwnerCleanup => "owner_cleanup".to_string(), + }, + removed: totals.removed, + failed: totals.failed_all(), + bytes: totals.reported_done, + freed: observed.map(|delta| delta.max(0).unsigned_abs()), + observed, + at: now_seconds(), + cleanup: self.cleanup_results.clone(), + }); + } + + /// The removals since the scan on screen, for the agent: what it needs + /// to say how much a run of batches freed without a rescan. + fn agent_ledger(&self) -> Option { + let cohorts = self.ledger.since(self.scans_done); + let totals = crate::ledger::Ledger::totals(cohorts)?; + let seconds = |at: std::time::SystemTime| { + at.duration_since(std::time::UNIX_EPOCH) + .map_or(0, |since| since.as_secs().cast_signed()) + }; + Some(disktree_link::RemovalLedger { + cohorts: cohorts + .iter() + .map(|cohort| disktree_link::RemovalCohort { + mode: match cohort.mode { + RemovalMode::Trash => "trash".to_string(), + RemovalMode::Permanent => "permanent".to_string(), + RemovalMode::OwnerCleanup => { + "owner_cleanup".to_string() + } + }, + removed: cohort.removed, + failed: cohort.failed, + reported: cohort.reported, + private: cohort.private, + observed: cohort.observed(), + started: seconds(cohort.started), + finished: seconds(cohort.finished), + }) + .collect(), + reported: totals.reported, + private: totals.private, + observed: totals.observed, + }) + } + + /// What the window shows, for the agent. + pub fn agent_state(&self) -> State { + State { + version: VERSION, + app_version: env!("CARGO_PKG_VERSION").into(), + root: self.root_path.clone(), + current: self.current_path(), + screen: screen_name(self.screen).to_string(), + scanning: self.scan.is_some(), + scanned: self.tree.is_some(), + marks: self + .marks + .items() + .iter() + .map(|target| Mark { + path: target.path.clone(), + bytes: target.bytes, + is_dir: target.is_dir, + }) + .collect(), + estimate: (self.tree.is_some() + && self.scan.is_none() + && self.remote.is_none()) + .then(|| self.agent_selection_estimate(&self.plan())), + space: self.space.map(|space| Space { + total: space.total, + free: space.free, + available: space.available, + }), + removal: self + .agent + .as_ref() + .and_then(|agent| agent.last_removal.clone()), + removal_operation: self + .agent + .as_ref() + .and_then(|agent| agent.removal_operation.clone()), + removals: self.agent_ledger(), + tree: self.tree.as_deref().map(|tree| TreeSummary { + bytes: tree.root().bytes, + files: tree.root().files, + dirs: u64::from(tree.root().dirs), + scanned_at: self.scanned_at, + elapsed_ms: self.scan_elapsed.map_or(0, |elapsed| { + u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX) + }), + unreadable: self.progress.errors, + apparent_size: self.options.apparent_size, + include_hidden: self.options.include_hidden, + }), + insights: self + .tree + .as_deref() + .map(|tree| { + self.insights + .iter() + .map(|candidate| Insight { + path: path_of( + &self.root_path, + tree.root(), + &candidate.crumbs, + PathStyle::Native, + ), + bytes: candidate.bytes, + what: candidate.finding.describe(), + }) + .collect() + }) + .unwrap_or_default(), + remote: self.remote.clone(), + } + } + + pub(crate) fn agent_selection_estimate( + &self, + plan: &Plan, + ) -> SelectionEstimate { + // Apparent lengths cannot project physical savings, and disabling + // APFS metadata cannot establish that all listed blocks are private. + if self.removal_mode == RemovalMode::OwnerCleanup + || self.options.apparent_size + || (cfg!(target_os = "macos") && !self.options.apfs_clone_metadata) + { + return SelectionEstimate::unknown(plan); + } + let mut estimate = SelectionEstimate::of(plan); + if let Some(tree) = &self.tree { + let mut resolver = crate::marks::Resolver::new( + &self.root_path, + tree.root(), + PathStyle::Native, + ); + let nodes: Vec> = plan + .targets + .iter() + .filter_map(|target| resolver.resolve(&target.path)) + .map(|(_, node)| node) + .collect(); + estimate = estimate.with_shared(nodes); + } + estimate.partial |= + self.progress.errors > 0 || self.options.max_depth.is_some(); + estimate + } +} diff --git a/crates/disktree-app/src/agent_removal.rs b/crates/disktree-app/src/agent_removal.rs new file mode 100644 index 00000000..5731cb05 --- /dev/null +++ b/crates/disktree-app/src/agent_removal.rs @@ -0,0 +1,578 @@ +//! Explicit, single-use MCP removal intents. UI automation is never approval. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Weak}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use disktree_core::removal::{Plan, Target, detect_trash_backend}; +use disktree_core::tree::Tree; +use disktree_link::{ + ConfirmedRemoval, PathDecision, RemovalChoice, RemovalPreview, Response, +}; +use gpui_kit::Context; + +use crate::state::{Disktree, Screen}; + +const LIFETIME: Duration = Duration::from_mins(5); +static NEXT_PREVIEW: AtomicU64 = AtomicU64::new(0); + +/// A bounded recursive inspection can outlast a link request. Its result +/// belongs to this exact scan/selection, never to a later set of marks. +#[derive(Debug)] +pub struct RawInspection { + root: std::path::PathBuf, + marks: Vec, + targets: Vec, + tree: Weak, + created: Instant, + result: Option>, +} + +impl RawInspection { + fn matches(&self, app: &Disktree, plan: &Plan) -> bool { + self.root == app.root_path + && self.marks == app.marks.items() + && self.targets == plan.targets + && self.created.elapsed() < LIFETIME + && app.tree.as_ref().is_some_and(|tree| { + Weak::ptr_eq(&self.tree, &Arc::downgrade(tree)) + }) + } +} + +#[derive(Debug)] +pub struct PreparedRemoval { + preview: RemovalPreview, + /// A cache cleanup's confirmed decisions, run as they were previewed. + cleanup: Option, + marks: Vec, + tree: Weak, + created: Instant, +} + +impl PreparedRemoval { + fn accepts(&self, request: &ConfirmedRemoval) -> bool { + let preview = &self.preview; + self.created.elapsed() <= LIFETIME + && request.preview_id == preview.preview_id + && request.mode == preview.mode + && request.paths == preview.paths + && !preview.confirmation.is_empty() + && request.confirmation == preview.confirmation + } +} + +impl Disktree { + /// Associate a native UI run with a preview only for the same selection, + /// mode and scan. This records an outcome; it never authorizes a run. + pub(crate) fn track_agent_removal(&mut self) { + let matches = self + .agent + .as_ref() + .and_then(|a| a.removal_preview.as_ref()) + .is_some_and(|prepared| { + prepared.preview.root == self.root_path + && prepared.preview.mode.mode() == self.removal_mode + && prepared.marks == self.marks.items() + && self.tree.as_ref().is_some_and(|tree| { + Weak::ptr_eq(&Arc::downgrade(tree), &prepared.tree) + }) + && prepared.preview.paths.iter().eq(self + .run_list + .items + .iter() + .map(|item| &item.target.path)) + }); + if matches && let Some(agent) = &mut self.agent { + let prepared = + agent.removal_preview.take().expect("matched preview"); + agent.removal_operation = Some(disktree_link::RemovalOperation { + preview_id: prepared.preview.preview_id, + mode: prepared.preview.mode, + paths: prepared.preview.paths, + finished: false, + removed: 0, + failed: 0, + pending: self.run_list.items.len(), + }); + agent.removal_operation_epoch = self.run_epoch; + } + } + + pub(crate) fn update_agent_removal(&mut self, finished: bool) { + if let Some(agent) = &mut self.agent + && agent.removal_operation_epoch == self.run_epoch + && let Some(operation) = &mut agent.removal_operation + { + let totals = self.run_list.totals(); + operation.finished = finished; + operation.removed = totals.removed; + operation.failed = totals.failed_all(); + operation.pending = totals.total - totals.removed - totals.failed; + } + } + + pub(crate) fn agent_prepare_removal( + &mut self, + mode: RemovalChoice, + decisions: Option<&[PathDecision]>, + files: Option, + cx: &mut Context<'_, Self>, + ) -> Response { + // A new preview revokes the previous one even if preparation fails. + if let Some(agent) = &mut self.agent { + agent.removal_preview = None; + } + if mode == RemovalChoice::OwnerCleanup && self.cleanup_ready().is_err() + { + // A failed check says why once; the next request checks again, + // rather than reporting "preparing" for good. + if let Some(reason) = self.cleanup_failed() { + self.cleanup_review = None; + return Response::error(reason); + } + if !self.cleanup_preparing() { + self.prepare_cleanup(cx); + } + return Response::error(self.cleanup_description()); + } + if mode != RemovalChoice::OwnerCleanup { + self.prepare_raw_inspection(cx); + } + match self.prepare_removal_intent(mode, decisions, files) { + Ok(prepared) => { + let preview = prepared.preview.clone(); + let Some(agent) = &mut self.agent else { + return Response::error("No agent link is attached"); + }; + // Proposals without decisions inform; they cannot be + // confirmed, so nothing is kept to confirm against. + if !preview.confirmation.is_empty() { + agent.removal_preview = Some(prepared); + } + Response::RemovalPreview(preview) + } + Err(reason) => Response::error(reason), + } + } + + fn prepare_raw_inspection(&mut self, cx: &Context<'_, Self>) { + if self.remote.is_some() + || self.scan.is_some() + || self.screen == Screen::Running + || self.restarting + || self.marks.is_empty() + { + return; + } + let Some(tree) = &self.tree else { + return; + }; + let plan = + disktree_core::removal::plan(self.marks.items(), &self.root_path); + if !plan.blocked.is_empty() || plan.is_empty() { + return; + } + if self + .agent + .as_ref() + .and_then(|agent| agent.raw_inspection.as_ref()) + .is_some_and(|inspection| inspection.matches(self, &plan)) + { + return; + } + let Some(agent) = &mut self.agent else { + return; + }; + let created = Instant::now(); + agent.raw_inspection = Some(RawInspection { + root: self.root_path.clone(), + marks: self.marks.items().to_vec(), + targets: plan.targets.clone(), + tree: Arc::downgrade(tree), + created, + result: None, + }); + let task = cx.background_executor().spawn(async move { + disktree_core::cleanup::check_raw(&plan.targets) + }); + cx.spawn(async move |this, cx| { + let result = task.await; + let _ = this.update(cx, |this, cx| { + if let Some(inspection) = this + .agent + .as_mut() + .and_then(|agent| agent.raw_inspection.as_mut()) + && inspection.created == created + { + inspection.result = Some(result); + } + cx.notify(); + }); + }) + .detach(); + } + + fn raw_inspection_ready(&self, plan: &Plan) -> Result<(), String> { + let inspection = self + .agent + .as_ref() + .and_then(|agent| agent.raw_inspection.as_ref()) + .filter(|inspection| inspection.matches(self, plan)) + .ok_or( + "Prepare a new raw-removal preview for this scan and selection", + )?; + inspection.result.as_ref() + .ok_or("Raw removal inspection is preparing; retry only the read-only preview shortly")? + .clone() + } + + fn prepare_removal_intent( + &self, + mode: RemovalChoice, + decisions: Option<&[PathDecision]>, + files: Option, + ) -> Result { + if self.remote.is_some() + || self.scan.is_some() + || self.screen == Screen::Running + || self.restarting + { + return Err("Removal requires a complete, idle local scan".into()); + } + if mode == RemovalChoice::Trash + && !detect_trash_backend().is_available() + { + return Err("Trash is unavailable; permanent deletion requires a new preview and separate user confirmation".into()); + } + let tree = self.tree.as_ref().ok_or("No complete scan is available")?; + if mode == RemovalChoice::OwnerCleanup { + return self.prepare_cleanup_intent(decisions, files, tree); + } + if decisions.is_some() || files.is_some() { + return Err("Decisions apply only to owner_cleanup".into()); + } + let plan = { + // Do not let a previously selected UI mode change the meaning + // of an MCP raw-removal request. + disktree_core::removal::plan(self.marks.items(), &self.root_path) + }; + if !plan.blocked.is_empty() { + return Err(format!( + "Removal guards refuse: {}", + plan.blocked + .iter() + .map(|blocked| format!( + "{}: {}", + blocked.path.display(), + blocked.reason + )) + .collect::>() + .join("; ") + )); + } + if plan.is_empty() { + return Err("Nothing is marked".into()); + } + self.raw_inspection_ready(&plan)?; + let limit = crate::safety::load(self.removal_settings_dir.as_deref())?; + let volumes = limit.check(&plan.targets)?; + let nonce = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|error| error.to_string())? + .as_nanos(); + Ok(PreparedRemoval { + preview: RemovalPreview { + preview_id: format!( + "{}-{nonce:x}-{}", + std::process::id(), + NEXT_PREVIEW.fetch_add(1, Ordering::Relaxed) + ), + root: self.root_path.clone(), + mode, + paths: plan + .targets + .iter() + .map(|target| target.path.clone()) + .collect(), + bytes: plan.bytes(), + estimate: self.agent_selection_estimate(&plan), + limit_percent: limit.percent(), + volumes, + expires_in_seconds: LIFETIME.as_secs(), + cleanup: vec![], + proposals: vec![], + decisions: vec![], + files: None, + confirmation: mode.confirmation().into(), + consent: String::new(), + }, + cleanup: None, + marks: self.marks.items().to_vec(), + tree: Arc::downgrade(tree), + created: Instant::now(), + }) + } + + /// A cache cleanup preview. Without decisions it lists what each path + /// offers and cannot be confirmed; with one decision per marked path it + /// is a single-use preview of exactly those steps and their phrase. + fn prepare_cleanup_intent( + &self, + decisions: Option<&[PathDecision]>, + files: Option, + tree: &Arc, + ) -> Result { + use disktree_core::cleanup::Action; + let prepared = self.cleanup_ready()?; + let limit = crate::safety::load(self.removal_settings_dir.as_deref())?; + let files_action = match files { + None => Action::Skip, + Some(RemovalChoice::Trash) => { + if !detect_trash_backend().is_available() { + return Err("Trash is unavailable; choose permanent deletion for Delete files, which needs its own confirmation".into()); + } + Action::Trash + } + Some(RemovalChoice::Permanent) => Action::Permanent, + Some(RemovalChoice::OwnerCleanup) => { + return Err("Delete files uses trash or permanent".into()); + } + }; + let approved = match decisions { + None => None, + Some(named) => { + let named: Vec<_> = named + .iter() + .map(|decision| (decision.path.clone(), decision.action)) + .collect(); + let decisions = prepared.decisions_for(&named)?; + Some(prepared.approve(&decisions, files_action)?) + } + }; + let (plan, volumes) = match &approved { + Some(approved) => { + (approved.plan.clone(), limit.check(&approved.plan.targets)?) + } + None => (disktree_core::removal::Plan::default(), vec![]), + }; + let nonce = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|error| error.to_string())? + .as_nanos(); + let preview = RemovalPreview { + preview_id: if approved.is_some() { + format!( + "{}-{nonce:x}-{}", + std::process::id(), + NEXT_PREVIEW.fetch_add(1, Ordering::Relaxed) + ) + } else { + String::new() + }, + root: self.root_path.clone(), + mode: RemovalChoice::OwnerCleanup, + paths: plan + .targets + .iter() + .map(|target| target.path.clone()) + .collect(), + bytes: plan.bytes(), + estimate: disktree_link::SelectionEstimate::unknown(&plan), + limit_percent: limit.percent(), + volumes, + expires_in_seconds: LIFETIME.as_secs(), + cleanup: approved.as_ref().map_or_else(Vec::new, |approved| { + approved + .steps + .iter() + .filter_map(|step| match step { + disktree_core::cleanup::Step::Owner(index) => { + approved.prepared.operations.get(*index).cloned() + } + disktree_core::cleanup::Step::Files { .. } => None, + }) + .collect() + }), + proposals: prepared.proposals.clone(), + decisions: approved + .as_ref() + .map_or_else(Vec::new, |approved| approved.decisions.clone()), + files: approved + .as_ref() + .filter(|approved| approved.file_steps() > 0) + .and(files), + confirmation: approved + .as_ref() + .map_or("", |approved| approved.confirmation()) + .into(), + consent: approved.as_ref().map_or_else( + || prepared.description(), + disktree_core::cleanup::Approved::description, + ), + }; + Ok(PreparedRemoval { + preview, + cleanup: approved, + marks: self.marks.items().to_vec(), + tree: Arc::downgrade(tree), + created: Instant::now(), + }) + } + + pub(crate) fn agent_remove( + &mut self, + request: &ConfirmedRemoval, + cx: &mut Context<'_, Self>, + ) -> Response { + if self + .agent + .as_ref() + .and_then(|a| a.removal_operation.as_ref()) + .is_some_and(|operation| { + operation.preview_id == request.preview_id + && operation.mode == request.mode + && operation.paths == request.paths + }) + { + return Response::State(self.agent_state()); + } + // Consume before validation: failures and retries need a new preview. + let Some(prepared) = self + .agent + .as_mut() + .and_then(|agent| agent.removal_preview.take()) + else { + return Response::error( + "No unused removal preview; prepare a new preview and obtain user confirmation", + ); + }; + let preview = &prepared.preview; + if !prepared.accepts(request) { + return Response::error( + "Removal confirmation does not match the unexpired preview; obtain a new preview and explicit user confirmation", + ); + } + if self.root_path != preview.root + || self.marks.items() != prepared.marks + || self.tree.as_ref().is_none_or(|tree| { + !Weak::ptr_eq(&Arc::downgrade(tree), &prepared.tree) + }) + { + return Response::error( + "Scan or marked paths changed after preview; obtain a new preview and user confirmation", + ); + } + let decisions: Vec = preview + .proposals + .iter() + .zip(&preview.decisions) + .map(|(proposal, action)| PathDecision { + path: proposal.selected.clone(), + action: *action, + }) + .collect(); + let fresh = match self.prepare_removal_intent( + request.mode, + (request.mode == RemovalChoice::OwnerCleanup) + .then_some(decisions.as_slice()), + preview.files, + ) { + Ok(fresh) => fresh, + Err(reason) => return Response::error(reason), + }; + // Confirmation uses the prepared read-only result. The removal + // worker independently inspects again before any filesystem write. + // No later preview may reuse this operation's inspection. + if let Some(agent) = &mut self.agent { + agent.raw_inspection = None; + } + if fresh.preview.limit_percent != preview.limit_percent + || fresh.preview.volumes != preview.volumes + || fresh.preview.cleanup != preview.cleanup + || fresh.preview.paths != preview.paths + || fresh.preview.decisions != preview.decisions + || fresh.preview.confirmation != preview.confirmation + { + return Response::error( + "Removal policy or volume capacity changed; obtain a new preview and user confirmation", + ); + } + self.removal_mode = request.mode.mode(); + self.confirm_open = false; + self.rescan_after_removal = request.rescan; + let cleanup = prepared.cleanup.clone(); + // Starting a run associates both UI and MCP runs with this preview. + if let Some(agent) = &mut self.agent { + agent.removal_preview = Some(prepared); + } + // Held to the agent limit, not the window's: with the window's Off + // the preview was checked at the agent limit, and growth since must + // be refused at the same limit. + self.begin_agent_removal(cleanup, cx); + if self.screen != Screen::Running { + if let Some(agent) = &mut self.agent { + agent.removal_preview = None; + } + return Response::error( + "Removal did not start; inspect status before preparing another preview", + ); + } + self.note_agent(None, "started confirmed removal".into()); + Response::State(self.agent_state()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn expired_or_different_intents_are_not_accepted() { + let mut prepared = PreparedRemoval { + preview: RemovalPreview { + preview_id: "fixture-id".into(), + root: "/fixture".into(), + mode: RemovalChoice::Permanent, + paths: vec!["/fixture/junk".into()], + bytes: 123, + estimate: disktree_link::SelectionEstimate::unknown( + &disktree_core::removal::Plan::default(), + ), + limit_percent: 5, + volumes: vec![], + expires_in_seconds: LIFETIME.as_secs(), + cleanup: vec![], + proposals: vec![], + decisions: vec![], + files: None, + confirmation: RemovalChoice::Permanent.confirmation().into(), + consent: String::new(), + }, + cleanup: None, + marks: vec![], + tree: Weak::new(), + created: Instant::now(), + }; + let request = ConfirmedRemoval { + rescan: false, + preview_id: "fixture-id".into(), + mode: RemovalChoice::Permanent, + paths: vec!["/fixture/junk".into()], + confirmation: "PERMANENTLY DELETE".into(), + }; + assert!(prepared.accepts(&request)); + let mut trash = request.clone(); + trash.mode = RemovalChoice::Trash; + assert!(!prepared.accepts(&trash)); + let mut extra = request.clone(); + extra.paths.push("/fixture/keep".into()); + assert!(!prepared.accepts(&extra)); + let mut no_confirmation = request.clone(); + no_confirmation.confirmation.clear(); + assert!(!prepared.accepts(&no_confirmation)); + prepared.created = Instant::now() + .checked_sub(LIFETIME + Duration::from_secs(1)) + .expect("expiration before now"); + assert!(!prepared.accepts(&request)); + } +} diff --git a/crates/disktree-app/src/app_menu.rs b/crates/disktree-app/src/app_menu.rs index faee4762..2a1e6a39 100644 --- a/crates/disktree-app/src/app_menu.rs +++ b/crates/disktree-app/src/app_menu.rs @@ -1,11 +1,18 @@ //! The menu bar and the application-wide shortcuts. //! -//! GPUI adds neither on its own. On macOS an app without them has an empty -//! menu bar and no ⌘Q, so this is where disktree becomes a Mac app. GPUI -//! draws no menu bar on Linux or Windows, so there the same actions get the -//! shortcuts their users expect, with ctrl, and nothing else. +//! GPUI adds neither on its own: without them a Mac app has an empty menu +//! bar and no ⌘Q. The layout is the Pwr family's (PwrSuite menus v1, as +//! PwrRoute, PwrGit and PwrAgnt have it): [App] · File · Edit · View · Go · +//! Window · Help, with Go for back and forward as Finder has it. [`menus`] +//! is a pure template for either platform, so the tests can hold both to +//! the standard. macOS installs it as the global menu bar; Windows and +//! Linux have none, so the strip's menu button opens the same template as +//! one dropdown (`views::app_menu_dropdown`). Design: "Menus and Help +//! Windows" in the PwrDisk Claude Design project, turns 1 and 2. -use gpui_kit::{App, KeyBinding, Menu, MenuItem, SystemMenuType}; +use gpui_kit::{App, KeyBinding, Keystroke, Menu, MenuItem, SystemMenuType}; + +use crate::{help, settings}; pub use menu_actions::*; @@ -27,90 +34,579 @@ mod menu_actions { HideOthers, /// Show every application again. ShowAll, - /// Close the focused window, which quits: there is only one. + /// Close the focused window. Closing the main one quits. CloseWindow, + /// Minimize the focused window. + Minimize, + /// Zoom the focused window. + Zoom, /// Scan the current root again. Rescan, /// Choose a directory to scan. OpenFolder, + /// The local and SSH source chooser. + ChooseSource, /// Reveal the tile a key acts on in Finder. ShowInFinder, + /// Open Settings › Updates and check now. + CheckForUpdates, + /// Open Settings › About. + About, /// Back through the directories visited. GoBack, /// Forward again, after going back. GoForward, + /// Settings › Agents (MCP): how to connect an AI agent. + ConnectAgent, + /// Put back the marks the review screen's Unmark all took. + Undo, + /// Edit's rows: the focused text field's own keys, replayed + /// (see [`replay`]). + Cut, + Copy, + Paste, + SelectAll, + /// View: the main window's screens and its keyboard overlay. + ShowExplore, + ShowReview, + ShowKeyboardShortcuts, + /// View: the explore screen as a treemap or as a file list, the + /// way Finder's ⌘1 and ⌘2 switch icons and list. + ShowTreemap, + ShowFileList, + /// View: interface zoom, the window's own `ctrl =` / `ctrl -` / + /// `ctrl 0`. + ZoomIn, + ZoomOut, + ActualSize, + /// Off macOS: open or close the strip's menu (Alt or F10). + ToggleAppMenu, ] ); } +/// The key context no element ever has. Edit's and zoom's shortcuts are +/// bound in it so the menu shows ⌘C and ⌘= while the keys themselves still +/// reach the focused text field and the window's own key handler, which +/// read raw keystrokes. Bound anywhere a window has, ⌘V would become the +/// Paste action and the field would never see it. +const MENU_ONLY: &str = "MenuShortcutOnly"; + +/// Which menu bar to build: macOS's, or the one Windows and Linux use. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Platform { + Mac, + Other, +} + +impl Platform { + pub const fn current() -> Self { + if cfg!(target_os = "macos") { + Self::Mac + } else { + Self::Other + } + } + + /// The modifier its shortcuts take. + const fn modifier(self) -> &'static str { + match self { + Self::Mac => "cmd", + Self::Other => "ctrl", + } + } + + /// What the file manager is called, for Show in Finder. + const fn file_manager(self) -> &'static str { + // The Mac menu is checked first so its template reads the same + // wherever the tests that build it run. + if matches!(self, Self::Mac) { + "Show in Finder" + } else if cfg!(windows) { + "Show in Explorer" + } else { + "Show in File Manager" + } + } +} + /// Install the menus, the shortcuts and the quit-on-close rule. pub fn install(cx: &mut App) { - // A single-window utility has nothing left to show once its window is - // gone; staying alive would leave a Dock icon with no window behind it. + // Closing the main window quits: a utility with nothing left to show + // would leave a Dock icon with no window behind it. Settings, Help's + // documents and Logs come and go without that. cx.on_window_closed(|cx, _| { - if cx.windows().is_empty() { + let main_open = cx.windows().into_iter().any(|window| { + window.downcast::().is_some() + }); + if !main_open { cx.quit(); } }) .detach(); + // A downloaded update is handed to Velopack by the quit hook + // `updater::install` registers, which every route to quitting runs; + // handing it off here as well started a second updater. cx.on_action(|_: &Quit, cx| cx.quit()); cx.on_action(|_: &CloseWindow, cx| { - if let Some(window) = cx.active_window() { - let _ = window.update(cx, |_, window, _| window.remove_window()); - } + in_front_window(cx, |window, _| window.remove_window()); + }); + cx.on_action(|_: &Minimize, cx| { + in_front_window(cx, |window, _| window.minimize_window()); + }); + cx.on_action(|_: &Zoom, cx| { + in_front_window(cx, |window, _| window.zoom_window()); + }); + cx.on_action(|_: &Cut, cx| replay("x", cx)); + cx.on_action(|_: &Copy, cx| replay("c", cx)); + cx.on_action(|_: &Paste, cx| replay("v", cx)); + cx.on_action(|_: &SelectAll, cx| replay("a", cx)); + cx.on_action(|_: &ZoomIn, cx| replay("=", cx)); + cx.on_action(|_: &ZoomOut, cx| replay("-", cx)); + cx.on_action(|_: &ActualSize, cx| replay("0", cx)); + cx.on_action(|_: &About, cx| { + cx.defer(|cx| settings::open(settings::Pane::About, cx)); + }); + cx.on_action(|_: &CheckForUpdates, cx| { + // The main window answers in a toast, from whichever window asked: + // it comes forward so the answer is seen. + cx.defer(|cx| { + let Some(main) = main_window(cx) else { + return; + }; + let _ = main.update(cx, |this, window, cx| { + window.activate_window(); + this.check_for_updates(cx); + }); + }); + }); + // The main window's rows (Rescan, Open Folder, Choose Source, Show in + // Finder, the screens and the history) are handled by that window, + // which owns the scan and the selection; see `views::root`. From + // another window they bring it forward first. + for forward in MAIN_WINDOW_ACTIONS { + forward(cx); + } + settings::install(cx); + help::install(cx); + + let platform = Platform::current(); + cx.bind_keys(bindings(platform)); + if platform == Platform::Mac { + cx.on_action(|_: &Hide, cx| cx.hide()); + cx.on_action(|_: &HideOthers, cx| cx.hide_other_apps()); + cx.on_action(|_: &ShowAll, cx| cx.unhide_other_apps()); + cx.set_menus(menus(platform)); + } +} + +/// Actions the main window answers. Chosen while another PwrDisk window is +/// in front, each brings the main window forward and dispatches there, so +/// File › Rescan from the Logs window still rescans. +const MAIN_WINDOW_ACTIONS: [fn(&mut App); 12] = [ + |cx| forward_to_main::(cx), + |cx| forward_to_main::(cx), + |cx| forward_to_main::(cx), + |cx| forward_to_main::(cx), + |cx| forward_to_main::(cx), + |cx| forward_to_main::(cx), + |cx| forward_to_main::(cx), + |cx| forward_to_main::(cx), + |cx| forward_to_main::(cx), + |cx| forward_to_main::(cx), + |cx| forward_to_main::(cx), + |cx| forward_to_main::(cx), +]; + +/// An app-level fallback for `A`: it only runs when no element in the +/// window in front handled it, which is when that window is not the main +/// one. +fn forward_to_main(cx: &mut App) { + cx.on_action(|_: &A, cx| { + cx.defer(|cx| { + let Some(main) = main_window(cx) else { + return; + }; + let _ = main.update(cx, |_, window, cx| { + window.activate_window(); + window.dispatch_action(Box::new(A::default()), cx); + }); + }); }); - // `Rescan`, `OpenFolder`, `ShowInFinder` and the history are handled by - // the window, which owns the scan and the selection; see `views::root`. - if !cfg!(target_os = "macos") { - cx.bind_keys([ - KeyBinding::new("ctrl-q", Quit, None), - KeyBinding::new("ctrl-w", CloseWindow, None), - KeyBinding::new("ctrl-o", OpenFolder, None), - KeyBinding::new("ctrl-r", Rescan, None), +} + +/// The main window, which owns the scan, the marks and the toasts. +fn main_window( + cx: &App, +) -> Option> { + cx.windows() + .into_iter() + .find_map(|window| window.downcast::()) +} + +/// Every shortcut for `platform`. +fn bindings(platform: Platform) -> Vec { + let modifier = platform.modifier(); + let key = |chord: &str| format!("{modifier}-{chord}"); + let mut bindings = vec![ + KeyBinding::new(&key("q"), Quit, None), + KeyBinding::new(&key("w"), CloseWindow, None), + KeyBinding::new(&key("m"), Minimize, None), + KeyBinding::new(&key("o"), OpenFolder, None), + KeyBinding::new(&key("shift-o"), ChooseSource, None), + KeyBinding::new(&key("r"), Rescan, None), + KeyBinding::new(&key("1"), ShowTreemap, None), + KeyBinding::new(&key("2"), ShowFileList, None), + // ⌘R is taken by Rescan, as in a browser; `o` reveals without a + // modifier too. + KeyBinding::new(&key("shift-r"), ShowInFinder, None), + KeyBinding::new(&key(","), settings::OpenSettings, None), + // In the main window only, where the marks are; a text field's own + // binding is deeper, so it still undoes its typing. + KeyBinding::new(&key("z"), Undo, Some("Disktree")), + KeyBinding::new(&key("x"), Cut, Some(MENU_ONLY)), + KeyBinding::new(&key("c"), Copy, Some(MENU_ONLY)), + KeyBinding::new(&key("v"), Paste, Some(MENU_ONLY)), + KeyBinding::new(&key("a"), SelectAll, Some(MENU_ONLY)), + KeyBinding::new(&key("="), ZoomIn, Some(MENU_ONLY)), + KeyBinding::new(&key("-"), ZoomOut, Some(MENU_ONLY)), + KeyBinding::new(&key("0"), ActualSize, Some(MENU_ONLY)), + // The keyboard overlay's own key, shown beside its row. + KeyBinding::new("?", ShowKeyboardShortcuts, Some(MENU_ONLY)), + ]; + match platform { + Platform::Mac => bindings.extend([ + KeyBinding::new("cmd-h", Hide, None), + KeyBinding::new("alt-cmd-h", HideOthers, None), + // Finder's and Safari's back and forward; alt-arrows work too. + KeyBinding::new("cmd-[", GoBack, None), + KeyBinding::new("cmd-]", GoForward, None), + ]), + Platform::Other => bindings.extend([ KeyBinding::new("f5", Rescan, None), - KeyBinding::new("ctrl-shift-r", ShowInFinder, None), - ]); - return; + KeyBinding::new("f10", ToggleAppMenu, None), + // A lone Alt: GPUI's modifier-only keystroke, pressed and + // released with nothing else. + KeyBinding::new("alt", ToggleAppMenu, None), + ]), } - cx.on_action(|_: &Hide, cx| cx.hide()); - cx.on_action(|_: &HideOthers, cx| cx.hide_other_apps()); - cx.on_action(|_: &ShowAll, cx| cx.unhide_other_apps()); - cx.bind_keys([ - KeyBinding::new("cmd-q", Quit, None), - KeyBinding::new("cmd-h", Hide, None), - KeyBinding::new("alt-cmd-h", HideOthers, None), - KeyBinding::new("cmd-w", CloseWindow, None), - KeyBinding::new("cmd-r", Rescan, None), - KeyBinding::new("cmd-o", OpenFolder, None), - // ⌘R is taken by Rescan, as in a browser; Xcode uses ⌘⇧R-like - // chords for its reveals, and `o` does the same without a modifier. - KeyBinding::new("cmd-shift-r", ShowInFinder, None), - // Finder's and Safari's back and forward; alt-arrows work too. - KeyBinding::new("cmd-[", GoBack, None), - KeyBinding::new("cmd-]", GoForward, None), - ]); - cx.set_menus([ - Menu::new("disktree").items([ + bindings +} + +/// Edit's and View's zoom rows: the same key, sent to the window in front +/// as if pressed. The text fields handle ⌘X/⌘C/⌘V/⌘A (Ctrl elsewhere) +/// themselves and the main window its zoom keys, so a menu click does +/// exactly what the shortcut does. The keys are bound only in +/// [`MENU_ONLY`], so this never comes back here. +fn replay(key: &str, cx: &mut App) { + let modifier = Platform::current().modifier(); + let Ok(keystroke) = Keystroke::parse(&format!("{modifier}-{key}")) else { + return; + }; + in_front_window(cx, move |window, cx| { + window.dispatch_keystroke(keystroke, cx); + }); +} + +/// Runs `f` on the window in front, once the action that asked is done: +/// GPUI can still hold the window an action was dispatched in, and an +/// update inside that dispatch fails without a word. +fn in_front_window( + cx: &mut App, + f: impl FnOnce(&mut gpui_kit::Window, &mut App) + 'static, +) { + let Some(window) = cx.active_window() else { + return; + }; + cx.defer(move |cx| { + let _ = window.update(cx, |_, window, cx| f(window, cx)); + }); +} + +/// The menu bar, in the family's order, for `platform`. +pub fn menus(platform: Platform) -> Vec { + let mac = platform == Platform::Mac; + let mut menus = Vec::new(); + if mac { + menus.push(Menu::new("PwrDisk").items([ + MenuItem::action("About PwrDisk", About), + MenuItem::action("Check for Updates\u{2026}", CheckForUpdates), + MenuItem::separator(), + MenuItem::action("Settings\u{2026}", settings::OpenSettings), + MenuItem::separator(), MenuItem::os_submenu("Services", SystemMenuType::Services), MenuItem::separator(), - MenuItem::action("Hide disktree", Hide), + MenuItem::action("Hide PwrDisk", Hide), MenuItem::action("Hide Others", HideOthers), MenuItem::action("Show All", ShowAll), MenuItem::separator(), - MenuItem::action("Quit disktree", Quit), - ]), - Menu::new("File").items([ - MenuItem::action("Open Folder\u{2026}", OpenFolder), - MenuItem::action("Show in Finder", ShowInFinder), - MenuItem::separator(), - MenuItem::action("Rescan", Rescan), - MenuItem::separator(), - MenuItem::action("Close Window", CloseWindow), - ]), - Menu::new("Go").items([ - MenuItem::action("Back", GoBack), - MenuItem::action("Forward", GoForward), - ]), - ]); + MenuItem::action("Quit PwrDisk", Quit), + ])); + } + + let mut file = vec![ + MenuItem::action("Open Folder\u{2026}", OpenFolder), + MenuItem::action("Choose Source\u{2026}", ChooseSource), + MenuItem::separator(), + MenuItem::action(platform.file_manager(), ShowInFinder), + MenuItem::action("Rescan", Rescan), + MenuItem::separator(), + ]; + if !mac { + file.push(MenuItem::action("Settings\u{2026}", settings::OpenSettings)); + file.push(MenuItem::separator()); + } + file.push(MenuItem::action("Close Window", CloseWindow)); + if !mac { + file.push(MenuItem::action("Quit", Quit)); + } + menus.push(Menu::new("File").items(file)); + + // Undo is Unmark all's; no field here keeps a history, so no Redo. + menus.push(Menu::new("Edit").items([ + MenuItem::action("Undo", Undo), + MenuItem::separator(), + MenuItem::action("Cut", Cut), + MenuItem::action("Copy", Copy), + MenuItem::action("Paste", Paste), + MenuItem::separator(), + MenuItem::action("Select All", SelectAll), + ])); + + // The app's own screens open View; then interface zoom, which PwrDisk + // has (a GPUI app usually does not). macOS adds Enter Full Screen. + menus.push(Menu::new("View").items([ + MenuItem::action("Explore", ShowExplore), + MenuItem::action("Review Marked", ShowReview), + MenuItem::action("Keyboard Shortcuts", ShowKeyboardShortcuts), + MenuItem::separator(), + MenuItem::action("as Treemap", ShowTreemap), + MenuItem::action("as File List", ShowFileList), + MenuItem::separator(), + MenuItem::action("Zoom In", ZoomIn), + MenuItem::action("Zoom Out", ZoomOut), + MenuItem::action("Actual Size", ActualSize), + ])); + + menus.push(Menu::new("Go").items([ + MenuItem::action("Back", GoBack), + MenuItem::action("Forward", GoForward), + ])); + + // macOS lists the open windows under these itself. + let mut window = vec![MenuItem::action("Minimize", Minimize)]; + if mac { + window.push(MenuItem::action("Zoom", Zoom)); + } + menus.push(Menu::new("Window").items(window)); + + menus.push(Menu::new("Help").items(help_items(platform))); + menus +} + +/// Help, in the standard's fixed order: learn, get help, the project, the +/// legal notices; off macOS, Check for Updates… and About last. No Website +/// row: PwrDisk has no site yet, and no Replay Onboarding: it has none +/// (every row has something behind it). +fn help_items(platform: Platform) -> Vec { + let mut items = vec![ + MenuItem::action("PwrDisk Documentation", help::OpenDocumentation), + MenuItem::action("Changelog", help::OpenChangelog), + // Where a person looks for "how do I hook this up"; the same + // overlay opens from the line under the disk meter. + MenuItem::action("Connect an AI Agent (MCP)\u{2026}", ConnectAgent), + MenuItem::separator(), + MenuItem::action("Report an Issue\u{2026}", help::ReportIssue), + MenuItem::action( + "Report a Security Vulnerability\u{2026}", + help::ReportVulnerability, + ), + MenuItem::action("Copy Diagnostics Info", help::CopyDiagnostics), + MenuItem::action("Logs", help::OpenLogs), + MenuItem::separator(), + MenuItem::action("View Source", help::ViewSource), + MenuItem::separator(), + MenuItem::action("View License", help::ViewLicense), + MenuItem::action("Third-Party Notices", help::ThirdPartyNotices), + ]; + if platform == Platform::Other { + items.push(MenuItem::separator()); + items.push(MenuItem::action( + "Check for Updates\u{2026}", + CheckForUpdates, + )); + items.push(MenuItem::action("About PwrDisk", About)); + } + items +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A menu as its labels, with "---" for a separator and "" + /// for the OS's submenu. + fn labels(menu: &Menu) -> Vec { + menu.items + .iter() + .map(|item| match item { + MenuItem::Separator => "---".to_owned(), + MenuItem::Action { name, .. } => name.to_string(), + MenuItem::Submenu(menu) => format!("[{}]", menu.name), + MenuItem::SystemMenu(menu) => format!("<{}>", menu.name), + }) + .collect() + } + + fn menu<'a>(menus: &'a [Menu], name: &str) -> &'a Menu { + menus + .iter() + .find(|menu| menu.name == name) + .unwrap_or_else(|| panic!("no {name} menu")) + } + + #[test] + fn the_menu_bar_follows_the_family_order() { + let names = |platform| { + menus(platform) + .iter() + .map(|menu| menu.name.to_string()) + .collect::>() + }; + assert_eq!( + names(Platform::Mac), + ["PwrDisk", "File", "Edit", "View", "Go", "Window", "Help"] + ); + assert_eq!( + names(Platform::Other), + ["File", "Edit", "View", "Go", "Window", "Help"] + ); + } + + #[test] + fn the_mac_app_menu_opens_with_about_and_updates() { + let menus = menus(Platform::Mac); + assert_eq!( + labels(menu(&menus, "PwrDisk")), + [ + "About PwrDisk", + "Check for Updates…", + "---", + "Settings…", + "---", + "", + "---", + "Hide PwrDisk", + "Hide Others", + "Show All", + "---", + "Quit PwrDisk", + ] + ); + assert_eq!( + labels(menu(&menus, "File")), + [ + "Open Folder…", + "Choose Source…", + "---", + "Show in Finder", + "Rescan", + "---", + "Close Window" + ] + ); + assert_eq!(labels(menu(&menus, "Window")), ["Minimize", "Zoom"]); + } + + #[test] + fn elsewhere_settings_is_in_file_and_about_ends_help() { + let menus = menus(Platform::Other); + let file = labels(menu(&menus, "File")); + assert_eq!( + file[file.len() - 5..], + ["---", "Settings…", "---", "Close Window", "Quit"] + ); + let help = labels(menu(&menus, "Help")); + assert_eq!( + help[help.len() - 3..], + ["---", "Check for Updates…", "About PwrDisk"] + ); + assert_eq!(labels(menu(&menus, "Window")), ["Minimize"]); + } + + #[test] + fn help_is_in_the_standard_order_on_both_platforms() { + let expected = [ + "PwrDisk Documentation", + "Changelog", + "Connect an AI Agent (MCP)\u{2026}", + "---", + "Report an Issue…", + "Report a Security Vulnerability…", + "Copy Diagnostics Info", + "Logs", + "---", + "View Source", + "---", + "View License", + "Third-Party Notices", + ]; + for platform in [Platform::Mac, Platform::Other] { + let menus = menus(platform); + let help = labels(menu(&menus, "Help")); + assert_eq!(help[..expected.len()], expected, "{platform:?}"); + } + assert_eq!( + labels(menu(&menus(Platform::Mac), "Help")).len(), + expected.len() + ); + } + + #[test] + fn view_lists_the_screens_and_zoom_and_edit_has_no_undo() { + for platform in [Platform::Mac, Platform::Other] { + let menus = menus(platform); + assert_eq!( + labels(menu(&menus, "View")), + [ + "Explore", + "Review Marked", + "Keyboard Shortcuts", + "---", + "as Treemap", + "as File List", + "---", + "Zoom In", + "Zoom Out", + "Actual Size" + ] + ); + assert_eq!( + labels(menu(&menus, "Edit")), + ["Undo", "---", "Cut", "Copy", "Paste", "---", "Select All"] + ); + assert_eq!(labels(menu(&menus, "Go")), ["Back", "Forward"]); + } + } + + #[test] + fn every_row_but_the_services_menu_has_an_action() { + for platform in [Platform::Mac, Platform::Other] { + for menu in menus(platform) { + for item in &menu.items { + assert!( + matches!( + item, + MenuItem::Separator + | MenuItem::Action { .. } + | MenuItem::SystemMenu(_) + ), + "{} has a submenu", + menu.name + ); + } + } + } + } } diff --git a/crates/disktree-app/src/aux_window.rs b/crates/disktree-app/src/aux_window.rs new file mode 100644 index 00000000..640f9cdd --- /dev/null +++ b/crates/disktree-app/src/aux_window.rs @@ -0,0 +1,168 @@ +//! What the windows other than the main one share: Settings, Help's +//! documents and Logs. Their options (the same frame as the main window: +//! no native title bar, the stoplights in the strip on macOS), one window +//! of each kind (a second open brings it forward), and the frame around +//! their content. + +use gpui_kit::{ + AnyElement, App, AppContext as _, Bounds, Context, InteractiveElement as _, + IntoElement, ParentElement as _, Render, Styled as _, TitlebarOptions, + Window, WindowBounds, WindowHandle, WindowOptions, div, point, px, size, +}; +use gpui_omarchy::ActiveTheme as _; + +use crate::chrome::{self, Drags, Frame}; +use crate::semantics; +use crate::ui; +use gpui_kit::KeyDownEvent; +use gpui_kit::base::input::{IndentInline, OutdentInline}; + +/// A window's title (the Window menu, the taskbar and Waybar read it), its +/// size and its least size. +pub struct Spec { + pub title: &'static str, + pub size: (f32, f32), + pub min: (f32, f32), +} + +/// Brings `existing` forward if it is still open; `true` when it was. +pub fn activate( + existing: Option>, + cx: &mut App, +) -> bool { + let Some(handle) = existing else { + return false; + }; + let shown = handle + .update(cx, |_, window, _| window.activate_window()) + .is_ok(); + if shown { + cx.activate(true); + } + shown +} + +/// The open window of kind `V` that `matches`, if any. +pub fn find( + cx: &App, + matches: impl Fn(&V) -> bool, +) -> Option> { + cx.windows().into_iter().find_map(|window| { + let handle = window.downcast::()?; + let view = handle.read(cx).ok()?; + matches(view).then_some(handle) + }) +} + +/// Opens a window in front, centred on the display the user is working +/// on: the main window's, when it is in front. +pub fn open( + spec: &Spec, + cx: &mut App, + build: impl FnOnce(&mut Window, &mut Context<'_, V>) -> V, +) -> Option> { + let display = crate::placement::display_for_new_window(cx); + let bounds = + Bounds::centered(display, size(px(spec.size.0), px(spec.size.1)), cx); + let handle = cx.open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(bounds)), + // GPUI reads the bounds relative to this display. + display_id: display, + titlebar: Some(TitlebarOptions { + title: Some(spec.title.into()), + // As the main window: the strip is the title bar. + appears_transparent: true, + traffic_light_position: Some(point( + px(ui::chrome::STOPLIGHTS.0), + px(ui::chrome::STOPLIGHTS.1), + )), + }), + app_owns_titlebar_drag: true, + app_id: Some("pwrdisk".to_owned()), + window_min_size: Some(size(px(spec.min.0), px(spec.min.1))), + ..Default::default() + }, + |window, cx| { + ui::sync_scale(window, cx); + if crate::appearance::follows_system( + std::env::home_dir().as_deref(), + ) { + crate::appearance::follow(window); + } + cx.new(|cx| { + cx.observe_button_layout_changed(window, |_, _, cx| { + cx.notify(); + }) + .detach(); + build(window, cx) + }) + }, + ); + match handle { + Ok(handle) => { + cx.activate(true); + Some(handle) + } + Err(error) => { + log::warn!( + target: "pwrdisk", + "could not open the {} window: {error}", + spec.title + ); + None + } + } +} + +/// The window: the strip with `crumbs` and `actions`, `body` under it, in +/// the frame the platform needs. +pub fn frame( + crumbs: &[&'static str], + actions: impl IntoElement, + body: impl IntoElement, + window: &mut Window, + cx: &Context<'_, V>, +) -> AnyElement { + let frame = Frame::detect(window, cx); + let theme = cx.omarchy().clone(); + let content = div() + .id("aux-root") + // Tab walks every control, the title strip's buttons included, so + // it is taken here, above them all, rather than by each window's + // body. A text field binds Tab to indenting, and bindings run + // before key handlers, so its actions are caught too. Interface + // zoom is taken here for the same reason: every window gets it. + .capture_key_down(|event: &KeyDownEvent, window, cx| { + if ui::zoom_interface(event, window, cx) { + cx.stop_propagation(); + return; + } + let keys = &event.keystroke; + if keys.key == "tab" + && !keys.modifiers.control + && !keys.modifiers.platform + { + semantics::advance_focus(window, cx, keys.modifiers.shift, None); + cx.stop_propagation(); + } + }) + .capture_action(|_: &IndentInline, window, cx| { + semantics::advance_focus(window, cx, false, None); + cx.stop_propagation(); + }) + .capture_action(|_: &OutdentInline, window, cx| { + semantics::advance_focus(window, cx, true, None); + cx.stop_propagation(); + }) + .flex() + .flex_col() + .size_full() + .bg(theme.background) + .text_color(theme.foreground) + .font_family(theme.font.clone()) + .text_size(ui::text::BODY) + .child(chrome::aux_strip(&frame, crumbs, actions, window, cx)) + .child(div().flex().flex_col().flex_1().min_h_0().child(body)); + chrome::client_frame(&frame, content, window, &theme) +} diff --git a/crates/disktree-app/src/build_info.rs b/crates/disktree-app/src/build_info.rs new file mode 100644 index 00000000..34211b49 --- /dev/null +++ b/crates/disktree-app/src/build_info.rs @@ -0,0 +1,371 @@ +//! Which build this is: the version, profile and architecture, and the +//! checkout, branch and commit `build.rs` read from git when the binary was +//! built. Settings › About and Diagnostics draw from one [`BuildInfo`], and +//! their copy buttons write one [`BuildInfo::report`], as PwrRoute's do. +//! +//! Nothing here reads a checkout at run time, and nothing here is a link. + +/// Where this binary came from. Strings are empty-free: an unknown value is +/// `None`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BuildInfo { + /// "0.5.0". + pub version: String, + /// "debug" or "release". + pub profile: &'static str, + /// "aarch64". + pub arch: &'static str, + /// All 40 hex characters. + pub commit: Option, + /// The commit's subject line. + pub subject: Option, + /// The commit's time, in seconds since the epoch. + pub commit_time: Option, + /// `None` for a detached HEAD. + pub branch: Option, + /// The tag on HEAD, if any. + pub tag: Option, + /// The tree had uncommitted changes. + pub dirty: bool, + /// The checkout's absolute path; never set for a CI build. + pub checkout: Option, + /// When it was built, only when `dirty` (seconds since the epoch). + pub built_at: Option, +} + +fn known(value: &'static str) -> Option { + let value = value.trim(); + (!value.is_empty()).then(|| value.to_owned()) +} + +impl BuildInfo { + /// This binary, as `build.rs` saw it. + pub fn current() -> Self { + Self { + version: env!("CARGO_PKG_VERSION").to_owned(), + profile: if cfg!(debug_assertions) { + "debug" + } else { + "release" + }, + arch: std::env::consts::ARCH, + commit: known(env!("PWRDISK_BUILD_COMMIT")), + subject: known(env!("PWRDISK_BUILD_SUBJECT")), + commit_time: known(env!("PWRDISK_BUILD_COMMIT_TIME")) + .and_then(|t| t.parse().ok()), + branch: known(env!("PWRDISK_BUILD_BRANCH")), + tag: known(env!("PWRDISK_BUILD_TAG")), + dirty: !env!("PWRDISK_BUILD_DIRTY").is_empty(), + checkout: known(env!("PWRDISK_BUILD_CHECKOUT")), + built_at: known(env!("PWRDISK_BUILD_TIME")) + .and_then(|t| t.parse().ok()), + } + } + + #[cfg(test)] + /// Contrived, for tests: a worktree on a + /// branch with nothing uncommitted. + pub fn fixture() -> Self { + Self { + version: "0.5.0".to_owned(), + profile: "debug", + arch: "aarch64", + commit: Some("5e1c07a2f19d4b6c08e3a7d5b2c91f40e6a8d317".to_owned()), + subject: Some("show which build is running".to_owned()), + commit_time: Some(1_793_196_120), + branch: Some("feat/build-identity".to_owned()), + tag: None, + dirty: false, + checkout: Some( + "/Users/you/.pwragent/worktrees/k3x9q2ab/PwrDisk".to_owned(), + ), + built_at: None, + } + } + + /// A release: the release profile, built from exactly its `vX.Y.Z` + /// tag with nothing uncommitted. Everything else is a dev build. + pub fn is_release(&self) -> bool { + self.profile == "release" + && !self.dirty + && self.tag.as_deref() + == Some(format!("v{}", self.version).as_str()) + } + + /// The first 8 characters of the commit. + pub fn short_commit(&self) -> Option<&str> { + self.commit + .as_deref() + .map(|commit| commit.get(..8).unwrap_or(commit)) + } + + /// "5e1c07a2", with "+" for uncommitted changes: Diagnostics' Version. + pub fn short_commit_marked(&self) -> Option { + self.short_commit().map(|short| { + format!("{short}{}", if self.dirty { "+" } else { "" }) + }) + } + + /// About's header: "Built 2026-10-28 from v0.14.0 · Stable · Latest", + /// with the release channel in force passed in. + /// + /// The date is the build's own time only when the tree had changes; + /// a clean build records none (see `build.rs`), and is its commit, so + /// it is dated by that. It names the tag of a release, else the + /// branch, else the commit. Knowing none of that, it is the channel. + pub fn header_line(&self, channel: &str) -> String { + let date = self + .built_at + .or(self.commit_time) + .and_then(local) + .map(|time| format!(" {}", time.format("%Y-%m-%d"))) + .unwrap_or_default(); + let source = match (&self.tag, &self.branch) { + (Some(tag), _) if self.is_release() => Some(tag.clone()), + (_, Some(branch)) => Some(branch.clone()), + _ => self.short_commit().map(str::to_owned), + }; + let source = source + .map(|source| format!(" from {source}")) + .unwrap_or_default(); + // Built outside a checkout there is nothing to say but the + // channel, and a bare "Built" would read as a fragment. + if date.is_empty() && source.is_empty() { + return channel.to_owned(); + } + format!("Built{date}{source} \u{00b7} {channel}") + } + + /// "“show which build is running” · committed Oct 28 14:02". + pub fn commit_line(&self) -> Option { + let subject = self + .subject + .as_deref() + .map(|subject| format!("\u{201c}{subject}\u{201d}")); + let when = self + .commit_time + .and_then(local) + .map(|time| format!("committed {}", time.format("%b %-d %H:%M"))); + match (subject, when) { + (Some(subject), Some(when)) => { + Some(format!("{subject} \u{00b7} {when}")) + } + (one, other) => one.or(other), + } + } + + /// "Built at 14:32 with uncommitted changes, …", only when there were. + pub fn changes_line(&self) -> Option { + if !self.dirty { + return None; + } + Some(match self.built_at.and_then(local) { + Some(time) => format!( + "Built {} with uncommitted changes, so it is more than this commit.", + time.format("%b %-d at %H:%M") + ), + None => "Built with uncommitted changes, so it is more than this commit.".to_owned(), + }) + } + + /// The text every "copy the build" button writes: About's Copy build + /// info, and the top of Diagnostics' Copy. The checkout is + /// the full path, one you can `cd` to. + pub fn report(&self) -> String { + const PAD: &str = " "; + let mut lines = vec![format!( + "PwrDisk {} ({}, {})", + self.version, self.profile, self.arch + )]; + if let Some(checkout) = &self.checkout { + lines.push(format!("Checkout: {checkout}")); + } + if self.is_release() + && let Some(tag) = &self.tag + { + lines.push(format!("Tag: {tag}")); + } else { + lines.push(format!( + "Branch: {}", + self.branch.as_deref().unwrap_or("detached HEAD") + )); + } + let changes = if self.dirty { + " + uncommitted changes" + } else { + "" + }; + lines.push(format!( + "Commit: {}{changes}", + self.commit.as_deref().unwrap_or("unknown") + )); + if let Some(subject) = &self.subject { + lines.push(format!("{PAD}{subject}")); + } + if let Some(built) = self.built_at.and_then(local) { + lines.push(format!("Built: {}", built.format("%Y-%m-%d %H:%M"))); + } + let mut report = lines.join("\n"); + report.push('\n'); + report + } +} + +fn local(seconds: i64) -> Option> { + chrono::DateTime::from_timestamp(seconds, 0) + .map(|time| time.with_timezone(&chrono::Local)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn release() -> BuildInfo { + BuildInfo { + profile: "release", + tag: Some("v0.5.0".to_owned()), + branch: None, + checkout: None, + commit: Some("42a50803e6b1c9d27f0a4c35e8d1b6a0f9c2e471".to_owned()), + subject: Some("chore(release): v0.5.0".to_owned()), + ..BuildInfo::fixture() + } + } + + #[test] + fn the_current_build_has_a_version_and_a_profile() { + let build = BuildInfo::current(); + assert_eq!(build.version, env!("CARGO_PKG_VERSION")); + assert!(["debug", "release"].contains(&build.profile)); + if let Some(commit) = &build.commit { + assert_eq!(commit.len(), 40, "{commit}"); + } + assert_eq!(build.built_at.is_some(), build.dirty); + } + + #[test] + fn only_a_clean_release_build_of_its_own_tag_is_a_release() { + assert!(release().is_release()); + assert!(!BuildInfo::fixture().is_release()); + let dirty = BuildInfo { + dirty: true, + ..release() + }; + assert!(!dirty.is_release()); + let debug = BuildInfo { + profile: "debug", + ..release() + }; + assert!(!debug.is_release()); + let other_tag = BuildInfo { + tag: Some("v0.4.0".to_owned()), + ..release() + }; + assert!(!other_tag.is_release()); + } + + #[test] + fn the_commit_is_cut_to_eight_and_marked_for_changes() { + let build = BuildInfo::fixture(); + assert_eq!(build.short_commit(), Some("5e1c07a2")); + assert_eq!(build.short_commit_marked().as_deref(), Some("5e1c07a2")); + let dirty = BuildInfo { + dirty: true, + ..build + }; + assert_eq!(dirty.short_commit_marked().as_deref(), Some("5e1c07a2+")); + } + + #[test] + fn the_report_names_the_checkout_branch_and_commit() { + assert_eq!( + BuildInfo::fixture().report(), + "PwrDisk 0.5.0 (debug, aarch64)\n\ + Checkout: /Users/you/.pwragent/worktrees/k3x9q2ab/PwrDisk\n\ + Branch: feat/build-identity\n\ + Commit: 5e1c07a2f19d4b6c08e3a7d5b2c91f40e6a8d317\n\ + \x20 show which build is running\n" + ); + } + + #[test] + fn a_release_report_names_its_tag_and_no_checkout() { + assert_eq!( + release().report(), + "PwrDisk 0.5.0 (release, aarch64)\n\ + Tag: v0.5.0\n\ + Commit: 42a50803e6b1c9d27f0a4c35e8d1b6a0f9c2e471\n\ + \x20 chore(release): v0.5.0\n" + ); + } + + #[test] + fn a_detached_build_with_changes_says_so_and_when_it_was_built() { + let build = BuildInfo { + branch: None, + dirty: true, + built_at: Some(1_793_197_920), + ..BuildInfo::fixture() + }; + let report = build.report(); + assert!(report.contains("Branch: detached HEAD\n"), "{report}"); + assert!( + report.contains("5e1c07a2f19d4b6c08e3a7d5b2c91f40e6a8d317 + uncommitted changes\n"), + "{report}" + ); + assert!(report.contains("\nBuilt: 20"), "{report}"); + assert!(build.changes_line().is_some()); + assert_eq!(BuildInfo::fixture().changes_line(), None); + } + + #[test] + fn the_header_names_the_date_the_source_and_the_channel() { + // Dates are local, so check the shape around them. + let release = release().header_line("Stable \u{00b7} Latest"); + assert!(release.starts_with("Built 20"), "{release}"); + assert!( + release.ends_with(" from v0.5.0 \u{00b7} Stable \u{00b7} Latest"), + "{release}" + ); + let branch = BuildInfo::fixture().header_line("Beta \u{00b7} Latest"); + assert!( + branch.ends_with( + " from feat/build-identity \u{00b7} Beta \u{00b7} Latest" + ), + "{branch}" + ); + let detached = BuildInfo { + branch: None, + ..BuildInfo::fixture() + }; + assert!( + detached + .header_line("x") + .ends_with(" from 5e1c07a2 \u{00b7} x") + ); + let bare = BuildInfo { + commit: None, + commit_time: None, + branch: None, + ..BuildInfo::fixture() + }; + assert_eq!(bare.header_line("x"), "x"); + } + + #[test] + fn nothing_known_still_reports_the_version() { + let bare = BuildInfo { + commit: None, + subject: None, + commit_time: None, + branch: None, + checkout: None, + ..BuildInfo::fixture() + }; + assert_eq!( + bare.report(), + "PwrDisk 0.5.0 (debug, aarch64)\nBranch: detached HEAD\nCommit: unknown\n" + ); + assert_eq!(bare.commit_line(), None); + } +} diff --git a/crates/disktree-app/src/chrome.rs b/crates/disktree-app/src/chrome.rs new file mode 100644 index 00000000..d91878bf --- /dev/null +++ b/crates/disktree-app/src/chrome.rs @@ -0,0 +1,894 @@ +//! The window's title strip, and the frame around the window where disktree +//! has to draw one. +//! +//! The native title bar is gone wherever the platform lets it go: the strip +//! is the title bar, the masthead and the view settings in one band. Each +//! end of it may hold window controls — the stoplights on the left on +//! macOS, painted caption buttons on the right on Windows, and, under a Linux +//! compositor that leaves the frame to the client, whichever buttons its +//! `button-layout` asks for on whichever side it names. That is the one +//! platform decision: [`Frame`] says what each end holds, and the strip lays +//! the brand and its contents out between them. +//! +//! The window title is still set and kept current (see `state.rs`): the +//! Window menu, Mission Control, the taskbar and Waybar read it. It is only +//! no longer painted. + +use std::sync::{Arc, LazyLock}; + +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::{ + AnyElement, Context, CursorStyle, Decorations, Div, Edges, FontWeight, + Hsla, Image, ImageFormat, InteractiveElement as _, IntoElement as _, + MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement as _, Pixels, + ResizeEdge, Stateful, StatefulInteractiveElement as _, Styled as _, Tiling, + Window, WindowButton, WindowButtonLayout, WindowControlArea, + WindowControls, div, img, px, rgb, svg, white, +}; +use gpui_omarchy::{ActiveTheme as _, IconName, Theme}; + +use crate::widgets::with_tooltip; + +use crate::palette; +use crate::state::Disktree; +use crate::ui::{self, chrome, space}; + +/// Which system the window is on, as far as its frame is concerned. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Platform { + MacOs, + Windows, + Linux, +} + +impl Platform { + pub const fn current() -> Self { + if cfg!(target_os = "macos") { + Self::MacOs + } else if cfg!(windows) { + Self::Windows + } else { + Self::Linux + } + } +} + +/// What one end of the strip holds. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Controls { + /// Nothing: the strip's own padding. + None, + /// The macOS stoplights. The system draws them; the strip leaves room. + Stoplights, + /// Window buttons disktree paints, in this order. + Buttons(Vec), +} + +/// The window's frame: what each end of the strip holds, and whether +/// disktree draws the edges too. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Frame { + pub platform: Platform, + pub leading: Controls, + pub trailing: Controls, + /// Set when disktree draws the whole frame — a Linux compositor that + /// offers no server-side decorations, such as GNOME's — with the sides + /// the compositor has tiled, which keep no resize ring. + pub client_side: Option, +} + +/// GPUI's own fallback when the desktop's setting cannot be read: every +/// button, on the right. It only ever reports none off Linux. +const FALLBACK_LAYOUT: WindowButtonLayout = WindowButtonLayout { + left: [None; 3], + right: [ + Some(WindowButton::Minimize), + Some(WindowButton::Maximize), + Some(WindowButton::Close), + ], +}; + +impl Frame { + /// The frame this window has now. + pub fn detect(window: &Window, cx: &gpui_kit::App) -> Self { + Self::new( + Platform::current(), + window.window_decorations(), + cx.button_layout(), + window.window_controls(), + window.is_fullscreen(), + ) + } + + pub fn new( + platform: Platform, + decorations: Decorations, + layout: Option, + controls: WindowControls, + fullscreen: bool, + ) -> Self { + let none = Self { + platform, + leading: Controls::None, + trailing: Controls::None, + client_side: None, + }; + match platform { + // In full screen AppKit takes the stoplights away with the menu + // bar, and the room kept for them would be a dead gap. + Platform::MacOs if fullscreen => none, + Platform::MacOs => Self { + leading: Controls::Stoplights, + ..none + }, + // GPUI removes the caption and draws no buttons in its place. + Platform::Windows => Self { + trailing: Controls::Buttons(vec![ + WindowButton::Minimize, + WindowButton::Maximize, + WindowButton::Close, + ]), + ..none + }, + // Hyprland and KDE grant server-side decorations: Hyprland draws + // no frame by design and KDE draws its own, so the strip keeps + // out of both. + Platform::Linux => match decorations { + Decorations::Server => none, + Decorations::Client { tiling } => { + let layout = layout.unwrap_or(FALLBACK_LAYOUT); + // A button for something the compositor will not do + // would do nothing; close is always honoured. + let side = |buttons: [Option; 3]| { + let shown: Vec<_> = buttons + .into_iter() + .flatten() + .filter(|button| match button { + WindowButton::Minimize => controls.minimize, + WindowButton::Maximize => controls.maximize, + WindowButton::Close => true, + }) + .collect(); + if shown.is_empty() { + Controls::None + } else { + Controls::Buttons(shown) + } + }; + Self { + leading: side(layout.left), + trailing: side(layout.right), + client_side: Some(tiling), + ..none + } + } + }, + } + } + + /// The ring kept on each side for the shadow and the resize grip: none + /// on a side the compositor has tiled, nor anywhere it draws the frame. + fn ring(&self) -> Edges { + let open = |tiled: bool| { + if tiled { px(0.) } else { chrome::RESIZE_RING } + }; + self.client_side + .map_or_else(Edges::default, |tiling| Edges { + top: open(tiling.top), + right: open(tiling.right), + bottom: open(tiling.bottom), + left: open(tiling.left), + }) + } + + /// How far the content sits inside the window on each side: the ring, + /// then the hairline border, where disktree draws the frame. The + /// pointer and the window's size come in window coordinates, and + /// anything placed against them in the content has to take this off. + pub fn content_edges(&self) -> Edges { + let border = if self.client_side.is_some() { + px(1.) + } else { + px(0.) + }; + let ring = self.ring(); + Edges { + top: ring.top + border, + right: ring.right + border, + bottom: ring.bottom + border, + left: ring.left + border, + } + } + + /// Whether dragging the strip has to move the window by asking for it. + /// Windows does it from the caption area it is told about, and a + /// compositor that draws the frame has its own way to move a window. + const fn moves_itself(&self) -> bool { + match self.platform { + Platform::MacOs => true, + Platform::Windows => false, + Platform::Linux => self.client_side.is_some(), + } + } +} + +/// The app icon, from the same file the Dock, the desktop entry and the +/// installer use, so the window shows the mark people already know. +/// Settings › About draws it too. An SVG, so it is sharp at any size and +/// loads the same on macOS, Windows and Linux. +pub static MARK: LazyLock> = LazyLock::new(|| { + Arc::new(Image::from_bytes( + ImageFormat::Svg, + include_bytes!("../../../assets/disktree.svg").to_vec(), + )) +}); + +/// A window whose strip moves it. The press arms a move that the first +/// motion starts (see [`drag_area`]); the view keeps that one flag. +pub trait Drags: 'static { + fn strip_drag(&mut self) -> &mut bool; +} + +impl Drags for Disktree { + fn strip_drag(&mut self) -> &mut bool { + &mut self.strip_drag + } +} + +/// Windows' own close-button red, which it uses whatever the theme. +const CLOSE_RED: u32 = 0x00c4_2b1c; + +/// The strip: window controls at either end, the brand, then `content` — +/// the trail and the settings on explore, nothing on the other screens, +/// which carry their own heading. +pub fn strip( + frame: &Frame, + wordmark: bool, + content: impl gpui_kit::IntoElement, + window: &Window, + cx: &Context<'_, Disktree>, +) -> Stateful
{ + let theme = cx.omarchy().clone(); + let maximized = window.is_maximized(); + let leading = controls( + frame, + &frame.leading, + "window-controls-leading", + maximized, + &theme, + cx, + ); + let trailing = controls( + frame, + &frame.trailing, + "window-controls-trailing", + maximized, + &theme, + cx, + ); + div() + .id("title-strip") + .debug_selector(|| "title-strip".into()) + .flex() + .flex_row() + .items_center() + .flex_shrink_0() + // The band, then the divider under it: a divider inside the band + // would leave an odd height the stoplights cannot centre in. + .min_h(chrome::STRIP + px(1.)) + .border_b_1() + .border_color(theme.divider()) + .when(frame.trailing == Controls::None, |strip| strip.pr(space::LG)) + .children(leading) + // The brand replaces the old logo's source picker action. Keep + // its full-height padding clickable so the target has no dead edge. + .child(with_tooltip( + div() + .id("strip-brand") + .debug_selector(|| "strip-brand".into()) + .flex() + .items_center() + .self_stretch() + .flex_shrink_0() + .cursor_pointer() + .when(frame.leading == Controls::None, |area| { + area.pl(space::LG) + }) + .pr(space::LG) + .child(brand(wordmark, &theme)) + .on_click(cx.listener(|this, _, window, cx| { + this.open_volumes(cx); + this.apply_focus(window, cx); + })), + "Choose local or SSH source · v", + )) + .child( + div() + .flex() + .flex_row() + .items_center() + .self_stretch() + .flex_1() + .min_w_0() + .when(frame.trailing != Controls::None, |row| { + row.mr(space::SM) + }) + .child(content), + ) + .children(trailing) +} + +/// The strip of a window that is not the main one: Settings, Help's +/// documents and Logs. The same band, controls and brand, then the +/// window's place as crumbs ("Help › Changelog"), and `actions` at the +/// end. Everything but the controls and `actions` moves the window. +pub fn aux_strip( + frame: &Frame, + crumbs: &[&'static str], + actions: impl gpui_kit::IntoElement, + window: &Window, + cx: &Context<'_, V>, +) -> Stateful
{ + let theme = cx.omarchy().clone(); + let maximized = window.is_maximized(); + let leading = controls( + frame, + &frame.leading, + "window-controls-leading", + maximized, + &theme, + cx, + ); + let trailing = controls( + frame, + &frame.trailing, + "window-controls-trailing", + maximized, + &theme, + cx, + ); + let last = crumbs.len().saturating_sub(1); + let trail = crumbs.iter().enumerate().fold( + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .min_w_0() + .overflow_hidden(), + |trail, (index, crumb)| { + trail + .child( + div() + .text_size(crate::ui::text::TITLE) + .text_color(theme.secondary) + .child("\u{203a}"), + ) + .child( + div() + .text_size(crate::ui::text::TITLE) + .whitespace_nowrap() + .when(index == last, |crumb| { + crumb + .text_color(theme.bright) + .font_weight(FontWeight::SEMIBOLD) + }) + .when(index != last, |crumb| { + crumb.text_color(theme.foreground) + }) + .child(*crumb), + ) + }, + ); + div() + .id("title-strip") + .debug_selector(|| "title-strip".into()) + .flex() + .flex_row() + .items_center() + .flex_shrink_0() + .min_h(chrome::STRIP + px(1.)) + .border_b_1() + .border_color(theme.divider()) + .when(frame.trailing == Controls::None, |strip| { + strip.pr(space::LG) + }) + .children(leading) + .child( + drag_area(frame, "aux-strip-drag", cx) + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .self_stretch() + .flex_1() + .min_w_0() + .when(frame.leading == Controls::None, |area| { + area.pl(space::LG) + }) + .child(brand( + window.viewport_size().width.as_f32() + / window.rem_size().as_f32() + >= ui::COMPACT_WINDOW_REMS, + &theme, + )) + .child(trail), + ) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .flex_shrink_0() + .when(frame.trailing != Controls::None, |row| row.mr(space::SM)) + .child(actions), + ) + .children(trailing) +} + +/// Part of the strip that moves the window: everything that is not a +/// control. On Windows the system is told where its caption is and does +/// the rest — moving, snapping, maximizing on a double click and the system +/// menu on a right click. +pub fn drag_area( + frame: &Frame, + id: &'static str, + cx: &Context<'_, V>, +) -> Stateful
{ + let area = div().id(id).debug_selector(move || id.into()); + let platform = frame.platform; + if platform == Platform::Windows { + return area.window_control_area(WindowControlArea::Drag); + } + if !frame.moves_itself() { + return area; + } + area.on_mouse_down( + MouseButton::Left, + cx.listener(move |this, event: &MouseDownEvent, window, _| { + *this.strip_drag() = event.click_count < 2; + if event.click_count >= 2 { + if platform == Platform::MacOs { + // Zoom, minimize or nothing, as System Settings says. + window.titlebar_double_click(); + } else { + window.zoom_window(); + } + } + }), + ) + .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, window, _| { + // The move starts on the first motion, not on the press, so that + // a second press can still arrive as a double click. + if *this.strip_drag() + && event.pressed_button == Some(MouseButton::Left) + { + *this.strip_drag() = false; + window.start_window_move(); + } + })) + .on_mouse_up( + MouseButton::Left, + cx.listener(|this: &mut V, _, _, _| *this.strip_drag() = false), + ) + // Motion only reaches the area while the pointer is over it, so a + // press that leaves before its first motion is released elsewhere; it + // must not stay armed for the next drag that crosses the strip. + .on_mouse_up_out( + MouseButton::Left, + cx.listener(|this: &mut V, _, _, _| *this.strip_drag() = false), + ) + .when(platform == Platform::Linux, |area| { + area.on_mouse_down(MouseButton::Right, |event, window, _| { + window.show_window_menu(event.position); + }) + }) +} + +/// The icon and the name, centred on the band. +fn brand(wordmark: bool, theme: &Theme) -> Div { + div() + .flex() + .flex_row() + .items_center() + .gap(chrome::LOCKUP_GAP) + .child(img(MARK.clone()).size(chrome::MARK).flex_shrink_0()) + .when(wordmark, |brand| { + brand.child( + div() + .text_size(chrome::WORDMARK) + .line_height(chrome::WORDMARK) + .font_weight(FontWeight::BOLD) + .text_color(theme.bright) + .whitespace_nowrap() + .child("PwrDisk"), + ) + }) +} + +/// One end of the strip. +fn controls( + frame: &Frame, + controls: &Controls, + selector: &'static str, + maximized: bool, + theme: &Theme, + cx: &Context<'_, V>, +) -> Option { + match controls { + Controls::None => None, + Controls::Stoplights => Some( + drag_area(frame, selector, cx) + .w(chrome::STOPLIGHT_ZONE) + .h(chrome::STRIP) + .flex_shrink_0() + .into_any_element(), + ), + Controls::Buttons(buttons) => { + let row = div() + .id(selector) + .debug_selector(move || selector.into()) + .flex() + .flex_row() + .items_center() + .flex_shrink_0(); + let row = + if frame.platform == Platform::Windows { + row.children(buttons.iter().map(|&button| { + caption_button(button, maximized, theme) + })) + } else { + row.gap(space::SM).px(space::SM).children( + buttons.iter().map(|&button| { + window_button(button, maximized, theme) + }), + ) + }; + Some(row.into_any_element()) + } + } +} + +/// A Windows caption button. It has no click handler: the system hit-tests +/// it as the real button, so hovering maximize offers snap layouts and the +/// press does what Windows does. +fn caption_button( + button: WindowButton, + maximized: bool, + theme: &Theme, +) -> Stateful
{ + let group = button.id(); + let area = match button { + WindowButton::Minimize => WindowControlArea::Min, + WindowButton::Maximize => WindowControlArea::Max, + WindowButton::Close => WindowControlArea::Close, + }; + let close = button == WindowButton::Close; + let hover = theme.hover_fill(); + let ink = theme.foreground; + let lit = if close { white() } else { ink }; + div() + .id(button.id()) + .group(group) + .flex() + .items_center() + .justify_center() + .flex_shrink_0() + .w(chrome::CAPTION_BUTTON) + .h(chrome::STRIP) + .window_control_area(area) + .hover(move |style| { + if close { + style.bg(rgb(CLOSE_RED)) + } else { + style.bg(hover) + } + }) + .child(glyph(button, maximized, ink, group, lit)) +} + +/// A painted Linux window button. Square, like every other surface here. +fn window_button( + button: WindowButton, + maximized: bool, + theme: &Theme, +) -> Stateful
{ + let group = button.id(); + let (rest, hover) = palette::window_button(theme); + div() + .id(button.id()) + .group(group) + .flex() + .items_center() + .justify_center() + .flex_shrink_0() + .size(chrome::WINDOW_BUTTON) + .bg(rest) + .hover(move |style| style.bg(hover)) + .on_click(move |_, window, _| match button { + WindowButton::Minimize => window.minimize_window(), + WindowButton::Maximize => window.zoom_window(), + WindowButton::Close => window.remove_window(), + }) + .child(glyph(button, maximized, theme.bright, group, theme.bright)) +} + +/// The mark on a window button, drawn rather than taken from a font so it +/// looks the same everywhere; `lit` is its colour while `group` is hovered. +fn glyph( + button: WindowButton, + maximized: bool, + ink: Hsla, + group: &'static str, + lit: Hsla, +) -> AnyElement { + match button { + WindowButton::Minimize => div() + .w(chrome::GLYPH) + .h(px(1.)) + .bg(ink) + .group_hover(group, move |style| style.bg(lit)) + .into_any_element(), + // Restore: the window it would go back to, behind the one it is. + WindowButton::Maximize if maximized => div() + .relative() + .size(chrome::GLYPH) + .child( + div() + .absolute() + .top_0() + .right_0() + .size(chrome::GLYPH_BEHIND) + .border_t_1() + .border_r_1() + .border_color(ink), + ) + .child( + div() + .absolute() + .bottom_0() + .left_0() + .size(chrome::GLYPH_BEHIND) + .border_1() + .border_color(ink), + ) + .into_any_element(), + WindowButton::Maximize => div() + .size(chrome::GLYPH) + .border_1() + .border_color(ink) + .group_hover(group, move |style| style.border_color(lit)) + .into_any_element(), + WindowButton::Close => svg() + .path(IconName::Close.path()) + .size(chrome::CLOSE_GLYPH) + .text_color(ink) + .group_hover(group, move |style| style.text_color(lit)) + .into_any_element(), + } +} + +/// Wrap the window's content in the frame a client-side window needs: a +/// ring for the shadow and the resize grip on every side the compositor has +/// not tiled, and a hairline border. Anywhere else the content is the whole +/// window. +pub fn client_frame( + frame: &Frame, + content: Stateful
, + window: &mut Window, + theme: &Theme, +) -> AnyElement { + let Some(tiling) = frame.client_side else { + // A compositor that takes the frame back takes the whole surface: + // an inset left over would draw its frame inside the shadow ring. + if window.client_inset().is_some_and(|inset| inset > px(0.)) { + window.set_client_inset(px(0.)); + } + return content.into_any_element(); + }; + let ring = chrome::RESIZE_RING; + if window.client_inset() != Some(ring) { + window.set_client_inset(ring); + } + let open = frame.ring(); + let mut outer = div() + .id("client-frame") + .debug_selector(|| "client-frame".into()) + .relative() + .size_full() + .pt(open.top) + .pb(open.bottom) + .pl(open.left) + .pr(open.right) + .child( + div() + .size_full() + .border_1() + .border_color(theme.border) + .when(!tiling.is_tiled(), gpui_kit::Styled::shadow_lg) + .child(content), + ); + for (edge, tiled) in [ + (ResizeEdge::Top, tiling.top), + (ResizeEdge::Bottom, tiling.bottom), + (ResizeEdge::Left, tiling.left), + (ResizeEdge::Right, tiling.right), + ] { + if !tiled { + outer = outer.child(grip(edge, ring)); + } + } + for (edge, a, b) in [ + (ResizeEdge::TopLeft, tiling.top, tiling.left), + (ResizeEdge::TopRight, tiling.top, tiling.right), + (ResizeEdge::BottomLeft, tiling.bottom, tiling.left), + (ResizeEdge::BottomRight, tiling.bottom, tiling.right), + ] { + if !a && !b { + outer = outer.child(grip(edge, ring)); + } + } + outer.into_any_element() +} + +/// One resize handle in the ring, with the cursor that says so. +fn grip(edge: ResizeEdge, ring: Pixels) -> Stateful
{ + let (cursor, id) = match edge { + ResizeEdge::Top => (CursorStyle::ResizeUpDown, "grip-top"), + ResizeEdge::Bottom => (CursorStyle::ResizeUpDown, "grip-bottom"), + ResizeEdge::Left => (CursorStyle::ResizeLeftRight, "grip-left"), + ResizeEdge::Right => (CursorStyle::ResizeLeftRight, "grip-right"), + ResizeEdge::TopLeft => { + (CursorStyle::ResizeUpLeftDownRight, "grip-top-left") + } + ResizeEdge::BottomRight => { + (CursorStyle::ResizeUpLeftDownRight, "grip-bottom-right") + } + ResizeEdge::TopRight => { + (CursorStyle::ResizeUpRightDownLeft, "grip-top-right") + } + ResizeEdge::BottomLeft => { + (CursorStyle::ResizeUpRightDownLeft, "grip-bottom-left") + } + }; + let grip = div() + .id(id) + .debug_selector(move || id.into()) + .absolute() + .cursor(cursor) + .on_mouse_down(MouseButton::Left, move |_, window, _| { + window.start_window_resize(edge); + }); + // Edges run between the corners; corners are a ring-sized square. + match edge { + ResizeEdge::Top => grip.top_0().left(ring).right(ring).h(ring), + ResizeEdge::Bottom => grip.bottom_0().left(ring).right(ring).h(ring), + ResizeEdge::Left => grip.left_0().top(ring).bottom(ring).w(ring), + ResizeEdge::Right => grip.right_0().top(ring).bottom(ring).w(ring), + ResizeEdge::TopLeft => grip.top_0().left_0().size(ring), + ResizeEdge::TopRight => grip.top_0().right_0().size(ring), + ResizeEdge::BottomLeft => grip.bottom_0().left_0().size(ring), + ResizeEdge::BottomRight => grip.bottom_0().right_0().size(ring), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn frame( + platform: Platform, + decorations: Decorations, + layout: Option, + ) -> Frame { + Frame::new( + platform, + decorations, + layout, + WindowControls::default(), + false, + ) + } + + const CLIENT: Decorations = Decorations::Client { + tiling: Tiling { + top: false, + left: false, + right: false, + bottom: false, + }, + }; + + #[test] + fn macos_leaves_room_for_the_stoplights_on_the_left() { + let mac = frame(Platform::MacOs, Decorations::Server, None); + assert_eq!(mac.leading, Controls::Stoplights); + assert_eq!(mac.trailing, Controls::None); + assert!(mac.client_side.is_none()); + let full = Frame::new( + Platform::MacOs, + Decorations::Server, + None, + WindowControls::default(), + true, + ); + assert_eq!(full.leading, Controls::None, "no dead gap in full screen"); + } + + #[test] + fn windows_paints_its_caption_buttons_on_the_right() { + let windows = frame(Platform::Windows, Decorations::Server, None); + assert_eq!(windows.leading, Controls::None); + assert_eq!( + windows.trailing, + Controls::Buttons(vec![ + WindowButton::Minimize, + WindowButton::Maximize, + WindowButton::Close, + ]) + ); + } + + #[test] + fn a_linux_compositor_that_draws_the_frame_gets_no_controls() { + let hyprland = frame(Platform::Linux, Decorations::Server, None); + assert_eq!(hyprland.leading, Controls::None); + assert_eq!(hyprland.trailing, Controls::None); + assert!(hyprland.client_side.is_none()); + } + + #[test] + fn a_client_side_frame_follows_the_desktops_button_layout() { + // GNOME's "close,minimize:maximize": two on the left, one on the + // right, in that order. + let layout = WindowButtonLayout { + left: [ + Some(WindowButton::Close), + Some(WindowButton::Minimize), + None, + ], + right: [Some(WindowButton::Maximize), None, None], + }; + let gnome = frame(Platform::Linux, CLIENT, Some(layout)); + assert_eq!( + gnome.leading, + Controls::Buttons(vec![ + WindowButton::Close, + WindowButton::Minimize + ]) + ); + assert_eq!( + gnome.trailing, + Controls::Buttons(vec![WindowButton::Maximize]) + ); + assert!(gnome.client_side.is_some()); + + // Unreadable: every button on the right. + let fallback = frame(Platform::Linux, CLIENT, None); + assert_eq!(fallback.leading, Controls::None); + assert_eq!( + fallback.trailing, + Controls::Buttons(vec![ + WindowButton::Minimize, + WindowButton::Maximize, + WindowButton::Close, + ]) + ); + } + + #[test] + fn buttons_for_what_the_compositor_will_not_do_are_left_out() { + let controls = WindowControls { + fullscreen: false, + maximize: false, + minimize: false, + window_menu: true, + }; + let frame = Frame::new(Platform::Linux, CLIENT, None, controls, false); + assert_eq!( + frame.trailing, + Controls::Buttons(vec![WindowButton::Close]) + ); + } +} diff --git a/crates/disktree-app/src/cleanup.rs b/crates/disktree-app/src/cleanup.rs new file mode 100644 index 00000000..3408447f --- /dev/null +++ b/crates/disktree-app/src/cleanup.rs @@ -0,0 +1,260 @@ +//! Cache cleanup belongs to the selected scan and marks. Owners are +//! resolved off the UI thread, and preparing never runs or deletes +//! anything. The person decides each marked path: Skip (the default), the +//! owner's exact command, or deleting the files, which needs its own tick. + +use std::path::PathBuf; +use std::sync::{Arc, Weak}; +use std::time::Instant; + +use disktree_core::cleanup::{Action, Approved, Decision, Prepared}; +use disktree_core::removal::Target; +use disktree_core::tree::Tree; +use gpui_kit::Context; +use gpui_omarchy::Status; + +use crate::state::{Disktree, Screen}; + +#[derive(Debug)] +pub struct Review { + root: PathBuf, + marks: Vec, + tree: Weak, + created: Instant, + result: Option>, + /// One per proposal, in its order. Skip until the person chooses. + decisions: Vec, + /// How Delete files removes: Trash or Permanent. + files: Action, + /// The confirmation's separate consent to deleting files directly. + files_ticked: bool, + /// The decisions turned into steps, kept until they change: Review + /// reads it several times a frame, and building it plans the steps + /// against the mount table each time. + approved: Option>, +} + +impl Review { + fn approve(&mut self) { + self.approved = match &self.result { + Some(Ok(prepared)) => { + Some(prepared.approve(&self.decisions, self.files)) + } + _ => None, + }; + } + + /// No age limit: a person may take their time deciding, and an + /// agent's preview carries its own lifetime. What could go stale is + /// checked again on the worker right before each step: the owner's + /// executable, version, configured root and scope, the guards, the + /// capacity limit and whether the path is in use. + fn matches(&self, app: &Disktree) -> bool { + self.root == app.root_path + && self.marks == app.marks.items() + && app.remote.is_none() + && app.scan.is_none() + && app.tree.as_ref().is_some_and(|tree| { + Weak::ptr_eq(&self.tree, &Arc::downgrade(tree)) + }) + } +} + +impl Disktree { + fn cleanup_review(&self) -> Result<&Review, String> { + self.cleanup_review + .as_ref() + .filter(|review| review.matches(self)) + .ok_or_else(|| { + "Check owners for this scan and selection first".to_string() + }) + } + + /// The read-only proposals for this exact scan and selection. + pub(crate) fn cleanup_ready(&self) -> Result<&Prepared, String> { + self.cleanup_review()? + .result + .as_ref() + .ok_or( + "Owner check is preparing; retry the read-only preview shortly", + )? + .as_ref() + .map_err(Clone::clone) + } + + /// A finished check that failed as a whole, such as an environment + /// that cannot be captured. Per-path failures are proposals instead. + pub(crate) fn cleanup_failed(&self) -> Option { + match &self.cleanup_review().ok()?.result { + Some(Err(reason)) => Some(reason.clone()), + _ => None, + } + } + + pub(crate) fn cleanup_preparing(&self) -> bool { + self.cleanup_review() + .is_ok_and(|review| review.result.is_none()) + } + + /// The person's decisions in the window, as steps to run. + pub(crate) fn cleanup_approved(&self) -> Result<&Approved, String> { + self.cleanup_ready()?; + self.cleanup_review()? + .approved + .as_ref() + .ok_or("Choose an action for every marked path")? + .as_ref() + .map_err(Clone::clone) + } + + pub(crate) fn cleanup_decision(&self, index: usize) -> Decision { + self.cleanup_review().map_or(Decision::Skip, |review| { + review.decisions.get(index).copied().unwrap_or_default() + }) + } + + pub(crate) fn cleanup_files(&self) -> Action { + self.cleanup_review() + .map_or_else(|_| self.default_files(), |review| review.files) + } + + pub(crate) fn cleanup_files_ticked(&self) -> bool { + self.cleanup_review() + .is_ok_and(|review| review.files_ticked) + } + + /// Trash when it exists, as everywhere else in PwrDisk: the safer + /// default, even though a cache's space returns only once emptied. + const fn default_files(&self) -> Action { + if self.trash_backend.is_available() { + Action::Trash + } else { + Action::Permanent + } + } + + pub(crate) fn decide_cleanup( + &mut self, + index: usize, + decision: Decision, + cx: &mut Context<'_, Self>, + ) { + let allowed = self.cleanup_ready().is_ok_and(|prepared| { + prepared + .proposals + .get(index) + .is_some_and(|proposal| proposal.allows(decision)) + }); + if !allowed { + return; + } + if let Some(review) = &mut self.cleanup_review + && let Some(slot) = review.decisions.get_mut(index) + { + *slot = decision; + // A change to what is deleted asks for the tick again. + review.files_ticked = false; + review.approve(); + } + self.confirm_open = false; + cx.notify(); + } + + pub(crate) fn set_cleanup_files( + &mut self, + files: Action, + cx: &mut Context<'_, Self>, + ) { + if files == Action::Trash && !self.trash_backend.is_available() { + return; + } + if let Some(review) = &mut self.cleanup_review { + review.files = files; + review.files_ticked = false; + review.approve(); + } + self.confirm_open = false; + cx.notify(); + } + + pub(crate) fn tick_cleanup_files(&mut self, cx: &mut Context<'_, Self>) { + if let Some(review) = &mut self.cleanup_review { + review.files_ticked = !review.files_ticked; + } + cx.notify(); + } + + /// Every proposal, or why there are none yet. + pub(crate) fn cleanup_description(&self) -> String { + match self.cleanup_ready() { + Ok(prepared) => prepared.description(), + Err(reason) => reason, + } + } + + pub(crate) fn prepare_cleanup(&mut self, cx: &mut Context<'_, Self>) { + if self.remote.is_some() + || self.scan.is_some() + || self.screen == Screen::Running + || self.marks.is_empty() + { + self.say( + "Cache cleanup needs a complete, idle local scan and marked paths", + Status::Warning, + cx, + ); + cx.notify(); + return; + } + // Do not start another probe while this exact request is pending. + if self.cleanup_preparing() { + return; + } + let Some(tree) = &self.tree else { + return; + }; + let root = self.root_path.clone(); + let marks = self.marks.items().to_vec(); + let tree = Arc::downgrade(tree); + let created = Instant::now(); + self.cleanup_review = Some(Review { + root: root.clone(), + marks: marks.clone(), + tree, + created, + result: None, + decisions: vec![Decision::Skip; marks.len()], + files: self.default_files(), + files_ticked: false, + approved: None, + }); + self.confirm_open = false; + let path = self.cleanup_path.clone(); + let task = cx.background_executor().spawn(async move { + match path { + Some(path) => disktree_core::cleanup::prepare_on_path( + &marks, &root, &path, + ), + None => disktree_core::cleanup::prepare(&marks, &root), + } + }); + cx.spawn(async move |this, cx| { + let result = task.await; + let _ = this.update(cx, |this, cx| { + if let Some(review) = &mut this.cleanup_review + && review.created == created + { + if let Ok(prepared) = &result { + review.decisions = + vec![Decision::Skip; prepared.proposals.len()]; + } + review.result = Some(result); + review.approve(); + } + cx.notify(); + }); + }) + .detach(); + cx.notify(); + } +} diff --git a/crates/disktree-app/src/cleanup_view.rs b/crates/disktree-app/src/cleanup_view.rs new file mode 100644 index 00000000..f957ad69 --- /dev/null +++ b/crates/disktree-app/src/cleanup_view.rs @@ -0,0 +1,363 @@ +//! Review's cache cleanup: under each marked path, what Check owners found +//! and exactly what would run, then the person's choice for that path; and +//! in the summary, the counts and how Delete files removes. + +use std::fmt::Write as _; +use std::path::Path; + +use disktree_core::cleanup::{ + Action, Decision, OWNER_RECOVERABILITY, Operation, Problem, Proposal, +}; +use disktree_core::removal::RemovalMode; +use disktree_core::size::human_bytes; +use gpui_kit::{ + AnyElement, Context, Div, InteractiveElement as _, IntoElement, + ParentElement, SharedString, Styled, Window, div, +}; +use gpui_omarchy::{ButtonVariant, ChoiceItem, Theme, button, button_group}; + +use crate::semantics::AccessibleButton as _; +use crate::state::Disktree; +use crate::ui::{space, text}; +use crate::widgets; + +fn caption(text_: impl Into, color: gpui_kit::Hsla) -> Div { + div() + .text_size(text::CAPTION) + .text_color(color) + .child(text_.into()) +} + +/// Monospace, so argument boundaries and paths line up and read exactly. +fn exact(text_: impl Into, theme: &Theme) -> Div { + caption(text_, theme.foreground).font_family(theme.mono_font.clone()) +} + +/// What the proposal says first, and the colour it is ruled in. +fn status( + proposal: &Proposal, + operations: &[Operation], + theme: &Theme, +) -> (String, gpui_kit::Hsla) { + let owner = proposal.owner.map_or("", |owner| owner.label()); + match (&proposal.issue, proposal.operations.first()) { + (None, Some(first)) => ( + format!( + "Ready \u{b7} {} {}", + operations[*first].owner.label(), + operations[*first].version + ), + theme.success, + ), + (Some(_), Some(_)) => ( + "Partly ready: some of its commands are unavailable".into(), + theme.warning, + ), + (Some(issue), None) if issue.problem == Problem::Refused => { + (format!("Refused \u{b7} {owner}"), theme.danger) + } + (Some(issue), None) if issue.problem == Problem::UnknownOwner => ( + "Unknown owner \u{b7} not known to be disposable".into(), + theme.warning, + ), + (Some(issue), None) => { + let label = issue.problem.label(); + let mut first = label.chars(); + let label = first.next().map_or_else(String::new, |head| { + head.to_uppercase().chain(first).collect() + }); + (format!("{label} \u{b7} {owner}"), theme.warning) + } + (None, None) => ("No owner command".into(), theme.warning), + } +} + +#[allow( + clippy::unnecessary_debug_formatting, + reason = "Consent must expose argument boundaries and control characters" +)] +fn command_lines(operation: &Operation) -> String { + let mut lines = format!( + "Executable {:?}\nArguments {:?}\n", + operation.command.executable, operation.command.arguments + ); + if !operation.command.environment.is_empty() { + let _ = + writeln!(lines, "Environment {:?}", operation.command.environment); + } + let _ = write!( + lines, + "Directory {:?}\nCache root {:?}\nScope {:?}", + operation.command.working_directory, + operation.cache_root, + operation.scope + ); + lines +} + +/// The proposal for marked path `index`, drawn under its row in Review. +pub fn proposal( + app: &Disktree, + index: usize, + path: &Path, + theme: &Theme, + window: &mut Window, + cx: &mut Context<'_, Disktree>, +) -> Option { + if app.removal_mode != RemovalMode::OwnerCleanup || app.remote.is_some() { + return None; + } + let block = |color| { + div() + .id(SharedString::from(format!("cleanup-proposal-{index}"))) + .debug_selector(move || format!("cleanup-proposal-{index}")) + .flex() + .flex_col() + .gap(space::XS) + .ml(space::XL) + .mr(space::MD) + .mb(space::SM) + .pl(space::MD) + .border_l_2() + .border_color(color) + }; + if app.cleanup_preparing() { + return Some( + block(theme.secondary) + .child(caption("Checking owner\u{2026}", theme.secondary)) + .into_any_element(), + ); + } + let prepared = app.cleanup_ready().ok()?; + let proposal = prepared + .proposals + .get(index) + .filter(|proposal| proposal.selected == path)?; + let decision = app.cleanup_decision(index); + let (headline, color) = status(proposal, &prepared.operations, theme); + let mut element = block(color).child( + div() + .text_size(text::CAPTION) + .text_color(color) + .child(headline), + ); + for operation in &proposal.operations { + let operation = &prepared.operations[*operation]; + element = element.child(exact(command_lines(operation), theme)); + if operation.wider() { + element = element.child(caption( + "Wider than selected: the command acts on the whole scope, \ + including unselected siblings.", + theme.warning, + )); + } + element = element.child(caption( + format!( + "{} {} {OWNER_RECOVERABILITY}", + operation.effects, operation.limitations + ), + theme.secondary, + )); + } + if let Some(issue) = &proposal.issue { + element = + element.child(caption(issue.detail.clone(), theme.foreground)); + } + + let run = match proposal.operations.as_slice() { + [] => format!( + "Run {}", + proposal + .owner + .map_or("owner command", |owner| owner.command_label()) + ), + [only] => { + format!("Run {}", prepared.operations[*only].owner.command_label()) + } + many => format!("Run {} owner commands", many.len()), + }; + let entity = cx.entity().downgrade(); + let choice = button_group( + SharedString::from(format!("cleanup-decision-{index}")), + vec![ + ChoiceItem::new("skip", "Skip"), + ChoiceItem::new("owner", run) + .disabled(!proposal.allows(Decision::Owner)), + ChoiceItem::new("delete", "Delete files") + .disabled(!proposal.allows(Decision::DeleteFiles)), + ], + Some(match decision { + Decision::Skip => 0, + Decision::Owner => 1, + Decision::DeleteFiles => 2, + }), + move |choice, _, cx| { + let decision = match choice { + 1 => Decision::Owner, + 2 => Decision::DeleteFiles, + _ => Decision::Skip, + }; + let _ = entity.update(cx, |this, cx| { + this.decide_cleanup(index, decision, cx); + }); + }, + window, + cx, + ); + element = element.child(div().flex().child(choice)); + + match (&proposal.delete, &proposal.delete_issue) { + (Some(disclosure), _) if decision == Decision::DeleteFiles => { + element = element.child( + div() + .debug_selector(move || format!("cleanup-delete-{index}")) + .flex() + .flex_col() + .gap(space::XS) + .p(space::SM) + .border_1() + .border_color(theme.danger) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.bright) + .child(format!( + "Delete files directly: {}, {}", + app.display_path(&proposal.selected), + human_bytes(proposal.bytes) + )), + ) + .child(caption( + disclosure.description(app.cleanup_files()), + theme.foreground, + )), + ); + } + (None, Some(issue)) => { + element = element.child(caption( + format!("Delete files unavailable: {}", issue.description()), + theme.secondary, + )); + } + _ => {} + } + Some(element.into_any_element()) +} + +/// The summary's cleanup section: what Check owners does, the counts of +/// what was chosen, and how Delete files removes. +pub fn summary( + app: &Disktree, + theme: &Theme, + window: &mut Window, + cx: &mut Context<'_, Disktree>, +) -> Div { + let mut section = div().flex().flex_col().gap(space::MD); + let preparing = app.cleanup_preparing(); + let ready = app.cleanup_ready(); + let check = button( + "check-owners", + if preparing { + "Checking owners\u{2026}" + } else if ready.is_ok() { + "Check owners again" + } else { + "Check owners" + }, + ButtonVariant::Outline, + cx, + ) + .debug_selector(|| "check-owners".into()) + .semantic_disabled(preparing) + .on_click(cx.listener(|this, _, _, cx| this.prepare_cleanup(cx))); + section = section.child(check); + let prepared = match ready { + Ok(prepared) => prepared, + Err(reason) => { + if !preparing && app.cleanup_review.is_some() { + section = section.child(caption(reason, theme.warning)); + } + return section; + } + }; + let decisions: Vec<_> = (0..prepared.proposals.len()) + .map(|index| app.cleanup_decision(index)) + .collect(); + let count = |wanted: Decision| { + decisions + .iter() + .filter(|decision| **decision == wanted) + .count() + }; + section = section + .child(widgets::row( + "Owner commands", + count(Decision::Owner).to_string(), + cx, + )) + .child(widgets::row( + "Delete files", + count(Decision::DeleteFiles).to_string(), + cx, + )) + .child(widgets::row( + "Skipped", + count(Decision::Skip).to_string(), + cx, + )); + if count(Decision::DeleteFiles) > 0 { + let entity = cx.entity().downgrade(); + let files = button_group( + "cleanup-files-mode", + vec![ + ChoiceItem::new("trash", "Trash") + .disabled(!app.trash_backend.is_available()), + ChoiceItem::new("permanent", "Permanently"), + ], + Some(usize::from(app.cleanup_files() == Action::Permanent)), + move |index, _, cx| { + let _ = entity.update(cx, |this, cx| { + this.set_cleanup_files( + if index == 0 { + Action::Trash + } else { + Action::Permanent + }, + cx, + ); + }); + }, + window, + cx, + ); + section = section + .child( + div() + .flex() + .flex_col() + .gap(space::XS) + .child(caption("Delete files by", theme.secondary)) + .child(div().flex().child(files)), + ) + .child(caption( + disktree_core::cleanup::files_recoverability( + app.cleanup_files(), + ), + theme.secondary, + )); + } + if let Err(reason) = app.cleanup_approved() + && decisions.iter().any(|decision| *decision != Decision::Skip) + { + section = section.child(caption(reason, theme.warning)); + } + section +} + +/// What Review's mode explains for a cache cleanup. +pub const EXPLANATION: &str = "Check owners finds each marked path's \ + installed owner, version and configured cache without changing \ + anything. Then choose for each path: Skip, the owner's exact command, \ + or Delete files. Nothing is chosen for you, and a failed owner command \ + never deletes files instead. Listed allocation is an upper bound; \ + freed space is measured afterwards, and cleanup rescans."; diff --git a/crates/disktree-app/src/diag_log.rs b/crates/disktree-app/src/diag_log.rs new file mode 100644 index 00000000..90201d5a --- /dev/null +++ b/crates/disktree-app/src/diag_log.rs @@ -0,0 +1,336 @@ +//! The diagnostic log: `main.log` in [`log_dir`] (`~/Library/Logs/PwrDisk` +//! on macOS), beside the other Pwr apps' logs. +//! +//! One logger for the `log` facade, so PwrDisk's own messages, Velopack's +//! updater and GPUI's warnings land in one file. A Finder or Start menu +//! launch has no terminal, and stderr goes nowhere; this is what is left +//! when a scan was slow, a removal refused or an update failed. When stderr +//! is a terminal (a dev run) each line is echoed there too. +//! +//! Never a scanned path: scans name people, clients and volumes. Lines say +//! what happened and how long it took; Help › Logs and Copy Diagnostics Info +//! can then be shared without reading them first. +//! +//! `main.log` is rotated to `main.old.log` past [`MAX_BYTES`], so the two +//! together stay under twice that. + +use std::{ + cell::Cell, + fs::{self, File, OpenOptions}, + io::{self, IsTerminal as _, Write as _}, + path::{Path, PathBuf}, + sync::{Mutex, OnceLock, PoisonError}, +}; + +use log::{Level, LevelFilter, Log, Metadata, Record}; + +/// When `main.log` is moved aside to `main.old.log`. +pub const MAX_BYTES: u64 = 1024 * 1024; + +const FILE: &str = "main.log"; +const OLD_FILE: &str = "main.old.log"; + +static PATH: OnceLock = OnceLock::new(); + +thread_local! { + /// This thread is inside [`Logger::log`], holding its lock: a panic + /// there must not log again (the panic hook would wait on that lock). + static LOGGING: Cell = const { Cell::new(false) }; +} + +/// Where the log is being written, once [`install`] found a directory. +pub fn path() -> Option<&'static Path> { + PATH.get().map(PathBuf::as_path) +} + +/// Where the log lives: `~/Library/Logs/PwrDisk` on macOS, as the other +/// Pwr apps' logs do; `%LOCALAPPDATA%\\PwrDisk\\logs` on Windows; and +/// `$XDG_STATE_HOME/pwrdisk` (`~/.local/state/pwrdisk`) on Linux, the XDG +/// home for logs. +pub fn log_dir() -> Option { + let home = std::env::home_dir(); + if cfg!(target_os = "macos") { + home.map(|home| home.join("Library/Logs/PwrDisk")) + } else if cfg!(windows) { + std::env::var_os("LOCALAPPDATA") + .map(|base| PathBuf::from(base).join("PwrDisk").join("logs")) + } else { + std::env::var_os("XDG_STATE_HOME") + .map(PathBuf::from) + .filter(|path| path.is_absolute()) + .or_else(|| home.map(|home| home.join(".local/state"))) + .map(|base| base.join("pwrdisk")) + } +} + +/// Installs the logger and a panic hook that logs the panic. Call once, at +/// the top of `main`. `PWRDISK_LOG=debug` (or `trace`, `warn`, ...) sets +/// PwrDisk's own level; Velopack logs at info, everything else at warn. +pub fn install() { + let level = std::env::var("PWRDISK_LOG") + .ok() + .and_then(|value| value.parse::().ok()) + .unwrap_or(LevelFilter::Info); + let file = log_dir().and_then(|dir| { + let file = LogFile::open(&dir).map_err(|error| { + eprintln!( + "pwrdisk: no diagnostic log in {}: {error}", + dir.display() + ); + }); + file.ok() + }); + if let Some(file) = &file { + let _ = PATH.set(file.path.clone()); + } + let logger = Logger { + own: level, + file: Mutex::new(file), + echo: io::stderr().is_terminal(), + }; + if log::set_boxed_logger(Box::new(logger)).is_err() { + return; + } + log::set_max_level(level.max(LevelFilter::Info)); + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + if !LOGGING.get() { + log::error!(target: "pwrdisk", "panic: {info}"); + } + previous(info); + })); +} + +struct Logger { + /// PwrDisk's own level. + own: LevelFilter, + file: Mutex>, + echo: bool, +} + +impl Log for Logger { + fn enabled(&self, metadata: &Metadata<'_>) -> bool { + metadata.level() <= level_for(metadata.target(), self.own) + } + + fn log(&self, record: &Record<'_>) { + if !self.enabled(record.metadata()) { + return; + } + let line = format_line( + &chrono::Local::now() + .format("%Y-%m-%dT%H:%M:%S%.3f%:z") + .to_string(), + record.level(), + record.target(), + &record.args().to_string(), + ); + if self.echo { + let _ = io::stderr().write_all(line.as_bytes()); + } + LOGGING.set(true); + if let Some(file) = self + .file + .lock() + .unwrap_or_else(PoisonError::into_inner) + .as_mut() + { + file.write(&line); + } + LOGGING.set(false); + } + + fn flush(&self) {} +} + +/// The most verbose level kept for `target`. +fn level_for(target: &str, own: LevelFilter) -> LevelFilter { + // The binary's crate is `pwrdisk`; the scanner's is `disktree_core`. + if target.starts_with("pwrdisk") || target.starts_with("disktree") { + own + } else if target.starts_with("velopack") { + LevelFilter::Info + } else { + LevelFilter::Warn + } +} + +/// `2026-10-24T07:31:02.123-04:00 INFO pwrdisk::scan: scan finished ...`, one +/// line: a message's own newlines are escaped, so each record stays one line +/// for grep. +fn format_line( + time: &str, + level: Level, + target: &str, + message: &str, +) -> String { + let message = message.trim_end().replace('\n', "\\n"); + format!("{time} {level:<5} {target}: {message}\n") +} + +/// `main.log`, appended to, and moved to `main.old.log` when it grows past +/// [`MAX_BYTES`]. +/// +/// Other PwrDisk processes write it too (a second window's launch, +/// Velopack's hooks), and any of them can rotate it. So nothing +/// is held open: each line opens the file the path names now, checks that +/// file's own size, appends and closes. A few lines per scan make that +/// cheap, and no process can be left writing to a file another one moved. +struct LogFile { + path: PathBuf, +} + +impl LogFile { + fn open(dir: &Path) -> io::Result { + fs::create_dir_all(dir)?; + let log = Self { + path: dir.join(FILE), + }; + // Fails here, at install, rather than silently on every line. + drop(open_append(&log.path)?); + Ok(log) + } + + fn write(&self, line: &str) { + let Ok(mut file) = self.rotated_if_full(line.len() as u64) else { + return; + }; + let _ = file.write_all(line.as_bytes()); + } + + /// The file to append `extra` bytes to: `main.log`, moved aside first + /// when they would take it past [`MAX_BYTES`]. + fn rotated_if_full(&self, extra: u64) -> io::Result { + let file = open_append(&self.path)?; + if file.metadata()?.len() + extra <= MAX_BYTES { + return Ok(file); + } + drop(file); + fs::rename(&self.path, self.path.with_file_name(OLD_FILE))?; + open_append(&self.path) + } +} + +/// Appends to `path`, creating it readable by this user only: it says what +/// this user did and when. +fn open_append(path: &Path) -> io::Result { + let mut options = OpenOptions::new(); + options.create(true).append(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; + options.mode(0o600); + } + options.open(path) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_line_is_one_line_with_time_level_and_target() { + assert_eq!( + format_line( + "2026-10-24T07:31:02.123-04:00", + Level::Warn, + "pwrdisk::scan", + "first\nsecond\n" + ), + "2026-10-24T07:31:02.123-04:00 WARN pwrdisk::scan: first\\nsecond\n" + ); + } + + #[test] + fn pwrdisk_follows_its_level_velopack_logs_info_and_the_rest_warns() { + assert_eq!( + level_for("pwrdisk::scan", LevelFilter::Debug), + LevelFilter::Debug + ); + assert_eq!( + level_for("disktree_core::scan", LevelFilter::Info), + LevelFilter::Info + ); + assert_eq!( + level_for("velopack::manager", LevelFilter::Debug), + LevelFilter::Info + ); + assert_eq!(level_for("gpui", LevelFilter::Debug), LevelFilter::Warn); + } + + #[test] + fn the_log_moves_aside_past_its_limit_and_keeps_one_old_file() { + let dir = tempfile::tempdir().unwrap(); + let log = LogFile::open(dir.path()).unwrap(); + let line = format!("{}\n", "x".repeat(1023)); + for _ in 0..(MAX_BYTES / 1024) { + log.write(&line); + } + assert_eq!( + fs::metadata(dir.path().join(FILE)).unwrap().len(), + MAX_BYTES + ); + assert!(!dir.path().join(OLD_FILE).exists()); + + log.write("next\n"); + assert_eq!( + fs::read_to_string(dir.path().join(FILE)).unwrap(), + "next\n" + ); + assert_eq!( + fs::metadata(dir.path().join(OLD_FILE)).unwrap().len(), + MAX_BYTES + ); + + // Reopened past the limit (another process wrote it), it starts fresh. + drop(log); + fs::write(dir.path().join(FILE), "y".repeat(MAX_BYTES as usize)) + .unwrap(); + let log = LogFile::open(dir.path()).unwrap(); + log.write("after\n"); + assert_eq!( + fs::read_to_string(dir.path().join(FILE)).unwrap(), + "after\n" + ); + } + + #[test] + fn a_rotation_by_another_process_is_followed_not_overwritten() { + let dir = tempfile::tempdir().unwrap(); + let ours = LogFile::open(dir.path()).unwrap(); + ours.write("ours 1\n"); + // Another process fills the log and rotates it. + let theirs = LogFile::open(dir.path()).unwrap(); + theirs.write(&"t".repeat(MAX_BYTES as usize - "ours 1\n".len())); + theirs.write("theirs\n"); + assert_eq!( + fs::read_to_string(dir.path().join(FILE)).unwrap(), + "theirs\n" + ); + + ours.write("ours 2\n"); + assert_eq!( + fs::read_to_string(dir.path().join(FILE)).unwrap(), + "theirs\nours 2\n" + ); + assert!( + fs::read_to_string(dir.path().join(OLD_FILE)) + .unwrap() + .starts_with("ours 1\n") + ); + } + + #[cfg(unix)] + #[test] + fn the_log_is_readable_by_its_owner_only() { + use std::os::unix::fs::PermissionsExt as _; + let dir = tempfile::tempdir().unwrap(); + let log = LogFile::open(dir.path()).unwrap(); + log.write("x\n"); + let mode = fs::metadata(dir.path().join(FILE)) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o600); + } +} diff --git a/crates/disktree-app/src/diagnostics.rs b/crates/disktree-app/src/diagnostics.rs new file mode 100644 index 00000000..1b29589a --- /dev/null +++ b/crates/disktree-app/src/diagnostics.rs @@ -0,0 +1,505 @@ +//! Diagnostics: what this copy runs with, as Settings › Diagnostics shows +//! it and Help › Copy Diagnostics Info puts it on the clipboard. One model, +//! one [`Diagnostics::report`], so a paste into an issue says exactly what +//! the pane says. +//! +//! The report is the family's (PwrGit's sections, PwrRoute's build lines +//! first). It never carries what was scanned: a scan's root, host and +//! volume names say who someone works for and what they keep, so the scan +//! is described by its kind and its counts only. PwrDisk's own folders are +//! shown with `~` for home. + +use disktree_core::path_style::PathStyle; +use std::fmt::Write as _; +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use gpui_kit::App; +use gpui_omarchy::ActiveTheme as _; + +use crate::build_info::BuildInfo; +use crate::marks::display_path; +use crate::state::Disktree; + +/// One line of a section: "Label: value". +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Fact { + pub label: &'static str, + pub value: String, +} + +/// A titled group of facts: a card in the pane, a `[Title]` block in the +/// report. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Section { + pub title: &'static str, + pub facts: Vec, +} + +/// Everything the pane draws and the report writes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Diagnostics { + /// When this was read, as an RFC 3339 local time. + pub collected: String, + pub build: BuildInfo, + pub sections: Vec
, + /// The log file, for the pane's Open Logs; `None` when there is none. + pub log: Option, + /// The settings folder, for the pane's Open settings folder. + pub settings_dir: Option, +} + +/// The facts the model is built from, read from the process and the OS +/// by [`collect`] and contrived by the tests. +#[derive(Clone, Debug)] +pub struct Facts { + pub collected: String, + pub build: BuildInfo, + pub os: String, + pub home: Option, + /// `Some(version)` when Velopack installed this copy. + pub installed: Option, + /// "Stable · Latest (follows this build)". + pub channel: String, + /// The last check's outcome, or `None` before the first. + pub last_check: Option, + pub settings_dir: Option, + pub log: Option, + /// The main window's, when it is open. + pub session: Option, +} + +/// What the main window is doing, without a single path in it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Session { + pub remote: bool, + pub apparent_size: bool, + pub scan: ScanState, + pub files: Option, + pub elapsed: Option, + /// "Balanced (8 workers)". + pub power: String, + pub theme: String, + pub follows_system: bool, + pub zoom_percent: u32, + pub marked: usize, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ScanState { + /// The source chooser is up, or nothing has been scanned yet. + None, + Running, + Complete, + /// The message is left out: it can name the path that failed. + Failed, +} + +fn fact(label: &'static str, value: impl Into) -> Fact { + Fact { + label, + value: value.into(), + } +} + +/// The model from its parts. +pub fn build(facts: &Facts) -> Diagnostics { + let home = facts.home.as_deref(); + let shown = |path: Option<&Path>, none: &str| { + path.map_or_else( + || none.to_owned(), + |path| display_path(path, home, PathStyle::Native), + ) + }; + let mut sections = vec![ + Section { + title: "Platform", + facts: vec![fact("Operating system", facts.os.clone())], + }, + Section { + title: "Updates", + facts: vec![ + fact( + "Installed", + facts.installed.as_ref().map_or_else( + || { + "Not by an installer, so this copy does not \ + update itself" + .to_owned() + }, + |version| format!("Velopack {version}"), + ), + ), + fact("Channel", facts.channel.clone()), + fact( + "Last check", + facts + .last_check + .clone() + .unwrap_or_else(|| "Not checked this session".into()), + ), + ], + }, + Section { + title: "Paths", + facts: vec![ + fact( + "Settings folder", + shown( + facts.settings_dir.as_deref(), + "None: no home folder", + ), + ), + fact("Log", shown(facts.log.as_deref(), "None this session")), + ], + }, + ]; + if let Some(session) = &facts.session { + sections.push(session_section(session)); + } + Diagnostics { + collected: facts.collected.clone(), + build: facts.build.clone(), + sections, + log: facts.log.clone(), + settings_dir: facts.settings_dir.clone(), + } +} + +fn session_section(session: &Session) -> Section { + let source = if session.remote { "SSH" } else { "local" }; + let size = if session.apparent_size { + "apparent size" + } else { + "allocated size" + }; + let state = match session.scan { + ScanState::None => "nothing scanned yet", + ScanState::Running => "scanning", + ScanState::Complete => "complete", + ScanState::Failed => "failed", + }; + let mut facts = vec![fact("Scan", format!("{source}, {size}, {state}"))]; + if let Some(files) = session.files { + let count = thousands(files); + facts.push(fact( + "Files", + session.elapsed.map_or_else( + || count.clone(), + |elapsed| format!("{count} in {:.1} s", elapsed.as_secs_f64()), + ), + )); + } + facts.push(fact("Marked", session.marked.to_string())); + facts.push(fact("Power efficiency", session.power.clone())); + let theme = if session.follows_system { + format!("{}, follows the system appearance", session.theme) + } else { + format!("{}, from Omarchy", session.theme) + }; + facts.push(fact("Theme", theme)); + facts.push(fact("Interface zoom", format!("{}%", session.zoom_percent))); + Section { + title: "Session", + facts, + } +} + +impl Diagnostics { + /// The clipboard's text: a heading, the build's lines (as About's Copy + /// build info writes them), then each section as `[Title]` and + /// "Label: value" lines. + pub fn report(&self) -> String { + let mut out = format!( + "PwrDisk diagnostics, collected {}\n\n{}", + self.collected, + self.build.report() + ); + for section in &self.sections { + let _ = write!(out, "\n[{}]\n", section.title); + for fact in §ion.facts { + let _ = writeln!(out, "{}: {}", fact.label, fact.value); + } + } + out + } + + /// "0.11.0 · release · aarch64 · ee680cbd": the pane's Version line. + pub fn version_line(&self) -> String { + let build = &self.build; + let mut line = format!( + "{} \u{b7} {} \u{b7} {}", + build.version, build.profile, build.arch + ); + if let Some(short) = build.short_commit_marked() { + let _ = write!(line, " \u{b7} {short}"); + } + line + } +} + +/// "1,204,331": exact, since a count in an issue is compared, not read. +/// The Logs window counts its lines with it too. +pub fn thousands(value: u64) -> String { + let digits = value.to_string(); + let mut out = String::with_capacity(digits.len() + digits.len() / 3); + for (index, digit) in digits.chars().enumerate() { + if index > 0 && (digits.len() - index).is_multiple_of(3) { + out.push(','); + } + out.push(digit); + } + out +} + +/// Reads this process, the OS and the main window. +pub fn collect(cx: &App) -> Diagnostics { + use crate::updater::{self, Installation}; + let installed = match updater::installation() { + Installation::Velopack { version } => Some(version), + Installation::NotInstalled { .. } => None, + }; + let installed_version = updater::installed_version(); + let selection = updater::selection(); + let slot = selection.resolve(&installed_version); + let channel = if selection.is_inferred() { + format!("{slot} (follows this build)") + } else { + format!("{slot} (picked)") + }; + let state = updater::state(); + let last_check = if state.checking { + Some("checking now".to_owned()) + } else { + state.last.as_ref().map(|(_, outcome)| outcome.to_string()) + }; + let session = cx.windows().into_iter().find_map(|window| { + let handle = window.downcast::()?; + handle.read(cx).ok().map(|app| session(app, cx)) + }); + build(&Facts { + collected: chrono::Local::now() + .format("%Y-%m-%dT%H:%M:%S%:z") + .to_string(), + build: BuildInfo::current(), + os: os_description(), + home: std::env::home_dir(), + installed, + channel, + last_check, + settings_dir: updater::settings_dir(), + log: crate::diag_log::path().map(Path::to_path_buf), + session, + }) +} + +fn session(app: &Disktree, cx: &App) -> Session { + let scan = if app.scan.is_some() || app.remote_scan.is_some() { + ScanState::Running + } else if app.scan_error.is_some() { + ScanState::Failed + } else if app.tree.is_some() { + ScanState::Complete + } else { + ScanState::None + }; + let power = app.power_choice.unwrap_or_default(); + #[allow( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "the rem is a small positive zoom step" + )] + let zoom_percent = (app.rem / crate::ui::BASE_REM * 100.0).round() as u32; + Session { + remote: app.remote.is_some(), + apparent_size: app.options.apparent_size, + scan, + files: app.tree.as_ref().map(|tree| tree.root().files), + elapsed: app.scan_elapsed, + power: power.label(app.cpu_threads), + theme: cx.omarchy().name.to_string(), + follows_system: crate::appearance::follows_system(app.home.as_deref()), + zoom_percent, + marked: app.marks.items().len(), + } +} + +/// "macOS 26.1 (aarch64)": the release from the system's own files, as +/// PwrRoute reads it; Windows by name only. +pub fn os_description() -> String { + // Read once: Settings collects the diagnostics again whenever the + // updater's state moves, and the OS does not change under a running + // process. + static DESCRIPTION: std::sync::OnceLock = + std::sync::OnceLock::new(); + DESCRIPTION.get_or_init(read_os_description).clone() +} + +fn read_os_description() -> String { + let arch = std::env::consts::ARCH; + let version = if cfg!(target_os = "macos") { + fs::read_to_string("/System/Library/CoreServices/SystemVersion.plist") + .ok() + .and_then(|xml| plist_string(&xml, "ProductVersion")) + .map(|version| format!("macOS {version}")) + } else if cfg!(windows) { + None + } else { + fs::read_to_string("/etc/os-release") + .ok() + .and_then(|text| os_release_name(&text)) + }; + let name = version.unwrap_or_else(|| match std::env::consts::OS { + "macos" => "macOS".to_owned(), + "windows" => "Windows".to_owned(), + other => other.to_owned(), + }); + format!("{name} ({arch})") +} + +/// The `` after `key` in a plist, without a parser: the +/// system version file is small and regular. +fn plist_string(xml: &str, key: &str) -> Option { + let after_key = &xml[xml.find(&format!("{key}"))?..]; + let start = after_key.find("")? + "".len(); + let end = after_key[start..].find("")? + start; + Some(after_key[start..end].trim().to_owned()) +} + +/// `PRETTY_NAME` from `/etc/os-release`, unquoted. +fn os_release_name(text: &str) -> Option { + text.lines() + .find_map(|line| line.strip_prefix("PRETTY_NAME=")) + .map(|value| value.trim().trim_matches('"').to_owned()) + .filter(|name| !name.is_empty()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn facts() -> Facts { + Facts { + collected: "2026-10-30T00:12:03-04:00".to_owned(), + build: BuildInfo::fixture(), + os: "macOS 26.1 (aarch64)".to_owned(), + home: Some(PathBuf::from("/Users/someone")), + installed: Some("0.5.0".to_owned()), + channel: "Stable \u{b7} Latest (follows this build)".to_owned(), + last_check: None, + settings_dir: Some(PathBuf::from( + "/Users/someone/Library/Application Support/pwrdisk", + )), + log: Some(PathBuf::from( + "/Users/someone/Library/Logs/PwrDisk/main.log", + )), + session: Some(Session { + remote: true, + apparent_size: false, + scan: ScanState::Complete, + files: Some(1_204), + elapsed: Some(Duration::from_millis(14_230)), + power: "Balanced (8 workers)".to_owned(), + theme: "Tokyo Night".to_owned(), + follows_system: true, + zoom_percent: 100, + marked: 3, + }), + } + } + + #[test] + fn the_report_leads_with_the_build_then_each_section() { + let report = build(&facts()).report(); + assert!( + report.starts_with( + "PwrDisk diagnostics, collected 2026-10-30T00:12:03-04:00\n\n\ + PwrDisk 0.5.0 (debug, aarch64)\n" + ), + "{report}" + ); + // Diagnostics describes this client, even for an SSH session, so + // every separator in its own paths follows the client. + let sep = std::path::MAIN_SEPARATOR; + let settings = format!( + "Settings folder: ~{sep}Library{sep}Application Support{sep}pwrdisk\n" + ); + let log = + format!("Log: ~{sep}Library{sep}Logs{sep}PwrDisk{sep}main.log\n"); + for line in [ + "\n[Platform]\nOperating system: macOS 26.1 (aarch64)\n", + "\n[Updates]\nInstalled: Velopack 0.5.0\n", + "Last check: Not checked this session\n", + &settings, + &log, + "\n[Session]\nScan: SSH, allocated size, complete\n", + "Files: 1,204 in 14.2 s\n", + "Marked: 3\n", + "Theme: Tokyo Night, follows the system appearance\n", + "Interface zoom: 100%\n", + ] { + assert!(report.contains(line), "{line:?} missing from\n{report}"); + } + } + + #[test] + fn nothing_scanned_is_ever_in_the_report() { + // The session carries no path field at all; the only paths are + // PwrDisk's own, shown from home. + let report = build(&facts()).report(); + assert!(!report.contains("/Users/someone"), "{report}"); + let without_window = Facts { + session: None, + ..facts() + }; + assert!(!build(&without_window).report().contains("[Session]")); + } + + #[test] + fn a_copy_not_installed_by_velopack_says_it_does_not_update() { + let facts = Facts { + installed: None, + ..facts() + }; + assert!( + build(&facts) + .report() + .contains("Installed: Not by an installer") + ); + } + + #[test] + fn counts_are_exact_with_separators() { + assert_eq!(thousands(0), "0"); + assert_eq!(thousands(999), "999"); + assert_eq!(thousands(1_204_331), "1,204,331"); + } + + #[test] + fn the_version_line_carries_the_short_commit() { + assert_eq!( + build(&facts()).version_line(), + "0.5.0 \u{b7} debug \u{b7} aarch64 \u{b7} 5e1c07a2" + ); + } + + #[test] + fn the_os_is_read_from_the_system_files() { + let plist = "ProductNamemacOS\ + ProductVersion26.1"; + assert_eq!( + plist_string(plist, "ProductVersion").as_deref(), + Some("26.1") + ); + assert_eq!( + os_release_name("NAME=Arch\nPRETTY_NAME=\"Arch Linux\"\n") + .as_deref(), + Some("Arch Linux") + ); + assert!( + os_description() + .ends_with(&format!("({})", std::env::consts::ARCH)) + ); + } +} diff --git a/crates/disktree-app/src/doc_window.rs b/crates/disktree-app/src/doc_window.rs new file mode 100644 index 00000000..eeb7b4cf --- /dev/null +++ b/crates/disktree-app/src/doc_window.rs @@ -0,0 +1,913 @@ +//! Help's document windows: Changelog, View License and Third-Party +//! Notices, as PwrRoute, PwrGit and PwrAgnt show them. The documents are +//! compiled in, so each window shows exactly what this build ships and +//! works offline on every platform, bundle or not. +//! +//! The changelog is drawn from its Markdown (headings, bullets, `code`, +//! **bold**); license and notices use measured monospace wrapping at the +//! current width/scale, capped by [`WRAP_COLUMNS`]. Only visible rows of the +//! notices' megabyte are drawn; Copy always retains the original source. + +use std::rc::Rc; + +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::{ + AnyElement, App, ClipboardItem, Context, FocusHandle, FontWeight, + HighlightStyle, InteractiveElement as _, IntoElement, KeyDownEvent, + ParentElement as _, Render, Role, ScrollHandle, ScrollStrategy, + SharedString, StatefulInteractiveElement as _, Styled as _, StyledText, + UniformListScrollHandle, Window, WindowHandle, div, uniform_list, +}; +use gpui_omarchy::{ActiveTheme as _, ButtonVariant, Theme, button}; + +use crate::aux_window::{self, Spec}; +use crate::chrome::Drags; +use crate::ui::{size, space, text}; + +pub const CHANGELOG: &str = include_str!("../../../CHANGELOG.md"); +pub const LICENSE: &str = include_str!("../../../LICENSE"); +pub const THIRD_PARTY_NOTICES: &str = + include_str!("../../../THIRD_PARTY_LICENSES"); + +/// Maximum columns when the document window has room. +pub const WRAP_COLUMNS: usize = 100; + +/// The window's Copy button. +pub const COPY_ID: &str = "doc-copy"; + +/// Which document. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Doc { + Changelog, + License, + ThirdPartyNotices, +} + +impl Doc { + /// The crumb after "Help ›". + pub const fn title(self) -> &'static str { + match self { + Self::Changelog => "Changelog", + Self::License => "License", + Self::ThirdPartyNotices => "Third-Party Notices", + } + } + + const fn spec(self) -> Spec { + Spec { + title: match self { + Self::Changelog => "PwrDisk Changelog", + Self::License => "PwrDisk License", + Self::ThirdPartyNotices => "PwrDisk Third-Party Notices", + }, + size: (920.0, 760.0), + min: (640.0, 480.0), + } + } + + pub const fn source(self) -> &'static str { + match self { + Self::Changelog => CHANGELOG, + Self::License => LICENSE, + Self::ThirdPartyNotices => THIRD_PARTY_NOTICES, + } + } +} + +/// Opens `doc`'s window, or brings it forward. +pub fn open(doc: Doc, cx: &mut App) { + let existing = aux_window::find::(cx, |view| view.doc == doc); + if aux_window::activate(existing, cx) { + return; + } + open_window(doc, cx); +} + +/// A new window for `doc`, for `open` and the tests. +pub fn open_window(doc: Doc, cx: &mut App) -> Option> { + aux_window::open(&doc.spec(), cx, |window, cx| { + let view = DocWindow::new(doc, cx); + window.focus(&view.focus, cx); + view + }) +} + +/// The window's view. +pub struct DocWindow { + pub doc: Doc, + body: Body, + copied: bool, + strip_drag: bool, + pub focus: FocusHandle, + pub position: usize, + block_scroll: ScrollHandle, + wrap_key: Option<(u32, u32, SharedString)>, +} + +enum Body { + Changelog(Vec), + /// Wrapped lines, shared with the list's row builder. + Lines(Rc>, UniformListScrollHandle), +} + +impl Drags for DocWindow { + fn strip_drag(&mut self) -> &mut bool { + &mut self.strip_drag + } +} + +impl DocWindow { + pub fn new(doc: Doc, cx: &Context<'_, Self>) -> Self { + let body = match doc { + Doc::Changelog => { + Body::Changelog(changelog(CHANGELOG, env!("CARGO_PKG_VERSION"))) + } + Doc::License | Doc::ThirdPartyNotices => Body::Lines( + Rc::new( + wrap(doc.source(), WRAP_COLUMNS) + .into_iter() + .map(SharedString::from) + .collect(), + ), + UniformListScrollHandle::new(), + ), + }; + Self { + doc, + body, + copied: false, + strip_drag: false, + focus: cx.focus_handle().tab_stop(true), + position: 0, + block_scroll: ScrollHandle::new(), + wrap_key: None, + } + } + + /// Wrap against measured glyph widths after a resize or shared scale + /// change. Keep the relative reading position; Copy always uses source. + fn reflow(&mut self, window: &Window, theme: &Theme) { + let Body::Lines(lines, scroll) = &mut self.body else { + return; + }; + let rem = window.rem_size(); + let font = gpui_kit::font(theme.mono_font.clone()); + let font_size = rem * text::BODY.0; + let font_id = window.text_system().resolve_font(&font); + let advance = window + .text_system() + .advance(font_id, font_size, 'm') + .map_or(font_size * 0.6, |size| size.width); + // Body and row padding plus border clearance. A 100-column ceiling + // keeps wide windows readable without imposing it on narrow ones. + let room = (window.viewport_size().width - rem * 5.0) + .max(advance * 8.0) + .min(advance * WRAP_COLUMNS as f32); + // Monospace text wraps the same until a whole column is gained or + // lost, so a live resize re-wraps the megabyte of notices once per + // column rather than once per pixel. + let columns = (room / advance).floor(); + let width = advance * columns; + let key = ( + columns.to_bits(), + rem.as_f32().to_bits(), + theme.mono_font.clone(), + ); + if self.wrap_key.as_ref() == Some(&key) { + return; + } + self.wrap_key = Some(key); + let mut wrapper = window.text_system().line_wrapper(font, font_size); + let mut rows = Vec::new(); + for raw in self.doc.source().lines() { + let expanded = raw.replace('\t', " "); + if expanded.is_empty() { + rows.push(SharedString::from("")); + continue; + } + let fragments = [gpui_kit::LineFragment::text(&expanded)]; + let mut starts = vec![0]; + starts.extend( + // SameIndent is how GPUI wrapped before the argument + // existed; only the break offsets are used here. + wrapper + .wrap_line( + &fragments, + width, + gpui_kit::IndentAdjustment::SameIndent, + ) + .map(|boundary| boundary.ix), + ); + starts.push(expanded.len()); + starts.dedup(); + rows.extend(starts.windows(2).map(|range| { + SharedString::from(expanded[range[0]..range[1]].to_owned()) + })); + } + self.position = + self.position.saturating_mul(rows.len()) / lines.len().max(1); + self.position = self.position.min(rows.len().saturating_sub(1)); + *lines = Rc::new(rows); + scroll.scroll_to_item(self.position, ScrollStrategy::Top); + } + + fn key( + &mut self, + event: &KeyDownEvent, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) { + let key = &event.keystroke.key; + if (event.keystroke.modifiers.platform + || event.keystroke.modifiers.control) + && key == "c" + { + self.copy(cx); + } else { + if matches!(&self.body, Body::Changelog(_)) + && matches!(key.as_str(), "pageup" | "pagedown") + { + crate::ui::scroll_key( + key, + &self.block_scroll, + window.rem_size(), + ); + self.position = self.block_scroll.top_item(); + cx.notify(); + cx.stop_propagation(); + return; + } + let page = match &self.body { + Body::Changelog(_) => 1, + Body::Lines(_, scroll) => { + let measured = scroll.0.borrow(); + measured.last_item_size.map_or(1, |size| { + ((measured.base_handle.bounds().size.height.as_f32() + / size.item.height.as_f32()) + .floor() as usize) + .saturating_sub(1) + .max(1) + }) + } + }; + let count = match &self.body { + Body::Changelog(blocks) => blocks.len(), + Body::Lines(lines, _) => lines.len(), + }; + self.position = match key.as_str() { + "home" => 0, + "end" => count.saturating_sub(1), + "up" => self.position.saturating_sub(1), + "down" => { + self.position.saturating_add(1).min(count.saturating_sub(1)) + } + "pageup" => self.position.saturating_sub(page), + "pagedown" => self + .position + .saturating_add(page) + .min(count.saturating_sub(1)), + _ => return, + }; + match &self.body { + Body::Changelog(_) => { + if matches!(key.as_str(), "home" | "end") { + crate::ui::scroll_key( + key, + &self.block_scroll, + window.rem_size(), + ); + } else { + self.block_scroll.scroll_to_item(self.position); + } + } + Body::Lines(_, scroll) => { + scroll.scroll_to_item(self.position, ScrollStrategy::Top); + } + } + cx.notify(); + } + cx.stop_propagation(); + } + + fn copy(&mut self, cx: &mut Context<'_, Self>) { + cx.write_to_clipboard(ClipboardItem::new_string( + self.doc.source().to_owned(), + )); + self.copied = true; + cx.notify(); + } +} + +impl Render for DocWindow { + fn render( + &mut self, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) -> impl IntoElement { + crate::ui::sync_scale(window, cx); + let theme = cx.omarchy().clone(); + self.reflow(window, &theme); + let label = if self.copied { "Copied" } else { "Copy" }; + let copy = button(COPY_ID, label, ButtonVariant::Secondary, cx) + .accessibility_label(format!( + "{} {}", + if self.copied { + "Copied" + } else { + "Copy complete" + }, + self.doc.title() + )) + .debug_selector(|| COPY_ID.into()) + .on_click(cx.listener(|this, _, _, cx| this.copy(cx))); + let position = self.position; + let body = match &self.body { + Body::Changelog(blocks) => div() + .id("doc-scroll") + .debug_selector(|| "doc-scroll".into()) + .role(Role::Document) + .aria_label(CHANGELOG_LABEL) + .track_focus(&self.focus) + .on_key_down(cx.listener(Self::key)) + .flex_1() + .min_h_0() + .overflow_y_scroll() + .track_scroll(&self.block_scroll) + .py(space::XL) + .flex() + .flex_col() + // Each block is a direct child, so the scroll handle can + // bring the current one into view; each takes the column's + // width and side padding the single column used to have, + // and the window-wide scroll area keeps its scrollbar at + // the window's edge. + .children(blocks.iter().enumerate().map(|(index, block)| { + div() + .id(("doc-block", index)) + .role(if matches!(block, Block::Version { .. }) { + Role::Heading + } else { + Role::Paragraph + }) + .aria_label(block.label()) + .when( + index == position, + gpui_kit::StatefulInteractiveElement::aria_active_descendant, + ) + .max_w(size::DOCUMENT) + .px(space::XXL) + .child(draw_block(block, &theme)) + })) + .into_any_element(), + Body::Lines(lines, scroll) => { + let rows = lines.clone(); + let ink = theme.foreground; + let mono = theme.mono_font.clone(); + div() + .id("document-text") + .role(Role::Document) + .aria_label(format!( + "{}; {} lines. {LINES_KEYS}", + self.doc.title(), + rows.len() + )) + .track_focus(&self.focus) + .on_key_down(cx.listener(Self::key)) + .flex_1() + .min_h_0() + .p(space::LG) + .child( + div() + .size_full() + .border_1() + .border_color(theme.divider()) + .bg(theme.inset) + .py(space::SM) + .child( + uniform_list( + "doc-lines", + rows.len(), + move |range, _, _| { + range + .map(|index| { + document_line( + index, + &rows[index], + index == position, + ) + .px(space::LG) + .font_family(mono.clone()) + .text_size(text::BODY) + .text_color(ink) + .whitespace_nowrap() + .child(rows[index].clone()) + }) + .collect() + }, + ) + .track_scroll(scroll) + .size_full(), + ), + ) + .into_any_element() + } + }; + aux_window::frame(&["Help", self.doc.title()], copy, body, window, cx) + } +} + +/// The keys a document reader takes, for assistive technology. +const LINES_KEYS: &str = "Up/Down reads a line, PageUp/PageDown reads \ + a page, Home/End reaches either end, Command or Control C \ + copies all"; + +const CHANGELOG_LABEL: &str = "Changelog; Up/Down reads a block, \ + PageUp/PageDown scrolls a page, Home/End reaches either end, \ + Command or Control C copies all"; + +/// One line of a plain document, named with its number; the current line +/// is the reader's active descendant. +fn document_line( + index: usize, + line: &SharedString, + current: bool, +) -> gpui_kit::Stateful { + crate::semantics::text( + ("document-line", index), + format!("Line {}: {line}", index + 1), + ) + .when( + current, + gpui_kit::StatefulInteractiveElement::aria_active_descendant, + ) + .debug_selector(move || { + if current { + "document-current".into() + } else { + format!("document-line-{index}") + } + }) +} + +// ---- The changelog ------------------------------------------------------- + +/// A piece of the changelog, top to bottom. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Block { + /// `## v0.2.2 - 2026-10-24`: the version, its date, and whether it is + /// this copy's. + Version { + name: String, + date: Option, + current: bool, + }, + /// `- Area - what changed`. + Bullet(Vec), + /// Any other text. + Paragraph(Vec), +} + +impl Block { + fn label(&self) -> String { + match self { + Self::Version { + name, + date, + current, + } => format!( + "{name} {}{}", + date.as_deref().unwrap_or(""), + if *current { "; this copy" } else { "" } + ), + Self::Bullet(spans) | Self::Paragraph(spans) => { + spans.iter().map(|span| span.text.as_str()).collect() + } + } + } +} + +/// A run of inline text. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Span { + pub text: String, + pub style: Inline, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Inline { + Plain, + Bold, + Code, +} + +/// The changelog's blocks: the `# Changelog` title is the window's crumb, +/// and a version with nothing under it (an empty Unreleased) is left out. +pub fn changelog(markdown: &str, version: &str) -> Vec { + let mut blocks = Vec::new(); + let mut paragraph: Vec<&str> = Vec::new(); + let flush = |paragraph: &mut Vec<&str>, blocks: &mut Vec| { + if !paragraph.is_empty() { + blocks.push(Block::Paragraph(spans(¶graph.join(" ")))); + paragraph.clear(); + } + }; + for line in markdown.lines() { + let trimmed = line.trim(); + if trimmed.is_empty() { + flush(&mut paragraph, &mut blocks); + } else if let Some(heading) = trimmed.strip_prefix("## ") { + flush(&mut paragraph, &mut blocks); + let (name, date) = match heading.split_once(" - ") { + Some((name, date)) => { + (name.trim(), Some(date.trim().to_owned())) + } + None => (heading.trim(), None), + }; + let current = name.strip_prefix('v') == Some(version); + blocks.push(Block::Version { + name: name.to_owned(), + date, + current, + }); + } else if trimmed.starts_with("# ") { + flush(&mut paragraph, &mut blocks); + } else if trimmed.starts_with("###") { + // A subsection ("### Fixed"): its words in bold, as a line. + flush(&mut paragraph, &mut blocks); + blocks.push(Block::Paragraph(vec![Span { + text: trimmed.trim_start_matches('#').trim().to_owned(), + style: Inline::Bold, + }])); + } else if let Some(item) = trimmed + .strip_prefix("- ") + .or_else(|| trimmed.strip_prefix("* ")) + { + flush(&mut paragraph, &mut blocks); + blocks.push(Block::Bullet(bullet_spans(item))); + } else if let Some(Block::Bullet(last)) = blocks.last_mut() + && paragraph.is_empty() + && line.starts_with(" ") + { + // A bullet's continuation line. + for span in std::iter::once(Span { + text: " ".to_owned(), + style: Inline::Plain, + }) + .chain(spans(trimmed)) + { + match last.last_mut() { + Some(end) if end.style == span.style => { + end.text.push_str(&span.text); + } + _ => last.push(span), + } + } + } else { + paragraph.push(trimmed); + } + } + flush(&mut paragraph, &mut blocks); + // The text above the first version is for whoever writes the notes + // (how a release's section is used), not for someone reading them. + let first = blocks + .iter() + .position(|block| matches!(block, Block::Version { .. })) + .unwrap_or(blocks.len()); + blocks.drain(..first); + // Drop versions with nothing under them. + let mut kept = Vec::with_capacity(blocks.len()); + for (index, block) in blocks.iter().enumerate() { + let empty_version = matches!(block, Block::Version { .. }) + && !matches!( + blocks.get(index + 1), + Some(Block::Bullet(_) | Block::Paragraph(_)) + ); + if !empty_version { + kept.push(block.clone()); + } + } + kept +} + +/// "Area - what changed": the area in bold, as the changelog's convention. +fn bullet_spans(item: &str) -> Vec { + match item.split_once(" - ") { + Some((area, rest)) + if !area.contains('`') && area.split_whitespace().count() <= 5 => + { + let mut out = vec![Span { + text: format!("{area} \u{2014} "), + style: Inline::Bold, + }]; + out.extend(spans(rest)); + out + } + _ => spans(item), + } +} + +/// Inline Markdown: `code` and **bold**; everything else as written. +pub fn spans(text: &str) -> Vec { + let mut out: Vec = Vec::new(); + let mut push = |text: &str, style: Inline| { + if text.is_empty() { + return; + } + match out.last_mut() { + Some(last) if last.style == style => last.text.push_str(text), + _ => out.push(Span { + text: text.to_owned(), + style, + }), + } + }; + let mut rest = text; + while !rest.is_empty() { + let code = rest.find('`'); + let bold = rest.find("**"); + match (code, bold) { + (Some(start), bold) if bold.is_none_or(|bold| start < bold) => { + if let Some(len) = rest[start + 1..].find('`') { + push(&rest[..start], Inline::Plain); + push(&rest[start + 1..start + 1 + len], Inline::Code); + rest = &rest[start + 2 + len..]; + } else { + push(rest, Inline::Plain); + rest = ""; + } + } + (_, Some(start)) => { + if let Some(len) = rest[start + 2..].find("**") { + push(&rest[..start], Inline::Plain); + push(&rest[start + 2..start + 2 + len], Inline::Bold); + rest = &rest[start + 4 + len..]; + } else { + push(rest, Inline::Plain); + rest = ""; + } + } + _ => { + push(rest, Inline::Plain); + rest = ""; + } + } + } + out +} + +fn draw_block(block: &Block, theme: &Theme) -> AnyElement { + match block { + Block::Version { + name, + date, + current, + } => div() + .flex() + .items_center() + .gap(space::MD) + .pt(space::XL) + .pb(space::SM) + .mb(space::XS) + .border_b_1() + .border_color(theme.divider()) + .child( + div() + .text_size(text::HEADING) + .font_weight(FontWeight::BOLD) + .text_color(theme.bright) + .child(name.clone()), + ) + .when_some(date.clone(), |row, date| { + row.child( + div() + .font_family(theme.mono_font.clone()) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(date), + ) + }) + .when(*current, |row| { + row.child( + div() + .px(space::SM) + .border_1() + .border_color(theme.success) + .text_color(theme.success) + .font_family(theme.mono_font.clone()) + .text_size(text::CAPTION) + .child("This copy"), + ) + }) + .into_any_element(), + Block::Bullet(spans) => div() + .flex() + .gap(space::MD) + .py(space::XS) + .child( + div() + .flex_none() + .pt(space::SM) + .child(div().size(size::BULLET).bg(theme.accent)), + ) + .child(styled(spans, theme).flex_1().min_w_0()) + .into_any_element(), + Block::Paragraph(spans) => { + styled(spans, theme).py(space::XS).into_any_element() + } + } +} + +/// Spans as one wrapping run: bold in the bright ink, code in the accent +/// on a faint fill (a highlight cannot change font). +fn styled(spans: &[Span], theme: &Theme) -> gpui_kit::Div { + let mut content = String::new(); + let mut highlights = Vec::new(); + for span in spans { + let start = content.len(); + content.push_str(&span.text); + let style = match span.style { + Inline::Plain => continue, + Inline::Bold => HighlightStyle { + color: Some(theme.bright), + font_weight: Some(FontWeight::BOLD), + ..Default::default() + }, + Inline::Code => HighlightStyle { + color: Some(theme.accent), + background_color: Some(theme.accent.opacity(0.12)), + ..Default::default() + }, + }; + highlights.push((start..content.len(), style)); + } + div() + .text_size(text::BODY) + .line_height(gpui_kit::relative(1.6)) + .text_color(theme.foreground) + .child(StyledText::new(content).with_highlights(highlights)) +} + +// ---- Plain text ---------------------------------------------------------- + +/// `text`'s lines, each broken at spaces to at most `columns` characters +/// (a word longer than that is cut). Tabs become four spaces. +pub fn wrap(text: &str, columns: usize) -> Vec { + let mut out = Vec::new(); + for line in text.lines() { + let line = line.replace('\t', " "); + if line.chars().count() <= columns { + out.push(line); + continue; + } + let indent: String = line.chars().take_while(|c| *c == ' ').collect(); + // A deep indent would leave no room: drop it. + let indent = if indent.len() * 2 < columns { + indent + } else { + String::new() + }; + let mut current = indent.clone(); + let mut has_word = false; + for word in line.split(' ').filter(|word| !word.is_empty()) { + if has_word + && current.chars().count() + 1 + word.chars().count() > columns + { + out.push(std::mem::replace(&mut current, indent.clone())); + has_word = false; + } + if has_word { + current.push(' '); + } + current.push_str(word); + has_word = true; + while current.chars().count() > columns { + out.push(current.chars().take(columns).collect()); + current = current.chars().skip(columns).collect(); + } + } + if !current.is_empty() { + out.push(current); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_changelog_reads_as_versions_and_bullets() { + let blocks = changelog( + "# Changelog\n\nHow to write these notes.\n\n## Unreleased\n\n## v0.2.2 - 2026-10-24\n\n- Browser hand-off - \ + Gives the `front` away.\n Continued here.\n- Plain bullet with **bold**\n\n\ + Important: a note.\n\n### Fixed\n\n## v0.2.1 - 2026-10-23\n\n- Rules - One.\n", + "0.2.2", + ); + assert_eq!( + blocks, + vec![ + Block::Version { + name: "v0.2.2".into(), + date: Some("2026-10-24".into()), + current: true, + }, + Block::Bullet(vec![ + Span { + text: "Browser hand-off \u{2014} ".into(), + style: Inline::Bold + }, + Span { + text: "Gives the ".into(), + style: Inline::Plain + }, + Span { + text: "front".into(), + style: Inline::Code + }, + Span { + text: " away. Continued here.".into(), + style: Inline::Plain + }, + ]), + Block::Bullet(vec![ + Span { + text: "Plain bullet with ".into(), + style: Inline::Plain + }, + Span { + text: "bold".into(), + style: Inline::Bold + }, + ]), + Block::Paragraph(vec![Span { + text: "Important: a note.".into(), + style: Inline::Plain + }]), + Block::Paragraph(vec![Span { + text: "Fixed".into(), + style: Inline::Bold + }]), + Block::Version { + name: "v0.2.1".into(), + date: Some("2026-10-23".into()), + current: false, + }, + Block::Bullet(vec![ + Span { + text: "Rules \u{2014} ".into(), + style: Inline::Bold + }, + Span { + text: "One.".into(), + style: Inline::Plain + }, + ]), + ] + ); + } + + #[test] + fn the_shipped_changelog_reads_as_versions() { + let blocks = changelog(CHANGELOG, env!("CARGO_PKG_VERSION")); + assert!( + blocks + .iter() + .any(|block| matches!(block, Block::Version { .. })), + "CHANGELOG.md has no version sections" + ); + } + + #[test] + fn unclosed_marks_stay_as_written() { + assert_eq!( + spans("a `b and **c"), + vec![Span { + text: "a `b and **c".into(), + style: Inline::Plain + }] + ); + } + + #[test] + fn long_lines_wrap_at_spaces_and_keep_their_indent() { + assert_eq!( + wrap("short\n one two three four", 10), + ["short", " one two", " three", " four"] + ); + assert_eq!(wrap("abcdefghijkl", 5), ["abcde", "fghij", "kl"]); + assert_eq!(wrap("", 5), Vec::::new()); + assert_eq!(wrap("a\n\nb", 5), ["a", "", "b"]); + } + + #[test] + fn the_documents_are_compiled_in() { + assert!(LICENSE.contains("MIT")); + assert!(THIRD_PARTY_NOTICES.len() > 10_000); + assert!( + wrap(THIRD_PARTY_NOTICES, WRAP_COLUMNS) + .iter() + .all(|line| line.chars().count() <= WRAP_COLUMNS) + ); + } +} diff --git a/crates/disktree-app/src/dock_icon.rs b/crates/disktree-app/src/dock_icon.rs new file mode 100644 index 00000000..88a66294 --- /dev/null +++ b/crates/disktree-app/src/dock_icon.rs @@ -0,0 +1,113 @@ +//! The Dock icon of a run outside the app bundle. +//! +//! `make run`, `cargo run` and the bare release binary all start disktree +//! with no bundle around it, so macOS has no icon to draw and the Dock shows +//! the generic executable. `AppKit` lets a running app replace its Dock icon +//! with an image, so the app carries its own and paints it whenever the +//! bundle it runs in, if any, names none. +//! +//! The image is drawn literally. macOS 26 gives Liquid Glass only to a +//! bundle's Icon Composer icon and has no API to ask for it at run time, so +//! the glass is baked into the image instead: `DockIcon-glass.png` is the +//! shipped icon as macOS 26 itself draws it, rendered by +//! `packaging/macos/render-dock-icons.swift`. macOS 15 and earlier draw a +//! flat icon on Apple's legacy tile, and get `DockIcon.png`, which is that. + +#![allow( + unsafe_code, + reason = "one AppKit setter objc2 marks unsafe; the call says why it is \ + sound" +)] + +use objc2::{AllocAnyThread as _, MainThreadMarker}; +use objc2_app_kit::{NSApplication, NSImage}; +use objc2_foundation::{NSBundle, NSData, NSString}; + +const FLAT: &[u8] = include_bytes!("../../../packaging/macos/DockIcon.png"); +const GLASS: &[u8] = + include_bytes!("../../../packaging/macos/DockIcon-glass.png"); + +/// Give the Dock an icon unless the bundle the app runs in has one. +/// +/// For the main thread, once `AppKit` is up: the closure `Application::run` +/// calls back is that, and by then the Dock tile exists to paint. Anywhere +/// else this does nothing. +pub fn install() { + let Some(mtm) = MainThreadMarker::new() else { + return; + }; + if bundle_names_an_icon() { + return; + } + let data = NSData::with_bytes(embedded(draws_liquid_glass())); + let Some(image) = NSImage::initWithData(NSImage::alloc(), &data) else { + return; + }; + let app = NSApplication::sharedApplication(mtm); + // SAFETY: the setter is main-thread only, which `mtm` proves, and takes + // an image AppKit retains for itself. + unsafe { app.setApplicationIconImage(Some(&image)) }; +} + +/// Whether the main bundle names an icon for macOS to draw. Outside a bundle +/// `NSBundle.mainBundle` is the executable's directory and names nothing. +fn bundle_names_an_icon() -> bool { + let bundle = NSBundle::mainBundle(); + ["CFBundleIconName", "CFBundleIconFile"].iter().any(|key| { + bundle + .objectForInfoDictionaryKey(&NSString::from_str(key)) + .is_some() + }) +} + +/// Whether this Mac draws app icons in Liquid Glass: macOS 26 and later, +/// which is Darwin 25. +/// +/// The kernel release, not `NSProcessInfo`: macOS 26 reports itself as 16.0 +/// to a binary linked against an older SDK, which is what a Mac with the +/// Command Line Tools or Xcode 16 builds. +fn draws_liquid_glass() -> bool { + darwin_major(&rustix::system::uname().release().to_string_lossy()) + .is_some_and(|major| major >= 25) +} + +/// The major version of a Darwin release such as `25.6.0`. +fn darwin_major(release: &str) -> Option { + release.split('.').next()?.parse().ok() +} + +/// The icon for the look this Mac gives its icons. +const fn embedded(liquid_glass: bool) -> &'static [u8] { + if liquid_glass { GLASS } else { FLAT } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Both files decode, and to the size the renderer promises: the Dock + /// draws at most 128 pt, twice that on a Retina display. + #[test] + fn both_dock_icons_are_512_pixel_pngs() { + for liquid_glass in [false, true] { + let bytes = embedded(liquid_glass); + assert!(bytes.starts_with(b"\x89PNG\r\n\x1a\n")); + let image = NSImage::initWithData( + NSImage::alloc(), + &NSData::with_bytes(bytes), + ) + .expect("a decodable PNG"); + let size = image.size(); + assert_eq!((size.width, size.height), (512., 512.)); + } + // The glass one is a render of the flat one, never the same file. + assert_ne!(embedded(true), embedded(false)); + } + + #[test] + fn darwin_25_is_the_first_to_draw_liquid_glass() { + assert_eq!(darwin_major("25.6.0"), Some(25)); + assert_eq!(darwin_major("24.6.0"), Some(24)); + assert_eq!(darwin_major(""), None); + } +} diff --git a/crates/disktree-app/src/file_list.rs b/crates/disktree-app/src/file_list.rs new file mode 100644 index 00000000..8728b86d --- /dev/null +++ b/crates/disktree-app/src/file_list.rs @@ -0,0 +1,485 @@ +//! Bounded semantic navigation over the complete scan, never its preview. + +use crate::semantics::AccessibleButton as _; + +use std::fmt::Write as _; +use std::path::Path; + +use disktree_core::filter::Keep; +use disktree_core::size::human_bytes; +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::{ + Context, Div, InteractiveElement as _, ParentElement as _, Role, + SharedString, Stateful, StatefulInteractiveElement as _, Styled, div, +}; +use gpui_omarchy::{ActiveTheme as _, ButtonVariant, button}; + +use crate::state::Disktree; +use crate::ui::{size, space, text}; + +/// Explicit pages keep offscreen entries reachable to AT while bounding +/// layout and semantic work independently of the size of the scan. +pub const PAGE_SIZE: usize = 100; + +/// Lossless IDs distinguish paths even when their display text is identical. +pub fn path_id(path: &Path) -> SharedString { + let mut id = String::from("path-"); + for byte in path.as_os_str().as_encoded_bytes() { + write!(id, "{byte:02x}").expect("writing a string"); + } + id.into() +} + +fn entry_semantics( + path: &Path, + label: String, + selected: bool, +) -> Stateful
{ + div() + .id(path_id(path)) + .accessibility_id(path_id(path)) + .role(Role::ListBoxOption) + .aria_label(label) + .aria_selected(selected) + .when( + selected, + gpui_kit::StatefulInteractiveElement::aria_active_descendant, + ) +} + +impl Disktree { + pub fn file_turn_page(&mut self, step: isize, cx: &mut Context<'_, Self>) { + let entries = + self.layout_filter().is_some().then(|| self.file_entries()); + let count = entries.as_ref().map_or_else( + || self.current().map_or(0, |node| node.children().len()), + Vec::len, + ); + if count == 0 { + return; + } + let last = (count - 1) / PAGE_SIZE; + let page = self + .file_page + .min(last) + .saturating_add_signed(step) + .min(last); + let position = page * PAGE_SIZE; + let mut crumbs = self.crumbs.clone(); + crumbs.push( + entries + .as_ref() + .map_or(position, |entries| entries[position]), + ); + self.file_page = page; + self.file_scroll.scroll_to_item(0); + self.pointer_active = false; + self.select(Some(crumbs), cx); + } + /// What the list's header adds when a filter thins it. Compact, the + /// legend row is not drawn, so the list itself says what the legend + /// keeps; a search says so in its own field. + pub fn list_filter_note(&self) -> String { + if self.filter_applied { + " · filtered".to_owned() + } else if self.legend.is_active() { + format!(" · filtered: {} (esc clears)", self.legend.summary()) + } else { + String::new() + } + } + + /// An entry's size as its row says it. A partly shown folder says what + /// passed and what it holds in all, as its tile does: "48 MiB of 196 + /// MiB". + pub fn entry_size( + &self, + crumbs: &[usize], + node: disktree_core::tree::Node<'_>, + ) -> String { + match self.layout_filter().and_then(|m| m.keep(crumbs)) { + Some(Keep::Partial { bytes, .. }) => { + format!("{} of {}", human_bytes(bytes), human_bytes(node.bytes)) + } + _ => human_bytes(node.bytes), + } + } + + pub fn file_entries(&self) -> Vec { + let Some(node) = self.current() else { + return Vec::new(); + }; + let children = node.children(); + let Some(filter) = self.layout_filter() else { + return (0..children.len()).collect(); + }; + // One buffer for every child: under a filter this runs per frame, + // in directories that can hold millions of files. + let mut crumbs = self.crumbs.clone(); + crumbs.push(0); + let last = crumbs.len() - 1; + (0..children.len()) + .filter(|index| { + crumbs[last] = *index; + filter.keep_at(&crumbs, children.at(*index)).is_some() + }) + .collect() + } + + pub fn file_step(&mut self, step: isize, cx: &mut Context<'_, Self>) { + let entries = + self.layout_filter().is_some().then(|| self.file_entries()); + let count = entries.as_ref().map_or_else( + || self.current().map_or(0, |node| node.children().len()), + Vec::len, + ); + if count == 0 { + return; + } + let current = self.selected.as_ref().and_then(|crumbs| { + (crumbs.len() == self.crumbs.len() + 1 + && crumbs.starts_with(&self.crumbs)) + .then(|| { + entries.as_ref().map_or_else( + || crumbs.last().copied().filter(|index| *index < count), + |entries| { + entries.iter().position(|i| Some(i) == crumbs.last()) + }, + ) + }) + .flatten() + }); + let next = + current.map_or(0, |i| i.saturating_add_signed(step).min(count - 1)); + let mut crumbs = self.crumbs.clone(); + crumbs.push(entries.as_ref().map_or(next, |entries| entries[next])); + self.pointer_active = false; + self.file_page = next / PAGE_SIZE; + self.file_scroll.scroll_to_item(next % PAGE_SIZE); + self.select(Some(crumbs), cx); + } +} + +pub fn compact(window: &gpui_kit::Window, rem: f32) -> bool { + window.viewport_size().height.as_f32() / rem + < size::FILE_LIST_FULL_DETAILS.0 +} + +pub fn list( + app: &Disktree, + window: &gpui_kit::Window, + cx: &Context<'_, Disktree>, +) -> Stateful
{ + let compact = compact(window, app.rem); + let theme = cx.omarchy(); + // Unfiltered navigation needs only the visible page, even in a directory + // with millions of zero-weight files that the mosaic cannot draw. + let entries = app.layout_filter().is_some().then(|| app.file_entries()); + let count = entries.as_ref().map_or_else( + || app.current().map_or(0, |node| node.children().len()), + Vec::len, + ); + let page = app.file_page.min(count.saturating_sub(1) / PAGE_SIZE); + let start = page * PAGE_SIZE; + let end = (start + PAGE_SIZE).min(count); + let filtered = app.list_filter_note(); + let summary = format!( + "{} · {} entries · showing {}–{}{filtered}", + app.current_path().display(), + count, + usize::from(count > 0) + start, + end, + ); + let mut rows = div().id("file-rows").role(Role::ListBox) + .track_focus(&app.file_focus) + .tab_index(0).tab_stop(true) + .border_2().border_color(theme.background.opacity(0.)) + .focus_visible(|style| style.border_color(theme.accent)) + .aria_label(summary.clone()) + .aria_description("Up/Down select; Enter opens a directory; Backspace returns to its parent; Space marks; c reviews. PageUp/PageDown change pages.") + .flex().flex_col().flex_1().min_h_0().track_scroll(&app.file_scroll).overflow_y_scroll(); + if count == 0 { + rows = rows.child( + crate::semantics::text( + "empty", + "No entries in this directory or filter", + ) + .p(space::LG) + .child("No entries in this directory or filter"), + ); + } + for position in start..end { + let index = entries + .as_ref() + .map_or(position, |entries| entries[position]); + let mut crumbs = app.crumbs.clone(); + crumbs.push(index); + let Some(node) = app.node_at(&crumbs) else { + continue; + }; + let Some(path) = app.path_at(&crumbs) else { + continue; + }; + let selected = app.selected.as_ref() == Some(&crumbs); + let marked = app.marks.contains(&path, app.path_style()); + let covered = app.marks.ancestor(&path, app.path_style()).is_some(); + let removed = app.was_removed(&path); + let filtered = app + .matches + .as_ref() + .is_some_and(|m| m.keep_at(&crumbs, node).is_none()); + let size = app.entry_size(&crumbs, node); + // Clone blocks are not what removing the entry frees; say so + // where the size is read, and nowhere when there are none. + let split = crate::views::clone_split(node); + let clones = split + .as_ref() + .map_or_else(String::new, |split| format!(" · {split}")); + let spoken = split + .as_ref() + .map_or_else(String::new, |split| format!("; {split}")); + let label = format!( + "{}; {}; {} ({} bytes){}; {}; last written {}; {}{}{}", + path.display(), + if node.is_dir() { "directory" } else { "file" }, + size, + node.bytes, + spoken, + node.category.label(), + crate::widgets::ago(crate::state::now_seconds(), node.modified), + if removed { + "removed since the scan" + } else if marked { + "marked" + } else if covered { + "inside a marked directory" + } else { + "not marked" + }, + if node.read_error { "; unreadable" } else { "" }, + if filtered { + "; does not match filter" + } else { + "" + } + ); + let row = entry_semantics(&path, label, selected) + .a11y_synthetic_children(move |b| { + b.parent_node().set_position_in_set(position + 1); + b.parent_node().set_size_of_set(count); + }) + .debug_selector(move || format!("file-row-{position}")) + .flex_shrink_0() + .min_h(size::FILE_ENTRY) + .p(space::SM) + .border_b_1() + .border_color(theme.divider()) + .when(selected, |row| row.bg(theme.hover_fill()).border_l_2()) + .child(format!( + "{}{} · {}{clones} · {}", + if node.is_dir() { "▸ " } else { "" }, + node.name(), + size, + if removed { + "Removed since the scan" + } else if marked { + "Marked" + } else { + node.category.label() + } + )) + .on_click(cx.listener(move |this, _, window, cx| { + this.pointer_active = false; + this.select(Some(crumbs.clone()), cx); + window.focus(&this.file_focus, cx); + })); + rows = rows.child(row); + } + div() + .id("file-list") + .debug_selector(|| "file-list".into()) + .flex() + .flex_col() + .flex_1() + .min_w_0() + .min_h_0() + .child( + crate::semantics::text("file-summary", summary.clone()) + .text_size(text::CAPTION) + .p(space::SM) + .when(compact, |header| { + header + .flex() + .items_center() + .gap(space::SM) + .child( + div() + .flex_1() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .child( + app.current_path().display().to_string(), + ), + ) + .child(div().flex_shrink_0().child(format!( + "{count} entries · {}–{end}{filtered}", + usize::from(count > 0) + start + ))) + }) + .when(!compact, |header| header.child(summary)), + ) + .child(rows) + .child( + div() + .flex() + .flex_col() + .flex_shrink_0() + .when(compact, |actions| { + actions.flex_row().flex_wrap().gap(space::SM) + }) + .child( + div() + .flex() + .gap(space::SM) + .child( + button( + "file-open", + if compact { + "Open" + } else { + "Open selected directory" + }, + ButtonVariant::Outline, + cx, + ) + .accessibility_label("Open selected directory") + .min_h(size::POINTER_TARGET) + .semantic_disabled( + !app.selected + .as_ref() + .and_then(|c| app.node_at(c)) + .is_some_and( + disktree_core::tree::Node::is_dir, + ), + ) + .on_click(cx.listener( + |this, _, window, cx| { + this.pointer_active = false; + this.descend(cx); + window.focus(&this.file_focus, cx); + }, + )), + ) + .child( + button( + "file-mark", + if compact { + // Visible words stay inside the + // accessible name, for voice control. + "Mark or unmark" + } else { + "Mark or unmark selected path" + }, + ButtonVariant::Outline, + cx, + ) + .accessibility_label("Mark or unmark selected path") + .min_h(size::POINTER_TARGET) + .semantic_disabled(app.selected.is_none()) + .on_click(cx.listener( + |this, _, _, cx| this.toggle_mark_selected(cx), + )), + ), + ) + .child( + div() + .flex() + .gap(space::SM) + .child( + button( + "file-previous", + if compact { + "Previous" + } else { + "Previous 100 entries" + }, + ButtonVariant::Outline, + cx, + ) + .accessibility_label("Previous 100 entries") + .min_h(size::POINTER_TARGET) + .debug_selector(|| "file-previous".into()) + .semantic_disabled(page == 0) + .on_click(cx.listener( + |this, _, window, cx| { + this.file_turn_page(-1, cx); + window.focus(&this.file_focus, cx); + }, + )), + ) + .child( + button( + "file-next", + if compact { + "Next" + } else { + "Next 100 entries" + }, + ButtonVariant::Outline, + cx, + ) + .accessibility_label("Next 100 entries") + .min_h(size::POINTER_TARGET) + .debug_selector(|| "file-next".into()) + .semantic_disabled(end == count) + .on_click(cx.listener( + |this, _, window, cx| { + this.file_turn_page(1, cx); + window.focus(&this.file_focus, cx); + }, + )), + ), + ), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use gpui_kit::{Element as _, accesskit}; + + #[test] + fn entry_role_selection_and_identity_follow_the_path() { + let path = Path::new("/Fixtures/Résumé 日本語.txt"); + for selected in [false, true] { + let element = entry_semantics( + path, + "Résumé 日本語.txt; 4096 bytes; marked".into(), + selected, + ); + let mut node = + accesskit::Node::new(element.a11y_role().expect("entry role")); + element.write_a11y_info(&mut node); + assert_eq!(node.role(), Role::ListBoxOption); + assert_eq!(node.is_selected(), Some(selected)); + assert_eq!( + node.label(), + Some("Résumé 日本語.txt; 4096 bytes; marked") + ); + assert_eq!(node.author_id(), Some(path_id(path).as_ref())); + } + assert_ne!(path_id(path), path_id(Path::new("/Fixtures/other.txt"))); + } + + #[cfg(unix)] + #[test] + fn native_path_ids_do_not_alias_lossy_display_names() { + use std::os::unix::ffi::OsStrExt as _; + let a = Path::new(std::ffi::OsStr::from_bytes(b"/Fixtures/\xff")); + let b = Path::new(std::ffi::OsStr::from_bytes(b"/Fixtures/\xfe")); + assert_eq!(a.to_string_lossy(), b.to_string_lossy()); + assert_ne!(path_id(a), path_id(b)); + } +} diff --git a/crates/disktree-app/src/git.rs b/crates/disktree-app/src/git.rs index b4a69e31..3fc630ff 100644 --- a/crates/disktree-app/src/git.rs +++ b/crates/disktree-app/src/git.rs @@ -1,12 +1,19 @@ //! What git knows about a checkout, for the selection panel. //! //! Before deleting an agent worktree the question is "would anything be -//! lost": uncommitted changes, stashes, commits nobody pushed. That is three -//! cheap git calls, run off the UI thread when a checkout is selected and -//! remembered per path. +//! lost": uncommitted changes, stashes, commits nobody pushed. That is a +//! few git calls, run off the UI thread when [`crate::git_store`] says so, +//! each inside the probe's time limit: `git status` walks the worktree, and +//! a big enough one would otherwise keep a process busy for minutes. +use std::io::Read as _; use std::path::Path; -use std::process::{Command, Stdio}; +use std::process::{Command, Output, Stdio}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use crate::git_store::Probe; /// A checkout's state, as far as losing work is concerned. #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -50,25 +57,96 @@ impl GitState { } } +#[cfg(test)] +thread_local! { + /// Calls to [`is_checkout`], for the test that holds the panel to one + /// per selection. + pub static CHECKS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Whether `path` is the top of a checkout: it has a `.git` directory, or the /// `.git` file a worktree gets. pub fn is_checkout(path: &Path) -> bool { + #[cfg(test)] + CHECKS.set(CHECKS.get() + 1); std::fs::symlink_metadata(path.join(".git")).is_ok() } -/// Ask git. `None` when `path` is not a checkout or git is not installed. -pub fn state(path: &Path) -> Option { +/// When a probe has to stop: its time is up, or nobody wants it any more. +pub struct Limit { + deadline: Instant, + cancel: Arc, +} + +impl Limit { + pub fn new(within: Duration, cancel: Arc) -> Self { + Self { + deadline: Instant::now() + within, + cancel, + } + } + + fn reached(&self) -> bool { + self.cancel.load(Ordering::Relaxed) || Instant::now() >= self.deadline + } + + fn remaining(&self) -> Duration { + self.deadline.saturating_duration_since(Instant::now()) + } +} + +/// A probe stopped at its [`Limit`] before git finished. +#[derive(Debug, PartialEq, Eq)] +pub struct Cut; + +/// Ask git about the checkout at `path`, within `limit`. +pub fn probe(path: &Path, limit: &Limit) -> Probe { + match state(path, limit) { + Ok(Some(state)) => Probe::Known(state), + Ok(None) => Probe::Unreadable, + Err(Cut) => Probe::TimedOut, + } +} + +/// Run [`probe`] within `within` on a thread of its own. It spends most +/// of that waiting on git, which would otherwise hold one of the threads +/// GPUI's background work shares; `git_store::MAX_RUNNING` bounds how +/// many there are at once. +pub fn probe_on_thread( + path: &Path, + within: Duration, + cancel: Arc, +) -> async_channel::Receiver { + let (sender, answer) = async_channel::bounded(1); + let path = path.to_path_buf(); + // If no thread can be made the sender goes with the closure, and the + // window reads the closed channel as an unreadable checkout. + let _ = std::thread::Builder::new() + .name("git probe".to_string()) + .spawn(move || { + let limit = Limit::new(within, cancel); + let _ = sender.send_blocking(probe(&path, &limit)); + }); + answer +} + +/// `None` when `path` is not a checkout or git is not installed. +fn state(path: &Path, limit: &Limit) -> Result, Cut> { if !is_checkout(path) || !git_installed() { - return None; + return Ok(None); } - let changed = if names_its_own_filters(path) { + let changed = if names_its_own_filters(path, limit)? { None } else { // Submodules are other checkouts with configs of their own. - let status = run( + let Some(status) = run( path, &["status", "--porcelain=v1", "-z", "--ignore-submodules=all"], - )?; + limit, + )? + else { + return Ok(None); + }; Some(status.split('\0').filter(|line| !line.is_empty()).count()) }; // Counted from the reflog, not listed: `stash list` is `git log`, which @@ -77,16 +155,18 @@ pub fn state(path: &Path) -> Option { let stashes = run( path, &["rev-list", "--walk-reflogs", "--count", "refs/stash"], - ) + limit, + )? .and_then(|count| count.trim().parse().ok()) .unwrap_or(0); - let unpushed = run(path, &["rev-list", "--count", "@{upstream}..HEAD"]) - .and_then(|count| count.trim().parse().ok()); - Some(GitState { + let unpushed = + run(path, &["rev-list", "--count", "@{upstream}..HEAD"], limit)? + .and_then(|count| count.trim().parse().ok()); + Ok(Some(GitState { changed, stashes, unpushed, - }) + })) } /// Whether running `git` runs git. On macOS `/usr/bin/git` is there even @@ -123,7 +203,7 @@ fn git_installed() -> bool { /// not asked for its status at all. Filters from the user's own config, such /// as git-lfs, are theirs and still run. Reading config runs nothing; if it /// cannot be read, the answer is the cautious one. -fn names_its_own_filters(path: &Path) -> bool { +fn names_its_own_filters(path: &Path, limit: &Limit) -> Result { let Some(output) = git( path, &[ @@ -133,10 +213,12 @@ fn names_its_own_filters(path: &Path) -> bool { "--get-regexp", r"^filter\.", ], - ) else { - return true; + limit, + )? + else { + return Ok(true); }; - match output.status.code() { + Ok(match output.status.code() { // No filter anywhere. Some(1) => false, Some(0) => { @@ -145,18 +227,27 @@ fn names_its_own_filters(path: &Path) -> bool { }) } _ => true, - } + }) } -fn run(path: &Path, args: &[&str]) -> Option { - let output = git(path, args)?; - output - .status - .success() - .then(|| String::from_utf8_lossy(&output.stdout).into_owned()) +fn run( + path: &Path, + args: &[&str], + limit: &Limit, +) -> Result, Cut> { + Ok(git(path, args, limit)?.and_then(|output| { + output + .status + .success() + .then(|| String::from_utf8_lossy(&output.stdout).into_owned()) + })) } -fn git(path: &Path, args: &[&str]) -> Option { +fn git( + path: &Path, + args: &[&str], + limit: &Limit, +) -> Result, Cut> { let mut command = Command::new("git"); // disktree is a GUI program on Windows, with no console to lend: without // this, every probe flashes a console window of its own. @@ -201,15 +292,237 @@ fn git(path: &Path, args: &[&str]) -> Option { .env("GIT_OPTIONAL_LOCKS", "0") .env("GIT_NO_LAZY_FETCH", "1") .stdin(Stdio::null()) - .stderr(Stdio::null()) - .output() - .ok() + .stderr(Stdio::null()); + output_within(&mut command, limit) +} + +/// How often a probe looks at whether git exited or its limit is up. Small +/// against the limit, large against what a check costs. +const POLL: Duration = Duration::from_millis(5); + +/// How long output is waited for after git exits, even at the limit: the +/// reader thread needs a moment to hand over what git wrote last. +const READ_GRACE: Duration = Duration::from_millis(50); + +/// Run `command` to the end, or kill it at `limit`. `Ok(None)` when it +/// could not be started. +fn output_within( + command: &mut Command, + limit: &Limit, +) -> Result, Cut> { + // A probe whose time is up, or that nobody wants, starts nothing more. + if limit.reached() { + return Err(Cut); + } + // Its own process group, so a cut stops what git started too: a + // user-level filter such as `git-lfs filter-process` would otherwise + // keep hashing after git was killed. + #[cfg(unix)] + std::os::unix::process::CommandExt::process_group(command, 0); + let Ok(mut child) = command.stdout(Stdio::piped()).spawn() else { + return Ok(None); + }; + // Read as it is written: a `status` listing more than a pipe holds + // would otherwise wait on us while we wait on it. The reader is never + // joined: anything git started that kept the pipe open would keep it + // reading past the limit, so the output is waited for on a channel + // instead, within what is left of the limit. + let (sender, read) = std::sync::mpsc::channel(); + if let Some(mut stdout) = child.stdout.take() { + std::thread::spawn(move || { + let mut out = Vec::new(); + let _ = stdout.read_to_end(&mut out); + let _ = sender.send(out); + }); + } + let ended = loop { + match exited(&mut child) { + Ok(true) => break true, + Ok(false) if limit.reached() => break false, + Ok(false) => std::thread::sleep(POLL), + Err(_) => break false, + } + }; + if !ended { + stop(&mut child); + return if limit.reached() { Err(Cut) } else { Ok(None) }; + } + // At least a moment, so output git finished writing just before the + // limit is not taken for output something else holds open. + let wait = limit.remaining().max(READ_GRACE); + let stdout = match read.recv_timeout(wait) { + Ok(out) => out, + // Git exited but something it started still holds its output. + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + stop(&mut child); + return Err(Cut); + } + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Vec::new(), + }; + let Ok(status) = child.wait() else { + return Ok(None); + }; + Ok(Some(Output { + status, + stdout, + stderr: Vec::new(), + })) +} + +/// Whether `child` has exited, without reaping it on Unix: until it is +/// reaped its id, which is also its process group's, cannot go to another +/// process, so [`stop`] cannot signal a stranger's group. +#[cfg(unix)] +#[allow( + clippy::needless_pass_by_ref_mut, + reason = "one signature with Windows, whose `try_wait` needs it" +)] +fn exited(child: &mut std::process::Child) -> std::io::Result { + use rustix::process::{Pid, WaitId, WaitIdOptions, waitid}; + let options = + WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT; + Ok(waitid(WaitId::Pid(Pid::from_child(child)), options)?.is_some()) +} + +#[cfg(not(unix))] +fn exited(child: &mut std::process::Child) -> std::io::Result { + Ok(child.try_wait()?.is_some()) +} + +/// Kill a probe's git and, on Unix, everything in its process group. +/// +/// Windows has no process group to signal; a job object would need Win32 +/// calls this crate keeps out (`unsafe` lives in `disktree-core`). What git +/// starts there talks to it over pipes, so it sees end-of-file and exits +/// when git is killed, as `git-lfs filter-process` does. +fn stop(child: &mut std::process::Child) { + // The leader is not reaped yet (see `exited`), so the group's id is + // still git's, and this reaches a child holding git's output too. + #[cfg(unix)] + let _ = rustix::process::kill_process_group( + rustix::process::Pid::from_child(child), + rustix::process::Signal::KILL, + ); + let _ = child.kill(); + let _ = child.wait(); } #[cfg(test)] mod tests { use super::*; + /// Ask with time to spare, as the tests of what git says do. + fn ask(path: &Path) -> Option { + let limit = Limit::new(Duration::from_mins(1), Arc::default()); + state(path, &limit).ok().flatten() + } + + #[cfg(unix)] + #[test] + fn a_command_past_its_limit_is_killed_and_says_so() { + let limit = Limit::new(Duration::from_millis(50), Arc::default()); + let started = Instant::now(); + let ran = output_within(Command::new("sleep").arg("30"), &limit); + assert_eq!(ran.map(|output| output.is_some()), Err(Cut)); + assert!( + started.elapsed() < Duration::from_secs(10), + "it did not wait for the command" + ); + } + + #[cfg(unix)] + #[test] + fn a_cancelled_command_stops() { + let cancel = Arc::new(AtomicBool::new(true)); + let limit = Limit::new(Duration::from_mins(1), cancel); + let ran = output_within(Command::new("sleep").arg("30"), &limit); + assert_eq!(ran.map(|output| output.is_some()), Err(Cut)); + } + + #[cfg(unix)] + #[test] + fn output_held_open_after_exit_is_cut_at_the_limit() { + // The shell exits at once, leaving a child that keeps stdout open. + let limit = Limit::new(Duration::from_millis(200), Arc::default()); + let started = Instant::now(); + let ran = output_within( + Command::new("sh").args(["-c", "sleep 30 & echo started"]), + &limit, + ); + assert_eq!(ran.map(|output| output.is_some()), Err(Cut)); + assert!( + started.elapsed() < Duration::from_secs(10), + "it did not wait for the child holding the pipe" + ); + } + + /// Whether a process with this id is still running. + #[cfg(unix)] + fn alive(pid: &str) -> bool { + Command::new("kill") + .args(["-0", pid]) + .stderr(Stdio::null()) + .status() + .is_ok_and(|status| status.success()) + } + + #[cfg(unix)] + #[test] + fn a_cut_stops_what_the_command_started() { + let dir = tempfile::tempdir().expect("tempdir"); + let pid_file = dir.path().join("child"); + let script = + format!("sleep 30 & echo $! > '{}'; wait", pid_file.display()); + let limit = Limit::new(Duration::from_millis(300), Arc::default()); + let ran = + output_within(Command::new("sh").args(["-c", &script]), &limit); + assert_eq!(ran.map(|output| output.is_some()), Err(Cut)); + let pid = std::fs::read_to_string(&pid_file).expect("the child ran"); + let pid = pid.trim(); + // Killed, it is reaped by whoever adopted it; give that a moment. + let gone = (0..200).any(|_| { + std::thread::sleep(Duration::from_millis(10)); + !alive(pid) + }); + assert!(gone, "the child {pid} outlived the cut"); + } + + #[cfg(unix)] + #[test] + fn output_larger_than_a_pipe_is_read_while_it_runs() { + let limit = Limit::new(Duration::from_secs(30), Arc::default()); + let output = output_within( + Command::new("sh").args(["-c", "head -c 1000000 /dev/zero"]), + &limit, + ) + .expect("within the limit") + .expect("it ran"); + assert!(output.status.success()); + assert_eq!(output.stdout.len(), 1_000_000); + } + + #[test] + fn a_probe_on_its_own_thread_answers_on_the_channel() { + let dir = tempfile::tempdir().expect("tempdir"); + let answer = + probe_on_thread(dir.path(), Duration::from_mins(1), Arc::default()); + assert_eq!(answer.recv_blocking(), Ok(Probe::Unreadable)); + } + + #[test] + fn a_probe_that_runs_out_of_time_reports_it() { + let dir = tempfile::tempdir().expect("tempdir"); + std::fs::write(dir.path().join(".git"), "gitdir: elsewhere") + .expect("write"); + let runs = Command::new("git").arg("--version").output(); + if !git_installed() || runs.is_err() { + return; // no git on this machine + } + // Already past its limit: whatever git is asked first is cut. + let limit = Limit::new(Duration::ZERO, Arc::default()); + assert_eq!(probe(dir.path(), &limit), Probe::TimedOut); + } + #[test] fn summaries_say_what_would_be_lost() { let clean = GitState { @@ -243,7 +556,7 @@ mod tests { #[test] fn reads_a_real_checkout() { let dir = tempfile::tempdir().expect("tempdir"); - assert_eq!(state(dir.path()), None, "not a checkout"); + assert_eq!(ask(dir.path()), None, "not a checkout"); let git = |args: &[&str]| { Command::new("git") .arg("-C") @@ -256,7 +569,7 @@ mod tests { return; // no git on this machine } std::fs::write(dir.path().join("a.txt"), "hi").expect("write"); - let state = state(dir.path()).expect("a checkout"); + let state = ask(dir.path()).expect("a checkout"); assert_eq!(state.changed, Some(1), "one untracked file"); assert_eq!(state.stashes, 0); } @@ -289,7 +602,7 @@ mod tests { } let hook = hook.to_string_lossy(); assert!(git(&["config", "core.fsmonitor", &hook])); - assert!(state(dir.path()).is_some()); + assert!(ask(dir.path()).is_some()); assert!(!marker.exists(), "the checkout's fsmonitor ran"); } @@ -350,7 +663,7 @@ mod tests { assert!(git(&["config", "log.showSignature", "true"], None).is_some()); assert!(git(&["config", "gpg.program", &gpg], None).is_some()); - let state = state(dir.path()).expect("a checkout"); + let state = ask(dir.path()).expect("a checkout"); assert!(!marker.exists(), "the checkout's gpg.program ran"); assert_eq!(state.stashes, 1, "the stash is still counted"); } @@ -400,7 +713,7 @@ mod tests { // the filter, to know whether it changed. std::fs::write(dir.path().join("file.txt"), "x").expect("rewrite"); - let state = state(dir.path()).expect("a checkout"); + let state = ask(dir.path()).expect("a checkout"); assert_eq!(state.changed, None, "not asked"); assert!(!marker.exists(), "the checkout's filter ran"); } diff --git a/crates/disktree-app/src/git_store.rs b/crates/disktree-app/src/git_store.rs new file mode 100644 index 00000000..13519775 --- /dev/null +++ b/crates/disktree-app/src/git_store.rs @@ -0,0 +1,597 @@ +//! Which checkouts git is asked about, when, and how many at once. +//! +//! The side panel's Git figure costs a `git status`, which can walk a +//! whole worktree. The panel draws on every frame and the pointer crosses +//! dozens of checkouts a second, so nothing here runs on a frame's say-so: +//! a frame says what it would like ([`GitStore::want`]), and the store +//! decides what runs ([`GitStore::next_jobs`]). +//! +//! - **Kinds of ask.** A selection is a direct action and always gets in. +//! A hover that dwells is an implied one, and a refresh of a stale answer +//! is the least urgent; both spend a token from a small bucket. +//! - **At most [`MAX_RUNNING`] at once**, newest wish first within a kind: +//! what the user is looking at now beats what they looked at before. +//! - **Deadlines.** A wish lapses when nobody repeats it for a while; one +//! that reaches the head of the queue lapsed is dropped unrun. +//! - **Answers age.** A selected checkout is asked again once its answer is +//! stale; a hover shows whatever answer there is. +//! - **Generations.** [`GitStore::clear`] drops the queue, cancels what is +//! running and ignores whatever it still reports. +//! +//! The store keeps no clock and runs nothing: every call takes `now`, and +//! the window runs the jobs, so the tests drive it with invented times. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use rustc_hash::FxHashMap; + +use crate::git::GitState; + +/// Probes running at once. Two, so one slow checkout cannot hold up every +/// other answer until its time limit. +pub const MAX_RUNNING: usize = 2; + +/// How long the pointer rests on a checkout before that counts as asking. +/// Long enough that sweeping across a mosaic asks nothing, short enough +/// that pausing to read a tile feels immediate. +pub const DWELL: Duration = Duration::from_millis(500); + +/// How long one probe may take before its git is killed. A checkout this +/// slow to read is one whose answer says so, not one to wait on. +pub const PROBE_LIMIT: Duration = Duration::from_secs(5); + +/// When an answer is old enough to ask again, for the selected checkout. +pub const FRESH_FOR: Duration = Duration::from_mins(1); +/// A failure is asked again much later: another time-out costs as much. +const FAILURE_FRESH_FOR: Duration = Duration::from_mins(10); + +/// Tokens the bucket holds, so a few deliberate hovers in a row all count. +const BUCKET: u32 = 4; +/// One token comes back this often: at most 30 hovers or refreshes a +/// minute once the bucket is empty. +const REFILL: Duration = Duration::from_secs(2); + +/// Starts one probe of the checkout at a path, stopping when the flag is +/// set, and hands back where its answer will arrive. The window's runs +/// `git::probe` within [`PROBE_LIMIT`] on a thread of its own +/// (`git::probe_on_thread`); tests count calls with their own and answer +/// at once ([`ready`]). A channel closed without an answer reads as +/// [`Probe::Unreadable`]. +pub type GitProbe = + Arc) -> async_channel::Receiver>; + +/// A probe's answer that is already there, for the tests' probes. +#[cfg(test)] +pub fn ready(probe: Probe) -> async_channel::Receiver { + let (sender, answer) = async_channel::bounded(1); + let _ = sender.try_send(probe); + answer +} + +/// What brought the ask, most urgent first. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Ask { + /// The selection: a key or a click put it there. + Direct, + /// A hover that stayed for [`DWELL`]. + Dwell, + /// The selected checkout's answer went stale. + Refresh, +} + +impl Ask { + /// Whether the wish came from the selection rather than the pointer. + /// There is one of each at a time, so a newer wish from the same one + /// makes an older wish for another checkout moot. + const fn by_selection(self) -> bool { + !matches!(self, Self::Dwell) + } + + /// How long a wish lasts in the queue without being repeated. A + /// frame repeats it while the tile is still the one shown, so this is + /// how long after the user moves on that the wish lapses. + const fn lasts(self) -> Duration { + match self { + Self::Direct => Duration::from_secs(3), + Self::Dwell => Duration::from_millis(1500), + Self::Refresh => Duration::from_secs(5), + } + } +} + +/// What a probe found. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Probe { + Known(GitState), + /// Git is missing or could not read the checkout. + Unreadable, + /// Git took longer than [`PROBE_LIMIT`] and was stopped. + TimedOut, +} + +impl Probe { + /// The Git figure's value. + pub fn summary(&self) -> String { + match self { + Self::Known(state) => state.summary(), + Self::Unreadable => "not readable".to_string(), + // Stopped at its limit: say so rather than leave "asking" up, + // or call it clean. + Self::TimedOut => "too large to check".to_string(), + } + } + + const fn fresh_for(&self) -> Duration { + match self { + Self::Known(_) => FRESH_FOR, + Self::Unreadable | Self::TimedOut => FAILURE_FRESH_FOR, + } + } +} + +/// What the panel shows for a checkout. +#[derive(Debug, PartialEq, Eq)] +pub enum Shown<'a> { + /// The last answer, stale or not: a refresh replaces it when it lands. + Answer(&'a Probe), + /// Waiting for a probe, or for the pointer to settle. + Asking, +} + +/// What became of a wish. +#[derive(Debug, PartialEq, Eq)] +pub enum Wanted { + /// A fresh enough answer is there; ask again at `stale_at`. + Answered { stale_at: Instant }, + /// Queued or running. + Pending, + /// The bucket is empty; a token is back at `retry_at`. + Refused { retry_at: Instant }, +} + +/// A probe for the window to run, off the UI thread. +#[derive(Clone, Debug)] +pub struct Job { + pub path: PathBuf, + /// Set when the store no longer wants the answer: the probe stops. + pub cancel: Arc, + generation: u64, +} + +struct Waiting { + path: PathBuf, + ask: Ask, + /// When a frame last wanted it: the newest goes first. + wanted_at: Instant, + deadline: Instant, +} + +struct Answer { + probe: Probe, + at: Instant, +} + +pub struct GitStore { + answers: FxHashMap, + queue: Vec, + running: FxHashMap>, + bucket: Bucket, + generation: u64, + /// Wishes dropped at the head of the queue, for the tests. + pub lapsed: usize, +} + +impl GitStore { + pub fn new(now: Instant) -> Self { + Self { + answers: FxHashMap::default(), + queue: Vec::new(), + running: FxHashMap::default(), + bucket: Bucket::new(now), + generation: 0, + lapsed: 0, + } + } + + /// A frame would like to know about `path`. + pub fn want(&mut self, path: &Path, ask: Ask, now: Instant) -> Wanted { + // Arrowing through a row of checkouts selects each for a moment; + // only where the selection stops is still wanted. What already + // runs finishes and is remembered. + self.queue.retain(|waiting| { + waiting.path == path + || waiting.ask.by_selection() != ask.by_selection() + }); + if self.running.contains_key(path) { + return Wanted::Pending; + } + let ask = match self.answers.get(path) { + Some(answer) => { + let stale_at = answer.at + answer.probe.fresh_for(); + // A hover shows what is known; only the selection refreshes. + if now < stale_at || ask != Ask::Direct { + return Wanted::Answered { stale_at }; + } + Ask::Refresh + } + None => ask, + }; + if let Some(waiting) = + self.queue.iter_mut().find(|waiting| waiting.path == path) + { + waiting.ask = waiting.ask.min(ask); + waiting.wanted_at = now; + waiting.deadline = waiting.deadline.max(now + ask.lasts()); + return Wanted::Pending; + } + // The selection is what the user asked for, so the bucket never + // turns it away; it only meters what they did not ask for outright. + if ask != Ask::Direct + && let Err(retry_at) = self.bucket.take(now) + { + return Wanted::Refused { retry_at }; + } + self.queue.push(Waiting { + path: path.to_path_buf(), + ask, + wanted_at: now, + deadline: now + ask.lasts(), + }); + Wanted::Pending + } + + /// The probes to start now, within [`MAX_RUNNING`]. + pub fn next_jobs(&mut self, now: Instant) -> Vec { + let mut jobs = Vec::new(); + while self.running.len() < MAX_RUNNING { + let Some(head) = self + .queue + .iter() + .enumerate() + .min_by_key(|(_, waiting)| { + (waiting.ask, std::cmp::Reverse(waiting.wanted_at)) + }) + .map(|(index, _)| index) + else { + break; + }; + let waiting = self.queue.swap_remove(head); + if waiting.deadline <= now { + self.lapsed += 1; + continue; + } + let cancel = Arc::new(AtomicBool::new(false)); + self.running.insert(waiting.path.clone(), cancel.clone()); + jobs.push(Job { + path: waiting.path, + cancel, + generation: self.generation, + }); + } + jobs + } + + /// A job ended. False when its answer is no longer wanted. + pub fn finish(&mut self, job: &Job, probe: Probe, now: Instant) -> bool { + if job.generation != self.generation { + return false; + } + self.running.remove(&job.path); + self.answers + .insert(job.path.clone(), Answer { probe, at: now }); + true + } + + /// Whether there is an answer for `path`, stale or not. + pub fn answered(&self, path: &Path) -> bool { + self.answers.contains_key(path) + } + + pub fn shown(&self, path: &Path) -> Shown<'_> { + self.answers + .get(path) + .map_or(Shown::Asking, |answer| Shown::Answer(&answer.probe)) + } + + /// Forget everything: a new scan, or another machine. What is running + /// is told to stop, and its answer is ignored when it comes. + pub fn clear(&mut self) { + self.cancel_running(); + self.generation += 1; + self.answers.clear(); + self.queue.clear(); + } + + fn cancel_running(&mut self) { + for (_, cancel) in self.running.drain() { + cancel.store(true, Ordering::Relaxed); + } + } +} + +/// A closed window stops its probes rather than leave git running. +impl Drop for GitStore { + fn drop(&mut self) { + self.cancel_running(); + } +} + +/// A token bucket kept as the time it is next full minus its capacity +/// (the generic cell rate algorithm): one instant instead of a count and a +/// clock, and no fractions. +struct Bucket { + /// When the next token would be due if none were saved up. + due: Instant, +} + +impl Bucket { + const fn new(now: Instant) -> Self { + Self { due: now } + } + + /// How far ahead of `due` a full bucket lets a take run. + fn burst() -> Duration { + REFILL * (BUCKET - 1) + } + + /// Spend a token, or say when one is back. + fn take(&mut self, now: Instant) -> Result<(), Instant> { + if self.due > now + Self::burst() { + return Err(self.due.checked_sub(Self::burst()).unwrap_or(now)); + } + self.due = self.due.max(now) + REFILL; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn clean() -> Probe { + Probe::Known(GitState { + changed: Some(0), + unpushed: Some(0), + ..GitState::default() + }) + } + + fn path(name: &str) -> PathBuf { + PathBuf::from("/checkouts").join(name) + } + + /// Take every slot with a probe of its own: each is selected and + /// started before the next, as a selection that stays would be. + fn fill_slots(store: &mut GitStore, now: Instant) -> Vec { + (0..MAX_RUNNING) + .flat_map(|n| { + store.want(&path(&format!("busy-{n}")), Ask::Direct, now); + store.next_jobs(now) + }) + .collect() + } + + #[test] + fn a_selection_runs_once_and_then_reads_the_answer() { + let t0 = Instant::now(); + let mut store = GitStore::new(t0); + let alpha = path("alpha"); + assert_eq!(store.want(&alpha, Ask::Direct, t0), Wanted::Pending); + let jobs = store.next_jobs(t0); + assert_eq!(jobs.len(), 1); + assert_eq!(store.shown(&alpha), Shown::Asking); + + // Every frame asks again while it runs; nothing more starts. + for _ in 0..10 { + assert_eq!(store.want(&alpha, Ask::Direct, t0), Wanted::Pending); + assert!(store.next_jobs(t0).is_empty()); + } + + let done = t0 + Duration::from_millis(80); + assert!(store.finish(&jobs[0], clean(), done)); + assert_eq!(store.shown(&alpha), Shown::Answer(&clean())); + assert_eq!( + store.want(&alpha, Ask::Direct, done), + Wanted::Answered { + stale_at: done + FRESH_FOR + } + ); + assert!(store.next_jobs(done).is_empty()); + } + + #[test] + fn no_more_than_the_limit_run_at_once() { + let t0 = Instant::now(); + let mut store = GitStore::new(t0); + // A selection and a hover start; a third wish waits. + store.want(&path("selected"), Ask::Direct, t0); + store.want(&path("hovered"), Ask::Dwell, t0); + let first = store.next_jobs(t0); + assert_eq!(first.len(), MAX_RUNNING); + store.want(&path("next"), Ask::Direct, t0); + assert!(store.next_jobs(t0).is_empty(), "the slots are full"); + + // One finishing frees one slot for the wish that waited. + assert!(store.finish(&first[0], clean(), t0)); + let next = store.next_jobs(t0); + assert_eq!(next.len(), 1); + assert_eq!(next[0].path, path("next")); + } + + #[test] + fn a_selection_runs_before_a_hover() { + let t0 = Instant::now(); + let mut store = GitStore::new(t0); + let busy = fill_slots(&mut store, t0); + + let t1 = t0 + Duration::from_millis(100); + store.want(&path("hovered"), Ask::Dwell, t1); + let t2 = t1 + Duration::from_millis(100); + store.want(&path("selected"), Ask::Direct, t2); + + assert!(store.finish(&busy[0], clean(), t2)); + assert_eq!(store.next_jobs(t2)[0].path, path("selected")); + assert!(store.finish(&busy[1], clean(), t2)); + assert_eq!(store.next_jobs(t2)[0].path, path("hovered")); + } + + #[test] + fn arrowing_through_checkouts_runs_only_where_the_selection_stops() { + let t0 = Instant::now(); + let mut store = GitStore::new(t0); + let busy = fill_slots(&mut store, t0); + let mut now = t0; + for n in 0..10 { + now += Duration::from_millis(30); + store.want(&path(&format!("passed-{n}")), Ask::Direct, now); + } + // The pointer's wish is not the selection's to drop. + store.want(&path("hovered"), Ask::Dwell, now); + for job in &busy { + assert!(store.finish(job, clean(), now)); + } + let started: Vec<_> = store + .next_jobs(now) + .into_iter() + .map(|job| job.path) + .collect(); + assert_eq!(started, [path("passed-9"), path("hovered")]); + } + + #[test] + fn a_lapsed_wish_is_dropped_at_the_head_of_the_queue() { + let t0 = Instant::now(); + let mut store = GitStore::new(t0); + let slow = fill_slots(&mut store, t0); + // The pointer rested here, then moved on and never came back. + store.want(&path("passed"), Ask::Dwell, t0); + + let later = t0 + Ask::Dwell.lasts() + Duration::from_millis(1); + assert!(store.finish(&slow[0], Probe::TimedOut, later)); + assert!(store.next_jobs(later).is_empty(), "nothing left to run"); + assert_eq!(store.lapsed, 1); + assert_eq!(store.shown(&path("passed")), Shown::Asking); + } + + #[test] + fn a_wish_repeated_by_each_frame_does_not_lapse() { + let t0 = Instant::now(); + let mut store = GitStore::new(t0); + let slow = fill_slots(&mut store, t0); + let selected = path("selected"); + let mut now = t0; + for _ in 0..10 { + now += Duration::from_secs(1); + store.want(&selected, Ask::Direct, now); + } + assert!(store.finish(&slow[0], clean(), now)); + assert_eq!(store.next_jobs(now)[0].path, selected); + assert_eq!(store.lapsed, 0); + } + + #[test] + fn hovers_spend_tokens_and_a_selection_does_not() { + let t0 = Instant::now(); + let mut store = GitStore::new(t0); + for n in 0..BUCKET { + let wanted = + store.want(&path(&format!("hover-{n}")), Ask::Dwell, t0); + assert_eq!(wanted, Wanted::Pending); + } + let refused = store.want(&path("one-more"), Ask::Dwell, t0); + assert_eq!( + refused, + Wanted::Refused { + retry_at: t0 + REFILL + } + ); + assert_eq!( + store.want(&path("selected"), Ask::Direct, t0), + Wanted::Pending, + "a selection is never turned away" + ); + assert_eq!( + store.want(&path("one-more"), Ask::Dwell, t0 + REFILL), + Wanted::Pending, + "a token is back" + ); + } + + #[test] + fn a_stale_answer_is_shown_and_refreshed_only_for_the_selection() { + let t0 = Instant::now(); + let mut store = GitStore::new(t0); + let alpha = path("alpha"); + store.want(&alpha, Ask::Direct, t0); + let job = store.next_jobs(t0).remove(0); + assert!(store.finish(&job, clean(), t0)); + + let stale = t0 + FRESH_FOR; + assert!(matches!( + store.want(&alpha, Ask::Dwell, stale), + Wanted::Answered { .. } + )); + assert!(store.next_jobs(stale).is_empty(), "a hover never refreshes"); + + assert_eq!(store.want(&alpha, Ask::Direct, stale), Wanted::Pending); + assert_eq!(store.next_jobs(stale).len(), 1); + assert_eq!( + store.shown(&alpha), + Shown::Answer(&clean()), + "the old answer stays up while the refresh runs" + ); + } + + #[test] + fn a_time_out_is_remembered_and_not_retried_soon() { + let t0 = Instant::now(); + let mut store = GitStore::new(t0); + let huge = path("huge"); + store.want(&huge, Ask::Direct, t0); + let job = store.next_jobs(t0).remove(0); + let done = t0 + PROBE_LIMIT; + assert!(store.finish(&job, Probe::TimedOut, done)); + assert_eq!(store.shown(&huge), Shown::Answer(&Probe::TimedOut)); + let minute = done + FRESH_FOR; + assert!(matches!( + store.want(&huge, Ask::Direct, minute), + Wanted::Answered { .. } + )); + assert!(store.next_jobs(minute).is_empty()); + } + + #[test] + fn clearing_stops_what_runs_and_ignores_its_answer() { + let t0 = Instant::now(); + let mut store = GitStore::new(t0); + let jobs = fill_slots(&mut store, t0); + assert_eq!(jobs.len(), MAX_RUNNING); + store.want(&path("still-waiting"), Ask::Direct, t0); + + store.clear(); + assert!(jobs.iter().all(|job| job.cancel.load(Ordering::Relaxed))); + assert!(!store.finish(&jobs[0], clean(), t0), "an old generation"); + assert_eq!(store.shown(&jobs[0].path), Shown::Asking); + assert!(store.next_jobs(t0).is_empty(), "the queue went too"); + } + + #[test] + fn the_figure_says_when_git_was_stopped() { + assert_eq!(Probe::TimedOut.summary(), "too large to check"); + assert_eq!(Probe::Unreadable.summary(), "not readable"); + assert_eq!(clean().summary(), "clean, no stash"); + } + + #[test] + fn dropping_the_store_stops_what_runs() { + let t0 = Instant::now(); + let mut store = GitStore::new(t0); + store.want(&path("alpha"), Ask::Direct, t0); + let jobs = store.next_jobs(t0); + drop(store); + assert!(jobs[0].cancel.load(Ordering::Relaxed)); + } +} diff --git a/crates/disktree-app/src/github_releases.rs b/crates/disktree-app/src/github_releases.rs new file mode 100644 index 00000000..ae170b03 --- /dev/null +++ b/crates/disktree-app/src/github_releases.rs @@ -0,0 +1,201 @@ +//! The published release list, from GitHub's REST API, for the release +//! channel ([`crate::update_channel`]): each release's tag, its Pre-release +//! flag, and whether it carries this platform's Velopack feed. +//! +//! One page of 30 is usually all of it. GitHub's "latest" release (the +//! newest promoted one) anchors the read: while it is not on the pages read +//! so far, the next page is read too, up to [`MAX_PAGES`], so a long run of +//! alphas cannot push Stable · Latest out of view. Unauthenticated, as +//! Velopack's own GitHub source is: 60 requests an hour per address, and a +//! check takes two. + +use std::{sync::Arc, time::Duration}; + +use serde::Deserialize; +use ureq::{ + Agent, + tls::{RootCerts, TlsConfig, TlsProvider}, +}; + +use crate::update_channel::Release; + +/// The repository's API root. +const API: &str = "https://api.github.com/repos/pwrdrvr/PwrDisk"; + +/// Releases per page: GitHub's default is 30. +const PER_PAGE: usize = 30; + +/// How far a read goes looking for the latest release. +pub const MAX_PAGES: usize = 10; + +const TIMEOUT: Duration = Duration::from_secs(20); + +/// A release as the API lists it, with only what choosing one needs. +#[derive(Deserialize)] +struct ApiRelease { + tag_name: String, + #[serde(default)] + draft: bool, + #[serde(default)] + prerelease: bool, + #[serde(default)] + assets: Vec, +} + +#[derive(Deserialize)] +struct ApiAsset { + name: String, +} + +/// The releases a copy on Velopack channel `channel` ("osx", "win") can +/// update to: published, with `releases..json` attached. +pub fn fetch(channel: &str) -> Result, String> { + let agent = agent(); + let latest = latest_tag(&agent)?; + let feed = feed_name(channel); + let mut releases = Vec::new(); + let mut seen_latest = latest.is_none(); + for page in 1..=MAX_PAGES { + let body = get( + &agent, + &format!("{API}/releases?per_page={PER_PAGE}&page={page}"), + )? + .ok_or_else(|| "GitHub has no release list for PwrDisk".to_owned())?; + let (usable, listed, tags) = parse_page(&body, &feed)?; + releases.extend(usable); + seen_latest |= + latest.as_ref().is_some_and(|latest| tags.contains(latest)); + if listed < PER_PAGE || seen_latest { + break; + } + } + Ok(releases) +} + +/// `releases..json`: the Velopack feed a release must carry. +pub fn feed_name(channel: &str) -> String { + format!("releases.{channel}.json") +} + +/// Where a release's files download from: Velopack's HTTP source reads +/// `releases..json` and the packages under it. +pub fn download_base(tag: &str) -> String { + format!("https://github.com/pwrdrvr/PwrDisk/releases/download/{tag}/") +} + +/// One page of the list: the usable releases, how many were listed, and +/// every tag listed (for the latest-release anchor). +fn parse_page( + body: &str, + feed: &str, +) -> Result<(Vec, usize, Vec), String> { + let listed: Vec = + serde_json::from_str(body).map_err(|error| { + format!("GitHub's release list did not parse ({error})") + })?; + let count = listed.len(); + let tags = listed.iter().map(|r| r.tag_name.clone()).collect(); + let usable = listed + .into_iter() + .filter(|r| { + !r.draft + && r.assets.iter().any(|a| a.name.eq_ignore_ascii_case(feed)) + }) + .map(|r| Release::new(r.tag_name, r.prerelease)) + .collect(); + Ok((usable, count, tags)) +} + +/// The newest promoted release's tag; `None` while nothing is promoted. +fn latest_tag(agent: &Agent) -> Result, String> { + #[derive(Deserialize)] + struct Latest { + tag_name: String, + } + let Some(body) = get(agent, &format!("{API}/releases/latest"))? else { + return Ok(None); + }; + serde_json::from_str::(&body) + .map(|latest| Some(latest.tag_name)) + .map_err(|error| { + format!("GitHub's latest release did not parse ({error})") + }) +} + +/// The body of a GET; `None` for a 404. +fn get(agent: &Agent, url: &str) -> Result, String> { + let mut response = agent + .get(url) + .header("Accept", "application/vnd.github+json") + .header("X-GitHub-Api-Version", "2022-11-28") + .call() + .map_err(|error| format!("could not reach GitHub ({error})"))?; + match response.status().as_u16() { + 200 => response + .body_mut() + .read_to_string() + .map(Some) + .map_err(|error| format!("could not read GitHub's answer ({error})")), + 404 => Ok(None), + 403 | 429 => { + Err("GitHub's hourly limit for this network is used up; try again later".into()) + } + status => Err(format!("GitHub answered {status}")), + } +} + +fn agent() -> Agent { + let tls = TlsConfig::builder() + .provider(TlsProvider::Rustls) + .unversioned_rustls_crypto_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .root_certs(RootCerts::PlatformVerifier) + .build(); + Agent::config_builder() + .http_status_as_error(false) + .timeout_global(Some(TIMEOUT)) + .user_agent(concat!("PwrDisk/", env!("CARGO_PKG_VERSION"))) + .tls_config(tls) + .build() + .new_agent() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_page_keeps_published_releases_with_this_platforms_feed() { + let body = r#"[ + {"tag_name": "v0.2.0-alpha.1", "draft": true, "prerelease": true, + "assets": [{"name": "releases.osx.json"}]}, + {"tag_name": "v0.1.0", "prerelease": true, + "assets": [{"name": "releases.osx.json"}, {"name": "releases.win.json"}]}, + {"tag_name": "v0.1.0-rc.3", "prerelease": false, + "assets": [{"name": "RELEASES-OSX.json"}, {"name": "Releases.OSX.json"}]}, + {"tag_name": "v0.0.9", "prerelease": false, + "assets": [{"name": "releases.win.json"}]} + ]"#; + let (usable, listed, tags) = + parse_page(body, &feed_name("osx")).unwrap(); + assert_eq!(listed, 4); + assert_eq!(tags.len(), 4); + assert_eq!( + usable, + [ + Release::new("v0.1.0", true), + Release::new("v0.1.0-rc.3", false) + ] + ); + assert!(parse_page("{", "releases.osx.json").is_err()); + } + + #[test] + fn a_release_downloads_from_its_own_tag() { + assert_eq!( + download_base("v0.1.0"), + "https://github.com/pwrdrvr/PwrDisk/releases/download/v0.1.0/" + ); + } +} diff --git a/crates/disktree-app/src/help.rs b/crates/disktree-app/src/help.rs new file mode 100644 index 00000000..da910710 --- /dev/null +++ b/crates/disktree-app/src/help.rs @@ -0,0 +1,130 @@ +//! Help: the menu's rows and what each does. Links to the project open in +//! the default browser; Changelog, the license, the notices and the log +//! open in PwrDisk's own windows (`doc_window`, `logs_window`) and work +//! offline. Copy Diagnostics Info writes Settings › Diagnostics' report +//! (`diagnostics`) and says so in a toast in the main window. + +use gpui_kit::{App, ClipboardItem}; + +use crate::doc_window::{self, Doc}; + +pub use help_actions::*; + +#[allow( + clippy::derive_partial_eq_without_eq, + reason = "GPUI's actions! macro writes the derives, not us" +)] +mod help_actions { + use gpui_kit::actions; + + actions!( + disktree, + [ + /// The README on GitHub: PwrDisk's documentation for now. + OpenDocumentation, + /// CHANGELOG.md in its own window. + OpenChangelog, + /// GitHub's new-issue page. + ReportIssue, + /// GitHub's private vulnerability report. + ReportVulnerability, + /// Diagnostics' lines on the clipboard. + CopyDiagnostics, + /// The diagnostic log in its own window. + OpenLogs, + /// The repository on GitHub. + ViewSource, + /// LICENSE in its own window. + ViewLicense, + /// THIRD_PARTY_LICENSES in its own window. + ThirdPartyNotices, + ] + ); +} + +/// The repository, from the workspace's `repository`. +pub const REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY"); + +pub fn documentation_url() -> String { + format!("{REPOSITORY}#readme") +} + +pub fn issue_url() -> String { + format!("{REPOSITORY}/issues/new") +} + +/// GitHub's private reporting, as the family's SECURITY.md asks for. +pub fn vulnerability_url() -> String { + format!("{REPOSITORY}/security/advisories/new") +} + +pub fn install(cx: &mut App) { + cx.on_action(|_: &OpenDocumentation, cx| { + cx.open_url(&documentation_url()); + }); + cx.on_action(|_: &ReportIssue, cx| cx.open_url(&issue_url())); + cx.on_action(|_: &ReportVulnerability, cx| { + cx.open_url(&vulnerability_url()); + }); + cx.on_action(|_: &ViewSource, cx| cx.open_url(REPOSITORY)); + // The windows wait for the dispatch to finish: chosen from inside the + // window it would bring forward, GPUI still holds it, so it could be + // neither read nor raised and a second would open. + let doc = |doc: Doc, cx: &mut App| { + cx.defer(move |cx| doc_window::open(doc, cx)); + }; + cx.on_action(move |_: &OpenChangelog, cx| doc(Doc::Changelog, cx)); + cx.on_action(move |_: &ViewLicense, cx| doc(Doc::License, cx)); + cx.on_action(move |_: &ThirdPartyNotices, cx| { + doc(Doc::ThirdPartyNotices, cx); + }); + cx.on_action(|_: &OpenLogs, cx| cx.defer(crate::logs_window::open)); + // Deferred: from the strip's menu the main window is still the one + // dispatching, and could not be read for its session. + cx.on_action(|_: &CopyDiagnostics, cx| cx.defer(copy_diagnostics)); +} + +/// Settings › Diagnostics' report on the clipboard, and a note in the +/// main window that it is there. +pub fn copy_diagnostics(cx: &mut App) { + let report = crate::diagnostics::collect(cx).report(); + cx.write_to_clipboard(ClipboardItem::new_string(report)); + log::info!(target: "pwrdisk", "help: copied diagnostics info"); + let main = cx + .windows() + .into_iter() + .find_map(|window| window.downcast::()); + if let Some(main) = main { + cx.defer(move |cx| { + let _ = main.update(cx, |app, _, cx| { + app.say( + "Diagnostics copied \u{b7} paste them into an issue", + gpui_omarchy::Status::Success, + cx, + ); + }); + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn links_point_at_the_repository() { + assert_eq!(REPOSITORY, "https://github.com/pwrdrvr/PwrDisk"); + assert_eq!( + documentation_url(), + "https://github.com/pwrdrvr/PwrDisk#readme" + ); + assert_eq!( + issue_url(), + "https://github.com/pwrdrvr/PwrDisk/issues/new" + ); + assert_eq!( + vulnerability_url(), + "https://github.com/pwrdrvr/PwrDisk/security/advisories/new" + ); + } +} diff --git a/crates/disktree-app/src/ledger.rs b/crates/disktree-app/src/ledger.rs new file mode 100644 index 00000000..2380a8cb --- /dev/null +++ b/crates/disktree-app/src/ledger.rs @@ -0,0 +1,185 @@ +//! What each removal since the last scan freed, three ways. +//! +//! A removal no longer ends in a rescan, so several can follow one scan, +//! and each is a cohort here. *Reported* is the listed allocation of what +//! went, a clone counted in every place it appears. *Private* is the part +//! the scan saw as theirs alone. *Observed* is the volume's free space +//! after minus before, which other programs move too. The totals add the +//! first two; the third runs from the first cohort's start to the last +//! one's finish, so it is a measurement and never a sum of guesses. + +use std::time::SystemTime; + +use disktree_core::removal::RemovalMode; + +/// A removal as it started: how, and the free space before. What it +/// targets and what became of each is the run's list, `run_list`. +#[derive(Clone, Debug)] +pub struct Start { + pub mode: RemovalMode, + /// Bytes available on the scanned volume, measured as it started. + pub before: Option, + pub started: SystemTime, +} + +/// One finished removal. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Cohort { + pub mode: RemovalMode, + pub removed: u64, + pub failed: usize, + /// The listed bytes of what was removed. + pub reported: u64, + /// What the scan saw as only theirs: `None` when it could not say, as + /// in an apparent-size scan. + pub private: Option, + pub before: Option, + pub after: Option, + pub started: SystemTime, + pub finished: SystemTime, +} + +impl Cohort { + /// Free space gained, negative when something else wrote more. + pub fn observed(&self) -> Option { + observed(self.before, self.after) + } +} + +fn observed(before: Option, after: Option) -> Option { + let (before, after) = (before?, after?); + Some(after.cast_signed().saturating_sub(before.cast_signed())) +} + +/// Every cohort since one scan. +#[derive(Clone, Debug, Default)] +pub struct Ledger { + /// The scan the cohorts follow, as `Disktree::scan_epoch` numbers it. + scan: u64, + cohorts: Vec, +} + +/// The cohorts added up. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Totals { + pub count: usize, + pub removed: u64, + pub reported: u64, + /// `None` once any cohort's private part is unknown. + pub private: Option, + /// From the first cohort's start to the last one's finish. + pub observed: Option, + pub started: SystemTime, + pub finished: SystemTime, +} + +impl Ledger { + /// A removal is starting after scan `scan`: a newer scan starts a new + /// ledger, since its figures already include what went before. + pub fn begin(&mut self, scan: u64) { + if self.scan != scan { + self.scan = scan; + self.cohorts.clear(); + } + } + + pub fn push(&mut self, cohort: Cohort) { + self.cohorts.push(cohort); + } + + /// Every cohort recorded, whatever has been scanned since: what the + /// Done screen lists while a rescan it asked for runs. + pub fn cohorts(&self) -> &[Cohort] { + &self.cohorts + } + + /// The cohorts since scan `scan`, which is all the tree on screen has + /// not seen. + pub fn since(&self, scan: u64) -> &[Cohort] { + if self.scan == scan { + &self.cohorts + } else { + &[] + } + } + + /// The cohorts added up: reported and private are sums, observed runs + /// from the first cohort's start to the last one's finish. The paths + /// each cohort removed are not kept: they are the user's, and the tree + /// already dropped them. + pub fn totals(cohorts: &[Cohort]) -> Option { + let (first, last) = (cohorts.first()?, cohorts.last()?); + Some(Totals { + count: cohorts.len(), + removed: cohorts.iter().map(|cohort| cohort.removed).sum(), + reported: cohorts.iter().map(|cohort| cohort.reported).sum(), + private: cohorts.iter().map(|cohort| cohort.private).sum(), + observed: observed(first.before, last.after), + started: first.started, + finished: last.finished, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + fn cohort( + reported: u64, + private: Option, + before: u64, + after: u64, + at: u64, + ) -> Cohort { + Cohort { + mode: RemovalMode::Permanent, + removed: 1, + failed: 0, + reported, + private, + before: Some(before), + after: Some(after), + started: SystemTime::UNIX_EPOCH + Duration::from_secs(at), + finished: SystemTime::UNIX_EPOCH + Duration::from_secs(at + 5), + } + } + + #[test] + fn totals_add_estimates_and_measure_from_first_start_to_last_finish() { + let mut ledger = Ledger::default(); + ledger.begin(1); + ledger.push(cohort(20_000, Some(200), 1_000, 1_195, 10)); + // Something else wrote 400 bytes between the two removals. + ledger.push(cohort(10_000, Some(10_000), 795, 10_595, 30)); + let totals = Ledger::totals(ledger.since(1)).expect("two cohorts"); + assert_eq!(totals.count, 2); + assert_eq!(totals.reported, 30_000); + assert_eq!(totals.private, Some(10_200)); + assert_eq!(totals.observed, Some(9_595), "measured, not summed"); + assert_eq!( + totals.started, + SystemTime::UNIX_EPOCH + Duration::from_secs(10) + ); + } + + #[test] + fn a_new_scan_starts_a_new_ledger() { + let mut ledger = Ledger::default(); + ledger.begin(1); + ledger.push(cohort(1, Some(1), 0, 1, 0)); + assert!(ledger.since(2).is_empty(), "scan 2 already saw it"); + assert_eq!(ledger.cohorts().len(), 1, "the Done screen still can"); + ledger.begin(2); + assert!(ledger.cohorts().is_empty()); + } + + #[test] + fn one_unknown_private_part_makes_the_total_unknown() { + let cohorts = [cohort(5, Some(5), 0, 5, 0), cohort(5, None, 5, 9, 9)]; + let totals = Ledger::totals(&cohorts).expect("totals"); + assert_eq!(totals.private, None); + assert_eq!(totals.observed, Some(9)); + } +} diff --git a/crates/disktree-app/src/legend.rs b/crates/disktree-app/src/legend.rs new file mode 100644 index 00000000..08218d5f --- /dev/null +++ b/crates/disktree-app/src/legend.rs @@ -0,0 +1,488 @@ +//! The legend as a filter. Each chip is shown, only, or hidden, and a click +//! moves it to the next: nothing set shows everything, a chip set to only +//! shows just that, and a hidden chip takes its bytes out. +//! +//! Kinds combine with OR and Suggested with AND: "Code" and "Cache" show +//! both, and Suggested narrows that to their cleanup suggestions. The age +//! chips filter the same way, and both sets apply in every mode, so "old +//! code" is one click in each. +//! +//! A click adds a kind; switching from one kind to another is the "only" +//! pill a chip shows on hover once its set filters (see +//! [`LegendFilter::offers_only`]), which makes it the set's one chip. + +use std::sync::Arc; + +use disktree_core::classify::Category; +use disktree_core::filter::{Keep, Rule, filter_with, shares}; +use gpui_kit::Context; + +use crate::palette::AGE_BUCKETS; +use crate::state::Disktree; + +/// Where one chip stands. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Chip { + #[default] + Shown, + Only, + Hidden, +} + +impl Chip { + /// What the next click makes it. + pub const fn next(self) -> Self { + match self { + Self::Shown => Self::Only, + Self::Only => Self::Hidden, + Self::Hidden => Self::Shown, + } + } + + /// The state as an assistive technology reads it. + pub const fn spoken(self) -> &'static str { + match self { + Self::Shown => "shown", + Self::Only => "only", + Self::Hidden => "hidden", + } + } +} + +/// Which chip. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ChipId { + Reclaimable, + /// A kind, by its index in [`Category::LEGEND`]. + Kind(usize), + /// An age, by its index in [`AGE_BUCKETS`]. + Age(usize), +} + +impl ChipId { + pub const fn label(self) -> &'static str { + match self { + // Suggested, not reclaimable: a hatch is a heuristic for review, + // never a promise that the space can be had back. + Self::Reclaimable => "Suggested", + Self::Kind(index) => Category::LEGEND[index].label(), + Self::Age(index) => AGE_BUCKETS[index].1, + } + } + + /// A stable name for element ids and tests. + pub fn key(self) -> String { + match self { + Self::Reclaimable => "legend-reclaimable".into(), + Self::Kind(index) => format!("legend-kind-{index}"), + Self::Age(index) => format!("legend-age-{index}"), + } + } +} + +/// Every chip's state. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct LegendFilter { + pub reclaimable: Chip, + pub kinds: [Chip; Category::LEGEND.len()], + pub ages: [Chip; AGE_BUCKETS.len()], +} + +impl LegendFilter { + pub const fn get(&self, id: ChipId) -> Chip { + match id { + ChipId::Reclaimable => self.reclaimable, + ChipId::Kind(index) => self.kinds[index], + ChipId::Age(index) => self.ages[index], + } + } + + const fn slot(&mut self, id: ChipId) -> &mut Chip { + match id { + ChipId::Reclaimable => &mut self.reclaimable, + ChipId::Kind(index) => &mut self.kinds[index], + ChipId::Age(index) => &mut self.ages[index], + } + } + + pub const fn cycle(&mut self, id: ChipId) { + let slot = self.slot(id); + *slot = slot.next(); + } + + /// Make `id` its set's one only chip, every other chip of the set + /// shown again, hidden ones included. The other set and Suggested are + /// left alone: "only" is about the set the chip belongs to. + pub fn solo(&mut self, id: ChipId) { + match id { + ChipId::Reclaimable => {} + ChipId::Kind(_) => self.clear_kinds(), + ChipId::Age(_) => self.clear_ages(), + } + *self.slot(id) = Chip::Only; + } + + /// Whether hovering `id` offers its "only" pill: when its set already + /// filters, so a click would add to or cycle the set rather than + /// narrow to this chip, and the pill would change something. With + /// nothing set a click already means only. Suggested is a set of its + /// own, where a click is the only there is. + pub fn offers_only(&self, id: ChipId) -> bool { + let set = match id { + ChipId::Reclaimable => return false, + ChipId::Kind(_) => self.kinds_active(), + ChipId::Age(_) => self.ages_active(), + }; + let mut solo = self.clone(); + solo.solo(id); + set && solo != *self + } + + pub fn is_active(&self) -> bool { + self.reclaimable != Chip::Shown + || self.kinds_active() + || self.ages_active() + } + + pub fn kinds_active(&self) -> bool { + self.kinds.iter().any(|chip| *chip != Chip::Shown) + } + + pub fn ages_active(&self) -> bool { + self.ages.iter().any(|chip| *chip != Chip::Shown) + } + + /// Whether any chip of the same set as `id` is set to only, which + /// fades the ones that are not. + pub fn narrowed(&self, id: ChipId) -> bool { + match id { + ChipId::Reclaimable => false, + ChipId::Kind(_) => self.kinds.contains(&Chip::Only), + ChipId::Age(_) => self.ages.contains(&Chip::Only), + } + } + + pub fn clear_kinds(&mut self) { + self.kinds = Default::default(); + } + + pub fn clear_ages(&mut self) { + self.ages = Default::default(); + } + + /// The rule a filtered view applies, with ages measured from `now`. + pub fn rule(&self, now: i64) -> Rule { + let bits = |chips: &[Chip], wanted: Chip| { + chips + .iter() + .enumerate() + .filter(|(_, chip)| **chip == wanted) + .fold(0_u16, |bits, (index, _)| { + bits | Rule::bit(Category::LEGEND[index]) + }) + }; + let ages = |wanted: Chip| { + self.ages + .iter() + .enumerate() + .filter(|(_, chip)| **chip == wanted) + .fold(0_u8, |bits, (index, _)| bits | 1 << index) + }; + Rule { + only: bits(&self.kinds, Chip::Only), + hidden: bits(&self.kinds, Chip::Hidden), + reclaimable: match self.reclaimable { + Chip::Shown => None, + Chip::Only => Some(true), + Chip::Hidden => Some(false), + }, + ages_only: ages(Chip::Only), + ages_hidden: ages(Chip::Hidden), + age_limits: AGE_BUCKETS.iter().map(|(limit, _)| *limit).collect(), + now, + } + } + + /// What the kind chips keep, in words: "Code, Cache", "Media + /// hidden", or both. `None` when they keep everything. + pub fn kinds_summary(&self) -> Option { + let labels = |wanted: Chip| { + Category::LEGEND + .iter() + .zip(&self.kinds) + .filter(|(_, chip)| **chip == wanted) + .map(|(category, _)| category.label()) + .collect::>() + }; + summary(&labels(Chip::Only), &labels(Chip::Hidden)) + } + + /// What the age chips keep, in words. + pub fn ages_summary(&self) -> Option { + let labels = |wanted: Chip| { + AGE_BUCKETS + .iter() + .zip(&self.ages) + .filter(|(_, chip)| **chip == wanted) + .map(|((_, label), _)| *label) + .collect::>() + }; + summary(&labels(Chip::Only), &labels(Chip::Hidden)) + } + + /// Everything the legend keeps, for the totals line: "suggested + /// Code, Cache · Older". + pub fn summary(&self) -> String { + let kinds = self.kinds_summary(); + let mut parts = Vec::new(); + match (self.reclaimable, kinds) { + (Chip::Only, Some(kinds)) => { + parts.push(format!("suggested {kinds}")); + } + (Chip::Only, None) => parts.push("suggested".to_owned()), + (Chip::Hidden, kinds) => { + parts.extend(kinds); + parts.push("suggested hidden".to_owned()); + } + (Chip::Shown, kinds) => parts.extend(kinds), + } + parts.extend(self.ages_summary()); + parts.join(" · ") + } + + /// What the next click on `id` does, for its tooltip, and what its + /// "only" pill does when it has one. + pub fn hint(&self, id: ChipId) -> String { + let label = id.label(); + let click = match self.get(id) { + Chip::Shown if self.narrowed(id) => format!("Click to add {label}"), + Chip::Shown => format!("Click to show only {label}"), + Chip::Only => format!("Showing {label} · click to hide it"), + Chip::Hidden => format!("{label} hidden · click to show it again"), + }; + if self.offers_only(id) { + format!("{click} · Only shows just {label}") + } else { + click + } + } +} + +/// "A, B" for chips set to only, "C hidden" for hidden ones, or both. +fn summary(only: &[&str], hidden: &[&str]) -> Option { + let mut parts = Vec::new(); + if !only.is_empty() { + parts.push(only.join(", ")); + } + if !hidden.is_empty() { + parts.push(format!("{} hidden", hidden.join(", "))); + } + (!parts.is_empty()).then(|| parts.join(" · ")) +} + +impl Disktree { + /// A click on a legend chip. + pub fn cycle_legend(&mut self, id: ChipId, cx: &mut Context<'_, Self>) { + self.legend.cycle(id); + self.legend_changed(cx); + } + + /// Show all, or the pill for the chips not on screen. + pub fn clear_legend( + &mut self, + part: Option, + cx: &mut Context<'_, Self>, + ) { + match part { + None => self.legend = LegendFilter::default(), + Some(ChipId::Kind(_)) => self.legend.clear_kinds(), + Some(ChipId::Age(_)) => self.legend.clear_ages(), + Some(ChipId::Reclaimable) => self.legend.reclaimable = Chip::Shown, + } + self.legend_changed(cx); + } + + /// The "only" pill on a chip, or `o` on a focused one. + pub fn solo_legend(&mut self, id: ChipId, cx: &mut Context<'_, Self>) { + self.legend.solo(id); + self.legend_changed(cx); + } + + fn legend_changed(&mut self, cx: &mut Context<'_, Self>) { + self.refresh_legend(cx); + // A search keeps to what the legend keeps, so it runs again. + if !self.find.trim().is_empty() { + self.refresh_matches(cx); + } + cx.notify(); + } + + /// When the legend leaves nothing of the directory on screen: what it + /// keeps in the whole scan, bytes and files, so the view can say + /// whether going elsewhere would show anything. `None` while there is + /// something to show, or while the filter is still being worked out. + pub fn legend_empty_here(&self) -> Option<(u64, u64)> { + if self.filter_applied + || self.legend_pending + || !self.legend.is_active() + { + return None; + } + let matches = self.legend_matches.as_deref()?; + match matches.keep(&self.crumbs) { + // The scanned root is never recorded, only summed: nothing + // passed when that sum is empty. + None | Some(Keep::Partial { bytes: 0, files: 0 }) => { + Some((matches.bytes, matches.files)) + } + Some(_) => None, + } + } + + /// The rule the legend sets, when it sets one. Ages are measured from + /// the scan, as the age colours are, so a chip keeps exactly the tiles + /// drawn in its colour however long the window has been open. + pub fn legend_rule(&self) -> Option { + self.legend + .is_active() + .then(|| self.legend.rule(self.scanned_at)) + } + + /// Work out what each chip would keep of the whole scan, off the UI + /// thread, for the sizes beside the chips. Once per tree: ages are + /// measured from the scan, as the age colours are. + pub fn refresh_shares(&mut self, cx: &Context<'_, Self>) { + self.shares_epoch += 1; + let epoch = self.shares_epoch; + let Some(tree) = self.tree.clone() else { + self.legend_shares = None; + return; + }; + let now = self.scanned_at; + let task = cx.background_executor().spawn(async move { + let limits: Vec = + AGE_BUCKETS.iter().map(|(limit, _)| *limit).collect(); + shares(tree.root(), now, &limits) + }); + cx.spawn(async move |this, cx| { + let found = task.await; + let _ = this.update(cx, |this, cx| { + if epoch == this.shares_epoch { + this.legend_shares = Some(Arc::new(found)); + cx.notify(); + } + }); + }) + .detach(); + } + + /// Work out what the legend keeps, from the scanned root down, off the + /// UI thread. Once, not per directory: moving around a filtered view + /// then needs no search, and every directory's share is already known. + pub fn refresh_legend(&mut self, cx: &Context<'_, Self>) { + self.legend_epoch += 1; + let epoch = self.legend_epoch; + let (Some(rule), Some(tree)) = (self.legend_rule(), self.tree.clone()) + else { + self.legend_matches = None; + self.legend_pending = false; + self.filter_epoch += 1; + return; + }; + self.legend_pending = true; + let task = cx.background_executor().spawn(async move { + filter_with(tree.root(), &[], "", Some(&rule)) + }); + cx.spawn(async move |this, cx| { + let found = task.await; + let _ = this.update(cx, |this, cx| { + if epoch != this.legend_epoch { + return; + } + this.legend_pending = false; + this.legend_matches = found.map(Arc::new); + this.filter_epoch += 1; + cx.notify(); + }); + }) + .detach(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_chip_goes_only_then_hidden_then_back() { + let mut legend = LegendFilter::default(); + let code = ChipId::Kind(0); + assert!(!legend.is_active()); + legend.cycle(code); + assert_eq!(legend.get(code), Chip::Only); + assert!(legend.narrowed(ChipId::Kind(3))); + assert!(!legend.narrowed(ChipId::Age(0))); + legend.cycle(code); + assert_eq!(legend.get(code), Chip::Hidden); + assert!(!legend.narrowed(ChipId::Kind(3))); + legend.cycle(code); + assert!(!legend.is_active()); + } + + #[test] + fn only_switches_a_set_to_one_chip_in_one_step() { + let mut legend = LegendFilter::default(); + let (code, cache, media) = + (ChipId::Kind(0), ChipId::Kind(7), ChipId::Kind(5)); + // Nothing set: a click already means only, so no pill. + assert!(!legend.offers_only(cache)); + legend.cycle(code); + // Code alone is already only Code; Cache would switch to it. + assert!(!legend.offers_only(code)); + assert!(legend.offers_only(cache)); + legend.solo(cache); + assert_eq!(legend.get(cache), Chip::Only); + assert_eq!(legend.get(code), Chip::Shown); + assert_eq!(legend.summary(), "Cache"); + + // A whole set, hidden chips too, collapses to the one. + legend.cycle(code); + legend.cycle(media); + legend.cycle(media); + legend.cycle(ChipId::Age(1)); + legend.cycle(ChipId::Reclaimable); + assert!(legend.offers_only(cache)); + legend.solo(code); + assert_eq!(legend.kinds_summary().as_deref(), Some("Code")); + // The other set and Suggested are not this set's business. + assert_eq!(legend.get(ChipId::Age(1)), Chip::Only); + assert_eq!(legend.reclaimable, Chip::Only); + assert!(!legend.offers_only(ChipId::Reclaimable)); + } + + #[test] + fn the_rule_and_the_words_say_the_same_thing() { + let mut legend = LegendFilter::default(); + legend.cycle(ChipId::Kind(0)); + legend.cycle(ChipId::Kind(7)); + let rule = legend.rule(0); + assert_eq!( + rule.only, + Rule::bit(Category::Code) | Rule::bit(Category::Cache) + ); + assert_eq!(legend.summary(), "Code, Cache"); + + legend.cycle(ChipId::Reclaimable); + assert_eq!(legend.rule(0).reclaimable, Some(true)); + assert_eq!(legend.summary(), "suggested Code, Cache"); + + let mut legend = LegendFilter::default(); + legend.cycle(ChipId::Kind(5)); + legend.cycle(ChipId::Kind(5)); + legend.cycle(ChipId::Age(4)); + assert_eq!(legend.rule(0).hidden, Rule::bit(Category::Media)); + assert_eq!(legend.rule(0).ages_only, 1 << 4); + assert_eq!(legend.summary(), "Media hidden · Older"); + assert_eq!(legend.kinds_summary().as_deref(), Some("Media hidden")); + } +} diff --git a/crates/disktree-app/src/log_view.rs b/crates/disktree-app/src/log_view.rs new file mode 100644 index 00000000..2fdf15b2 --- /dev/null +++ b/crates/disktree-app/src/log_view.rs @@ -0,0 +1,1126 @@ +//! The Logs window's model: `main.log`'s lines, parsed, filtered and +//! followed. Plain data and file reads; `logs_window.rs` draws it. Ported +//! from PwrRoute's `log_view.rs`, so the family's viewers behave alike. +//! +//! The file is the source, so the window shows lines from earlier launches +//! and from the other processes that write it (`diag_log`), and the log +//! never carries a scanned path to begin with. On open the window reads +//! `main.old.log` and `main.log`, keeps the last [`MAX_LINES`], then reads +//! only what was appended; a file that shrank, or another file under the +//! same name, was rotated, and is read again from the top. +//! +//! What the window shows is [`LogView::rows`]: the lines the levels let +//! through, and with a search in Filter mode only the matches, the context +//! around them and a gap row for each run hidden between; the mark, when +//! there is one, is a row of its own after the line it was dropped on. + +use std::collections::BTreeSet; +use std::fs::File; +use std::io::{self, Read as _, Seek as _, SeekFrom}; +use std::path::PathBuf; + +use gpui_kit::SharedString; +use serde::{Deserialize, Serialize}; + +/// Lines kept in the window. `main.log` rotates at a megabyte into +/// `main.old.log`, so this holds both files' lines with room to spare. +pub const MAX_LINES: usize = 20_000; + +/// The Context choices: lines kept on each side of a match. +pub const CONTEXT_CHOICES: [usize; 4] = [0, 1, 3, 5]; + +/// A line's level, as `diag_log` writes it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Level { + Error, + Warn, + Info, + /// Debug and trace: shown together. + Debug, +} + +impl Level { + pub const ALL: [Self; 4] = + [Self::Error, Self::Warn, Self::Info, Self::Debug]; + + pub const fn label(self) -> &'static str { + match self { + Self::Error => "Error", + Self::Warn => "Warning", + Self::Info => "Info", + Self::Debug => "Debug", + } + } + + fn parse(word: &str) -> Option { + match word { + "ERROR" => Some(Self::Error), + "WARN" => Some(Self::Warn), + "INFO" => Some(Self::Info), + "DEBUG" | "TRACE" => Some(Self::Debug), + _ => None, + } + } + + const fn index(self) -> usize { + self as usize + } +} + +/// What a search does to the lines. +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, +)] +#[serde(rename_all = "camelCase")] +pub enum SearchMode { + /// Only the matching lines stay, with their context. + #[default] + Filter, + /// Every line stays and the matches are marked. + Highlight, +} + +impl SearchMode { + pub const fn label(self) -> &'static str { + match self { + Self::Filter => "filter", + Self::Highlight => "highlight", + } + } +} + +/// One line of the log: `TIME LEVEL target: message`. A line in another +/// shape (a panic's continuation, a hand edit) is all message, at Info. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LogLine { + /// The stamp, as written: `2026-10-24T07:31:02.123-04:00`. + pub time: String, + pub level: Level, + /// Where the level word is in the line, in bytes. + pub level_range: std::ops::Range, + /// Where the target is, when the line names one. + pub target_range: Option>, + pub message: String, + /// The line as the file has it, kept so Copy is byte-exact and a row + /// draws without rebuilding it. + raw: SharedString, + /// `raw` in lowercase, for the search. + lower: String, + /// Characters in `raw`: how wide the line is unwrapped, in a mono face. + chars: usize, + /// It matches the current search: set when the line arrives and when + /// the query changes, so a poll searches only the new lines. + hit: bool, +} + +impl LogLine { + pub fn parse(line: &str) -> Self { + let parsed = (|| { + let (time, rest) = line.split_once(' ')?; + if !time.as_bytes().first()?.is_ascii_digit() { + return None; + } + // Byte offsets into `line` of a slice of it. + let at = + |part: &str| part.as_ptr() as usize - line.as_ptr() as usize; + let (word, after) = rest.trim_start().split_once(' ')?; + let level = Level::parse(word)?; + let after = after.trim_start(); + let (target, message) = + after.split_once(": ").unwrap_or(("", after)); + let level_start = at(word); + let target_start = at(after); + Some(Self { + time: time.to_owned(), + level, + level_range: level_start..level_start + word.len(), + target_range: (!target.is_empty()) + .then(|| target_start..target_start + target.len()), + message: message.to_owned(), + raw: SharedString::default(), + lower: String::new(), + chars: 0, + hit: false, + }) + })(); + let mut parsed = parsed.unwrap_or_else(|| Self { + time: String::new(), + level: Level::Info, + level_range: 0..0, + target_range: None, + message: line.to_owned(), + raw: SharedString::default(), + lower: String::new(), + chars: 0, + hit: false, + }); + parsed.lower = line.to_lowercase(); + parsed.chars = line.chars().count(); + parsed.raw = SharedString::from(line.to_owned()); + parsed + } + + /// The line as the file has it. + pub const fn raw(&self) -> &SharedString { + &self.raw + } + + /// The line in lowercase, as the search reads it. + pub fn lower(&self) -> &str { + &self.lower + } + + /// Case-insensitive: every word of the query is somewhere in the line. + pub fn matches(&self, words: &[String]) -> bool { + words.iter().all(|word| self.lower.contains(word.as_str())) + } +} + +/// How a line row is drawn. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Shown { + /// No search, or a line that does not match in Highlight mode. + Plain, + /// It matches the search. + Match, + /// Kept around a match, or shown from an opened gap. + Context, +} + +/// One row of the viewport. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Row { + /// A line, by index into [`LogView::lines`]. + Line { index: usize, shown: Shown }, + /// Lines hidden between matches: the first one's number and how many. + Gap { first: usize, count: usize }, + /// The mark. + Mark, +} + +/// A row by what it shows, not where: the same key on two reads is the same +/// row, drawn the same height. Line numbers outlive the lines dropped from +/// the front, so the list keeps its measurements across a poll. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum RowKey { + Line { number: usize, shown: Shown }, + Gap { first: usize, count: usize }, + Mark { after: usize }, +} + +/// A mark in the view, never in the file: after line `after`, dropped at +/// `label` ("12:39:00"). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Mark { + pub after: usize, + pub label: String, +} + +/// The lines in the window and how they are filtered. +#[derive(Clone, Debug)] +pub struct LogView { + /// Oldest first. The number of `lines[i]` is `first_number + i`. + pub lines: Vec, + /// The number of the first line kept, counting from 1 since the window + /// read its files. + pub first_number: usize, + /// Older lines were dropped past [`MAX_LINES`]. + pub truncated: bool, + /// The levels shown. + pub levels: [bool; 4], + pub mode: SearchMode, + /// Lines kept on each side of a match in Filter mode. + pub context: usize, + query_words: Vec, + /// Indexes into `lines` that pass the levels and match the search. + matches: Vec, + /// The current match, by number. + active: Option, + /// Gaps opened by a click, by their first line's number. + opened: BTreeSet, + mark: Option, + rows: Vec, + /// Indexes into `lines` of the line rows, in order. + visible: Vec, + /// Characters in the longest line shown. + widest: usize, + /// Lines kept at each level, kept as lines come and go. + counts: [usize; 4], + /// Bumped whenever the rows are rebuilt. + generation: u64, +} + +impl Default for LogView { + fn default() -> Self { + Self::with([true, true, true, false], SearchMode::Filter, 0) + } +} + +impl LogView { + /// An empty view with remembered settings: the levels shown, the + /// search mode and the context. + pub const fn with( + levels: [bool; 4], + mode: SearchMode, + context: usize, + ) -> Self { + Self { + lines: Vec::new(), + first_number: 1, + truncated: false, + levels, + mode, + context, + query_words: Vec::new(), + matches: Vec::new(), + active: None, + opened: BTreeSet::new(), + mark: None, + rows: Vec::new(), + visible: Vec::new(), + widest: 0, + counts: [0; 4], + generation: 0, + } + } + + /// Starts over with `text`, as read from the files. Numbers start + /// again at 1, so the mark and the opened gaps go. + pub fn replace(&mut self, text: &str) { + self.lines.clear(); + self.counts = [0; 4]; + self.first_number = 1; + self.truncated = false; + self.mark = None; + self.opened.clear(); + self.active = None; + self.append(text); + } + + /// Adds complete lines, dropping the oldest past [`MAX_LINES`]. + /// Returns how many of the added lines are errors. + pub fn append(&mut self, text: &str) -> usize { + let mut errors = 0; + for line in text.lines().filter(|line| !line.trim().is_empty()) { + let mut line = LogLine::parse(line); + line.hit = line.matches(&self.query_words); + self.counts[line.level.index()] += 1; + errors += usize::from(line.level == Level::Error); + self.lines.push(line); + } + if self.lines.len() > MAX_LINES { + let drop = self.lines.len() - MAX_LINES; + for line in self.lines.drain(..drop) { + self.counts[line.level.index()] -= 1; + } + self.first_number += drop; + self.truncated = true; + } + self.refilter(); + errors + } + + pub fn set_query(&mut self, query: &str) { + self.query_words = + query.split_whitespace().map(str::to_lowercase).collect(); + for line in &mut self.lines { + line.hit = line.matches(&self.query_words); + } + self.opened.clear(); + // A new search starts at its first match. + self.active = None; + self.refilter(); + } + + pub const fn searching(&self) -> bool { + !self.query_words.is_empty() + } + + pub fn set_mode(&mut self, mode: SearchMode) { + self.mode = mode; + self.opened.clear(); + self.refilter(); + } + + pub fn set_context(&mut self, lines: usize) { + self.context = lines; + self.opened.clear(); + self.refilter(); + } + + pub fn toggle_level(&mut self, level: Level) { + let slot = &mut self.levels[level.index()]; + *slot = !*slot; + self.refilter(); + } + + pub const fn shows(&self, level: Level) -> bool { + self.levels[level.index()] + } + + /// Shows the lines of the gap that starts at line `first`. + pub fn open_gap(&mut self, first: usize) { + self.opened.insert(first); + self.refilter(); + } + + /// The newest line's number, when there are lines. + pub const fn newest(&self) -> Option { + if self.lines.is_empty() { + None + } else { + Some(self.first_number + self.lines.len() - 1) + } + } + + /// Drops the mark after the newest line, replacing any other. + pub fn set_mark(&mut self, label: impl Into) { + let after = self.newest().unwrap_or(self.first_number - 1); + self.mark = Some(Mark { + after, + label: label.into(), + }); + self.refilter(); + } + + pub fn clear_mark(&mut self) { + self.mark = None; + self.refilter(); + } + + pub const fn mark(&self) -> Option<&Mark> { + self.mark.as_ref() + } + + /// The lines after the mark, by number, when any came in. + pub fn since_mark(&self) -> Option<(usize, usize)> { + let mark = self.mark.as_ref()?; + let newest = self.newest()?; + (newest > mark.after) + .then(|| ((mark.after + 1).max(self.first_number), newest)) + } + + fn refilter(&mut self) { + let levels = self.levels; + let shown: Vec = (0..self.lines.len()) + .filter(|&index| levels[self.lines[index].level.index()]) + .collect(); + let searching = self.searching(); + self.matches = if searching { + shown + .iter() + .copied() + .filter(|&index| self.lines[index].hit) + .collect() + } else { + Vec::new() + }; + let mut rows = Vec::with_capacity(shown.len() + 2); + if !searching { + rows.extend(shown.iter().map(|&index| Row::Line { + index, + shown: Shown::Plain, + })); + } else if self.mode == SearchMode::Highlight { + let mut matches = self.matches.iter().peekable(); + for &index in &shown { + let matched = matches.next_if(|&&m| m == index).is_some(); + rows.push(Row::Line { + index, + shown: if matched { Shown::Match } else { Shown::Plain }, + }); + } + } else { + self.filter_rows(&shown, &mut rows); + } + if let Some(mark) = &self.mark { + let first = self.first_number; + let at = rows + .iter() + .position(|row| match row { + Row::Line { index, .. } => first + index > mark.after, + Row::Gap { first, .. } => *first > mark.after, + Row::Mark => false, + }) + .unwrap_or(rows.len()); + rows.insert(at, Row::Mark); + } + self.visible = rows + .iter() + .filter_map(|row| match row { + Row::Line { index, .. } => Some(*index), + _ => None, + }) + .collect(); + self.widest = self + .visible + .iter() + .map(|&index| self.lines[index].chars) + .max() + .unwrap_or(0); + self.rows = rows; + self.generation += 1; + self.keep_active(); + } + + /// Filter mode's rows: the matches, `context` lines around each, and a + /// gap for every run between, unless that gap was opened. + fn filter_rows(&self, shown: &[usize], rows: &mut Vec) { + if self.matches.is_empty() { + // Nothing matched: no rows, and the window says so. + return; + } + let mut keep = vec![false; shown.len()]; + let mut matched = vec![false; shown.len()]; + let mut matches = self.matches.iter().peekable(); + for (at, &index) in shown.iter().enumerate() { + if matches.next_if(|&&m| m == index).is_some() { + matched[at] = true; + let from = at.saturating_sub(self.context); + let to = (at + self.context).min(shown.len() - 1); + keep[from..=to].iter_mut().for_each(|k| *k = true); + } + } + let mut at = 0; + while at < shown.len() { + if keep[at] { + rows.push(Row::Line { + index: shown[at], + shown: if matched[at] { + Shown::Match + } else { + Shown::Context + }, + }); + at += 1; + continue; + } + let start = at; + while at < shown.len() && !keep[at] { + at += 1; + } + let first = self.first_number + shown[start]; + if self.opened.contains(&first) { + rows.extend(shown[start..at].iter().map(|&index| Row::Line { + index, + shown: Shown::Context, + })); + } else { + rows.push(Row::Gap { + first, + count: at - start, + }); + } + } + } + + /// The current match stays on its line while it matches; else it moves + /// to the next match after it, or the last. + fn keep_active(&mut self) { + let first = self.first_number; + let numbers = || self.matches.iter().map(|index| first + index); + self.active = match self.active { + _ if self.matches.is_empty() => None, + None => numbers().next(), + Some(active) => numbers() + .find(|&number| number >= active) + .or_else(|| numbers().next_back()), + }; + } + + /// Changes whenever [`Self::rows`] may have. + pub const fn generation(&self) -> u64 { + self.generation + } + + /// The rows the viewport shows, in order. + pub fn rows(&self) -> &[Row] { + &self.rows + } + + pub fn row_key(&self, row: Row) -> RowKey { + match row { + Row::Line { index, shown } => RowKey::Line { + number: self.first_number + index, + shown, + }, + Row::Gap { first, count } => RowKey::Gap { first, count }, + Row::Mark => RowKey::Mark { + after: self.mark.as_ref().map_or(0, |mark| mark.after), + }, + } + } + + /// The row that shows line `number`, when one does. + pub fn row_of(&self, number: usize) -> Option { + let index = number.checked_sub(self.first_number)?; + self.rows.iter().position( + |row| matches!(row, Row::Line { index: i, .. } if *i == index), + ) + } + + /// The shown lines' indexes into `lines`. + pub fn visible(&self) -> &[usize] { + &self.visible + } + + /// Characters in the longest line shown. + pub const fn widest(&self) -> usize { + self.widest + } + + /// Lines that match the search. + pub const fn match_count(&self) -> usize { + self.matches.len() + } + + /// The current match's number. + pub const fn active(&self) -> Option { + self.active + } + + /// The current match's place among the matches, from 1. + pub fn active_place(&self) -> Option { + let index = self.active?.checked_sub(self.first_number)?; + self.matches.binary_search(&index).ok().map(|at| at + 1) + } + + /// Moves to the next match (or the previous), around the ends. Returns + /// its number. + pub fn step(&mut self, forward: bool) -> Option { + let count = self.matches.len(); + if count == 0 { + return None; + } + let at = self.active_place().map_or(0, |place| place - 1); + let next = if forward { + (at + 1) % count + } else { + (at + count - 1) % count + }; + self.active = Some(self.first_number + self.matches[next]); + self.active + } + + /// Lines at `level` among all kept, whatever the filter. + pub const fn count(&self, level: Level) -> usize { + self.counts[level.index()] + } + + /// "1,204 lines", "12 of 1,204 lines shown" while the levels hide + /// some, "4 of 1,204 lines match" while searching; " · 1 mark" with a + /// mark down. + pub fn summary(&self) -> String { + let total = self.lines.len(); + let shown = self.visible.len(); + let lines = if total == 1 { "line" } else { "lines" }; + let mut summary = if self.searching() { + format!( + "{} of {} {lines} match", + thousands(self.matches.len()), + thousands(total) + ) + } else if shown == total { + format!("{} {lines}", thousands(total)) + } else { + format!( + "{} of {} {lines} shown", + thousands(shown), + thousands(total) + ) + }; + if self.mark.is_some() { + summary.push_str(" \u{b7} 1 mark"); + } + summary + } +} + +/// 12345 as "12,345". +pub fn thousands(value: usize) -> String { + crate::diagnostics::thousands(value as u64) +} + +/// Follows `main.log`: what was read so far, and where. +#[derive(Debug)] +pub struct Tail { + pub path: PathBuf, + /// Bytes of `main.log` already read. + offset: u64, + /// A partial last line, kept as bytes until its newline arrives: a + /// read can stop inside a character, and decoding then would mangle + /// it. + pending: Vec, + /// The file read, so a rotation is noticed even after the new file grew + /// past the old offset. + identity: Option, + /// `main.log` was not there at the last full read: read everything + /// again once it is (Windows has no inode to tell a new file by). + missing: bool, +} + +/// What a poll found. +#[derive(Debug, PartialEq, Eq)] +pub enum Read { + /// Everything again: the first read, or the file was rotated. + All(String), + /// Lines appended since the last read. + More(String), + Nothing, +} + +impl Tail { + pub const fn new(path: PathBuf) -> Self { + Self { + path, + offset: 0, + pending: Vec::new(), + identity: None, + missing: false, + } + } + + /// `main.old.log` beside it. + fn old_path(&self) -> PathBuf { + self.path.with_file_name("main.old.log") + } + + /// The whole history: `main.old.log`, then `main.log`. A `main.log` + /// not there yet (just rotated, nothing written since) is empty; the + /// next poll that finds it reads everything again. + pub fn read_all(&mut self) -> io::Result { + let old = std::fs::read(self.old_path()).unwrap_or_default(); + let mut current = Vec::new(); + match File::open(&self.path) { + Ok(mut file) => { + self.identity = identity(&file.metadata()?); + self.missing = false; + file.read_to_end(&mut current)?; + } + // Not there yet, rotated or never written: shown as no output, + // and read again once it appears. + Err(error) if error.kind() == io::ErrorKind::NotFound => { + self.identity = None; + self.missing = true; + } + Err(error) => return Err(error), + } + self.offset = current.len() as u64; + let mut bytes = old; + if bytes.last().is_some_and(|&byte| byte != b'\n') { + bytes.push(b'\n'); + } + bytes.extend_from_slice(¤t); + self.pending.clear(); + Ok(self.complete_lines(bytes)) + } + + /// What changed since the last read. + pub fn poll(&mut self) -> io::Result { + let metadata = std::fs::metadata(&self.path)?; + let len = metadata.len(); + if self.missing + || len < self.offset + || identity(&metadata) != self.identity + { + return self.read_all().map(Read::All); + } + if len == self.offset { + return Ok(Read::Nothing); + } + let mut file = File::open(&self.path)?; + file.seek(SeekFrom::Start(self.offset))?; + let mut bytes = Vec::new(); + file.take(len - self.offset).read_to_end(&mut bytes)?; + self.offset += bytes.len() as u64; + let mut joined = std::mem::take(&mut self.pending); + joined.extend_from_slice(&bytes); + let text = self.complete_lines(joined); + Ok(if text.is_empty() { + Read::Nothing + } else { + Read::More(text) + }) + } + + /// `bytes` up to its last newline, decoded; the rest waits in + /// `pending`. A newline byte never sits inside a UTF-8 character, so + /// what is decoded holds only whole ones. + fn complete_lines(&mut self, mut bytes: Vec) -> String { + if let Some(end) = bytes.iter().rposition(|&byte| byte == b'\n') { + self.pending = bytes.split_off(end + 1); + String::from_utf8_lossy(&bytes).into_owned() + } else { + self.pending = bytes; + String::new() + } + } +} + +/// Which file a path names now: its inode where there is one. +#[cfg(unix)] +#[allow( + clippy::unnecessary_wraps, + reason = "Windows has no inode, and both share one signature" +)] +fn identity(metadata: &std::fs::Metadata) -> Option { + use std::os::unix::fs::MetadataExt as _; + Some(metadata.ino()) +} + +#[cfg(not(unix))] +const fn identity(_: &std::fs::Metadata) -> Option { + None +} + +#[cfg(test)] +mod tests { + use super::*; + + const INFO: &str = "2026-10-24T07:31:02.123-04:00 INFO pwrdisk::scan: \ + local scan finished: 1204 files in 0.4 s"; + const WARN: &str = "2026-10-24T07:31:03.000-04:00 WARN \ + pwrdisk::updater: GitHub said 403"; + + #[test] + fn a_line_parses_into_time_level_target_and_message() { + let line = LogLine::parse(INFO); + assert_eq!(line.time, "2026-10-24T07:31:02.123-04:00"); + assert_eq!(line.level, Level::Info); + assert_eq!(&INFO[line.level_range.clone()], "INFO"); + assert_eq!( + line.target_range.clone().map(|range| &INFO[range]), + Some("pwrdisk::scan") + ); + assert_eq!(line.message, "local scan finished: 1204 files in 0.4 s"); + assert_eq!(line.raw().as_ref(), INFO); + assert_eq!(LogLine::parse(WARN).level, Level::Warn); + + let odd = LogLine::parse("thread 'main' panicked"); + assert_eq!(odd.level, Level::Info); + assert_eq!(odd.message, "thread 'main' panicked"); + assert_eq!( + LogLine::parse("2026-10-24T07:31:02 TRACE gpui: x").level, + Level::Debug + ); + } + + #[test] + fn levels_and_words_filter_the_lines() { + let mut view = LogView::default(); + view.replace(&format!( + "{INFO}\n{WARN}\n\ + 2026-10-24T07:31:04.000-04:00 DEBUG pwrdisk::scan: 8 workers\n" + )); + assert_eq!(view.lines.len(), 3); + // Debug is off by default. + assert_eq!(view.visible(), [0, 1]); + assert_eq!(view.summary(), "2 of 3 lines shown"); + view.toggle_level(Level::Debug); + assert_eq!(view.visible(), [0, 1, 2]); + assert_eq!(view.summary(), "3 lines"); + view.set_query("GITHUB 403"); + assert_eq!(view.visible(), [1]); + view.set_query(""); + view.toggle_level(Level::Info); + assert_eq!(view.visible(), [1, 2]); + assert_eq!(view.count(Level::Warn), 1); + } + + #[test] + fn the_view_keeps_the_newest_lines() { + let mut view = LogView::default(); + let text = numbered(0..MAX_LINES + 10, "07:31:02"); + view.replace(&text); + assert_eq!(view.lines.len(), MAX_LINES); + assert!(view.truncated); + assert_eq!(view.first_number, 11); + assert_eq!(view.lines[0].message, "line 10"); + } + + #[test] + fn the_tail_follows_appends_partial_lines_and_rotation() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("main.log"); + std::fs::write(dir.path().join("main.old.log"), "old\n").unwrap(); + std::fs::write(&path, "one\ntw").unwrap(); + let mut tail = Tail::new(path.clone()); + assert_eq!(tail.read_all().unwrap(), "old\none\n"); + assert_eq!(tail.poll().unwrap(), Read::Nothing); + + let append = |text: &str| { + use std::io::Write as _; + let mut file = std::fs::OpenOptions::new() + .append(true) + .open(&path) + .unwrap(); + file.write_all(text.as_bytes()).unwrap(); + }; + append("o\nthree\n"); + assert_eq!(tail.poll().unwrap(), Read::More("two\nthree\n".to_owned())); + + // Rotated: the old file is what main.log was, main.log starts over. + std::fs::rename(&path, dir.path().join("main.old.log")).unwrap(); + std::fs::write(&path, "four\n").unwrap(); + assert_eq!( + tail.poll().unwrap(), + Read::All("one\ntwo\nthree\nfour\n".to_owned()) + ); + } + + #[test] + fn just_after_a_rotation_the_old_file_is_read() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("main.log"); + std::fs::write(dir.path().join("main.old.log"), "old\n").unwrap(); + let mut tail = Tail::new(path.clone()); + assert_eq!(tail.read_all().unwrap(), "old\n"); + std::fs::write(&path, "new\n").unwrap(); + assert_eq!(tail.poll().unwrap(), Read::All("old\nnew\n".to_owned())); + // With neither file there is no output yet, and the first line + // written is read. + let other = tempfile::tempdir().unwrap(); + let fresh = other.path().join("main.log"); + let mut none = Tail::new(fresh.clone()); + assert_eq!(none.read_all().unwrap(), ""); + std::fs::write(&fresh, "first\n").unwrap(); + assert_eq!(none.poll().unwrap(), Read::All("first\n".to_owned())); + } + + #[test] + fn a_character_cut_by_a_read_arrives_whole() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("main.log"); + std::fs::write(&path, "").unwrap(); + let mut tail = Tail::new(path.clone()); + assert_eq!(tail.read_all().unwrap(), ""); + let line = "Settings \u{203a} Updates\n".as_bytes(); + // Up to the middle of the three-byte '›'. + let cut = "Settings ".len() + 1; + let append = |bytes: &[u8]| { + use std::io::Write as _; + std::fs::OpenOptions::new() + .append(true) + .open(&path) + .unwrap() + .write_all(bytes) + .unwrap(); + }; + append(&line[..cut]); + assert_eq!(tail.poll().unwrap(), Read::Nothing); + append(&line[cut..]); + assert_eq!( + tail.poll().unwrap(), + Read::More("Settings \u{203a} Updates\n".to_owned()) + ); + } + + #[test] + fn counts_follow_the_lines_kept() { + let mut view = LogView::default(); + assert_eq!(view.append(&format!("{INFO}\n{WARN}\n")), 0); + let error = "2026-10-24T07:31:05.000-04:00 ERROR pwrdisk: refused"; + assert_eq!(view.append(&format!("{error}\n")), 1); + assert_eq!(view.count(Level::Error), 1); + assert_eq!(view.count(Level::Warn), 1); + let more = numbered(0..MAX_LINES, "07:31:06"); + view.append(&more); + assert_eq!(view.count(Level::Error), 0); + assert_eq!(view.count(Level::Warn), 0); + assert_eq!(view.count(Level::Info), MAX_LINES); + } + + /// Twelve lines, every fourth an error that says "failed". + fn twelve() -> LogView { + let mut view = LogView::default(); + let text: String = (1..=12) + .map(|n| { + if n % 4 == 0 { + format!( + "2026-10-24T07:31:02 ERROR pwrdisk::scan: \ + scan {n} failed\n" + ) + } else { + format!( + "2026-10-24T07:31:02 INFO pwrdisk::scan: \ + scan {n} finished\n" + ) + } + }) + .collect(); + view.replace(&text); + view + } + + /// `range` lines "line N", all at Info and at `time`. + fn numbered(range: std::ops::Range, time: &str) -> String { + use std::fmt::Write as _; + range.fold(String::new(), |mut text, n| { + let _ = writeln!(text, "2026-10-24T{time} INFO pwrdisk: line {n}"); + text + }) + } + + fn keys(view: &LogView) -> Vec { + view.rows().iter().map(|row| view.row_key(*row)).collect() + } + + #[test] + fn filter_keeps_matches_and_context_and_gaps_the_rest() { + use Shown::{Context, Match}; + let line = |number, shown| RowKey::Line { number, shown }; + let mut view = twelve(); + view.set_query("failed"); + assert_eq!(view.match_count(), 3); + assert_eq!( + keys(&view), + [ + RowKey::Gap { first: 1, count: 3 }, + line(4, Match), + RowKey::Gap { first: 5, count: 3 }, + line(8, Match), + RowKey::Gap { first: 9, count: 3 }, + line(12, Match), + ] + ); + assert_eq!(view.summary(), "3 of 12 lines match"); + + // ±1 keeps a line on each side; the gaps shrink. + view.set_context(1); + assert_eq!( + keys(&view), + [ + RowKey::Gap { first: 1, count: 2 }, + line(3, Context), + line(4, Match), + line(5, Context), + RowKey::Gap { first: 6, count: 1 }, + line(7, Context), + line(8, Match), + line(9, Context), + RowKey::Gap { + first: 10, + count: 1 + }, + line(11, Context), + line(12, Match), + ] + ); + assert_eq!(view.visible().len(), 8); + + // A clicked gap shows its lines, as context. + view.open_gap(1); + assert_eq!(keys(&view)[..2], [line(1, Context), line(2, Context)]); + // A new search closes it again. + view.set_query("scan 8"); + assert_eq!(view.match_count(), 1); + assert_eq!(keys(&view)[0], RowKey::Gap { first: 1, count: 6 }); + + // Nothing matches: no rows at all. + view.set_query("nowhere"); + assert!(view.rows().is_empty()); + assert_eq!(view.summary(), "0 of 12 lines match"); + } + + #[test] + fn highlight_keeps_every_line_and_marks_the_matches() { + let mut view = twelve(); + view.set_mode(SearchMode::Highlight); + view.set_query("failed"); + assert_eq!(view.rows().len(), 12); + assert_eq!( + keys(&view)[3], + RowKey::Line { + number: 4, + shown: Shown::Match + } + ); + assert_eq!( + keys(&view)[4], + RowKey::Line { + number: 5, + shown: Shown::Plain + } + ); + // Levels still apply. + view.toggle_level(Level::Info); + assert_eq!(view.rows().len(), 3); + } + + #[test] + fn the_current_match_steps_around_and_stays_on_its_line() { + let mut view = twelve(); + view.set_query("failed"); + assert_eq!((view.active(), view.active_place()), (Some(4), Some(1))); + assert_eq!(view.step(true), Some(8)); + assert_eq!(view.step(true), Some(12)); + assert_eq!(view.step(true), Some(4)); + assert_eq!(view.step(false), Some(12)); + assert_eq!(view.active_place(), Some(3)); + // New lines do not move it. + view.append( + "2026-10-24T07:31:03 ERROR pwrdisk::scan: scan 13 failed\n", + ); + assert_eq!((view.active(), view.active_place()), (Some(12), Some(3))); + assert_eq!(view.match_count(), 4); + // Hidden by a level with nothing left, there is none; shown + // again, the search starts over at its first match. + view.toggle_level(Level::Error); + assert_eq!(view.active(), None); + view.toggle_level(Level::Error); + assert_eq!(view.active(), Some(4)); + view.set_query(""); + assert_eq!(view.active(), None); + assert_eq!(view.step(true), None); + } + + #[test] + fn the_mark_sits_after_the_newest_line_and_selects_what_came_after() { + let mut view = twelve(); + assert_eq!(view.since_mark(), None); + view.set_mark("12:39:00"); + assert_eq!(view.mark().map(|mark| mark.after), Some(12)); + assert_eq!(view.rows().last(), Some(&Row::Mark)); + assert_eq!(view.since_mark(), None); + assert_eq!(view.summary(), "12 lines \u{b7} 1 mark"); + view.append( + "2026-10-24T07:31:03 INFO pwrdisk::scan: scan 13 finished\n\ + 2026-10-24T07:31:03 INFO pwrdisk::scan: scan 14 finished\n", + ); + assert_eq!(view.rows()[12], Row::Mark); + assert_eq!(view.since_mark(), Some((13, 14))); + // A second mark replaces the first. + view.set_mark("12:40:00"); + assert_eq!( + view.rows().iter().filter(|row| **row == Row::Mark).count(), + 1 + ); + assert_eq!(view.rows().last(), Some(&Row::Mark)); + // Filtered, it sits before the first row after it. + view.set_query("failed"); + assert_eq!(view.rows().last(), Some(&Row::Mark)); + view.clear_mark(); + assert_eq!(view.mark(), None); + // A rotation starts the numbers over, and the mark goes with them. + view.set_mark("12:42:00"); + view.replace("2026-10-24T07:31:03 INFO pwrdisk: one\n"); + assert_eq!(view.mark(), None); + } + + #[test] + fn row_keys_survive_lines_dropped_from_the_front() { + let mut view = LogView::default(); + let text = numbered(0..MAX_LINES, "07:31:02"); + view.replace(&text); + let before = keys(&view); + view.append("2026-10-24T07:31:02 INFO pwrdisk: one more\n"); + let after = keys(&view); + assert_eq!(after[..MAX_LINES - 1], before[1..]); + assert_eq!(view.row_of(2), Some(0)); + assert_eq!(view.row_of(1), None); + assert_eq!( + view.widest(), + "2026-10-24T07:31:02 INFO pwrdisk: line 19999".len() + ); + } +} diff --git a/crates/disktree-app/src/logs_fixture.rs b/crates/disktree-app/src/logs_fixture.rs new file mode 100644 index 00000000..27ff0fa8 --- /dev/null +++ b/crates/disktree-app/src/logs_fixture.rs @@ -0,0 +1,129 @@ +//! `pwrdisk logs-fixture LOG`, in debug builds only: the production Logs +//! window over a log the caller invented, for native accessibility checks +//! and screenshots of a log nobody minds showing. +//! +//! It lives in the binary, rather than an example that re-declares the +//! binary's modules, so a module added to `main.rs` cannot break it. It opens +//! that one window and nothing else: no main window, so no scan and no +//! removal; no agent link and no startup update check; no saved Logs view, +//! read or written; and `main` takes this path before it opens `main.log`, +//! so the real log is never written either. The menu bar is the app's, so +//! its Settings and Check for Updates still do what they do there; a check +//! that wants the fixture untouched leaves them alone. Release builds leave +//! it out, which is why the usage text does not mention it. +//! +//! `cargo run -p disktree-app -- logs-fixture /tmp/invented.log` + +use std::{ + ffi::OsString, + path::{Path, PathBuf}, +}; + +use anyhow::{Context as _, Result}; + +const COMMAND: &str = "logs-fixture"; + +/// Runs the fixture if the command line asks for it, and says how it went; +/// `None` when it asks for something else. +pub fn run_if_asked() -> Option> { + let own_logs = crate::diag_log::log_dir(); + requested(std::env::args_os().skip(1), own_logs.as_deref()) + .transpose() + .map(|log| log.map(open)) +} + +/// The log `logs-fixture LOG` names, program name already skipped. It +/// must be a file outside `own_logs`, the folder PwrDisk writes its own +/// log to, which can hold real paths. +fn requested( + args: impl IntoIterator, + own_logs: Option<&Path>, +) -> Result> { + let mut args = args.into_iter(); + if args.next().is_none_or(|arg| arg != COMMAND) { + return Ok(None); + } + let (Some(log), None) = (args.next(), args.next()) else { + anyhow::bail!("usage: pwrdisk {COMMAND} LOG"); + }; + let log = dunce::canonicalize(&log).with_context(|| { + format!("cannot read {}", Path::new(&log).display()) + })?; + anyhow::ensure!(log.is_file(), "{} is not a file", log.display()); + // Canonical on both sides, so a symlink or `..` cannot lead back in. + if let Some(own) = own_logs.and_then(|dir| dunce::canonicalize(dir).ok()) { + anyhow::ensure!( + !log.starts_with(&own), + "{} is in PwrDisk's own log folder; invent a log elsewhere", + log.display() + ); + } + Ok(Some(log)) +} + +/// Logs over `log`, with the menu bar so its shortcuts work as they do in +/// the app. Closing it quits, as closing the last window does there. +fn open(log: PathBuf) { + gpui_kit::application() + .with_assets(gpui_kit::assets::Assets) + .run(move |cx| { + gpui_omarchy::init(cx); + crate::app_menu::install(cx); + crate::logs_window::open_window(Some(log), None, cx); + cx.activate(true); + }); +} + +#[cfg(test)] +mod tests { + use std::ffi::OsStr; + + use super::*; + + fn ask(args: &[&OsStr], own: Option<&Path>) -> Result> { + requested(args.iter().map(|&arg| arg.to_owned()), own) + } + + #[test] + fn other_commands_are_not_the_fixture() { + for args in [&[][..], &["mcp"], &["."], &["--logs-fixture", "x"]] { + let args: Vec<&OsStr> = args.iter().map(OsStr::new).collect(); + assert!(ask(&args, None).expect("not ours").is_none()); + } + } + + #[test] + fn opens_only_an_existing_file_outside_the_app_logs() { + let temp = tempfile::tempdir().expect("tempdir"); + let invented = temp.path().join("invented.log"); + std::fs::write(&invented, "INFO invented\n").expect("log"); + let own = temp.path().join("own"); + std::fs::create_dir(&own).expect("own logs"); + let real = own.join("main.log"); + std::fs::write(&real, "INFO real\n").expect("real log"); + + let command = OsStr::new(COMMAND); + let found = ask(&[command, invented.as_os_str()], Some(&own)) + .expect("invented log") + .expect("the fixture"); + assert_eq!(found, dunce::canonicalize(&invented).expect("canonical")); + + let missing = temp.path().join("missing.log"); + // Through `..`, to the real log all the same. + let around = temp.path().join("own/../own/main.log"); + // Other case: macOS and Windows canonicalize it to the folder's own + // case, so it is refused there too; on Linux it does not exist. + let cased = temp.path().join("OWN/main.log"); + for args in [ + &[command][..], + &[command, missing.as_os_str()], + &[command, temp.path().as_os_str()], + &[command, invented.as_os_str(), OsStr::new("extra")], + &[command, real.as_os_str()], + &[command, around.as_os_str()], + &[command, cased.as_os_str()], + ] { + assert!(ask(args, Some(&own)).is_err(), "{args:?} is refused"); + } + } +} diff --git a/crates/disktree-app/src/logs_window.rs b/crates/disktree-app/src/logs_window.rs new file mode 100644 index 00000000..781f73d7 --- /dev/null +++ b/crates/disktree-app/src/logs_window.rs @@ -0,0 +1,2336 @@ +//! Help › Logs: `main.log`, live, in its own window. The family's viewer, +//! as PwrRoute has it: search that filters (with context and gap rows) or +//! highlights, previous and next match, the level toggles with Error and +//! Warning counts, Wrap with a hanging indent, Mark and Select since mark, +//! Live / Paused with a "new lines" pill, line selection in the number +//! gutter with Copy (and the diagnostics report, when asked), and the +//! file's Copy path and Reveal. Wrap, the search mode, Context, Include +//! diagnostics and the levels but Debug are remembered in `logs-view.json` +//! in the settings folder. +//! +//! The rows are a GPUI `list`, measured row by row: a wrapped line is as +//! tall as its text. GPUI's text has no hanging indent, so a wrapped line +//! is cut into rows here ([`LogsWindow::segments`]) and each continuation +//! is drawn indented. Unwrapped, every row is one line high and the text +//! scrolls sideways under a fixed gutter, so no line is ever clipped. +//! +//! The log never carries a scanned path (`diag_log`), so nothing here has +//! one to hide, and nothing here writes a line anywhere but the clipboard. +//! The model, parsing and the file reads are `log_view.rs`. + +use crate::semantics::AccessibleButton as _; +use disktree_core::path_style::PathStyle; +use std::fmt::Write as _; +use std::ops::Range; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use gpui_kit::base::input::{InputEvent, InputState}; +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::{ + AnyElement, App, AppContext as _, ClipboardItem, Context, Entity, + FocusHandle, Focusable as _, Font, FontWeight, HighlightStyle, Hsla, + IndentAdjustment, InteractiveElement as _, IntoElement, KeyDownEvent, + LineFragment, ListAlignment, ListOffset, ListState, MouseButton, + MouseDownEvent, ParentElement as _, Pixels, Rems, Render, ScrollWheelEvent, + SharedString, StatefulInteractiveElement as _, Styled as _, StyledText, + Window, WindowHandle, deferred, div, list, px, +}; +use gpui_omarchy::{ + ActiveTheme as _, ButtonVariant, IconName, Theme, button, icon, +}; + +use crate::widgets::with_tooltip; +use serde::{Deserialize, Serialize}; + +use crate::aux_window::{self, Spec}; +use crate::chrome::Drags; +use crate::log_view::{ + CONTEXT_CHOICES, Level, LogLine, LogView, Read, Row, RowKey, SearchMode, + Shown, Tail, thousands, +}; +use crate::ui::{icon as icon_size, size, space, text}; + +/// How often the file is read for new lines. +const POLL_EVERY: Duration = Duration::from_millis(500); +/// How long a status note ("Copied 3 lines") stays. +const NOTE_FOR: Duration = Duration::from_secs(3); +/// Rows kept above a line the window scrolls to (a match, the line Esc +/// returns to), so what led to it shows. +const REVEAL_ABOVE: usize = 2; + +/// What the reader is and which keys it takes, for assistive technology. +const READER_LABEL: &str = "Logs; Tab moves through controls; Escape \ + leaves search; Up/Down selects lines, Shift extends selection, \ + Home/End reaches either end, PageUp/PageDown scroll within wrapped \ + lines; Command or Control C copies selected lines"; +/// Where the view's settings are kept, in the settings folder. +const PREFS_FILE: &str = "logs-view.json"; + +pub const SEARCH_ID: &str = "logs-search"; +pub const LIVE_ID: &str = "logs-live"; +pub const COPY_ID: &str = "logs-copy"; +pub const COPY_PATH_ID: &str = "logs-copy-path"; +pub const REVEAL_ID: &str = "logs-reveal"; +pub const PILL_ID: &str = "logs-new-lines"; +pub const FILTER_ID: &str = "logs-mode-filter"; +pub const HIGHLIGHT_ID: &str = "logs-mode-highlight"; +pub const CONTEXT_ID: &str = "logs-context"; +pub const WRAP_ID: &str = "logs-wrap"; +pub const MARK_ID: &str = "logs-mark"; +pub const PREV_ID: &str = "logs-prev-match"; +pub const NEXT_ID: &str = "logs-next-match"; +pub const SINCE_MARK_ID: &str = "logs-select-since-mark"; +pub const CLEAR_MARK_ID: &str = "logs-clear-mark"; +pub const DIAGNOSTICS_ID: &str = "logs-include-diagnostics"; + +/// Wide enough for the toolbar on one row with Context showing. +const SPEC: Spec = Spec { + title: "PwrDisk Logs", + size: (1120.0, 720.0), + min: (880.0, 420.0), +}; + +/// The status bar's hint while a search is active. +const SEARCH_HINT: &str = + "Enter next \u{b7} Shift-Enter previous \u{b7} Esc clears"; + +/// What `logs-view.json` keeps: never Debug, never the search. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct LogsPrefs { + pub wrap: bool, + pub search_mode: SearchMode, + pub context_lines: usize, + pub include_diagnostics: bool, + pub error: bool, + pub warning: bool, + pub info: bool, +} + +impl Default for LogsPrefs { + fn default() -> Self { + Self { + // No line is clipped until someone asks for it. + wrap: true, + search_mode: SearchMode::Filter, + context_lines: 0, + include_diagnostics: false, + error: true, + warning: true, + info: true, + } + } +} + +impl LogsPrefs { + /// `path`'s settings; a missing or unreadable file is the defaults. + pub fn load(path: Option<&Path>) -> Self { + path.and_then(|path| std::fs::read_to_string(path).ok()) + .and_then(|text| serde_json::from_str::(&text).ok()) + .map(|mut prefs| { + // An edited file cannot ask for a Context the menu lacks. + if !CONTEXT_CHOICES.contains(&prefs.context_lines) { + prefs.context_lines = 0; + } + prefs + }) + .unwrap_or_default() + } + + fn save(&self, path: &Path) -> std::io::Result<()> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let mut text = serde_json::to_string_pretty(self) + .map_err(std::io::Error::other)?; + text.push('\n'); + std::fs::write(path, text) + } +} + +/// Opens Logs, or brings it forward. +pub fn open(cx: &mut App) { + let existing = aux_window::find::(cx, |_| true); + if aux_window::activate(existing, cx) { + return; + } + let prefs = crate::updater::settings_dir().map(|dir| dir.join(PREFS_FILE)); + open_window(crate::diag_log::path().map(Path::to_path_buf), prefs, cx); +} + +/// A new Logs window over `path` (`None`: there is no log file), keeping +/// its view in `prefs`; for `open` and the tests. +pub fn open_window( + path: Option, + prefs: Option, + cx: &mut App, +) -> Option> { + aux_window::open(&SPEC, cx, move |window, cx| { + let view = LogsWindow::new(path, prefs, window, cx); + view.search + .update(cx, |search, cx| search.focus(window, cx)); + view + }) +} + +/// The window's view. +pub struct LogsWindow { + pub view: LogView, + tail: Option, + /// Why there are no lines to show, when there are none. + pub problem: Option, + /// Where the view's settings are saved; `None` keeps them for now. + prefs_path: Option, + search: Entity, + /// The search as last applied. + query: String, + focus: FocusHandle, + list: ListState, + /// The rows the list was last told about, and the model's generation + /// they came from. + list_keys: Vec, + list_generation: Option, + /// New lines scroll into view. + pub live: bool, + /// Lines and errors that came in while paused. + pub new_lines: usize, + new_errors: usize, + /// Selected lines, by number (`LogView::first_number` counting): the + /// anchor and the other end. + pub selection: Option<(usize, usize)>, + /// The selection's far end moves with new lines: Select since mark, + /// or a Shift-click that reached the newest line. A plain click or + /// Select All stays put. + follows_tail: bool, + pub include_diagnostics: bool, + /// Long lines wrap; off, they scroll sideways. + pub wrap: bool, + /// With Wrap off: how far the text is scrolled left, and how far it can + /// go, in pixels the pointer moved. + pub h_offset: f32, + h_max: f32, + /// The mono face's advance and the room a line's text has, measured + /// on the last frame: what [`Self::segments`] wraps to. + pub char_width: f32, + pub text_width: f32, + context_open: bool, + /// Whether the Context menu was open when the press that may close it + /// began, so the press on its button does not open it again. + context_was_open: bool, + note: Option<(SharedString, u64)>, + note_generation: u64, + /// What the next frame scrolls to, once the list has the new rows. + pending_reveal: Reveal, + strip_drag: bool, +} + +impl Drags for LogsWindow { + fn strip_drag(&mut self) -> &mut bool { + &mut self.strip_drag + } +} + +impl LogsWindow { + pub fn new( + path: Option, + prefs_path: Option, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) -> Self { + let prefs = LogsPrefs::load(prefs_path.as_deref()); + // Debug is never remembered: every window opens without it. + let view = LogView::with( + [prefs.error, prefs.warning, prefs.info, false], + prefs.search_mode, + prefs.context_lines, + ); + let search = cx.new(|cx| { + InputState::new(window, cx) + .placeholder("Search logs") + .clean_on_escape() + }); + cx.subscribe(&search, |this, _, event: &InputEvent, cx| match event { + InputEvent::Change => { + let query = this.search.read(cx).value().to_string(); + this.query_changed(&query); + cx.notify(); + } + InputEvent::PressEnter { shift, .. } => this.step(!shift, cx), + InputEvent::Focus | InputEvent::Blur => {} + }) + .detach(); + cx.spawn(async move |this, cx| { + loop { + cx.background_executor().timer(POLL_EVERY).await; + if this.update(cx, Self::poll).is_err() { + break; + } + } + }) + .detach(); + let mut this = Self { + view, + tail: path.map(Tail::new), + problem: None, + prefs_path, + search, + query: String::new(), + focus: cx.focus_handle().tab_stop(true), + list: ListState::new(0, ListAlignment::Top, px(240.0)), + list_keys: Vec::new(), + list_generation: None, + live: true, + new_lines: 0, + new_errors: 0, + selection: None, + follows_tail: false, + include_diagnostics: prefs.include_diagnostics, + wrap: prefs.wrap, + h_offset: 0.0, + h_max: 0.0, + char_width: 7.2, + text_width: 800.0, + context_open: false, + context_was_open: false, + note: None, + note_generation: 0, + pending_reveal: Reveal::None, + strip_drag: false, + }; + this.reload(window); + this + } + + /// Reads everything again. + fn reload(&mut self, window: &Window) { + let Some(tail) = &mut self.tail else { + self.problem = Some( + "No log: PwrDisk could not create its log folder, so this \ + session writes only to the terminal." + .to_owned(), + ); + return; + }; + match tail.read_all() { + Ok(text) => { + self.view.replace(&text); + self.problem = None; + } + Err(error) => { + self.problem = + Some(format!("Could not read the log: {error}.")); + } + } + self.sync_list(window); + self.list.scroll_to_end(); + } + + /// Reads what the file gained since the last read; a rotation reads + /// it all again. + pub fn poll(&mut self, cx: &mut Context<'_, Self>) { + let Some(tail) = &mut self.tail else { + return; + }; + // Not there yet (nothing logged since a rotation): keep what is + // shown. + let Ok(read) = tail.poll() else { + return; + }; + match read { + Read::Nothing => return, + Read::All(text) => { + self.view.replace(&text); + self.problem = None; + self.selection = None; + self.follows_tail = false; + self.new_lines = 0; + self.new_errors = 0; + // Numbers start again at 1 for other text, so a row's key + // no longer names what the list measured: start it over. + self.list_keys.clear(); + } + Read::More(text) => { + self.problem = None; + let newest = self.view.newest(); + let before = self.view.lines.len() + self.view.first_number; + let errors = self.view.append(&text); + if !self.live { + self.new_lines += + self.view.lines.len() + self.view.first_number - before; + self.new_errors += errors; + } + self.follow_selection(newest); + } + } + cx.notify(); + } + + /// A following selection that ended on the newest line grows with the + /// lines that came after it, so Copy at the end of a repro takes them + /// too. + const fn follow_selection(&mut self, newest_before: Option) { + let (true, Some((anchor, end)), Some(before), Some(newest)) = ( + self.follows_tail, + self.selection, + newest_before, + self.view.newest(), + ) else { + return; + }; + if end == before { + self.selection = Some((anchor, newest)); + } + } + + /// A row's height before it is measured: one line of text. + fn row_height(window: &Window) -> Pixels { + window.rem_size() * size::LOG_ROW.0 + } + + /// Tells the list which rows changed since it last drew: lines dropped + /// from the front, then what differs between the rows both share at + /// the start and the end. Rows it already measured keep their height. + fn sync_list(&mut self, window: &Window) { + let generation = self.view.generation(); + if self.list_generation == Some(generation) { + return; + } + self.list_generation = Some(generation); + let keys: Vec = self + .view + .rows() + .iter() + .map(|row| self.view.row_key(*row)) + .collect(); + if keys == self.list_keys { + return; + } + let mut old = std::mem::take(&mut self.list_keys); + // Paused, the reader stays on the line at the top (or the next one + // still shown), whatever was spliced around or under it. + let scroll_top = self.list.logical_scroll_top(); + let top = (!self.live) + .then(|| { + old.get(scroll_top.item_ix.min(old.len())..)? + .iter() + .find_map(|key| match key { + RowKey::Line { number, .. } => Some(*number), + _ => None, + }) + }) + .flatten(); + if let (Some(first), Some(old_first)) = (keys.first(), old.first()) + && first != old_first + && let Some(dropped) = old.iter().position(|key| key == first) + { + self.list.splice(0..dropped, 0); + old.drain(..dropped); + } + let prefix = old.iter().zip(&keys).take_while(|(a, b)| a == b).count(); + let room = old.len().min(keys.len()) - prefix; + let suffix = old + .iter() + .rev() + .zip(keys.iter().rev()) + .take(room) + .take_while(|(a, b)| a == b) + .count(); + if prefix == 0 && suffix == 0 { + self.list.reset_with_uniform_height( + keys.len(), + Self::row_height(window), + ); + } else { + self.list.splice( + prefix..old.len() - suffix, + keys.len() - prefix - suffix, + ); + } + if let Some(top) = top + && let Some(row) = keys.iter().position( + |key| matches!(key, RowKey::Line { number, .. } if *number >= top), + ) + { + let same = matches!( + keys[row], + RowKey::Line { number, .. } if number == top + ); + self.list.scroll_to(ListOffset { + item_ix: row, + offset_in_item: if same { + scroll_top.offset_in_item + } else { + px(0.0) + }, + }); + } + self.list_keys = keys; + if self.live { + self.list.scroll_to_end(); + } + } + + /// Scrolls so row `row` is near the top, with a little above it. + fn reveal_row(&self, row: usize) { + self.list.scroll_to(ListOffset { + item_ix: row.saturating_sub(REVEAL_ABOVE), + offset_in_item: px(0.0), + }); + } + + /// Scrolls to the current match. + fn reveal_active(&self) { + if let Some(row) = self + .view + .active() + .and_then(|number| self.view.row_of(number)) + { + self.reveal_row(row); + } + } + + pub fn set_live(&mut self, live: bool, cx: &mut Context<'_, Self>) { + self.live = live; + if live { + self.new_lines = 0; + self.new_errors = 0; + self.list.scroll_to_end(); + } + cx.notify(); + } + + /// Whether the list shows its last row's bottom. + fn at_end(&self) -> bool { + let count = self.list.item_count(); + if count == 0 { + return true; + } + if let Some(end) = self.list.is_scrolled_to_end() { + return end; + } + // Not scrollable, or some heights are not known yet. + match self.list.bounds_for_item(count - 1) { + Some(last) => { + last.bottom() <= self.list.viewport_bounds().bottom() + px(1.0) + } + None => self.list.logical_scroll_top().item_ix >= count, + } + } + + // ---- The view's settings --------------------------------------------- + + const fn prefs(&self) -> LogsPrefs { + LogsPrefs { + wrap: self.wrap, + search_mode: self.view.mode, + context_lines: self.view.context, + include_diagnostics: self.include_diagnostics, + error: self.view.shows(Level::Error), + warning: self.view.shows(Level::Warn), + info: self.view.shows(Level::Info), + } + } + + fn save_prefs(&self) { + let Some(path) = &self.prefs_path else { + return; + }; + if let Err(error) = self.prefs().save(path) { + log::warn!( + target: "pwrdisk::logs", + "cannot save the Logs window's view: {error}" + ); + } + } + + pub fn set_wrap(&mut self, wrap: bool, cx: &mut Context<'_, Self>) { + self.wrap = wrap; + self.h_offset = 0.0; + // Every row's height changes. + self.list.remeasure(); + if self.live { + self.list.scroll_to_end(); + } + self.save_prefs(); + cx.notify(); + } + + pub fn set_mode(&mut self, mode: SearchMode, cx: &mut Context<'_, Self>) { + self.view.set_mode(mode); + self.pending_reveal = Reveal::Active; + self.save_prefs(); + cx.notify(); + } + + pub fn set_context(&mut self, lines: usize, cx: &mut Context<'_, Self>) { + self.context_open = false; + self.view.set_context(lines); + self.pending_reveal = Reveal::Active; + self.save_prefs(); + cx.notify(); + } + + pub fn toggle_level(&mut self, level: Level, cx: &mut Context<'_, Self>) { + self.view.toggle_level(level); + self.save_prefs(); + cx.notify(); + } + + fn toggle_diagnostics(&mut self, cx: &mut Context<'_, Self>) { + self.include_diagnostics = !self.include_diagnostics; + self.save_prefs(); + cx.notify(); + } + + // ---- Search ---------------------------------------------------------- + + #[cfg(test)] + pub fn scroll_offset(&self) -> Pixels { + self.list.scroll_px_offset_for_scrollbar().y + } + + /// The search field, for the tests to type into. + #[cfg(test)] + pub fn search_state(&self) -> Entity { + self.search.clone() + } + + /// The field changed. Cleared (Esc), the window stays on the line that + /// was the current match, now among all the others. + fn query_changed(&mut self, query: &str) { + // The field reports Enter as a change too, with the same text: that + // must not send the search back to its first match. + if query == self.query { + return; + } + query.clone_into(&mut self.query); + let back = self.view.active(); + self.view.set_query(query); + if self.view.searching() { + // Reading a search's results, not the tail. + self.live = false; + self.pending_reveal = Reveal::Active; + } else if !self.live { + self.pending_reveal = back.map_or(Reveal::None, Reveal::Line); + } + } + + /// Enter and Shift-Enter, and the field's chevrons. + pub fn step(&mut self, forward: bool, cx: &mut Context<'_, Self>) { + if self.view.step(forward).is_none() { + return; + } + self.live = false; + self.reveal_active(); + cx.notify(); + } + + fn open_gap(&mut self, first: usize, cx: &mut Context<'_, Self>) { + self.view.open_gap(first); + cx.notify(); + } + + // ---- Mark ------------------------------------------------------------ + + /// Drops the mark after the newest line, labelled with the time. + pub fn mark(&mut self, cx: &mut Context<'_, Self>) { + let now = chrono::Local::now().format("%H:%M:%S").to_string(); + self.view.set_mark(now); + cx.notify(); + } + + fn clear_mark(&mut self, cx: &mut Context<'_, Self>) { + self.view.clear_mark(); + cx.notify(); + } + + /// Selects every line after the mark; the selection then grows as new + /// lines come in. + pub fn select_since_mark( + &mut self, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) { + if let Some(range) = self.view.since_mark() { + self.selection = Some(range); + self.follows_tail = true; + window.focus(&self.focus, cx); + cx.notify(); + } + } + + // ---- Selection and copy ---------------------------------------------- + + fn set_note( + &mut self, + note: impl Into, + cx: &mut Context<'_, Self>, + ) { + self.note_generation += 1; + let generation = self.note_generation; + self.note = Some((note.into(), generation)); + cx.spawn(async move |this, cx| { + cx.background_executor().timer(NOTE_FOR).await; + let _ = this.update(cx, |this, cx| { + if this.note.as_ref().is_some_and(|(_, g)| *g == generation) { + this.note = None; + cx.notify(); + } + }); + }) + .detach(); + cx.notify(); + } + + /// The selected range, low to high, by number. + fn selected(&self) -> Option<(usize, usize)> { + self.selection.map(|(a, b)| (a.min(b), a.max(b))) + } + + /// The shown lines inside the selection, as indexes into the view. + fn selected_indexes(&self) -> Vec { + let Some((low, high)) = self.selected() else { + return Vec::new(); + }; + let first = self.view.first_number; + self.view + .visible() + .iter() + .copied() + .filter(|index| (low..=high).contains(&(first + index))) + .collect() + } + + /// A click in the gutter selects line `number`; with Shift it extends + /// the selection from its anchor. + pub fn click_number( + &mut self, + number: usize, + extend: bool, + cx: &mut Context<'_, Self>, + ) { + self.selection = match (self.selection, extend) { + (Some((anchor, _)), true) => Some((anchor, number)), + _ => Some((number, number)), + }; + self.follows_tail = extend && self.view.newest() == Some(number); + cx.notify(); + } + + pub fn select_all(&mut self, cx: &mut Context<'_, Self>) { + let visible = self.view.visible(); + if let (Some(first), Some(last)) = (visible.first(), visible.last()) { + let base = self.view.first_number; + self.selection = Some((base + first, base + last)); + self.follows_tail = false; + cx.notify(); + } + } + + /// The selection on the clipboard, after the diagnostics report when + /// asked: what a bug report wants. Neither holds a scanned path. + pub fn copy_selection(&mut self, cx: &mut Context<'_, Self>) { + let indexes = self.selected_indexes(); + if indexes.is_empty() { + return; + } + let mut out = String::new(); + if self.include_diagnostics { + out.push_str(&crate::diagnostics::collect(cx).report()); + out.push('\n'); + out.push_str(&self.copy_header(&indexes)); + out.push('\n'); + } + for &index in &indexes { + out.push_str(self.view.lines[index].raw()); + out.push('\n'); + } + cx.write_to_clipboard(ClipboardItem::new_string(out)); + let count = indexes.len(); + let lines = if count == 1 { "line" } else { "lines" }; + let with = if self.include_diagnostics { + " with diagnostics" + } else { + "" + }; + self.set_note(format!("Copied {count} {lines}{with}"), cx); + } + + /// "Log lines: 215–219 (5 of 1,204; levels: Error, Warning, Info)", + /// and the search with its mode while one is active. + fn copy_header(&self, indexes: &[usize]) -> String { + let first = self.view.first_number; + let low = indexes.first().map_or(0, |index| first + index); + let high = indexes.last().map_or(0, |index| first + index); + let levels: Vec<&str> = Level::ALL + .into_iter() + .filter(|level| self.view.shows(*level)) + .map(Level::label) + .collect(); + let mut header = format!( + "Log lines: {low}\u{2013}{high} ({} of {}; levels: {})\n", + thousands(indexes.len()), + thousands(self.view.lines.len()), + levels.join(", ") + ); + if self.view.searching() { + let context = if self.view.mode == SearchMode::Filter + && self.view.context > 0 + { + format!(", context \u{b1}{}", self.view.context) + } else { + String::new() + }; + let _ = writeln!( + header, + "Log search: \"{}\" ({}{context})", + self.query.trim(), + self.view.mode.label() + ); + } + header + } + + fn copy_path(&mut self, cx: &mut Context<'_, Self>) { + if let Some(tail) = &self.tail { + cx.write_to_clipboard(ClipboardItem::new_string( + tail.path.display().to_string(), + )); + self.set_note("Copied the log file path", cx); + } + } + + // ---- Keys and scrolling ---------------------------------------------- + + /// The window's keys, while the search field does not have them: it + /// edits, Enter steps through the matches and Esc clears it. + fn key( + &mut self, + event: &KeyDownEvent, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) { + if self.search.focus_handle(cx).is_focused(window) { + return; + } + let keystroke = &event.keystroke; + let command = + keystroke.modifiers.platform || keystroke.modifiers.control; + match (command, keystroke.key.as_str()) { + (true, "f") => { + self.search + .update(cx, |search, cx| search.focus(window, cx)); + } + (true, "a") => self.select_all(cx), + (true, "c") => self.copy_selection(cx), + (false, "pageup" | "pagedown") => { + // Four fifths of the view, so a line on the edge stays in + // sight across the page and a long wrapped line can be read + // a screen at a time. + let page = self.list.viewport_bounds().size.height * 0.8; + self.live = false; + self.list.scroll_by(if keystroke.key == "pageup" { + -page + } else { + page + }); + cx.notify(); + } + (false, "up" | "down" | "home" | "end") => { + let numbers: Vec<_> = self + .view + .rows() + .iter() + .filter_map(|row| match row { + Row::Line { index, .. } => { + Some(self.view.first_number + index) + } + _ => None, + }) + .collect(); + if let Some(last) = numbers.len().checked_sub(1) { + let at = self.selection.and_then(|(_, number)| { + numbers.iter().position(|n| *n == number) + }); + // With nothing selected yet, moving down starts at + // the first line and moving up at the last, rather + // than stepping past either. + let next = match (keystroke.key.as_str(), at) { + ("end", _) | ("up", None) => last, + ("home", _) | (_, None) => 0, + ("up", Some(at)) => at.saturating_sub(1), + (_, Some(at)) => (at + 1).min(last), + }; + let number = numbers[next]; + self.click_number(number, keystroke.modifiers.shift, cx); + self.live = false; + if keystroke.key == "end" { + self.list.scroll_to_end(); + } else if let Some(row) = self.view.row_of(number) { + self.reveal_row(row); + } + cx.notify(); + } + } + (false, "escape") => { + self.selection = None; + self.context_open = false; + cx.notify(); + } + _ => return, + } + cx.stop_propagation(); + } + + /// The list scrolled first (its handler runs before this one); this + /// pauses when that left the end, resumes when it reached it, and moves + /// unwrapped text sideways. + fn scrolled( + &mut self, + event: &ScrollWheelEvent, + window: &Window, + cx: &mut Context<'_, Self>, + ) { + let delta = event.delta.pixel_delta(Self::row_height(window)); + let (dx, dy) = (delta.x.as_f32(), delta.y.as_f32()); + if !self.wrap && dx != 0.0 { + let offset = (self.h_offset - dx).clamp(0.0, self.h_max); + if (offset - self.h_offset).abs() > f32::EPSILON { + self.h_offset = offset; + cx.notify(); + } + } + if dy > 0.0 && self.live && !self.at_end() { + // Scrolled up: stop following. + self.live = false; + cx.notify(); + } else if dy < 0.0 + && !self.live + && !self.view.searching() + && self.scrollable() + && self.at_end() + { + // Scrolled back down to the end of a list that scrolls; one that + // fits stays paused until Live or the pill. + self.set_live(true, cx); + } + } + + /// Whether the rows are taller than the viewport. + fn scrollable(&self) -> bool { + self.list.max_offset_for_scrollbar().y > px(0.0) + } + + /// The face the lines are drawn in, for measuring them. + fn mono_font(cx: &App) -> Font { + gpui_kit::font(cx.omarchy().mono_font.clone()) + } + + /// The hanging indent of a wrapped line's continuation rows. + fn indent(window: &Window) -> Pixels { + window.rem_size() * space::LG.0 + } + + /// Where `raw` breaks into rows when wrapped: byte ranges, one per row. + /// Every row wraps to the room left after the hanging indent, so a + /// continuation fits beside it. + pub fn segments( + &self, + raw: &str, + window: &Window, + cx: &App, + ) -> Vec> { + let width = + self.text_width - Self::indent(window).as_f32() - self.char_width; + if raw.is_empty() || width < self.char_width * 8.0 { + return std::iter::once(0..raw.len()).collect(); + } + let font_size = window.rem_size() * text::BODY.0; + let mut wrapper = window + .text_system() + .line_wrapper(Self::mono_font(cx), font_size); + let fragments = [LineFragment::text(raw)]; + let mut starts = vec![0]; + starts.extend( + // SameIndent is how GPUI wrapped before the argument existed; + // only the break offsets are used here. + wrapper + .wrap_line(&fragments, px(width), IndentAdjustment::SameIndent) + .map(|boundary| boundary.ix), + ); + starts.push(raw.len()); + starts.dedup(); + starts.windows(2).map(|pair| pair[0]..pair[1]).collect() + } + + /// Measures this frame's room for text and the mono face's advance, + /// and asks the list to measure again when the room changed. + fn measure(&mut self, window: &Window, cx: &App) { + let rem = window.rem_size(); + let to_px = |rems: Rems| (rem * rems.0).as_f32(); + let viewport = self.list.viewport_bounds().size.width.as_f32(); + // Before the first frame the list has no bounds: the window's + // width less the body's padding and the frame's hairlines. + let list_width = if viewport > 0.0 { + viewport + } else { + 2.0f32.mul_add( + -(to_px(space::LG) + 1.0), + window.viewport_size().width.as_f32(), + ) + }; + let text_width = (list_width + - to_px(size::LOG_GUTTER) + - to_px(space::MD) + - to_px(space::LG)) + .max(0.0); + let font_size = rem * text::BODY.0; + let font_id = window.text_system().resolve_font(&Self::mono_font(cx)); + if let Ok(advance) = + window.text_system().advance(font_id, font_size, 'm') + { + self.char_width = advance.width.as_f32(); + } + if (text_width - self.text_width).abs() >= 1.0 { + self.text_width = text_width; + if self.wrap { + self.list.remeasure(); + } + } + #[allow( + clippy::cast_precision_loss, + reason = "a line's width in characters is far below 2^24" + )] + let widest = self.view.widest() as f32; + self.h_max = widest.mul_add(self.char_width, -self.text_width).max(0.0); + self.h_offset = self.h_offset.min(self.h_max); + } +} + +// ---- Drawing -------------------------------------------------------------- + +const fn level_color(level: Level, theme: &Theme) -> Hsla { + match level { + Level::Error => theme.danger, + Level::Warn => theme.warning, + Level::Info => theme.accent, + Level::Debug => theme.secondary, + } +} + +impl Render for LogsWindow { + fn render( + &mut self, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) -> impl IntoElement { + crate::ui::sync_scale(window, cx); + // A test may change the view directly. + self.sync_list(window); + match std::mem::replace(&mut self.pending_reveal, Reveal::None) { + Reveal::None => {} + Reveal::Active => self.reveal_active(), + Reveal::Line(number) => { + if let Some(row) = self.view.row_of(number) { + self.reveal_row(row); + } + } + } + // The Context menu closes with its select. + if self.view.mode != SearchMode::Filter || !self.view.searching() { + self.context_open = false; + } + self.measure(window, cx); + let theme = cx.omarchy().clone(); + let actions = div() + .flex() + .flex_row() + .gap(space::SM) + .child( + button(COPY_PATH_ID, "Copy path", ButtonVariant::Secondary, cx) + .debug_selector(|| COPY_PATH_ID.into()) + .semantic_disabled(self.tail.is_none()) + .on_click(cx.listener(|this, _, _, cx| this.copy_path(cx))), + ) + .child( + button(REVEAL_ID, "Reveal", ButtonVariant::Secondary, cx) + .debug_selector(|| REVEAL_ID.into()) + .semantic_disabled(self.tail.is_none()) + .on_click(cx.listener(|this, _, _, cx| { + if let Some(tail) = &this.tail { + cx.reveal_path(&tail.path); + } + })), + ); + let content = div() + .id("logs-window") + // The search input consumes Escape itself, clearing its query, + // so the action is caught on the way down: an empty search + // hands the keys back to the reader instead. + .capture_action(cx.listener( + |this, _: &gpui_kit::base::input::Escape, window, cx| { + if this.search.read(cx).value().is_empty() { + window.focus(&this.focus, cx); + cx.stop_propagation(); + } + }, + )) + .track_focus(&self.focus) + .role(gpui_kit::Role::Group) + .aria_label(READER_LABEL) + .on_key_down(cx.listener( + |this, event: &KeyDownEvent, window, cx| { + this.key(event, window, cx); + }, + )) + .flex() + .flex_col() + .size_full() + .child(self.toolbar(&theme, window, cx)) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_h_0() + .px(space::LG) + .pb(space::SM) + .child(self.viewport(&theme, cx)), + ) + .child(self.status_bar(&theme)); + aux_window::frame(&["Help", "Logs"], actions, content, window, cx) + } +} + +/// What the next frame scrolls to, once the list knows the new rows. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Reveal { + #[default] + None, + /// The current match. + Active, + /// A line, by number. + Line(usize), +} + +impl LogsWindow { + fn toolbar( + &self, + theme: &Theme, + window: &Window, + cx: &mut Context<'_, Self>, + ) -> impl IntoElement { + let search = gpui_omarchy::input(SEARCH_ID, &self.search, window, cx) + .aria_label("Search log text").aria_description("Enter moves to the next match; Shift Enter to the previous match. Tab moves to log controls. Escape clears the query.") + .aria_value(self.search.read(cx).value()) + .debug_selector(|| SEARCH_ID.into()) + .prefix( + icon(IconName::Search) + .size(icon_size::SM) + .text_color(theme.secondary), + ) + .suffix(self.search_trailing(theme, cx)); + let mode = [ + ( + SearchMode::Filter, + FILTER_ID, + "Filter", + "Show only matching lines", + ), + ( + SearchMode::Highlight, + HIGHLIGHT_ID, + "Highlight", + "Show every line and highlight matches", + ), + ] + .into_iter() + .fold(segmented(theme), |seg, (mode, id, label, hint)| { + seg.child(with_tooltip( + // One of two, so radio buttons; the levels are checkboxes. + segment( + id, + label, + self.view.mode == mode, + gpui_kit::Role::RadioButton, + theme, + ) + .on_key_down(cx.listener( + move |this, event: &KeyDownEvent, _, cx| { + if matches!( + event.keystroke.key.as_str(), + "enter" | "space" + ) { + this.set_mode(mode, cx); + cx.stop_propagation(); + } + }, + )) + .on_click(cx.listener( + move |this, _, _, cx| { + this.set_mode(mode, cx); + }, + )), + hint, + )) + }); + let levels = + Level::ALL.into_iter().fold(segmented(theme), |seg, level| { + let on = self.view.shows(level); + let count = match level { + Level::Error | Level::Warn => self.view.count(level), + Level::Info | Level::Debug => 0, + }; + let label = if count > 0 { + format!("{} {}", level.label(), thousands(count)) + } else { + level.label().to_owned() + }; + let id = level_id(level); + seg.child( + segment(id, label, on, gpui_kit::Role::CheckBox, theme) + .on_key_down(cx.listener( + move |this, event: &KeyDownEvent, _, cx| { + if matches!( + event.keystroke.key.as_str(), + "enter" | "space" + ) { + this.toggle_level(level, cx); + cx.stop_propagation(); + } + }, + )) + .when(on, |item| { + item.text_color(level_color(level, theme)) + }) + .on_click(cx.listener(move |this, _, _, cx| { + this.toggle_level(level, cx); + })), + ) + }); + let wrap = with_tooltip( + button(WRAP_ID, "Wrap", ButtonVariant::Outline, cx) + .debug_selector(|| WRAP_ID.into()) + .selected(self.wrap) + .on_click(cx.listener(|this, _, _, cx| { + let wrap = !this.wrap; + this.set_wrap(wrap, cx); + })), + "Wrap long lines; off, they scroll sideways", + ); + let mark = with_tooltip( + button(MARK_ID, "Mark", ButtonVariant::Outline, cx) + .debug_selector(|| MARK_ID.into()) + .on_click(cx.listener(|this, _, _, cx| this.mark(cx))), + "Drop a mark after the newest line", + ); + let live = with_tooltip( + button( + LIVE_ID, + if self.live { "Live" } else { "Paused" }, + ButtonVariant::Outline, + cx, + ) + .debug_selector(|| LIVE_ID.into()) + .selected(self.live) + .on_click(cx.listener(|this, _, _, cx| { + let live = !this.live; + this.set_live(live, cx); + })), + if self.live { + "Pause the live log" + } else { + "Follow the log again" + }, + ); + let show_context = + self.view.mode == SearchMode::Filter && self.view.searching(); + div() + .debug_selector(|| "logs-toolbar".into()) + .flex() + .flex_row() + .flex_wrap() + .items_center() + .gap(space::SM) + .px(space::LG) + .py(space::SM) + .child( + div() + // A zero flex basis lets the other controls consume the + // row and squeeze the input to its search icon at 200%. + .flex_grow(1.) + .min_w(size::LOG_FILTER) + .w(size::LOG_FILTER) + .max_w_full() + .child(search), + ) + .child(mode) + .when(show_context, |bar| { + bar.child(self.context_select(theme, cx)) + }) + .child(levels) + .child(div().w(px(1.)).h(size::LOG_ROW).bg(theme.divider())) + .child(wrap) + .child(mark) + .child(live) + } + + /// Inside the search field: the shortcut while empty; the current + /// match as "1 of 4" and the previous and next chevrons while + /// searching. + fn search_trailing( + &self, + theme: &Theme, + cx: &Context<'_, Self>, + ) -> AnyElement { + if !self.view.searching() { + let hint = if cfg!(target_os = "macos") { + "\u{2318}F" + } else { + "Ctrl+F" + }; + return caption(hint, theme.secondary, theme).into_any_element(); + } + let count = self.view.match_count(); + let label = self.view.active_place().map_or_else( + || "No matches".to_owned(), + |place| format!("{place} of {}", thousands(count)), + ); + let step = |id: &'static str, name: IconName, hint: &'static str| { + let forward = id == NEXT_ID; + with_tooltip( + gpui_omarchy::icon_button( + id, + name, + hint, + ButtonVariant::Secondary, + cx, + ) + // The stock padding makes the chevrons taller than the + // field's text, so the toolbar would grow the moment a + // search starts; trimmed, the field keeps its height. + .py(space::XXS) + .debug_selector(move || id.into()) + .semantic_disabled(count == 0) + .on_click(cx.listener( + move |this, _, _, cx| { + this.step(forward, cx); + }, + )), + hint, + ) + }; + div() + .flex() + .flex_row() + .items_center() + .gap(space::XXS) + .child(div().mr(space::XS).child(caption( + label, + theme.secondary, + theme, + ))) + .child(step( + PREV_ID, + IconName::ChevronUp, + "Previous match (Shift-Enter)", + )) + .child(step(NEXT_ID, IconName::ChevronDown, "Next match (Enter)")) + .into_any_element() + } + + /// Context: lines kept around each match, in Filter mode with a query. + fn context_select( + &self, + theme: &Theme, + cx: &Context<'_, Self>, + ) -> impl IntoElement { + let menu = CONTEXT_CHOICES.into_iter().fold( + div() + .id("logs-context-menu") + .debug_selector(|| "logs-context-menu".into()) + // It drops over the lines; without this a scroll on it + // moved them, and the line beneath took the hover. + .occlude() + .absolute() + .top_full() + .left_0() + .mt(space::XS) + .w(size::LOG_CONTEXT_MENU) + .flex() + .flex_col() + .py(space::XS) + .border_1() + .border_color(theme.border) + .bg(theme.surface) + .shadow_lg() + .on_mouse_down_out(cx.listener(|this, _, _, cx| { + this.context_open = false; + cx.notify(); + })), + |menu, lines| { + let id = SharedString::from(format!("logs-context-{lines}")); + let selector = id.clone(); + menu.child( + div() + .id(id) + .debug_selector(move || selector.to_string()) + .role(gpui_kit::Role::MenuItem) + .aria_label(context_label(lines)) + .focusable() + .tab_stop(true) + .on_key_down(cx.listener( + move |this, event: &KeyDownEvent, _, cx| { + if matches!( + event.keystroke.key.as_str(), + "enter" | "space" + ) { + this.set_context(lines, cx); + cx.stop_propagation(); + } + }, + )) + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .px(space::MD) + .py(space::XS) + .cursor_pointer() + .hover(|row| row.bg(theme.hover_fill())) + .child(div().w(icon_size::MD).when( + lines == self.view.context, + |mark| { + mark.child( + icon(IconName::Check) + .size(icon_size::SM) + .text_color(theme.accent), + ) + }, + )) + .child(context_label(lines)) + .on_click(cx.listener(move |this, _, _, cx| { + this.set_context(lines, cx); + })), + ) + }, + ); + div() + .relative() + .flex_none() + .child(with_tooltip( + button( + CONTEXT_ID, + format!("{} \u{25be}", context_label(self.view.context)), + ButtonVariant::Outline, + cx, + ) + .debug_selector(|| CONTEXT_ID.into()) + .selected(self.context_open) + // Capture runs before the open menu's press-outside handler + // closes it. + .capture_any_mouse_down(cx.listener(|this, _, _, _| { + this.context_was_open = this.context_open; + })) + .on_click(cx.listener(|this, _, _, cx| { + this.context_open = !this.context_was_open; + cx.notify(); + })), + "Lines kept around each match", + )) + .when(self.context_open, |select| select.child(deferred(menu))) + } + + fn viewport( + &self, + theme: &Theme, + cx: &Context<'_, Self>, + ) -> impl IntoElement { + let frame = div() + .relative() + .flex_1() + .min_h_0() + .border_1() + .border_color(theme.divider()) + .bg(theme.inset) + .overflow_hidden(); + if let Some(problem) = &self.problem { + return frame.child( + crate::semantics::text("logs-problem", problem.clone()) + .role(gpui_kit::Role::Alert) + .child(centered(problem.clone(), theme)), + ); + } + if self.view.lines.is_empty() { + return frame.child( + crate::semantics::text("logs-empty", "No log output yet.") + .child(centered("No log output yet.", theme)), + ); + } + if self.view.rows().is_empty() { + return frame.child( + crate::semantics::text("logs-no-matches", "No lines match.") + .child(centered("No lines match.", theme)), + ); + } + let rows = list( + self.list.clone(), + cx.processor(|this, row: usize, window, cx| { + this.row(row, window, cx) + }), + ) + .size_full() + .py(space::XS); + frame + .child( + div() + .id("logs-viewport") + .debug_selector(|| "logs-viewport".into()) + .role(gpui_kit::Role::ListBox) + .aria_label(format!( + "{}; {}; {}", + self.view.summary(), + if self.live { + "following live" + } else { + "paused" + }, + self.selected().map_or_else( + || "no selection".into(), + |(low, high)| format!( + "selected lines {low} through {high}" + ) + ) + )) + .size_full() + .on_scroll_wheel(cx.listener( + |this, event: &ScrollWheelEvent, window, cx| { + this.scrolled(event, window, cx); + }, + )) + .child(rows), + ) + .when(!self.live && self.new_lines > 0, |frame| { + frame.child(self.pill(theme, cx)) + }) + .when(self.selection.is_some(), |frame| { + frame.child(self.selection_bar(theme, cx)) + }) + } + + fn row( + &self, + row: usize, + window: &Window, + cx: &Context<'_, Self>, + ) -> AnyElement { + let theme = cx.omarchy().clone(); + match self.view.rows().get(row).copied() { + Some(Row::Line { index, shown }) => { + self.line_row(index, shown, &theme, window, cx) + } + Some(Row::Gap { first, count }) => { + gap_row(first, count, &theme, cx) + } + Some(Row::Mark) => self.mark_row(&theme, cx), + None => div().into_any_element(), + } + } + + fn line_row( + &self, + index: usize, + shown: Shown, + theme: &Theme, + window: &Window, + cx: &Context<'_, Self>, + ) -> AnyElement { + let line = &self.view.lines[index]; + let number = self.view.first_number + index; + let selected = self + .selected() + .is_some_and(|(low, high)| (low..=high).contains(&number)); + let context = shown == Shown::Context; + let background = if selected { + Some(theme.selection) + } else if context { + None + } else { + match line.level { + Level::Error => Some(theme.danger.opacity(0.1)), + Level::Warn => Some(theme.warning.opacity(0.08)), + Level::Info | Level::Debug => None, + } + }; + let raw = line.raw().clone(); + let mut highlights = Vec::new(); + // Context lines are muted whole: no token colours. + if !line.time.is_empty() && !context { + highlights.push(( + 0..line.time.len(), + HighlightStyle { + color: Some(theme.secondary), + ..Default::default() + }, + )); + highlights.push(( + line.level_range.clone(), + HighlightStyle { + color: Some(level_color(line.level, theme)), + font_weight: matches!( + line.level, + Level::Error | Level::Warn + ) + .then_some(FontWeight::BOLD), + ..Default::default() + }, + )); + if let Some(target) = line.target_range.clone() { + highlights.push(( + target, + HighlightStyle { + color: Some(theme.foreground), + ..Default::default() + }, + )); + } + } + // Search hits on top, never overlapping the styles above: GPUI + // wants the ranges in order and apart, so hits replace them. The + // current match's first hit is solid. + if shown == Shown::Match { + let active = self.view.active() == Some(number); + let hits = search_hits(line, &self.query); + if !hits.is_empty() { + let styled: Vec<_> = hits + .into_iter() + .enumerate() + .map(|(at, hit)| (hit, hit_style(active && at == 0, theme))) + .collect(); + highlights = merge_hits(highlights, &styled); + } + } + let ink = if context { + theme.secondary + } else { + theme.bright + }; + let body = if self.wrap { + let segments = self.segments(&raw, window, cx); + div().flex().flex_col().children( + segments.into_iter().enumerate().map(|(at, range)| { + let part = clip_highlights(&highlights, &range); + line_text(raw[range].to_owned().into(), part, ink, theme) + .when(at > 0, |row| row.pl(space::LG)) + }), + ) + } else { + div().overflow_hidden().child( + line_text(raw, highlights, ink, theme) + // Scrolled sideways by the pointer. + .ml(px(-self.h_offset)) + .debug_selector(move || format!("log-text-{number}")), + ) + }; + div() + .id(("log-row", number)) + .debug_selector(move || format!("log-row-{number}")) + .role(gpui_kit::Role::ListBoxOption) + .aria_label(format!( + "Line {number}: {}{}", + line.raw(), + if context { "; context line" } else { "" } + )) + .aria_selected(selected) + .when( + self.selection.is_some_and(|(_, end)| end == number), + gpui_kit::StatefulInteractiveElement::aria_active_descendant, + ) + .w_full() + .flex() + .flex_row() + .when_some(background, gpui_kit::Styled::bg) + .child( + div() + .id(("log-number", number)) + .debug_selector(move || format!("log-number-{number}")) + .w(size::LOG_GUTTER) + .h(size::LOG_ROW) + .flex() + .flex_none() + .items_center() + .justify_end() + .pr(space::SM) + .border_r_1() + .border_color(theme.divider()) + .when(selected, |gutter| { + gutter.border_l_2().border_color(theme.accent) + }) + .cursor_pointer() + .hover(|gutter| gutter.bg(theme.hover_fill())) + .child(caption( + number.to_string(), + if selected { + theme.accent + } else { + theme.secondary + }, + theme, + )) + .on_mouse_down( + MouseButton::Left, + cx.listener( + move |this, event: &MouseDownEvent, window, cx| { + // The lines take the keys now: Copy, Select + // All and Esc are the selection's. + window.focus(&this.focus, cx); + this.click_number( + number, + event.modifiers.shift, + cx, + ); + }, + ), + ), + ) + .child( + div() + .flex_1() + .min_w_0() + .pl(space::MD) + .pr(space::LG) + .child(body), + ) + .into_any_element() + } + + /// "Mark · 12:39:00", the rule, Select since mark and remove. + fn mark_row(&self, theme: &Theme, cx: &Context<'_, Self>) -> AnyElement { + let label = self + .view + .mark() + .map(|mark| format!("Mark \u{b7} {}", mark.label)) + .unwrap_or_default(); + let since = self.view.since_mark().is_some(); + div() + .id("log-mark") + .debug_selector(|| "log-mark".into()) + .h(size::LOG_MARK) + .w_full() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .pl(size::LOG_GUTTER) + .pr(space::LG) + .child( + div() + .pl(space::MD) + .text_size(text::CAPTION) + .font_weight(FontWeight::SEMIBOLD) + .text_color(theme.accent) + .child(label), + ) + .child(div().flex_1().h(px(1.)).bg(theme.accent.opacity(0.5))) + .child( + button( + SINCE_MARK_ID, + "Select since mark", + ButtonVariant::Outline, + cx, + ) + .debug_selector(|| SINCE_MARK_ID.into()) + .semantic_disabled(!since) + .on_click(cx.listener( + |this, _, window, cx| { + this.select_since_mark(window, cx); + }, + )), + ) + .child(with_tooltip( + gpui_omarchy::icon_button( + CLEAR_MARK_ID, + IconName::Close, + "Remove the mark", + ButtonVariant::Secondary, + cx, + ) + .debug_selector(|| CLEAR_MARK_ID.into()) + .on_click(cx.listener(|this, _, _, cx| this.clear_mark(cx))), + "Remove the mark", + )) + .into_any_element() + } + + /// "↓ 12 new lines · 1 error", while paused; a click follows again. + fn pill(&self, theme: &Theme, cx: &Context<'_, Self>) -> impl IntoElement { + let lines = if self.new_lines == 1 { "line" } else { "lines" }; + let mut label = + format!("\u{2193} {} new {lines}", thousands(self.new_lines)); + if self.new_errors > 0 { + let errors = if self.new_errors == 1 { + "error" + } else { + "errors" + }; + let _ = write!(label, " \u{b7} {} {errors}", self.new_errors); + } + div() + .absolute() + .bottom(if self.selection.is_some() { + size::LOG_PILL_ABOVE_BAR + } else { + space::LG + }) + .left_0() + .right_0() + .flex() + .justify_center() + .child( + div() + .id(PILL_ID) + .debug_selector(|| PILL_ID.into()) + // Over the lines, as the selection bar is: it takes the + // pointer but lets a scroll through. + .block_mouse_except_scroll() + .px(space::LG) + .py(space::XS) + .border_1() + .border_color(theme.accent) + .bg(theme.surface) + .shadow_lg() + .cursor_pointer() + .text_color(theme.accent) + .font_weight(FontWeight::SEMIBOLD) + .child(label) + .on_click( + cx.listener(|this, _, _, cx| this.set_live(true, cx)), + ), + ) + } + + fn selection_bar( + &self, + theme: &Theme, + cx: &Context<'_, Self>, + ) -> impl IntoElement { + let indexes = self.selected_indexes(); + let first = self.view.first_number; + let since_mark = self.view.since_mark().is_some() + && self.selected() == self.view.since_mark(); + let lines = |count: usize| if count == 1 { "line" } else { "lines" }; + let label = match indexes.as_slice() { + [] => "No shown lines selected".to_owned(), + many if since_mark => format!( + "{} {} since mark", + thousands(many.len()), + lines(many.len()) + ), + [only] => format!("Line {}", first + only), + many => format!("{} lines selected", thousands(many.len())), + }; + let range = match (indexes.first(), indexes.last()) { + (Some(low), Some(high)) if low != high => { + Some(format!("{}\u{2013}{}", first + low, first + high)) + } + _ => None, + }; + let check = if self.include_diagnostics { + "\u{2611}" + } else { + "\u{2610}" + }; + let copy_keys = if cfg!(target_os = "macos") { + "\u{2318}C" + } else { + "Ctrl+C" + }; + div() + .absolute() + .bottom(space::LG) + .left_0() + .right_0() + .flex() + .justify_center() + .child( + div() + .id("logs-selection-bar") + .debug_selector(|| "logs-selection-bar".into()) + // It floats over the lines: a press on it must not pick + // the line number beneath, though a scroll still moves + // the lines, as it would anywhere over them. + .block_mouse_except_scroll() + .flex() + .flex_row() + .items_center() + .gap(space::MD) + .py(space::XS) + .pl(space::LG) + .pr(space::SM) + .border_1() + .border_color(theme.border) + .bg(theme.surface) + .shadow_lg() + .child(div().text_color(theme.bright).child(label)) + .when_some(range, |bar, range| { + bar.child(caption(range, theme.secondary, theme)) + }) + .child(with_tooltip( + div() + .id(DIAGNOSTICS_ID) + .debug_selector(|| DIAGNOSTICS_ID.into()) + .role(gpui_kit::Role::CheckBox) + .aria_label( + "Include diagnostics in copied log selection", + ) + .aria_toggled(if self.include_diagnostics { + gpui_kit::accesskit::Toggled::True + } else { + gpui_kit::accesskit::Toggled::False + }) + .focusable() + .tab_stop(true) + .on_key_down(cx.listener( + |this, event: &KeyDownEvent, _, cx| { + if matches!( + event.keystroke.key.as_str(), + "enter" | "space" + ) { + this.toggle_diagnostics(cx); + cx.stop_propagation(); + } + }, + )) + .flex() + .flex_row() + .items_center() + .gap(space::XS) + .cursor_pointer() + .text_color(theme.foreground) + .child(check) + .child("Include diagnostics") + .on_click(cx.listener(|this, _, _, cx| { + this.toggle_diagnostics(cx); + })), + "Start the copy with Copy Diagnostics Info's report", + )) + .child(with_tooltip( + button(COPY_ID, "Copy", ButtonVariant::Primary, cx) + .debug_selector(|| COPY_ID.into()) + .semantic_disabled(indexes.is_empty()) + .on_click(cx.listener(|this, _, _, cx| { + this.copy_selection(cx); + })), + copy_keys, + )) + .child( + gpui_omarchy::icon_button( + "logs-clear-selection", + IconName::Close, + "Clear the selection", + ButtonVariant::Secondary, + cx, + ) + .on_click(cx.listener( + |this, _, _, cx| { + this.selection = None; + cx.notify(); + }, + )), + ), + ) + } + + fn status_bar(&self, theme: &Theme) -> impl IntoElement { + let mut summary = + if !self.live && self.new_lines > 0 && !self.view.searching() { + format!( + "Paused \u{b7} {} new since you scrolled", + thousands(self.new_lines) + ) + } else { + self.view.summary() + }; + if self.view.truncated { + let _ = write!( + summary, + " \u{b7} the newest {}", + thousands(crate::log_view::MAX_LINES) + ); + } + let searching = self.view.searching(); + let place = self.tail.as_ref().filter(|_| !searching).map(|tail| { + format!( + "{} \u{b7} rotates at 1 MB to main.old.log", + crate::marks::display_path( + &tail.path, + std::env::home_dir().as_deref(), + PathStyle::Native + ) + ) + }); + div() + .flex() + .flex_row() + .flex_wrap() + .flex_none() + .items_center() + .gap(space::MD) + .px(space::LG) + .py(space::XS) + .border_t_1() + .border_color(theme.divider()) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child( + crate::semantics::text( + "logs-summary", + format!( + "{}; {}; {}", + summary, + if self.live { + "following live" + } else { + "paused" + }, + self.selected().map_or_else( + || "no selection".into(), + |(low, high)| format!( + "selected lines {low} through {high}" + ) + ) + ), + ) + .debug_selector(|| "logs-count".into()) + .child(summary), + ) + // The path fills the middle; without it a spacer keeps the note + // and the search hint at the right edge. + .map(|bar| match place { + Some(place) => bar.child( + crate::semantics::text("logs-path", place.clone()) + .flex_1() + .min_w_0() + .truncate() + .child(place), + ), + None => bar.child(div().flex_1()), + }) + .when_some(self.note.as_ref(), |bar, (note, _)| { + bar.child( + div() + .text_color(theme.success) + .child(format!("\u{2713} {note}")), + ) + }) + .when(searching, |bar| bar.child(SEARCH_HINT)) + } +} + +/// "No context", "Context ±3". +fn context_label(lines: usize) -> String { + if lines == 0 { + "No context".to_owned() + } else { + format!("Context \u{b1}{lines}") + } +} + +const fn level_id(level: Level) -> &'static str { + match level { + Level::Error => "logs-level-error", + Level::Warn => "logs-level-warn", + Level::Info => "logs-level-info", + Level::Debug => "logs-level-debug", + } +} + +/// A row of segments sharing one border: the search mode and the levels. +fn segmented(theme: &Theme) -> gpui_kit::Div { + div() + .flex() + .flex_row() + .flex_none() + .border_1() + .border_color(theme.border) +} + +/// One segment: on, it takes the accent's fill. +fn segment( + id: &'static str, + label: impl Into, + on: bool, + role: gpui_kit::Role, + theme: &Theme, +) -> gpui_kit::Stateful { + let label = label.into(); + div() + .id(id) + .debug_selector(move || id.into()) + .role(role) + .aria_label(label.clone()) + .aria_toggled(if on { + gpui_kit::accesskit::Toggled::True + } else { + gpui_kit::accesskit::Toggled::False + }) + .focusable() + .tab_stop(true) + .px(space::SM) + .py(space::XS) + .border_r_1() + .border_color(theme.divider()) + .cursor_pointer() + .font_weight(FontWeight::SEMIBOLD) + .text_color(if on { theme.bright } else { theme.secondary }) + .when(on, |item| item.bg(theme.accent.opacity(0.18))) + .hover(|item| item.bg(theme.hover_fill())) + .child(label) +} + +/// "214 lines hidden" between dashed rules; a click shows them. +fn gap_row( + first: usize, + count: usize, + theme: &Theme, + cx: &Context<'_, LogsWindow>, +) -> AnyElement { + let rule = theme.border; + let dashed = move || { + div() + .h(px(1.)) + .border_t_1() + .border_dashed() + .border_color(rule) + }; + let lines = if count == 1 { "line" } else { "lines" }; + with_tooltip( + div() + .id(("log-gap", first)) + .debug_selector(move || format!("log-gap-{first}")) + .h(size::LOG_GAP) + .w_full() + .flex() + .flex_row() + .items_center() + .gap(space::MD) + .pl(size::LOG_GUTTER) + .pr(space::LG) + .cursor_pointer() + .hover(|gap| gap.bg(theme.hover_fill())) + .child(dashed().w(space::LG).ml(space::MD).flex_none()) + .child(caption( + format!("{} {lines} hidden", thousands(count)), + theme.secondary, + theme, + )) + .child(dashed().flex_1()) + .on_click( + cx.listener(move |this, _, _, cx| this.open_gap(first, cx)), + ), + "Show these lines", + ) + .into_any_element() +} + +/// One visual row of a line's text, unwrapped. +fn line_text( + content: SharedString, + highlights: Vec<(Range, HighlightStyle)>, + ink: Hsla, + theme: &Theme, +) -> gpui_kit::Div { + div() + .h(size::LOG_ROW) + .whitespace_nowrap() + .font_family(theme.mono_font.clone()) + .text_size(text::BODY) + .line_height(size::LOG_ROW) + .text_color(ink) + .child(StyledText::new(content).with_highlights(highlights)) +} + +/// Small mono text: numbers, counts and key hints. +fn caption( + content: impl Into, + ink: Hsla, + theme: &Theme, +) -> gpui_kit::Div { + div() + .font_family(theme.mono_font.clone()) + .text_size(text::CAPTION) + .text_color(ink) + .whitespace_nowrap() + .child(content.into()) +} + +fn centered(message: impl Into, theme: &Theme) -> gpui_kit::Div { + div() + .size_full() + .flex() + .items_center() + .justify_center() + .text_color(theme.secondary) + .child(message.into()) +} + +/// A search hit: a soft accent fill, or the current match's solid one. +fn hit_style(current: bool, theme: &Theme) -> HighlightStyle { + if current { + HighlightStyle { + color: Some(theme.on_accent), + background_color: Some(theme.accent), + ..Default::default() + } + } else { + HighlightStyle { + color: Some(theme.bright), + background_color: Some(theme.accent.opacity(0.28)), + ..Default::default() + } + } +} + +/// Byte ranges of each search word in `line`, ignoring case, sorted and +/// merged. Found in the lowercase copy the line keeps for the search, so +/// a frame does not lowercase every row again. +fn search_hits(line: &LogLine, query: &str) -> Vec> { + let lower = line.lower(); + // Lowercasing can change byte lengths outside ASCII; then skip + // highlighting rather than cut a character. + if lower.len() != line.raw().len() { + return Vec::new(); + } + let mut hits: Vec> = Vec::new(); + for word in query.split_whitespace() { + let word = word.to_lowercase(); + let mut from = 0; + while let Some(at) = lower[from..].find(&word) { + let start = from + at; + hits.push(start..start + word.len()); + from = start + word.len().max(1); + } + } + hits.sort_by_key(|range| range.start); + let mut merged: Vec> = Vec::new(); + for hit in hits { + match merged.last_mut() { + Some(last) if hit.start <= last.end => { + last.end = last.end.max(hit.end); + } + _ => merged.push(hit), + } + } + merged +} + +/// The token styles with the search hits laid over them: each hit wins +/// where it falls, and what is left of a token keeps its style. +fn merge_hits( + styles: Vec<(Range, HighlightStyle)>, + hits: &[(Range, HighlightStyle)], +) -> Vec<(Range, HighlightStyle)> { + let mut out = Vec::new(); + for (range, style) in styles { + let mut start = range.start; + for (hit, _) in hits { + if hit.end <= start || hit.start >= range.end { + continue; + } + if hit.start > start { + out.push((start..hit.start, style)); + } + start = hit.end.min(range.end); + } + if start < range.end { + out.push((start..range.end, style)); + } + } + out.extend(hits.iter().cloned()); + out.sort_by_key(|(range, _)| range.start); + out +} + +/// The styles that fall inside `segment`, moved to start at its start. +fn clip_highlights( + highlights: &[(Range, HighlightStyle)], + segment: &Range, +) -> Vec<(Range, HighlightStyle)> { + highlights + .iter() + .filter_map(|(range, style)| { + let start = range.start.max(segment.start); + let end = range.end.min(segment.end); + (start < end) + .then(|| (start - segment.start..end - segment.start, *style)) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hits_are_found_ignoring_case_and_merged() { + assert_eq!( + search_hits( + &LogLine::parse("GitHub said 403; github again"), + "github" + ), + [0..6, 17..23] + ); + // Overlapping words merge into one hit. + let merged = search_hits(&LogLine::parse("abcdef"), "abc cde"); + assert_eq!((merged.len(), merged.first()), (1, Some(&(0..5)))); + assert!(search_hits(&LogLine::parse("anything"), "").is_empty()); + } + + #[test] + fn hits_cut_the_token_styles_they_cross() { + let token = HighlightStyle::default(); + let hit = HighlightStyle { + font_weight: Some(FontWeight::BOLD), + ..Default::default() + }; + let merged = merge_hits(vec![(0..10, token)], &[(3..5, hit)]); + let ranges: Vec<_> = merged.iter().map(|(r, _)| r.clone()).collect(); + assert_eq!(ranges, [0..3, 3..5, 5..10]); + } + + #[test] + fn a_wrapped_rows_styles_are_clipped_to_it() { + let style = HighlightStyle::default(); + let clipped = + clip_highlights(&[(2..8, style), (12..14, style)], &(5..10)); + // Only the first style reaches the row, moved to its start. + assert_eq!(clipped.len(), 1); + assert_eq!(clipped[0].0, 0..3); + } + + #[test] + fn the_view_is_remembered_but_never_debug() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(PREFS_FILE); + assert_eq!(LogsPrefs::load(Some(&path)), LogsPrefs::default()); + let prefs = LogsPrefs { + wrap: false, + search_mode: SearchMode::Highlight, + context_lines: 3, + include_diagnostics: true, + error: true, + warning: false, + info: true, + }; + prefs.save(&path).unwrap(); + assert_eq!(LogsPrefs::load(Some(&path)), prefs); + let saved = std::fs::read_to_string(&path).unwrap(); + assert!(!saved.contains("debug"), "{saved}"); + // A Context the menu lacks, or a broken file, is the default. + std::fs::write(&path, r#"{"contextLines": 4}"#).unwrap(); + assert_eq!(LogsPrefs::load(Some(&path)).context_lines, 0); + std::fs::write(&path, "{").unwrap(); + assert_eq!(LogsPrefs::load(Some(&path)), LogsPrefs::default()); + } +} diff --git a/crates/disktree-app/src/main.rs b/crates/disktree-app/src/main.rs index 904a9319..c73a2c02 100644 --- a/crates/disktree-app/src/main.rs +++ b/crates/disktree-app/src/main.rs @@ -11,19 +11,53 @@ // reach one. Ignored elsewhere. #![windows_subsystem = "windows"] +mod agent; +mod agent_removal; mod app_menu; mod appearance; +mod aux_window; +mod build_info; +mod chrome; +mod cleanup; +mod cleanup_view; +mod diag_log; +mod diagnostics; +mod doc_window; +#[cfg(target_os = "macos")] +mod dock_icon; +mod file_list; mod git; +mod git_store; +mod github_releases; +mod help; +mod ledger; +mod legend; +mod log_view; +#[cfg(debug_assertions)] +mod logs_fixture; +mod logs_window; +mod mark_guard; mod marks; mod palette; +mod placement; mod power; +mod run_list; +mod run_view; +mod safety; +mod semantics; +mod settings; mod state; #[cfg(test)] mod tests; +mod toasts; +mod toolbar; mod treemap_view; mod ui; +mod update_channel; +mod updater; mod views; mod widgets; +mod window_frame; use std::path::PathBuf; #[cfg(target_os = "macos")] @@ -52,11 +86,12 @@ struct Args { } const USAGE: &str = "\ -disktree — a treemap of what is using your disk +PwrDisk — a treemap of what is using your disk -usage: disktree [OPTIONS] [PATH] - disktree ssh HOST [OPTIONS] [PATH] - disktree extract-scanner ARCH OUTPUT +usage: pwrdisk [OPTIONS] [PATH] + pwrdisk ssh HOST [OPTIONS] [PATH] + pwrdisk extract-scanner ARCH OUTPUT + pwrdisk mcp Linux packaged builds deploy an embedded static scanner over SSH on demand. Unbundled development builds need disktree-scan on the remote PATH or in @@ -67,6 +102,8 @@ Use --check with ssh to deploy and scan without opening a window. arguments: PATH explicit directory to scan; omitted opens root selection + mcp serve an AI agent over stdio instead of opening a + window: `claude mcp add pwrdisk -- pwrdisk mcp` Without PATH, choose this computer or SSH, then a mount or directory. No scan starts before explicit acceptance. Nested mounts are excluded. @@ -97,8 +134,28 @@ options: "; fn main() -> Result<()> { + // First: Setup, updates and the uninstaller start pwrdisk.exe with a + // hook argument, which this runs and then exits, before a console or a + // window could appear. + updater::run_startup_hooks(); #[cfg(windows)] console::attach(); + // Before main.log is opened, so the fixture never writes the real one. + #[cfg(debug_assertions)] + if let Some(outcome) = logs_fixture::run_if_asked() { + #[cfg(windows)] + console::detach(); + return outcome; + } + // After the hooks, which exit at once and have nothing to say; before + // anything else, so a failure from here on is in main.log. + diag_log::install(); + log::info!( + target: "pwrdisk", + "started PwrDisk {} on {}", + env!("CARGO_PKG_VERSION"), + diagnostics::os_description() + ); let outcome = run(); #[cfg(windows)] console::detach(); @@ -106,13 +163,24 @@ fn main() -> Result<()> { } fn run() -> Result<()> { + // `pwrdisk mcp` is the agent's disktree: it scans and marks over stdin + // and stdout and opens no window of its own, though it may open one for + // the review screen. + if std::env::args_os().nth(1).is_some_and(|arg| arg == "mcp") { + return disktree_mcp::serve(); + } if extract_scanner()? { return Ok(()); } let saved = power::settings_path() .map_or_else( || Ok(power::PowerEfficiency::default()), - |path| power::load(&path), + |path| { + power::load_or_legacy( + &path, + power::legacy_settings_path().as_deref(), + ) + }, ) .unwrap_or_else(|error| { eprintln!("Cannot load Power Efficiency: {error}; using Balanced"); @@ -124,7 +192,7 @@ fn run() -> Result<()> { let host = args .remote .as_deref() - .context("--check requires disktree ssh HOST")?; + .context("--check requires pwrdisk ssh HOST")?; let scan = disktree_core::remote::RemoteScan::spawn( host, &disktree_core::remote::Request { @@ -141,9 +209,9 @@ fn run() -> Result<()> { "{}:{} — {} bytes, {} files, {} directories", host, snapshot.header.root.display(), - snapshot.tree.bytes, - snapshot.tree.files, - snapshot.tree.dirs + snapshot.tree.root().bytes, + snapshot.tree.root().files, + snapshot.tree.root().dirs ); return Ok(()); } @@ -161,7 +229,7 @@ fn run() -> Result<()> { && std::env::var_os("CMUX_SURFACE_ID").is_some() && std::env::var_os("DISKTREE_CMUX_DETACHED").is_none() { - Command::new(std::env::current_exe().context("find disktree")?) + Command::new(std::env::current_exe().context("find pwrdisk")?) .args(std::env::args_os().skip(1)) .env("DISKTREE_CMUX_DETACHED", "1") .stdin(Stdio::null()) @@ -170,19 +238,23 @@ fn run() -> Result<()> { // Zero makes the child the leader of a new process group. .process_group(0) .spawn() - .context("start disktree")?; + .context("start pwrdisk")?; return Ok(()); } let root = args.root.clone(); let depth = args.depth; let title_root = root.clone(); + let title_style = + disktree_core::path_style::PathStyle::of(args.remote.is_some()); gpui_kit::application() .with_assets(gpui_kit::assets::Assets) .run(move |cx| { gpui_omarchy::init(cx); app_menu::install(cx); + #[cfg(target_os = "macos")] + dock_icon::install(); let home = std::env::home_dir(); let native_look = appearance::follows_system(home.as_deref()); if native_look { @@ -190,37 +262,56 @@ fn run() -> Result<()> { } let options = args.options.clone(); let root_for_app = root.clone(); + // Where the user left it, else centred on the display they are + // working on; inside the display either way. Below 900 by 600 + // the treemap stops being readable, so ask the compositor not + // to go there, unless the display itself is smaller. + let place = window_frame::initial( + size(px(1440.), px(900.)), + size(px(900.), px(600.)), + cx, + ); let window = cx .open_window( WindowOptions { - window_bounds: Some(gpui_kit::WindowBounds::Windowed( - gpui_kit::Bounds::new( - gpui_kit::point(px(120.), px(90.)), - size(px(1440.), px(900.)), - ), - )), + window_bounds: Some(place.bounds), + // GPUI reads the bounds relative to this display. + display_id: place.display, titlebar: Some(gpui_kit::TitlebarOptions { title: Some( format!( - "disktree · {}", + "PwrDisk · {}", marks::display_path( &title_root, home.as_deref(), + title_style, ) ) .into(), ), - ..Default::default() + // The title strip is the title bar: macOS and + // Windows give it the top of the window, and + // AppKit puts its stoplights into it, centred on + // the band. Linux reads neither; there the + // compositor decides (see `chrome::Frame`). + appears_transparent: true, + traffic_light_position: Some(gpui_kit::point( + px(ui::chrome::STOPLIGHTS.0), + px(ui::chrome::STOPLIGHTS.1), + )), }), + // On macOS the strip moves the window itself, so + // AppKit does not hold back clicks on the trail and + // the settings to see whether they are a double + // click on the title bar. + app_owns_titlebar_drag: true, // Wayland app id. Hyprland reports it as the window // class, and the desktop entry's StartupWMClass and - // the documented window rule both match `disktree`. + // the documented window rule both match `pwrdisk`. // Left unset, the class is empty and that rule never // matches. - app_id: Some("disktree".to_owned()), - // Below this the treemap stops being readable, so ask - // the compositor not to go there. - window_min_size: Some(size(px(900.), px(600.))), + app_id: Some("pwrdisk".to_owned()), + window_min_size: Some(place.min_size), ..Default::default() }, move |window, cx| { @@ -228,6 +319,22 @@ fn run() -> Result<()> { appearance::follow(window); } cx.new(|cx| { + // A desktop that moves its window buttons to + // the other side moves them here too. + cx.observe_button_layout_changed( + window, + |_, _, cx| cx.notify(), + ) + .detach(); + // Moving or resizing is noted; the quit hook + // below writes it down. + cx.observe_window_bounds( + window, + |_, window, cx| { + window_frame::remember(window, cx); + }, + ) + .detach(); let mut app = if args.choose_root { Disktree::choose( options.clone(), @@ -250,7 +357,15 @@ fn run() -> Result<()> { }) }, ) - .expect("open the disktree window"); + .expect("open the PwrDisk window"); + + // Every route to quitting runs this, closing the window + // included, so the next launch opens where this one was left. + cx.on_app_quit(|_| { + window_frame::save(); + async {} + }) + .detach(); // The treemap owns the keyboard from the first frame; there is no // text field to focus first. @@ -258,6 +373,31 @@ fn run() -> Result<()> { let focus = this.focus.clone(); window.focus(&focus, cx); }); + // A check that starts or finishes redraws the window, which + // answers it in a toast, and Settings › Updates; a download's + // percent only the toast. + let _ = window.update(cx, |this, _, cx| { + this.apply_update_fixture(cx); + }); + updater::install(cx, toasts::updater_changed); + updater::check_in_background(updater::Trigger::Startup); + + // Listen for an agent. Another window already linked, or a + // system without the socket, leaves this one on its own; the + // agent then works headless and says so. + match disktree_link::Listener::bind() { + Ok(listener) => { + let _ = window.update(cx, |this, _, cx| { + this.attach_agent(listener, cx); + }); + } + Err(error) + if error.kind() != std::io::ErrorKind::Unsupported => + { + eprintln!("agent link not available: {error}"); + } + Err(_) => {} + } cx.activate(true); }); Ok(()) @@ -271,7 +411,7 @@ fn extract_scanner() -> Result { } anyhow::ensure!( args.len() == 3, - "usage: disktree extract-scanner ARCH OUTPUT" + "usage: pwrdisk extract-scanner ARCH OUTPUT" ); let archive = disktree_core::payload::Archive::current()? .context("no embedded scanners; build with cargo xtask portable")?; @@ -324,8 +464,7 @@ fn parse_args_with_power( let mut args = args.peekable(); let remote = if args.peek().is_some_and(|arg| arg == "ssh") { args.next(); - let host = - text(args.next(), "ssh needs a host, e.g. disktree ssh dev")?; + let host = text(args.next(), "ssh needs a host, e.g. pwrdisk ssh dev")?; disktree_core::remote::validate_host(&host)?; Some(host) } else { @@ -438,6 +577,14 @@ fn parse_args_with_power( ); let choose_root = root.is_none() && !disk && !check; if remote.is_some() { + // SSH hosts are Unix: a root such as `C:\x` names nothing there, and + // a relative one would be resolved against an unknown directory. + if let Some(root) = &root { + anyhow::ensure!( + disktree_core::remote::is_remote_absolute(root), + "an SSH path must start with /, as on the Unix host" + ); + } return Ok(Args { root: root.unwrap_or_default(), remote, @@ -593,6 +740,17 @@ mod argument_tests { assert_eq!(args.options.threads.max_threads, 4); assert_eq!(args.root, PathBuf::from("/only-on-the-remote-machine")); assert!(args.power.is_none()); + for root in ["relative", r"C:\Users", r"\srv"] { + assert!( + parse_args( + ["ssh", "dev", root] + .into_iter() + .map(std::ffi::OsString::from), + ) + .is_err(), + "{root} is not a path on a Unix host" + ); + } let args = parse_args( ["ssh", "dev", "--disk"] diff --git a/crates/disktree-app/src/mark_guard.rs b/crates/disktree-app/src/mark_guard.rs new file mode 100644 index 00000000..4580d7f0 --- /dev/null +++ b/crates/disktree-app/src/mark_guard.rs @@ -0,0 +1,557 @@ +//! What may be marked, and what Review asks before a removal past the +//! limit. +//! +//! The guards in `removal.rs` decide what may be removed; asking them only +//! in Review let a filled Mark for removal sit on `/Users`. So a mark is +//! judged when it is made: a protected path is never marked, and a mark +//! that takes a volume past Settings › Safety's limit needs Mark anyway +//! here and a second confirmation in Review. +//! +//! Review counts each disk on its own, as the worker does: a scan can hold +//! marks on a disk mounted inside it, and a share confirmed for one disk +//! says nothing about another. + +use std::collections::{BTreeMap, HashMap}; +use std::path::{Path, PathBuf}; + +use disktree_core::removal::{Plan, RemovalMode, Target}; +use disktree_core::removal_limit::{Ceilings, Limit, Usage}; +use gpui_kit::base::input::{InputEvent, InputState}; +use gpui_kit::{App, AppContext as _, Context, Focusable as _, Window}; +use gpui_omarchy::Status; + +use crate::safety::{Confirm, Policy, matches, phrase, share_percent}; +use crate::state::Disktree; + +/// Whether a new mark may be made. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum MarkCheck { + Allowed, + /// The guards refuse it, with their reason. No setting lifts this. + Protected(String), + /// Marking it takes the volume's marked total past the limit. + OverLimit(Share), +} + +/// Marked bytes as a share of the scanned volume. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Share { + pub bytes: u64, + pub capacity: u64, + /// Rounded up; see [`share_percent`]. + pub percent: u8, + pub limit: u8, +} + +impl Share { + fn over(bytes: u64, capacity: u64, limit: Limit) -> Option { + // `bytes > floor(capacity * limit / 100)`, as the worker's check + // counts it, without the rounding. + (u128::from(bytes) * 100 + > u128::from(capacity) * u128::from(limit.percent())) + .then(|| Self { + bytes, + capacity, + percent: share_percent(bytes, capacity), + limit: limit.percent(), + }) + } + + /// The share unrounded, for ordering two disks whose rounded shares + /// tie: parts per million of capacity. + fn bytes_share(&self) -> u128 { + u128::from(self.bytes) * 1_000_000 / u128::from(self.capacity.max(1)) + } +} + +/// One path's answer from the guards, kept while the inspector stays on +/// it: judging reads the filesystem, and the inspector draws every frame. +pub type RefusalCache = Option<(PathBuf, PathBuf, Option)>; + +/// The disk removing a path gives space back on. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Disk { + /// The worker's name for it, from + /// [`disktree_core::removal_limit::volume_of`]: the key a confirmed + /// share is raised under. + pub key: String, + pub capacity: u64, + /// Where it is mounted, for the person to read. + pub name: String, +} + +/// How Review finds a path's disk; [`disk_of`] outside tests. +pub type DiskProbe = fn(&Path) -> Result; + +/// The probe's answers by marked path, for Review's frames: the probe +/// reads the filesystem, and Review draws the gate every frame. +pub type DiskCache = HashMap>; + +/// The disk `path` is on, as the worker's check counts it, named by +/// where it is mounted. Both come from the path the check reads, so a +/// marked link is named by the disk it sits on, not the one it points to. +pub fn disk_of(path: &Path) -> Result { + let entry = disktree_core::removal_limit::volume_entry(path)?; + let (key, capacity) = disktree_core::removal_limit::volume_of(entry)?; + let name = disktree_core::space::volume_root_for(entry) + .map_or_else(|| key.clone(), |root| root.display().to_string()); + Ok(Disk { + key, + capacity, + name, + }) +} + +/// One disk a removal takes past the limit. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Over { + pub key: String, + pub name: String, + pub share: Share, +} + +/// Review's second confirmation: every disk a removal takes past the +/// window's limit, the largest share first, as the phrase reads them. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Gate { + pub over: Vec, + pub limit: u8, +} + +/// What a tick confirmed: each disk's share, and the mode. +pub type Ticked = (Vec<(String, u8)>, RemovalMode); + +impl Gate { + /// The disks of `usage` past `limit`; `None` when none is. + fn new( + usage: Vec, + names: &BTreeMap, + limit: Limit, + ) -> Option { + let mut over: Vec = usage + .into_iter() + .filter_map( + |Usage { + volume, + bytes, + capacity, + }| { + let share = Share::over(bytes, capacity, limit)?; + let name = names + .get(&volume) + .cloned() + .unwrap_or_else(|| volume.clone()); + Some(Over { + key: volume, + name, + share, + }) + }, + ) + .collect(); + // Stable, so equal shares keep the worker's key order. + over.sort_by_key(|over| std::cmp::Reverse(over.share.bytes_share())); + (!over.is_empty()).then(|| Self { + over, + limit: limit.percent(), + }) + } + + /// Each disk's share, in the gate's order. + pub fn percents(&self) -> Vec { + self.over.iter().map(|over| over.share.percent).collect() + } + + /// "30% of /" or "31% of / and 30% of /Volumes/USB". + pub fn summary(&self) -> String { + crate::safety::series( + self.over.iter().map(|over| { + format!("{}% of {}", over.share.percent, over.name) + }), + ) + } + + /// What a tick of this gate in `mode` confirms. + pub fn ticked(&self, mode: RemovalMode) -> Ticked { + ( + self.over + .iter() + .map(|over| (over.key.clone(), over.share.percent)) + .collect(), + mode, + ) + } + + /// `base`, with each disk here raised to its confirmed share and no + /// other: a mark on a disk this gate does not name stays at `base`. + fn ceilings(&self, base: Limit) -> Result { + self.over + .iter() + .try_fold(Ceilings::from(base), |ceilings, over| { + Ok(ceilings.raise( + over.key.clone(), + Limit::new(over.share.percent.max(1))?, + )) + }) + } +} + +impl Disktree { + /// Settings › Safety as last read. Read once and again before every + /// removal, never per frame; Settings saves it, and an unreadable file + /// is the default here, which is the stricter reading. + pub fn policy(&self) -> Policy { + *self.safety_policy.borrow_mut().get_or_insert_with(|| { + crate::safety::load_policy(self.removal_settings_dir.as_deref()) + .unwrap_or_default() + }) + } + + /// Read Settings › Safety again, as a removal must. + pub fn reload_policy(&self) -> Result { + let policy = + crate::safety::load_policy(self.removal_settings_dir.as_deref()); + *self.safety_policy.borrow_mut() = + Some(policy.clone().unwrap_or_default()); + policy + } + + /// Why the guards would refuse `path`. An SSH host's paths are never + /// judged against this computer's filesystem: nothing is removed + /// there, and its marks only export a list. + pub fn refusal_of(&self, path: &Path) -> Option { + if self.remote.is_some() { + return None; + } + if let Some((root, cached, reason)) = &*self.refusal_cache.borrow() + && *root == self.root_path + && cached == path + { + return reason.clone(); + } + let reason = disktree_core::removal::refusal(path, &self.root_path); + *self.refusal_cache.borrow_mut() = + Some((self.root_path.clone(), path.to_path_buf(), reason.clone())); + reason + } + + /// The marked total with `target` marked too: marks inside it are + /// absorbed by it, so they are not counted twice. + fn marked_with(&self, target: &Target) -> u64 { + let style = self.path_style(); + self.marks + .items() + .iter() + .filter(|mark| { + mark.path != target.path + && !style.is_below(&mark.path, &target.path) + }) + .map(|mark| mark.bytes) + .fold(target.bytes, u64::saturating_add) + } + + /// Whether marking `target` passes `limit` on the scanned volume. + /// Every mark counts against it, wherever it lives, so a mark on + /// another disk can be over- or under-counted here: a small disk + /// mounted inside the scan passes its own limit long before the scanned + /// one does. Review and the worker count each disk on its own, and + /// those are what hold a removal to the limit. + fn over_limit(&self, target: &Target, limit: Limit) -> Option { + Share::over(self.marked_with(target), self.capacity()?, limit) + } + + /// The scanned volume's capacity: the ticker's, or measured now when + /// it has no reading yet, so a mark made before the first reading is + /// still judged. + fn capacity(&self) -> Option { + self.space + .or_else(|| disktree_core::space::space_info(&self.root_path).ok()) + .map(|space| space.total) + } + + /// Whether `target`, not yet marked, may be marked now. + pub fn mark_check(&self, target: &Target) -> MarkCheck { + if let Some(reason) = self.refusal_of(&target.path) { + return MarkCheck::Protected(reason); + } + if self.remote.is_some() { + return MarkCheck::Allowed; + } + self.policy() + .limit + .and_then(|limit| self.over_limit(target, limit)) + .map_or(MarkCheck::Allowed, MarkCheck::OverLimit) + } + + /// Why an agent may not mark `target`, if it may not. An agent is held + /// to the limit with no way past it, and to the default one when the + /// window's is off: going past it is the person's call, in the window. + pub fn agent_mark_refusal(&self, target: &Target) -> Option { + if let Some(reason) = self.refusal_of(&target.path) { + return Some(reason); + } + let limit = self.policy().agent_limit(); + self.over_limit(target, limit).map(|share| { + format!( + "marking it would put {}% of the volume in the list, over \ + the {}% limit; only the person can mark past it, in the \ + window", + share.percent, share.limit + ) + }) + } + + /// The notice for a mark refused here; `None` when it was allowed. + pub fn mark_refusal_notice( + &self, + target: &Target, + check: &MarkCheck, + ) -> Option { + let name = self.display_path(&target.path); + match check { + MarkCheck::Allowed => None, + MarkCheck::Protected(reason) => Some(format!("{name}: {reason}")), + MarkCheck::OverLimit(share) => Some(format!( + "{name} would make the marked list {}% of this disk, over \ + the {}% limit; use \u{25be} beside Mark to mark it anyway", + share.percent, share.limit + )), + } + } + + /// The inspector's Mark anyway: the one way to mark past the limit. + /// Protected paths stay refused. + pub fn mark_anyway( + &mut self, + crumbs: &[usize], + cx: &mut Context<'_, Self>, + ) { + self.mark_menu = None; + self.toggle_mark_checked(crumbs, true, cx); + } + + /// The plan's bytes disk by disk, with each disk's name, as the + /// worker's check groups them. `fresh` asks the probe again and keeps + /// its answers; otherwise answers kept since Review opened are reused. + fn usage( + &self, + plan: &Plan, + fresh: bool, + ) -> Result<(Vec, BTreeMap), String> { + let mut cache = self.disk_cache.borrow_mut(); + let mut names = BTreeMap::new(); + let usage = + disktree_core::removal_limit::usage(&plan.targets, |path| { + let disk = if fresh { + let disk = (self.disk_probe)(path); + cache.insert(path.to_path_buf(), disk.clone()); + disk + } else { + cache + .entry(path.to_path_buf()) + .or_insert_with(|| (self.disk_probe)(path)) + .clone() + }?; + names.entry(disk.key.clone()).or_insert(disk.name); + Ok((disk.key, disk.capacity)) + })?; + Ok((usage, names)) + } + + /// Forget which disk each mark is on, so Review reads them again. Every + /// way into Review does this: a disk mounted or unmounted since the + /// last visit is then seen. + pub fn reread_disks(&self) { + self.disk_cache.borrow_mut().clear(); + } + + /// Every disk the plan takes past the window's limit, for Review's + /// second confirmation. `None` with the limit off, over SSH, or when a + /// disk cannot be read, where the worker's own check still stands. + pub fn removal_gate(&self, plan: &Plan) -> Option { + if self.remote.is_some() { + return None; + } + let limit = self.policy().limit?; + let (usage, names) = self.usage(plan, false).ok()?; + Gate::new(usage, &names, limit) + } + + /// The phrase Review asks for `gate`, in the current mode. + pub fn gate_phrase(&self, gate: &Gate) -> String { + phrase(&gate.percents(), self.removal_mode) + } + + /// Whether the person has confirmed `gate` as Settings asks. + pub fn gate_met(&self, gate: &Gate, cx: &App) -> bool { + match self.policy().confirm { + Confirm::Nothing => true, + Confirm::Tick => { + self.over_ticked.as_ref() + == Some(&gate.ticked(self.removal_mode)) + } + Confirm::Phrase => self.over_phrase.as_ref().is_some_and(|input| { + matches(&input.read(cx).value(), &self.gate_phrase(gate)) + }), + } + } + + /// The limits the worker holds this removal to: on each disk past the + /// window's limit, the share the person confirmed for that disk, so a + /// share that grew since is refused; on every other disk, the window's. + /// Err with the notice to show. + pub fn removal_limit( + &self, + plan: &Plan, + cx: &App, + ) -> Result { + let policy = self.reload_policy()?; + // Off still counts against a capacity, so an unknown one fails + // closed; it just never says no for size. + let base = policy.limit.map_or_else(|| Limit::new(100), Ok)?; + let (usage, names) = self.usage(plan, true)?; + let gate = policy + .limit + .filter(|_| self.remote.is_none()) + .and_then(|limit| Gate::new(usage, &names, limit)); + let ceilings = match gate { + Some(gate) if !self.gate_met(&gate, cx) => { + return Err(match policy.confirm { + Confirm::Tick => format!( + "this removes {}; tick the box to go past the {}% \ + limit", + gate.summary(), + gate.limit + ), + _ => format!( + "this removes {}; type \u{201c}{}\u{201d} to go past \ + the {}% limit", + gate.summary(), + self.gate_phrase(&gate), + gate.limit + ), + }); + } + Some(gate) => gate.ceilings(base)?, + None => Ceilings::from(base), + }; + ceilings.check_with(&plan.targets, |path| { + (self.disk_probe)(path).map(|disk| (disk.key, disk.capacity)) + })?; + Ok(ceilings) + } + + /// The limits an agent's removal is held to: the agent limit on every + /// disk. Review's confirmation never raises it, and the window's Off + /// never lifts it, so a share that grew past the limit since the + /// preview is refused on the worker as it was at the preview. + pub fn agent_removal_limit(&self, plan: &Plan) -> Result { + let ceilings = Ceilings::from(self.reload_policy()?.agent_limit()); + ceilings.check_with(&plan.targets, |path| { + (self.disk_probe)(path).map(|disk| (disk.key, disk.capacity)) + })?; + Ok(ceilings) + } + + /// Make Review's phrase field once there is a window to make it in. + /// Enter in it commits, as Enter on the list does, once it matches. + pub fn prepare_over_phrase( + &mut self, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) { + if self.over_phrase.is_some() { + return; + } + let input = cx.new(|cx| InputState::new(window, cx)); + cx.subscribe(&input, |this, _, event, cx| { + if matches!(event, InputEvent::PressEnter { .. }) { + this.commit(false, cx); + } + cx.notify(); + }) + .detach(); + self.over_phrase = Some(input); + } + + /// Whether the phrase field has the keys: Review's own keys, `?` + /// included, are letters typed into it then. + pub fn editing_phrase(&self, window: &Window, cx: &App) -> bool { + self.over_phrase.as_ref().is_some_and(|input| { + input.read(cx).focus_handle(cx).is_focused(window) + }) + } + + /// Show `notice` as a warning. + pub fn warn(&mut self, notice: String, cx: &mut Context<'_, Self>) { + self.say(notice, Status::Warning, cx); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_share_is_over_exactly_where_the_worker_refuses() { + let five = Limit::default(); + // 5% of 1000 is 50: 50 passes, 51 does not, as `Limit::check`. + assert_eq!(Share::over(50, 1000, five), None); + let over = Share::over(51, 1000, five).expect("over"); + assert_eq!((over.percent, over.limit), (6, 5)); + assert_eq!( + Share::over(u64::MAX, 1, five).map(|s| s.percent), + Some(100) + ); + } + + fn usage(volume: &str, bytes: u64, capacity: u64) -> Usage { + Usage { + volume: volume.into(), + bytes, + capacity, + } + } + + #[test] + fn a_gate_lists_each_disk_past_the_limit_and_raises_only_those() { + let names = BTreeMap::from([ + ("boot".to_owned(), "/".to_owned()), + ("usb".to_owned(), "/Volumes/USB".to_owned()), + ]); + let five = Limit::default(); + let gate = Gate::new( + vec![ + usage("boot", 190, 1000), + usage("other", 50, 1000), + usage("usb", 200, 1000), + ], + &names, + five, + ) + .expect("two disks past 5%"); + // Largest first. + assert_eq!(gate.percents(), [20, 19]); + assert_eq!(gate.summary(), "20% of /Volumes/USB and 19% of /"); + assert_eq!( + gate.ticked(RemovalMode::Trash), + ( + vec![("usb".to_owned(), 20), ("boot".to_owned(), 19)], + RemovalMode::Trash + ) + ); + let ceilings = gate.ceilings(five).expect("ceilings"); + assert_eq!(ceilings.of("usb").percent(), 20); + assert_eq!(ceilings.of("boot").percent(), 19); + assert_eq!(ceilings.of("other"), five, "within the limit, held to it"); + + assert_eq!( + Gate::new(vec![usage("boot", 50, 1000)], &names, five), + None + ); + // A disk with no name reads as its key. + let unnamed = Gate::new(vec![usage("disk9", 60, 1000)], &names, five) + .expect("past 5%"); + assert_eq!(unnamed.summary(), "6% of disk9"); + } +} diff --git a/crates/disktree-app/src/marks.rs b/crates/disktree-app/src/marks.rs index 7a03e476..4274b375 100644 --- a/crates/disktree-app/src/marks.rs +++ b/crates/disktree-app/src/marks.rs @@ -4,28 +4,227 @@ //! re-scanned after a removal, and a mark must survive that (or be reported as //! gone) rather than silently pointing at a different node. +use std::collections::BTreeSet; +use std::ops::Bound::{Excluded, Unbounded}; use std::path::{Path, PathBuf}; +use std::sync::{Arc, Weak}; +use disktree_core::path_style::PathStyle; use disktree_core::removal::Target; -use disktree_core::tree::{Metric, Node}; -use rustc_hash::FxHashSet; +use disktree_core::tree::{Facts, Metric, Node, Tree}; +use rustc_hash::{FxHashMap, FxHashSet}; + +#[cfg(test)] +pub mod work { + use std::cell::Cell; + + thread_local! { + pub static RESOLUTION: Cell = const { Cell::new(0) }; + pub static FRAMES: Cell = const { Cell::new(0) }; + pub static RENDERS: Cell = const { Cell::new(0) }; + pub static PLANS: Cell = const { Cell::new(0) }; + pub static REFRESHES: Cell = const { Cell::new(0) }; + pub static TILES: Cell = const { Cell::new(0) }; + pub static MARKING: Cell = const { Cell::new(0) }; + pub static COMPACTION: Cell = const { Cell::new(0) }; + pub static REVIEW: Cell = const { Cell::new(0) }; + pub static REVIEW_ROWS: Cell = const { Cell::new(0) }; + pub static COVERED_ROWS: Cell = const { Cell::new(0) }; + pub static BLOCKED_ROWS: Cell = const { Cell::new(0) }; + pub static DISCARDED: Cell = const { Cell::new(0) }; + } + + pub fn step() { + RESOLUTION.set(RESOLUTION.get() + 1); + } + + pub fn reset() { + RESOLUTION.set(0); + FRAMES.set(0); + RENDERS.set(0); + PLANS.set(0); + REFRESHES.set(0); + TILES.set(0); + MARKING.set(0); + COMPACTION.set(0); + REVIEW.set(0); + REVIEW_ROWS.set(0); + COVERED_ROWS.set(0); + BLOCKED_ROWS.set(0); + DISCARDED.set(0); + } +} /// Marked paths, in the order they were marked. #[derive(Debug, Default)] pub struct Marks { items: Vec, - index: FxHashSet, + // Path's component ordering makes descendants contiguous. The same + // index answers exact membership and whether a parent has any marks + // inside, without storing ancestor counts or scanning every mark. + index: BTreeSet, + resolved: Option, +} + +/// Retain only the allocation identity: a rescan must not keep the old tree +/// alive while a new one is being displayed. +#[derive(Debug)] +struct ResolvedMarks { + tree: Weak, + root_path: PathBuf, + metric: Metric, + style: PathStyle, + crumbs: Arc>>, +} + +// Component ordering keeps descendants contiguous in both namespaces. Keep +// the original spelling as the lookup value, including native non-UTF-8 paths. +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] +enum PathKey { + Native(PathBuf), + Posix(Vec), +} + +impl PathKey { + fn new(path: &Path, style: PathStyle) -> Self { + match style { + PathStyle::Native => Self::Native(path.to_path_buf()), + PathStyle::Posix => Self::Posix( + path.to_str() + .unwrap_or_default() + .split('/') + .map(str::to_owned) + .collect(), + ), + } + } +} + +#[derive(Debug)] +struct IndexedPath { + key: PathKey, + path: PathBuf, +} + +impl std::borrow::Borrow for IndexedPath { + fn borrow(&self) -> &PathKey { + &self.key + } +} + +impl PartialEq for IndexedPath { + fn eq(&self, other: &Self) -> bool { + self.key == other.key + } +} +impl Eq for IndexedPath {} +impl PartialOrd for IndexedPath { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} +impl Ord for IndexedPath { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.key.cmp(&other.key) + } } impl Marks { - pub fn contains(&self, path: &Path) -> bool { - self.index.contains(path) + pub fn contains(&self, path: &Path, style: PathStyle) -> bool { + self.index.contains(&PathKey::new(path, style)) + } + + /// Marked ancestor with the shortest stored spelling, excluding the + /// path itself: the outermost one for paths built by the scan. Preserve + /// that choice even for raw queues with redundant path separators. + pub fn ancestor(&self, path: &Path, style: PathStyle) -> Option<&Path> { + style + .ancestors(path) + .skip(1) + .filter_map(|ancestor| { + #[cfg(test)] + work::MARKING.set(work::MARKING.get() + 1); + self.index.get(&PathKey::new(ancestor, style)) + }) + .min_by_key(|ancestor| ancestor.path.as_os_str().len()) + .map(|entry| entry.path.as_path()) + } + + /// Drop strict descendants in one stable compaction, retaining the + /// parent's mark and unrelated marks in their existing order. + pub fn absorb(&mut self, path: &Path, style: PathStyle) -> usize { + #[cfg(test)] + work::MARKING.set(work::MARKING.get() + 1); + let has_descendant = self + .index + .range::(( + Excluded(PathKey::new(path, style)), + Unbounded, + )) + .next() + .is_some_and(|next| style.is_below(&next.path, path)); + // Most insertions are disjoint; proving that from the index keeps + // queuing M paths from doing M full scans of the ordered item list. + if !has_descendant { + return 0; + } + self.resolved = None; + let before = self.items.len(); + let index = &mut self.index; + self.items.retain(|item| { + #[cfg(test)] + work::COMPACTION.set(work::COMPACTION.get() + 1); + if style.is_below(&item.path, path) { + #[cfg(test)] + work::MARKING.set(work::MARKING.get() + 1); + index.remove(&PathKey::new(&item.path, style)); + false + } else { + true + } + }); + before - self.items.len() } pub fn items(&self) -> &[Target] { &self.items } + /// Bytes of the items strictly below `path`, as they were recorded. + pub fn below(&self, path: &Path, style: PathStyle) -> u64 { + // Descendants sort right after `path`: walk only them. + let mut below = self + .index + .range::(( + Excluded(PathKey::new(path, style)), + Unbounded, + )) + .take_while(|next| style.is_below(&next.path, path)) + .map(|next| next.path.as_path()) + .peekable(); + if below.peek().is_none() { + return 0; + } + let below: FxHashSet<&Path> = below.collect(); + self.items + .iter() + .filter(|item| below.contains(item.path.as_path())) + .map(|item| item.bytes) + .sum() + } + + /// Take `gone`'s bytes out of every item that holds some of it: a + /// directory marked after part of it was removed frees only the rest. + pub fn discount(&mut self, gone: &Self, style: PathStyle) { + if gone.is_empty() { + return; + } + for item in &mut self.items { + item.bytes = + item.bytes.saturating_sub(gone.below(&item.path, style)); + } + } + pub const fn len(&self) -> usize { self.items.len() } @@ -37,38 +236,63 @@ impl Marks { /// Mark `target`, or unmark it when it is already marked. /// /// Returns `true` when the path ended up marked. - pub fn toggle(&mut self, target: Target) -> bool { - if self.index.remove(&target.path) { - self.items.retain(|item| item.path != target.path); + pub fn toggle(&mut self, target: Target, style: PathStyle) -> bool { + self.resolved = None; + if self.index.remove(&PathKey::new(&target.path, style)) { + self.items.retain(|item| { + PathKey::new(&item.path, style) + != PathKey::new(&target.path, style) + }); false } else { - self.index.insert(target.path.clone()); + self.index.insert(IndexedPath { + key: PathKey::new(&target.path, style), + path: target.path.clone(), + }); self.items.push(target); true } } - pub fn remove(&mut self, path: &Path) { - if self.index.remove(path) { - self.items.retain(|item| item.path != path); + pub fn remove(&mut self, path: &Path, style: PathStyle) { + if self.index.remove(&PathKey::new(path, style)) { + self.resolved = None; + self.items.retain(|item| { + #[cfg(test)] + work::COMPACTION.set(work::COMPACTION.get() + 1); + PathKey::new(&item.path, style) != PathKey::new(path, style) + }); } } pub fn clear(&mut self) { + self.resolved = None; self.items.clear(); self.index.clear(); } - /// Re-read sizes from a freshly scanned tree and drop marks whose path no - /// longer exists, so the tally never claims space that is already gone. - pub fn refresh(&mut self, root_path: &Path, root: &Node, _metric: Metric) { + /// Re-read sizes from a freshly scanned tree. Missing paths stay marked + /// with zero bytes, so they cannot claim space that is already gone. + pub fn refresh( + &mut self, + root_path: &Path, + root: Node<'_>, + _metric: Metric, + style: PathStyle, + ) { + #[cfg(test)] + work::REFRESHES.set(work::REFRESHES.get() + 1); + self.resolved = None; + let mut resolver = Resolver::new(root_path, root, style); let mut resolved = Vec::with_capacity(self.items.len()); for item in &self.items { - match find(root_path, root, &item.path) { - Some(node) => resolved.push(Target { + #[cfg(test)] + work::step(); + match resolver.resolve(&item.path) { + Some((_, node)) => resolved.push(Target { bytes: node.bytes, is_dir: node.is_dir(), - hidden: is_hidden(&item.path), + hidden: is_hidden(&item.path, style), path: item.path.clone(), }), None => resolved.push(Target { @@ -79,44 +303,122 @@ impl Marks { } self.items = resolved; } + + /// Crumbs are display state, never removal authorization. Rebuild on every + /// mark mutation, refresh, tree replacement, root change or metric change. + pub fn crumbs( + &mut self, + root_path: &Path, + tree: &Arc, + metric: Metric, + style: PathStyle, + ) -> Arc>> { + if let Some(resolved) = &self.resolved + && resolved.tree.as_ptr() == Arc::as_ptr(tree) + && style.same(&resolved.root_path, root_path) + && resolved.metric == metric + && resolved.style == style + { + return Arc::clone(&resolved.crumbs); + } + let mut resolver = Resolver::new(root_path, tree.root(), style); + let mut crumbs = FxHashSet::default(); + for item in &self.items { + #[cfg(test)] + work::step(); + if let Some((path, _)) = resolver.resolve(&item.path) { + crumbs.insert(path); + } + } + let crumbs = Arc::new(crumbs); + self.resolved = Some(ResolvedMarks { + tree: Arc::downgrade(tree), + root_path: root_path.to_path_buf(), + metric, + style, + crumbs: Arc::clone(&crumbs), + }); + crumbs + } } -/// Walk the tree to the node at an absolute path. Path components are compared -/// one at a time, so a name containing a path separator cannot confuse it. -pub fn find<'a>( - root_path: &Path, - root: &'a Node, - path: &Path, -) -> Option<&'a Node> { - let relative = path.strip_prefix(root_path).ok()?; - let mut node = root; - for component in relative.components() { - let name = component.as_os_str().to_string_lossy(); - node = node - .children - .iter() - .find(|child| child.name.as_ref() == name)?; +/// A batch of path lookups indexes each visited directory's children once. +/// Work is O(S + M × D) expected hash operations: S sibling entries across +/// visited directories, M paths and D components per path. Unvisited subtrees +/// cost nothing, and no index is stored on the millions of scan nodes. +#[derive(Debug)] +pub struct Resolver<'a> { + root_path: &'a Path, + root: Node<'a>, + style: PathStyle, + /// Keyed by where a node's facts live, which is unique per node in + /// one tree: `Node` is a by-value cursor with no identity of its own. + indexes: FxHashMap<*const Facts, FxHashMap<&'a str, usize>>, +} + +impl<'a> Resolver<'a> { + pub fn new(root_path: &'a Path, root: Node<'a>, style: PathStyle) -> Self { + Self { + root_path, + root, + style, + indexes: FxHashMap::default(), + } + } + + /// Compare whole components with the scan's existing case-sensitive, + /// lossy name semantics. The first equal child wins, as in a linear walk. + pub fn resolve(&mut self, path: &Path) -> Option<(Vec, Node<'a>)> { + let relative = self.style.relative(self.root_path, path)?; + let mut node = self.root; + let mut crumbs = Vec::new(); + for name in relative { + #[cfg(test)] + work::step(); + let children = self + .indexes + .entry(std::ptr::from_ref(node.facts())) + .or_insert_with(|| { + let mut children = FxHashMap::default(); + for (index, child) in node.children().iter().enumerate() { + #[cfg(test)] + work::step(); + children.entry(child.name()).or_insert(index); + } + children + }); + let index = *children.get(name.as_ref())?; + crumbs.push(index); + node = node.children().at(index); + } + Some((crumbs, node)) } - Some(node) } /// A dotfile or dot-directory by name. -pub fn is_hidden(path: &Path) -> bool { - path.file_name() +pub fn is_hidden(path: &Path, style: PathStyle) -> bool { + style + .file_name(path) .is_some_and(|name| name.to_string_lossy().starts_with('.')) } /// Shorten a path for display: `~` for the home directory, and the path with -/// the home prefix replaced when it is below it. The separator after `~` is -/// the platform's, so Windows shows `~\AppData\Local`, not `~/AppData\Local`. -pub fn display_path(path: &Path, home: Option<&Path>) -> String { - match home - .and_then(|home| path.strip_prefix(home).ok().map(|rest| (home, rest))) - { - Some((_, rest)) if rest.as_os_str().is_empty() => "~".to_string(), - Some((_, rest)) => { - format!("~{}{}", std::path::MAIN_SEPARATOR, rest.display()) - } +/// the home prefix replaced when it is below it. The separator is the scanned +/// machine's, so Windows shows `~\AppData\Local`, not `~/AppData\Local`, and +/// a Unix host shows `~/.cache` on every client. +pub fn display_path( + path: &Path, + home: Option<&Path>, + style: PathStyle, +) -> String { + let separator = style.separator(); + match home.and_then(|home| style.relative(home, path)) { + Some(names) if names.is_empty() => "~".to_string(), + Some(names) => names.iter().fold("~".to_string(), |mut text, name| { + text.push(separator); + text.push_str(name); + text + }), None => path.display().to_string(), } } @@ -124,22 +426,45 @@ pub fn display_path(path: &Path, home: Option<&Path>) -> String { #[cfg(test)] mod tests { use super::*; - use disktree_core::tree::{NodeKind, aggregate}; + use disktree_core::tree::{Draft, NodeKind, aggregate}; - fn file(name: &str, bytes: u64) -> Node { - Node::entry(name, NodeKind::File, bytes) + fn file(name: &str, bytes: u64) -> Draft { + Draft::entry(name, NodeKind::File, bytes) } - fn tree() -> Node { - let mut root = Node::directory("home"); - let mut cache = Node::directory(".cache"); + fn draft() -> Draft { + let mut root = Draft::directory("home"); + let mut cache = Draft::directory(".cache"); cache.children.push(file("blob.bin", 900)); root.children.push(cache); root.children.push(file("notes.bin", 100)); + root + } + + fn tree() -> Tree { + let mut root = Tree::from(draft()); aggregate(&mut root, Metric::Bytes); root } + #[test] + fn below_sums_only_descendants_and_discount_leaves_the_rest() { + let mut gone = Marks::default(); + gone.toggle(target("/home/tobi/a/b", 30), PathStyle::Native); + gone.toggle(target("/home/tobi/a/c/d", 20), PathStyle::Native); + gone.toggle(target("/home/tobi/ab", 7), PathStyle::Native); + let a = Path::new("/home/tobi/a"); + assert_eq!(gone.below(a, PathStyle::Native), 50, "not the sibling ab"); + assert_eq!( + gone.below(Path::new("/home/tobi/a/b"), PathStyle::Native), + 0 + ); + let mut marks = Marks::default(); + marks.toggle(target("/home/tobi/a", 100), PathStyle::Native); + marks.discount(&gone, PathStyle::Native); + assert_eq!(marks.items()[0].bytes, 50); + } + fn target(path: &str, bytes: u64) -> Target { Target { path: PathBuf::from(path), @@ -149,22 +474,383 @@ mod tests { } } + #[test] + fn refresh_resolution_budget() { + let measure = |count| { + let root_path = std::env::temp_dir().join("marks-budget"); + let mut root = Draft::directory("root"); + let mut marks = Marks::default(); + for index in 0..count { + let name = format!("folder-{index:05}"); + let mut dir = Draft::directory(name.as_str()); + dir.children.push(file("payload", 1)); + root.children.push(dir); + marks.toggle( + Target { + path: root_path.join(name).join("payload"), + bytes: 0, + is_dir: false, + hidden: false, + }, + PathStyle::Native, + ); + } + let root = Tree::from(root); + work::reset(); + let start = std::time::Instant::now(); + for _ in 0..4 { + marks.refresh( + &root_path, + root.root(), + Metric::Bytes, + PathStyle::Native, + ); + } + let elapsed = start.elapsed(); + let operations = work::RESOLUTION.get(); + assert!(marks.items().iter().all(|item| item.bytes == 1)); + eprintln!( + "refresh M={count} N={} R=4 work={operations} wall={elapsed:?}", + count * 2 + ); + operations + }; + let small = measure(128); + let large = measure(1024); + assert!(large <= small * 16, "8x marks/folders: {small} -> {large}"); + assert!(large <= 1024 * 4 * 16, "absolute work cap: {large}"); + } + + #[test] + fn cached_crumbs_follow_every_invalidation_boundary() { + let root_path = Path::new("/home/tobi"); + let mut root = Arc::new(tree()); + let mut marks = Marks::default(); + marks.toggle(target("/home/tobi/.cache", 0), PathStyle::Native); + let first = + marks.crumbs(root_path, &root, Metric::Bytes, PathStyle::Native); + assert!(first.contains(&vec![0])); + work::reset(); + assert!(Arc::ptr_eq( + &first, + &marks.crumbs(root_path, &root, Metric::Bytes, PathStyle::Native) + )); + assert_eq!( + work::RESOLUTION.get(), + 0, + "unchanged frames need no lookup" + ); + assert_eq!( + Arc::strong_count(&root), + 1, + "the cache must not retain a scan" + ); + + marks.toggle(target("/home/tobi/notes.bin", 0), PathStyle::Native); + assert_eq!( + marks + .crumbs(root_path, &root, Metric::Bytes, PathStyle::Native) + .len(), + 2 + ); + marks.remove(Path::new("/home/tobi/.cache"), PathStyle::Native); + assert!( + marks + .crumbs(root_path, &root, Metric::Bytes, PathStyle::Native) + .contains(&vec![1]) + ); + marks.clear(); + assert!( + marks + .crumbs(root_path, &root, Metric::Bytes, PathStyle::Native) + .is_empty() + ); + marks.toggle(target("/home/tobi/notes.bin", 0), PathStyle::Native); + marks.toggle(target("/home/tobi/notes.bin", 0), PathStyle::Native); + assert!( + marks + .crumbs(root_path, &root, Metric::Bytes, PathStyle::Native) + .is_empty() + ); + marks.toggle(target("/home/tobi/notes.bin", 0), PathStyle::Native); + + let before = + marks.crumbs(root_path, &root, Metric::Bytes, PathStyle::Native); + let files = + marks.crumbs(root_path, &root, Metric::Files, PathStyle::Native); + assert!(!Arc::ptr_eq(&before, &files), "metric changes invalidate"); + marks.refresh(root_path, root.root(), Metric::Files, PathStyle::Native); + let refreshed = + marks.crumbs(root_path, &root, Metric::Files, PathStyle::Native); + assert!(!Arc::ptr_eq(&files, &refreshed), "refresh invalidates"); + assert!( + marks + .crumbs( + Path::new("/elsewhere"), + &root, + Metric::Files, + PathStyle::Native + ) + .is_empty() + ); + assert!( + marks + .crumbs(root_path, &root, Metric::Files, PathStyle::Native) + .contains(&vec![1]) + ); + + let old_tree = Arc::downgrade(&root); + // A tree's child lists are fixed once built: reorder a copy's draft. + let mut replacement = root.root().to_draft(); + replacement.children.reverse(); + root = Arc::new(Tree::from(replacement)); + assert!(old_tree.upgrade().is_none(), "old scan is released"); + assert!( + marks + .crumbs(root_path, &root, Metric::Files, PathStyle::Native) + .contains(&vec![0]) + ); + let mut emptied = root.root().to_draft(); + emptied.children.clear(); + root = Arc::new(Tree::from(emptied)); + assert!( + marks + .crumbs(root_path, &root, Metric::Files, PathStyle::Native) + .is_empty() + ); + } + + #[test] + fn resolver_preserves_scan_name_semantics() { + let root_path = Path::new("/home/tobi"); + // A second entry of the same name after aggregation, as a scan + // that decoded two names to one lossy text would leave it. + let mut root = { + let mut tree = Tree::from(draft()); + aggregate(&mut tree, Metric::Bytes); + tree.root().to_draft() + }; + root.children.push(file("notes.bin", 200)); + let root = Tree::from(root); + let mut resolver = + Resolver::new(root_path, root.root(), PathStyle::Native); + let (crumbs, node) = resolver + .resolve(&root_path.join("notes.bin")) + .expect("file"); + assert_eq!(crumbs, [1]); + assert_eq!(node.bytes, 100, "first equal scan name wins"); + assert!(resolver.resolve(&root_path.join("NOTES.BIN")).is_none()); + assert!(resolver.resolve(&root_path.join("notes")).is_none()); + assert!( + resolver + .resolve(&root_path.join(".cache/missing")) + .is_none() + ); + assert!(resolver.resolve(root_path).expect("root").0.is_empty()); + } + + #[cfg(unix)] + #[test] + fn resolver_preserves_lossy_non_utf8_components() { + use std::os::unix::ffi::OsStrExt as _; + let root_path = Path::new("/synthetic"); + let name = std::ffi::OsStr::from_bytes(b"file-\xff"); + let mut root = Draft::directory("root"); + root.children.push(file(&name.to_string_lossy(), 1)); + let root = Tree::from(root); + let mut resolver = + Resolver::new(root_path, root.root(), PathStyle::Native); + assert_eq!( + resolver + .resolve(&root_path.join(name)) + .expect("lossy scan name") + .0, + [0] + ); + } + + #[test] + fn ordered_marks_preserve_components_case_and_outermost_ancestor() { + let mut marks = Marks::default(); + for path in [ + "/synthetic/a/child", + "/synthetic/a", + "/synthetic/a-b", + "/synthetic/a.b", + "/synthetic/ab", + "/synthetic/A", + ] { + marks.toggle(target(path, 1), PathStyle::Native); + } + assert_eq!( + marks.ancestor( + Path::new("/synthetic/a/child/file"), + PathStyle::Native + ), + Some(Path::new("/synthetic/a")) + ); + assert_eq!( + marks.ancestor(Path::new("/synthetic/a"), PathStyle::Native), + None + ); + assert_eq!( + marks.ancestor(Path::new("/synthetic/a-b/file"), PathStyle::Native), + Some(Path::new("/synthetic/a-b")) + ); + assert_eq!( + marks.ancestor(Path::new("/synthetic/A/file"), PathStyle::Native), + Some(Path::new("/synthetic/A")) + ); + assert_eq!( + marks.absorb(Path::new("/synthetic/a"), PathStyle::Native), + 1 + ); + let expected: Vec<_> = [ + "/synthetic/a", + "/synthetic/a-b", + "/synthetic/a.b", + "/synthetic/ab", + "/synthetic/A", + ] + .map(PathBuf::from) + .into(); + assert_eq!( + marks + .items() + .iter() + .map(|item| item.path.clone()) + .collect::>(), + expected + ); + assert!( + marks + .items() + .iter() + .all(|item| marks.contains(&item.path, PathStyle::Native)) + ); + assert!( + !marks.contains(Path::new("/synthetic/a/child"), PathStyle::Native) + ); + marks.remove(Path::new("/synthetic/a"), PathStyle::Native); + assert_eq!( + marks.ancestor(Path::new("/synthetic/a/file"), PathStyle::Native), + None + ); + assert_eq!( + marks.absorb(Path::new("/synthetic/a"), PathStyle::Native), + 0, + "prefix lookalikes stay marked" + ); + marks.clear(); + assert_eq!(marks.absorb(Path::new("/synthetic"), PathStyle::Native), 0); + + // Raw control clients can supply redundant separators. Retain the + // original shortest-spelling rule rather than changing notices. + marks.toggle( + target("/synthetic/a////////////////////", 1), + PathStyle::Native, + ); + marks.toggle(target("/synthetic/a/child", 1), PathStyle::Native); + assert_eq!( + marks.ancestor( + Path::new("/synthetic/a/child/file"), + PathStyle::Native + ), + Some(Path::new("/synthetic/a/child")) + ); + } + + #[test] + fn absorption_invalidates_cached_crumbs_and_keeps_missing_paths_indexed() { + let root_path = Path::new("/home/tobi"); + let root = Arc::new(tree()); + let mut marks = Marks::default(); + marks + .toggle(target("/home/tobi/.cache/blob.bin", 0), PathStyle::Native); + marks.toggle(target("/home/tobi/.cache", 0), PathStyle::Native); + marks.toggle(target("/home/tobi/gone/nested", 100), PathStyle::Native); + let before = + marks.crumbs(root_path, &root, Metric::Bytes, PathStyle::Native); + assert_eq!(before.len(), 2); + assert_eq!( + marks.absorb(Path::new("/home/tobi/.cache"), PathStyle::Native), + 1 + ); + let after = + marks.crumbs(root_path, &root, Metric::Bytes, PathStyle::Native); + assert!(!Arc::ptr_eq(&before, &after)); + assert_eq!(after.len(), 1); + assert!(after.contains(&vec![0])); + marks.refresh(root_path, root.root(), Metric::Files, PathStyle::Native); + assert!( + marks.contains( + Path::new("/home/tobi/gone/nested"), + PathStyle::Native + ) + ); + assert_eq!( + marks.absorb(Path::new("/home/tobi/gone"), PathStyle::Native), + 1 + ); + assert!( + !marks.contains( + Path::new("/home/tobi/gone/nested"), + PathStyle::Native + ) + ); + } + + #[cfg(unix)] + #[test] + fn ordered_marks_keep_exact_non_utf8_paths() { + use std::os::unix::ffi::OsStrExt as _; + let root = Path::new("/synthetic"); + let parent = root.join(std::ffi::OsStr::from_bytes(b"not-\xff")); + let child = parent.join("file"); + let mut marks = Marks::default(); + marks.toggle( + Target { + path: child.clone(), + bytes: 1, + is_dir: false, + hidden: false, + }, + PathStyle::Native, + ); + marks.toggle( + Target { + path: parent.clone(), + bytes: 1, + is_dir: true, + hidden: false, + }, + PathStyle::Native, + ); + assert_eq!( + marks.ancestor(&child, PathStyle::Native), + Some(parent.as_path()) + ); + assert_eq!(marks.absorb(&parent, PathStyle::Native), 1); + assert!(marks.contains(&parent, PathStyle::Native)); + assert!(!marks.contains(&child, PathStyle::Native)); + } + #[test] fn toggling_marks_and_unmarks() { let mut marks = Marks::default(); - assert!(marks.toggle(target("/home/tobi/a", 1))); - assert!(marks.contains(Path::new("/home/tobi/a"))); + assert!(marks.toggle(target("/home/tobi/a", 1), PathStyle::Native)); + assert!(marks.contains(Path::new("/home/tobi/a"), PathStyle::Native)); assert_eq!(marks.len(), 1); - assert!(!marks.toggle(target("/home/tobi/a", 1))); + assert!(!marks.toggle(target("/home/tobi/a", 1), PathStyle::Native)); assert!(marks.is_empty()); } #[test] fn marking_the_same_path_twice_keeps_one_entry() { let mut marks = Marks::default(); - marks.toggle(target("/home/tobi/a", 1)); - marks.toggle(target("/home/tobi/a", 1)); - marks.toggle(target("/home/tobi/a", 1)); + marks.toggle(target("/home/tobi/a", 1), PathStyle::Native); + marks.toggle(target("/home/tobi/a", 1), PathStyle::Native); + marks.toggle(target("/home/tobi/a", 1), PathStyle::Native); assert_eq!(marks.len(), 1); } @@ -173,49 +859,45 @@ mod tests { let root_path = Path::new("/home/tobi"); let root = tree(); let mut marks = Marks::default(); - marks.toggle(target("/home/tobi/.cache", 0)); - marks.toggle(target("/home/tobi/gone", 500)); + marks.toggle(target("/home/tobi/.cache", 0), PathStyle::Native); + marks.toggle(target("/home/tobi/gone", 500), PathStyle::Native); - marks.refresh(root_path, &root, Metric::Bytes); - assert_eq!(marks.items()[0].bytes, 900); - assert!(marks.items()[0].is_dir); - assert!(marks.items()[0].hidden, "the .cache mark is hidden"); - assert_eq!(marks.items()[1].bytes, 0, "a path that no longer exists"); + // Removal bytes stay measured bytes even when the treemap shows files. + for metric in [Metric::Bytes, Metric::Files] { + marks.refresh(root_path, root.root(), metric, PathStyle::Native); + assert_eq!(marks.items()[0].bytes, 900); + assert!(marks.items()[0].is_dir); + assert!(marks.items()[0].hidden, "the .cache mark is hidden"); + assert_eq!( + marks.items()[1].bytes, + 0, + "a path that no longer exists" + ); + } } #[test] fn find_matches_whole_components_only() { let root = tree(); - assert!( - find( - Path::new("/home/tobi"), - &root, - Path::new("/home/tobi/.cache") - ) - .is_some() + let mut resolver = Resolver::new( + Path::new("/home/tobi"), + root.root(), + PathStyle::Native, ); + assert!(resolver.resolve(Path::new("/home/tobi/.cache")).is_some()); assert!( - find( - Path::new("/home/tobi"), - &root, - Path::new("/home/tobi/.cache/blob.bin") - ) - .is_some() + resolver + .resolve(Path::new("/home/tobi/.cache/blob.bin")) + .is_some() ); + assert!(resolver.resolve(Path::new("/home/tobi/cache")).is_none()); assert!( - find( - Path::new("/home/tobi"), - &root, - Path::new("/home/tobi/cache") - ) - .is_none() - ); - assert!( - find( + Resolver::new( Path::new("/elsewhere"), - &root, - Path::new("/home/tobi/notes.bin") + root.root(), + PathStyle::Native ) + .resolve(Path::new("/home/tobi/notes.bin")) .is_none() ); } @@ -225,11 +907,237 @@ mod tests { let home = Path::new("/home/tobi"); let separator = std::path::MAIN_SEPARATOR; assert_eq!( - display_path(&home.join(".cache").join("npm"), Some(home)), + display_path( + &home.join(".cache").join("npm"), + Some(home), + PathStyle::Native + ), format!("~{separator}.cache{separator}npm") ); - assert_eq!(display_path(home, Some(home)), "~"); - assert_eq!(display_path(Path::new("/var/log"), Some(home)), "/var/log"); - assert_eq!(display_path(Path::new("/var/log"), None), "/var/log"); + assert_eq!(display_path(home, Some(home), PathStyle::Native), "~"); + assert_eq!( + display_path(Path::new("/var/log"), Some(home), PathStyle::Native), + "/var/log" + ); + assert_eq!( + display_path(Path::new("/var/log"), None, PathStyle::Native), + "/var/log" + ); + } + /// Vary each input separately: files, marks, path depth and refreshes + /// must not be conflated with growing siblings and marks together. + #[test] + fn refresh_dimension_budget() { + let measure = |folders: usize, + marked: usize, + depth: usize, + repeats: usize| { + let root_path = std::env::temp_dir().join("marks-dimensions"); + let mut root = Draft::directory("root"); + let mut marks = Marks::default(); + for index in 0..folders { + let name = format!("folder-{index:05}"); + let mut child = file("payload", 1); + let mut relative = PathBuf::from(&name); + for _ in 1..depth { + let mut parent = Draft::directory("nested"); + parent.children.push(child); + child = parent; + relative.push("nested"); + } + let mut folder = Draft::directory(name); + folder.children.push(child); + root.children.push(folder); + relative.push("payload"); + if index >= folders - marked { + marks.toggle( + Target { + path: root_path.join(relative), + bytes: 0, + is_dir: false, + hidden: false, + }, + PathStyle::Native, + ); + } + } + let root = Tree::from(root); + work::reset(); + let start = std::time::Instant::now(); + for _ in 0..repeats { + marks.refresh( + &root_path, + root.root(), + Metric::Bytes, + PathStyle::Native, + ); + } + let operations = work::RESOLUTION.get(); + assert!(marks.items().iter().all(|item| item.bytes == 1)); + eprintln!( + "dimensions folders={folders} M={marked} D={} R={repeats} work={operations} wall={:?}", + depth + 1, + start.elapsed() + ); + operations + }; + let base = measure(128, 8, 1, 1); + let more_files = measure(1024, 8, 1, 1); + assert!(more_files <= base * 16); + let more_marks = measure(1024, 64, 1, 1); + assert!(more_marks <= more_files * 16); + let more_depth = measure(128, 8, 15, 1); + assert!(more_depth <= base * 16); + let more_refreshes = measure(128, 8, 1, 8); + assert_eq!(more_refreshes, base * 8); + assert!(more_files <= 1024 * 8 * 4); + } + /// A Unix host's paths read the same on every client: `/` after `~`, and + /// a name holding `\` is one name, not two. + #[test] + fn remote_paths_display_and_resolve_by_posix_rules() { + let posix = PathStyle::Posix; + let home = Path::new("/home/tobi"); + assert_eq!( + display_path(Path::new("/home/tobi/.cache/npm"), Some(home), posix), + "~/.cache/npm" + ); + assert_eq!( + display_path(Path::new("/home/tobix"), Some(home), posix), + "/home/tobix" + ); + let mut root = Draft::directory("home"); + root.children.push(file(r"a\b", 7)); + let root = Tree::from(root); + assert!( + Resolver::new(home, root.root(), posix) + .resolve(Path::new(r"/home/tobi/a\b")) + .is_some() + ); + assert!( + Resolver::new(home, root.root(), posix) + .resolve(Path::new("/home/tobi/a/b")) + .is_none() + ); + assert!(!is_hidden(Path::new(r"/srv/x\.hidden"), posix)); + assert!(is_hidden(Path::new("/srv/.cache"), posix)); + } + + /// Marks are keyed by the exact path text, so `/a/b\c` and `/a/b/c` + /// stay two marks even where `PathBuf` would call them equal. + #[test] + fn marks_compare_the_exact_path() { + let mut marks = Marks::default(); + marks.toggle(target(r"/srv/b\c", 1), PathStyle::Posix); + assert!(!marks.contains(Path::new("/srv/b/c"), PathStyle::Posix)); + assert!(marks.toggle(target("/srv/b/c", 1), PathStyle::Posix)); + assert_eq!(marks.len(), 2); + marks.remove(Path::new("/srv/b/c"), PathStyle::Posix); + assert!(marks.contains(Path::new(r"/srv/b\c"), PathStyle::Posix)); + } + + #[test] + fn posix_index_absorbs_only_whole_host_components() { + let style = PathStyle::Posix; + let mut marks = Marks::default(); + for path in [ + "/srv/a-b/keep", + "/srv/a/child", + r"/srv/a\b/keep", + "/srv/a:b/keep", + "/srv/a", + ] { + marks.toggle(target(path, 1), style); + } + assert_eq!(marks.absorb(Path::new("/srv/a"), style), 1); + let paths: Vec<_> = marks + .items() + .iter() + .map(|item| item.path.to_str().unwrap()) + .collect(); + assert_eq!( + paths, + ["/srv/a-b/keep", r"/srv/a\b/keep", "/srv/a:b/keep", "/srv/a"] + ); + assert_eq!( + marks + .ancestor(Path::new("/srv/a/next"), style) + .unwrap() + .to_str(), + Some("/srv/a") + ); + assert!(marks.ancestor(Path::new(r"/srv/a\b/next"), style).is_none()); + assert_eq!(marks.absorb(Path::new(r"/srv/a\b"), style), 1); + assert!(marks.contains(Path::new("/srv/a:b/keep"), style)); + assert!(marks.contains(Path::new("/srv/a-b/keep"), style)); + } + + #[test] + fn posix_refresh_and_crumb_cache_keep_ambiguous_windows_names_distinct() { + let style = PathStyle::Posix; + let root_path = Path::new("/srv"); + let mut root = Draft::directory("srv"); + let mut literal = Draft::directory(r"logs\old"); + literal.children.push(file("a:b", 7)); + let mut nested = Draft::directory("logs"); + let mut old = Draft::directory("old"); + old.children.push(file("a:b", 9)); + nested.children.push(old); + root.children.extend([literal, nested]); + let mut root = Tree::from(root); + aggregate(&mut root, Metric::Bytes); + let root = Arc::new(root); + let mut marks = Marks::default(); + for path in [r"/srv/logs\old/a:b", "/srv/logs/old/a:b"] { + marks.toggle(target(path, 0), style); + } + marks.refresh(root_path, root.root(), Metric::Bytes, style); + assert_eq!( + marks + .items() + .iter() + .map(|item| item.bytes) + .collect::>(), + [7, 9] + ); + let crumbs = marks.crumbs(root_path, &root, Metric::Bytes, style); + assert_eq!(crumbs.len(), 2); + for item in marks.items() { + let (path, node) = Resolver::new(root_path, root.root(), style) + .resolve(&item.path) + .unwrap(); + assert!(crumbs.contains(&path)); + assert_eq!(node.bytes, item.bytes); + } + let native = + marks.crumbs(root_path, &root, Metric::Bytes, PathStyle::Native); + assert!( + !Arc::ptr_eq(&crumbs, &native), + "path rules invalidate the cache" + ); + assert_eq!( + marks.crumbs(root_path, &root, Metric::Bytes, style).len(), + 2 + ); + } + + #[test] + fn posix_crumb_cache_compares_root_text_in_the_host_namespace() { + let style = PathStyle::Posix; + let root_path = Path::new(r"/srv/a\b"); + let mut root = Draft::directory("root"); + root.children.push(file("payload", 7)); + let root = Arc::new(Tree::from(root)); + let mut marks = Marks::default(); + marks.toggle(target(r"/srv/a\b/payload", 7), style); + assert_eq!( + marks.crumbs(root_path, &root, Metric::Bytes, style).len(), + 1 + ); + assert!( + marks + .crumbs(Path::new("/srv/a/b"), &root, Metric::Bytes, style) + .is_empty() + ); } } diff --git a/crates/disktree-app/src/palette.rs b/crates/disktree-app/src/palette.rs index 1f5ad7e7..67278782 100644 --- a/crates/disktree-app/src/palette.rs +++ b/crates/disktree-app/src/palette.rs @@ -29,7 +29,10 @@ const fn hue(category: Category) -> (f32, f32) { Category::Git => (0.955, 1.0), Category::Media => (0.745, 1.0), Category::Cache => (0.125, 0.95), + Category::FilesystemEvents => (0.31, 0.6), + Category::Spotlight => (0.855, 0.6), Category::Documents => (0.6, 0.18), + Category::VirtualMachine => (0.69, 0.7), Category::Other => (0.6, 0.08), } } @@ -130,13 +133,15 @@ pub const fn highlight(theme: &Theme) -> Hsla { theme.warning } -/// Text on a filled highlight. -pub const fn on_highlight(theme: &Theme) -> Hsla { - if dark(theme) { +/// Text on a filled highlight: dark on dark themes and light on light +/// ones, as before, unless that ink fails on this theme's highlight. +pub fn on_highlight(theme: &Theme) -> Hsla { + let preferred = if dark(theme) { theme.background } else { theme.bright - } + }; + ink_on(preferred, highlight(theme), 4.5) } /// The diagonal hatch over reclaimable space: quiet enough to leave the hue @@ -149,6 +154,16 @@ pub fn hatch(theme: &Theme) -> Hsla { } } +/// A window button disktree paints where a Linux compositor leaves the +/// frame to it, at rest and under the pointer: a quiet square that reads as +/// a control on any theme without competing with the trail beside it. +pub fn window_button(theme: &Theme) -> (Hsla, Hsla) { + ( + theme.foreground.opacity(0.08), + theme.foreground.opacity(0.16), + ) +} + /// Linear interpolation between two colours, in RGB: interpolating hue /// would drag a colour around the wheel on its way to a grey. pub fn mix(from: Hsla, to: Hsla, t: f32) -> Hsla { @@ -173,10 +188,149 @@ pub fn label_color(theme: &Theme, depth: u32) -> Hsla { if depth == 0 { base } else { base.opacity(0.88) } } +/// WCAG contrast after alpha compositing in sRGB, then linearizing. +pub fn contrast(ink: Hsla, surface: Hsla) -> f32 { + let luminance = |color: Hsla| { + let rgb = color.to_rgb(); + let linear = |channel: f32| { + if channel <= 0.040_45 { + channel / 12.92 + } else { + ((channel + 0.055) / 1.055).powf(2.4) + } + }; + 0.0722_f32.mul_add( + linear(rgb.b), + 0.7152_f32.mul_add(linear(rgb.g), 0.2126 * linear(rgb.r)), + ) + }; + let shown = mix(surface, Hsla { a: 1.0, ..ink }, ink.a); + let (a, b) = (luminance(shown), luminance(surface)); + (a.max(b) + 0.05) / (a.min(b) + 0.05) +} + +/// Keep the theme's ink when it passes; otherwise choose an opaque neutral. +/// One of black/white always exceeds 4.5:1 on an opaque flat surface. +pub fn ink_on(preferred: Hsla, surface: Hsla, minimum: f32) -> Hsla { + let preferred = Hsla { + a: 1.0, + ..preferred + }; + if contrast(preferred, surface) >= minimum { + return preferred; + } + let black: Hsla = gpui_kit::rgb(0x0000_0000).into(); + let white: Hsla = gpui_kit::rgb(0x00ff_ffff).into(); + if contrast(black, surface) >= contrast(white, surface) { + black + } else { + white + } +} + +/// A ring or mark keeps the theme's colour, translucency included, when it +/// passes over `surface`; otherwise it falls back to `ink_on`. Unlike text, +/// a painted quad's alpha composites once, so it can be measured as is. +pub fn boundary_on(preferred: Hsla, surface: Hsla, minimum: f32) -> Hsla { + if contrast(preferred, surface) >= minimum { + preferred + } else { + ink_on(preferred, surface, minimum) + } +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn audit_contrast_composites_alpha_before_linearizing() { + let black = gpui_kit::rgb(0x0000_0000).into(); + let white: Hsla = gpui_kit::rgb(0x00ff_ffff).into(); + assert!((contrast(white, black) - 21.0).abs() < 0.001); + assert!((contrast(white.opacity(0.0), black) - 1.0).abs() < 0.001); + assert!((contrast(white.opacity(0.5), black) - 5.281).abs() < 0.01); + } + + /// Legacy baseline formulas, retained to reproduce the original audit. + /// Production tile-state thresholds live in `treemap_view` tests. + #[test] + #[ignore = "prints audit measurements; does not certify contrast"] + fn audit_contrast_report() { + let categories = [ + Category::Code, + Category::AgentScratch, + Category::Toolchain, + Category::Synced, + Category::Git, + Category::Media, + Category::Documents, + Category::Cache, + Category::FilesystemEvents, + Category::Spotlight, + Category::Other, + ]; + println!("theme,pair,minimum_ratio,required"); + for (name, theme) in [ + ("tokyo-night", Theme::tokyo_night()), + ("flexoki-light", Theme::flexoki_light()), + ] { + let mut names = f32::INFINITY; + let mut values = f32::INFINITY; + let mut selected = f32::INFINITY; + for depth in 0..=4 { + let fills = categories + .iter() + .map(|&category| category_fill(&theme, category, depth)) + .chain( + (0..AGE_BUCKETS.len()) + .map(|bucket| age_fill(&theme, bucket, depth)), + ); + for fill in fills { + names = + names.min(contrast(label_color(&theme, depth), fill)); + values = values.min(contrast( + label_color(&theme, 1).opacity(0.5), + fill, + )); + selected = selected.min(contrast(highlight(&theme), fill)); + } + } + for (pair, ratio, required) in [ + ("tile-name", names, 4.5), + ("tile-size", values, 4.5), + ("selection-ring-vs-fill", selected, 3.0), + ( + "marked-name", + contrast( + theme.danger, + mix(theme.inset, theme.danger, 0.16), + ), + 4.5, + ), + ( + "secondary-caption", + contrast(theme.secondary.opacity(0.75), theme.background), + 4.5, + ), + ( + "highlight-button", + contrast( + if dark(&theme) { + theme.background + } else { + theme.bright + }, + highlight(&theme), + ), + 4.5, + ), + ] { + println!("{name},{pair},{ratio:.3},{required:.1}"); + } + } + } + fn theme(appearance: ThemeAppearance) -> Theme { match appearance { ThemeAppearance::Dark => Theme::tokyo_night(), diff --git a/crates/disktree-app/src/placement.rs b/crates/disktree-app/src/placement.rs new file mode 100644 index 00000000..5acd5495 --- /dev/null +++ b/crates/disktree-app/src/placement.rs @@ -0,0 +1,140 @@ +//! Which display a new window opens on: the one the user is working on, as +//! macOS places a new window, rather than the primary display GPUI falls +//! back to when it is given none. +//! +//! The display, in order: +//! 1. the one PwrDisk's focused window is on: Settings, Help's documents +//! and Logs open beside the main window; +//! 2. the one under the pointer, on macOS: the Dock icon or the Finder +//! window just clicked to launch PwrDisk; +//! 3. none, and GPUI's primary display. +//! +//! The main window only asks when it has no saved frame, or that frame's +//! display is gone (see `window_frame.rs`). Every opener passes the display +//! both to `Bounds::centered` and as `WindowOptions::display_id`: GPUI +//! reads the bounds relative to that display, and opens on the primary one +//! without it. + +use gpui_kit::{App, DisplayId}; + +/// The display a new PwrDisk window should open on, or `None` for the +/// primary display. +pub fn display_for_new_window(cx: &mut App) -> Option { + let focused = cx.active_window().and_then(|window| { + // Err while that window is the one being updated (a click in it + // opened this one): the pointer is on it then. + window + .update(cx, |_, window, cx| window.display(cx).map(|d| d.id())) + .ok() + .flatten() + }); + let connected: Vec = + cx.displays().iter().map(|display| display.id()).collect(); + choose(focused, under_pointer(), &connected) +} + +/// [`display_for_new_window`]'s rule, apart from the platform: the focused +/// window's display, else the pointer's, skipping any that is no longer +/// connected. +fn choose( + focused: Option, + pointer: Option, + connected: &[DisplayId], +) -> Option { + [focused, pointer] + .into_iter() + .flatten() + .find(|display| connected.contains(display)) +} + +/// The display under the mouse pointer, as GPUI names displays: the +/// screen's `NSScreenNumber`, the `CGDirectDisplayID` GPUI keys them by. +/// `None` off the main thread, or when no screen holds the pointer. +#[cfg(target_os = "macos")] +fn under_pointer() -> Option { + use objc2::MainThreadMarker; + use objc2_app_kit::{NSEvent, NSScreen}; + use objc2_foundation::{NSNumber, NSString}; + + let mtm = MainThreadMarker::new()?; + // Both in AppKit's global space: bottom-left origin, in points. + let mouse = NSEvent::mouseLocation(); + let key = NSString::from_str("NSScreenNumber"); + NSScreen::screens(mtm).iter().find_map(|screen| { + let frame = screen.frame(); + let held = in_frame( + ( + frame.origin.x, + frame.origin.y, + frame.size.width, + frame.size.height, + ), + (mouse.x, mouse.y), + ); + if !held { + return None; + } + let number = screen + .deviceDescription() + .objectForKey(&key)? + .downcast::() + .ok()?; + Some(DisplayId::new(u64::from(number.unsignedIntValue()))) + }) +} + +/// Windows and Linux: GPUI has no pointer position outside a window, so a +/// new window follows the focused one or opens on the primary display. +#[cfg(not(target_os = "macos"))] +const fn under_pointer() -> Option { + None +} + +/// Whether `point` lies in `frame`, both in the bottom-left-origin space +/// `AppKit` uses. A screen's frame holds its left and top edges: the +/// pointer at the very top of a screen is at `y + height`, and at its left +/// at `x`. +#[cfg(any(target_os = "macos", test))] +fn in_frame( + (x, y, width, height): (f64, f64, f64, f64), + (px, py): (f64, f64), +) -> bool { + (x..x + width).contains(&px) && py > y && py <= y + height +} + +#[cfg(test)] +mod tests { + use super::*; + + fn id(n: u64) -> DisplayId { + DisplayId::new(n) + } + + #[test] + fn the_focused_window_wins_then_the_pointer() { + let both = [id(1), id(2)]; + assert_eq!(choose(Some(id(2)), Some(id(1)), &both), Some(id(2))); + // No PwrDisk window yet (a launch): the pointer's. + assert_eq!(choose(None, Some(id(2)), &both), Some(id(2))); + // Neither: GPUI's primary display. + assert_eq!(choose(None, None, &both), None); + } + + #[test] + fn a_display_no_longer_connected_is_skipped() { + let one = [id(1)]; + assert_eq!(choose(Some(id(2)), Some(id(1)), &one), Some(id(1))); + assert_eq!(choose(Some(id(2)), Some(id(3)), &one), None); + } + + #[test] + fn a_screen_holds_its_top_and_left_edges_only() { + // A second screen to the right of a 1512-point laptop. + let right = (1512.0, 0.0, 2560.0, 1440.0); + assert!(in_frame(right, (1512.0, 700.0)), "its left edge"); + assert!(in_frame(right, (2000.0, 1440.0)), "its top edge"); + assert!(!in_frame(right, (1511.9, 700.0)), "the laptop's"); + assert!(!in_frame(right, (4072.0, 700.0)), "past its right edge"); + assert!(!in_frame(right, (2000.0, 0.0)), "its bottom edge"); + } +} diff --git a/crates/disktree-app/src/power.rs b/crates/disktree-app/src/power.rs index c4a05bd5..2154a444 100644 --- a/crates/disktree-app/src/power.rs +++ b/crates/disktree-app/src/power.rs @@ -100,9 +100,9 @@ pub fn cpu_threads() -> usize { /// Follow each desktop's user configuration location; never write beside /// the executable or scanned root. No home/config location means session-only. -pub fn settings_path() -> Option { +fn config_base() -> Option { let home = std::env::home_dir(); - let base = if cfg!(target_os = "macos") { + if cfg!(target_os = "macos") { home.map(|home| home.join("Library/Application Support")) } else if cfg!(windows) { std::env::var_os("APPDATA").map(PathBuf::from) @@ -111,8 +111,29 @@ pub fn settings_path() -> Option { .map(PathBuf::from) .filter(|path| path.is_absolute()) .or_else(|| home.map(|home| home.join(".config"))) - }; - base.map(|base| base.join("disktree/power-efficiency")) + } +} + +pub fn settings_path() -> Option { + config_base().map(|base| base.join("pwrdisk/power-efficiency")) +} + +/// Where disktree, which PwrDisk was forked from, kept the same setting. +/// Read only, so someone switching over keeps their choice; never written. +pub fn legacy_settings_path() -> Option { + config_base().map(|base| base.join("disktree/power-efficiency")) +} + +/// `load`, except that a missing file falls back to `legacy` when that +/// exists. The next save lands at `path`, which then wins. +pub fn load_or_legacy( + path: &Path, + legacy: Option<&Path>, +) -> io::Result { + match legacy { + Some(legacy) if !path.exists() && legacy.exists() => load(legacy), + _ => load(path), + } } pub fn load(path: &Path) -> io::Result { @@ -204,4 +225,26 @@ mod tests { ); assert!(save(dir.path(), PowerEfficiency::Miser).is_err()); } + + #[test] + fn a_disktree_setting_is_read_until_pwrdisk_saves_its_own() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("pwrdisk/power-efficiency"); + let legacy = dir.path().join("disktree/power-efficiency"); + assert_eq!( + load_or_legacy(&path, Some(&legacy)).expect("neither"), + PowerEfficiency::Balanced + ); + save(&legacy, PowerEfficiency::Miser).expect("legacy"); + assert_eq!( + load_or_legacy(&path, Some(&legacy)).expect("legacy"), + PowerEfficiency::Miser + ); + save(&path, PowerEfficiency::Aggressive).expect("save"); + assert_eq!( + load_or_legacy(&path, Some(&legacy)).expect("own"), + PowerEfficiency::Aggressive + ); + assert!(legacy.exists(), "the legacy file is never removed"); + } } diff --git a/crates/disktree-app/src/run_list.rs b/crates/disktree-app/src/run_list.rs new file mode 100644 index 00000000..1ba457dd --- /dev/null +++ b/crates/disktree-app/src/run_list.rs @@ -0,0 +1,349 @@ +//! The removal's own list: every target as the run started, what the scan +//! said each one was, and what happened to it. +//! +//! Removing and Done both draw it, so the list a person approved stays on +//! screen while it is worked through and after, instead of only the names +//! of what already went. It is also the run's only record: the counts the +//! agent is told, the ledger's cohort and what the tree marks as gone are +//! all read from it, so they cannot disagree with what the screen shows. + +use std::path::Path; + +use disktree_core::classify::{Category, Reclaim}; +use disktree_core::removal::Target; + +/// What happened to one item. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Status { + /// Not reported yet: waiting, in hand, or never reached after a stop. + Waiting, + Removed, + Failed(String), +} + +/// One target of the run. +#[derive(Clone, Debug)] +pub struct Item { + /// The plan's target, as the worker is given it: its path and the + /// listed allocation when it was marked. + pub target: Target, + /// The scan's kind for it, for its colour. + pub category: Category, + /// Why the scan thinks its space can be had back, if it does. + pub reclaim: Option, + /// What the scan saw as only this item's. `None` where it cannot say, + /// as in an apparent-size scan. + pub private: Option, + pub status: Status, +} + +impl Item { + /// Why it is on the list, in the words the legend and "Worth a look" + /// use: the reclaim reason when there is one, else its kind. + pub fn kind(&self) -> Option<&'static str> { + kind(self.category, self.reclaim) + } +} + +/// Why a path is listed, as Review and Removing both say it: the reclaim +/// reason when the scan has one, else its kind, else nothing. +pub fn kind( + category: Category, + reclaim: Option, +) -> Option<&'static str> { + reclaim + .map(Reclaim::label) + .or_else(|| (category != Category::Other).then(|| category.name())) +} + +/// The run's items in the order the worker takes them. +#[derive(Clone, Debug, Default)] +pub struct RunList { + pub items: Vec, + /// Where the next report is expected: the worker goes in plan order. + next: usize, + /// Keep the item in hand in view, as the live log keeps its newest + /// line: paused while the person has scrolled it out of view, and on + /// again once it is back in view or they ask. + pub follow: bool, + /// The wheel moved the list since the last poll, which then decides + /// whether that paused following. + pub scrolled_by_hand: bool, + /// Failures reported against no listed target. The worker reports + /// every failure, a start that failed included, against a listed one; + /// counted anyway, so the run never reads as clean when it was not. + unlisted_failures: usize, +} + +/// The run's figures so far, beside what the whole run would come to. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Totals { + pub removed: usize, + /// Listed items that failed, so `removed + failed` never exceeds + /// `total` and the rest are the ones not reached. + pub failed: usize, + /// Failures reported against no listed item. + pub unlisted: usize, + pub total: usize, + pub reported_done: u64, + pub reported_all: u64, + /// `None` once any item's private part is unknown. + pub private_done: Option, + pub private_all: Option, +} + +impl Totals { + /// Every failure the worker reported, listed or not: what the agent + /// and the ledger are told, so no failure is lost to a stray path. + pub const fn failed_all(&self) -> usize { + self.failed + self.unlisted + } +} + +impl RunList { + pub const fn new(items: Vec) -> Self { + Self { + items, + next: 0, + follow: true, + scrolled_by_hand: false, + unlisted_failures: 0, + } + } + + /// Record the worker's report on `path`. Returns the item's index, or + /// `None` for a path it never listed, which still counts if it failed. + pub fn settle( + &mut self, + path: &Path, + outcome: &Result<(), String>, + ) -> Option { + let waiting = |item: &Item| { + item.status == Status::Waiting && item.target.path == path + }; + // Reports come in plan order, so the expected one is checked + // first; the whole list only if the worker ever skips ahead. + let index = self + .items + .get(self.next..) + .and_then(|rest| rest.iter().position(waiting)) + .map(|offset| self.next + offset) + .or_else(|| self.items.iter().position(waiting)); + let Some(index) = index else { + if outcome.is_err() { + self.unlisted_failures += 1; + } + return None; + }; + self.items[index].status = match outcome { + Ok(()) => Status::Removed, + Err(error) => Status::Failed(error.clone()), + }; + self.next = index + 1; + Some(index) + } + + /// The item the worker has in hand, while it runs: the first one not + /// reported yet. + pub fn current(&self) -> Option { + let rest = self.items.get(self.next..)?; + rest.iter() + .position(|item| item.status == Status::Waiting) + .map(|offset| self.next + offset) + } + + /// The item to keep in view: the one in hand, or the last one + /// reported once there is none. + pub fn focus(&self) -> Option { + self.current().or_else(|| self.next.checked_sub(1)) + } + + /// The targets that went, in plan order: what the tree shows as gone + /// and the ledger's cohort counts. One pass, however long the list. + pub fn removed(&self) -> impl Iterator { + self.items + .iter() + .filter(|item| item.status == Status::Removed) + .map(|item| &item.target) + } + + pub fn totals(&self) -> Totals { + let mut totals = Totals { + unlisted: self.unlisted_failures, + total: self.items.len(), + private_done: Some(0), + private_all: Some(0), + ..Totals::default() + }; + let add = |sum: Option, part: Option| { + sum.zip(part).map(|(sum, part)| sum + part) + }; + for item in &self.items { + totals.reported_all += item.target.bytes; + totals.private_all = add(totals.private_all, item.private); + match item.status { + Status::Removed => { + totals.removed += 1; + totals.reported_done += item.target.bytes; + totals.private_done = + add(totals.private_done, item.private); + } + Status::Failed(_) => totals.failed += 1, + Status::Waiting => {} + } + } + totals + } +} + +/// `text`, a path as a person reads it, in about `budget` characters: +/// whole names are dropped from its middle into one `…`, keeping the first +/// name after `~` or the root, which says where it lives, and as much of +/// the end as fits, which says what it is. A path that cannot be made to +/// fit comes back as short as it goes; the row clips the rest. +pub fn elide_middle(text: &str, separator: char, budget: usize) -> String { + if text.chars().count() <= budget { + return text.to_string(); + } + let parts: Vec<&str> = text.split(separator).collect(); + // `~/code/…`, `/var/…` (an empty first part) or `C:\Users\…`: the + // root and the name under it. + let head = 2.min(parts.len()); + if parts.len() <= head + 1 { + return text.to_string(); + } + let sep = separator.to_string(); + let head_text = parts[..head].join(&sep); + let width = |tail: &[&str]| { + head_text.chars().count() + + 3 + + tail.iter().map(|name| name.chars().count()).sum::() + + tail.len().saturating_sub(1) + }; + let mut start = parts.len() - 1; + while start > head + 1 && width(&parts[start - 1..]) <= budget { + start -= 1; + } + format!("{head_text}{sep}\u{2026}{sep}{}", parts[start..].join(&sep)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn item(path: &str, bytes: u64, private: Option) -> Item { + Item { + target: Target { + path: path.into(), + bytes, + is_dir: true, + hidden: false, + }, + category: Category::Other, + reclaim: None, + private, + status: Status::Waiting, + } + } + + #[test] + fn a_short_path_is_left_alone() { + assert_eq!(elide_middle("~/code/app", '/', 40), "~/code/app"); + } + + #[test] + fn the_middle_goes_first_and_whole_names_at_a_time() { + let path = "~/code/clients/sample-co/apps/dashboard/packages/ui"; + assert_eq!( + elide_middle(path, '/', 36), + "~/code/\u{2026}/apps/dashboard/packages/ui" + ); + assert_eq!(elide_middle(path, '/', 24), "~/code/\u{2026}/packages/ui"); + // The last name stays, even past the budget. + assert_eq!(elide_middle(path, '/', 4), "~/code/\u{2026}/ui"); + } + + #[test] + fn an_absolute_path_keeps_its_first_directory() { + assert_eq!( + elide_middle("/var/lib/docker/overlay2/3f9c/diff", '/', 25), + "/var/\u{2026}/overlay2/3f9c/diff" + ); + } + + #[test] + fn a_windows_path_splits_on_its_own_separator() { + assert_eq!( + elide_middle(r"C:\Users\pat\AppData\Local\Temp\build", '\\', 22), + "C:\\Users\\\u{2026}\\Temp\\build" + ); + } + + #[test] + fn nothing_to_drop_returns_the_path() { + assert_eq!( + elide_middle("~/a-very-long-directory-name", '/', 8), + "~/a-very-long-directory-name" + ); + assert_eq!(elide_middle("~/one/two", '/', 4), "~/one/two"); + } + + #[test] + fn reports_settle_their_items_in_order() { + let mut list = RunList::new(vec![ + item("/r/a", 10, Some(4)), + item("/r/b", 20, Some(20)), + item("/r/c", 30, Some(30)), + ]); + assert_eq!(list.current(), Some(0)); + assert_eq!(list.settle(Path::new("/r/a"), &Ok(())), Some(0)); + assert_eq!(list.current(), Some(1)); + assert_eq!( + list.settle(Path::new("/r/b"), &Err("denied".into())), + Some(1) + ); + assert_eq!(list.current(), Some(2)); + let totals = list.totals(); + assert_eq!(totals.removed, 1); + assert_eq!(totals.failed, 1); + assert_eq!(totals.reported_done, 10); + assert_eq!(totals.reported_all, 60); + assert_eq!(totals.private_done, Some(4)); + assert_eq!(totals.private_all, Some(54)); + assert_eq!(list.items[1].status, Status::Failed("denied".into())); + // A path it never listed settles no item, but a failure still + // counts. + assert_eq!(list.settle(Path::new(""), &Err("x".into())), None); + assert_eq!(list.totals().failed, 1); + assert_eq!(list.totals().failed_all(), 2); + assert_eq!(list.settle(Path::new(""), &Ok(())), None); + assert_eq!(list.totals().failed_all(), 2); + assert_eq!(list.settle(Path::new("/r/c"), &Ok(())), Some(2)); + assert_eq!(list.current(), None); + let removed: Vec<_> = + list.removed().map(|target| target.path.clone()).collect(); + assert_eq!(removed, [Path::new("/r/a"), Path::new("/r/c")]); + } + + #[test] + fn one_unknown_private_part_makes_the_total_unknown() { + let list = RunList::new(vec![ + item("/r/a", 10, Some(4)), + item("/r/b", 20, None), + ]); + assert_eq!(list.totals().private_all, None); + assert_eq!(list.totals().private_done, Some(0)); + } + + #[test] + fn an_item_says_why_it_is_listed() { + let mut build = item("/r/target", 1, None); + build.reclaim = Some(Reclaim::BuildOutput); + build.category = Category::Code; + assert_eq!(build.kind(), Some("build output")); + let mut media = item("/r/movies", 1, None); + media.category = Category::Media; + assert_eq!(media.kind(), Some("media")); + assert_eq!(item("/r/x", 1, None).kind(), None); + } +} diff --git a/crates/disktree-app/src/run_view.rs b/crates/disktree-app/src/run_view.rs new file mode 100644 index 00000000..2b734555 --- /dev/null +++ b/crates/disktree-app/src/run_view.rs @@ -0,0 +1,1070 @@ +//! Removing and Done: the run's list, checked off as it goes, beside its +//! running figures. Both screens draw the same list in the same place, so +//! nothing moves when the run ends and the list never disappears. + +use std::fmt::Write as _; + +use disktree_core::removal::RemovalMode; +use disktree_core::size::human_bytes; +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::{ + AnyElement, Div, ElementId, FontWeight, Hsla, InteractiveElement as _, + IntoElement, ParentElement, SharedString, Stateful, + StatefulInteractiveElement as _, Styled, Window, div, px, relative, +}; +use gpui_omarchy::{ActiveTheme, ButtonVariant, Theme, button}; + +use crate::widgets::with_tooltip; + +use crate::run_list::{Item, Status, Totals}; +use crate::semantics::AccessibleButton as _; +use crate::state::{Disktree, Screen}; +use crate::ui::{icon, size, space, text}; +use crate::views::{ + REVIEW_COLUMNS_REMS, dialog_footer, ledger_table, screen_footer, + screen_header, signed_bytes, +}; +use crate::{palette, widgets}; + +/// Rems a row spends on everything but its name and folder: the checkbox, +/// the swatch, the kind chip, the size and status lanes and the gaps. +const ROW_FIXED_REMS: f32 = 22.0; +/// The same, without the status lane, in a narrow window. +const ROW_FIXED_COMPACT_REMS: f32 = 16.0; +/// Review's rows: the icon, the swatch, the kind chip, the share bar, the +/// size, Unmark and the gaps. +pub const REVIEW_ROW_FIXED_REMS: f32 = 30.0; +/// A caption character's average advance in ems, on the generous side: the +/// shortened folder should fit, and the row clips whatever does not. +const CAPTION_ADVANCE_EMS: f32 = 0.6; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Phase { + Running, + Done, +} + +/// How one row reads. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Row<'a> { + Waiting, + Current, + /// Never reached: the run was stopped first. + Skipped, + Removed, + Failed(&'a str), +} + +impl Row<'_> { + const fn dimmed(self) -> bool { + matches!(self, Self::Waiting | Self::Skipped) + } + + /// A cache cleanup's step says what it does, which can differ by row. + const fn label( + self, + mode: RemovalMode, + action: Option, + ) -> &'static str { + use disktree_core::cleanup::Action; + match (self, action) { + (Self::Current, Some(Action::Owner)) => { + return "running command\u{2026}"; + } + (Self::Current, Some(Action::Trash)) => return "moving\u{2026}", + (Self::Current, Some(Action::Permanent)) => { + return "removing\u{2026}"; + } + (Self::Removed, Some(Action::Trash)) => return "in trash", + (Self::Removed, Some(Action::Permanent)) => return "deleted", + _ => {} + } + match (self, mode) { + (Self::Waiting, _) => "waiting", + (Self::Current, RemovalMode::Trash) => "moving\u{2026}", + (Self::Current, RemovalMode::Permanent) => "removing\u{2026}", + (Self::Current, RemovalMode::OwnerCleanup) => "cleaning\u{2026}", + (Self::Skipped, _) => "not reached", + (Self::Removed, RemovalMode::Trash) => "in trash", + (Self::Removed, RemovalMode::Permanent) => "removed", + (Self::Removed, RemovalMode::OwnerCleanup) => "command succeeded", + (Self::Failed(_), _) => "failed", + } + } + + const fn color(self, theme: &Theme) -> Hsla { + match self { + Self::Waiting | Self::Skipped => theme.secondary, + Self::Current => theme.accent, + Self::Removed => theme.success, + Self::Failed(_) => theme.danger, + } + } +} + +const fn mode_phrase(mode: RemovalMode, done: bool) -> &'static str { + match (mode, done) { + (RemovalMode::Trash, false) => "moving to trash", + (RemovalMode::Trash, true) => "moved to trash", + (RemovalMode::Permanent, false) => "deleting permanently", + (RemovalMode::Permanent, true) => "deleted permanently", + (RemovalMode::OwnerCleanup, false) => "running cache cleanup", + (RemovalMode::OwnerCleanup, true) => "cache cleanup finished", + } +} + +// ── running ───────────────────────────────────────────────────────────── + +pub fn running( + app: &Disktree, + toasts: Option, + window: &Window, + cx: &gpui_kit::Context<'_, Disktree>, +) -> Div { + let theme = cx.omarchy().clone(); + let totals = app.run_list.totals(); + let settled = totals.removed + totals.failed; + div() + .flex() + .flex_col() + .flex_1() + .min_h_0() + .child(screen_header( + "Removing", + &format!( + "{settled} of {} \u{b7} {}", + totals.total, + mode_phrase(app.removal_mode, false) + ), + &theme, + cx, + )) + .child(body(app, Phase::Running, &totals, toasts, window, cx)) + .child(screen_footer( + dialog_footer( + // Linux keeps its keys in view, as review does; macOS and + // Windows have the button and `?`. + (crate::chrome::Platform::current() + == crate::chrome::Platform::Linux) + .then(|| { + widgets::hint( + "esc", + if app.removal_mode == RemovalMode::OwnerCleanup { + "cancel owner command" + } else { + "stop after this item" + }, + cx, + ) + .into_any_element() + }), + None, + // Outlined, not danger: it loses nothing, and what was + // removed stays removed either way. + Some( + button( + "stop-removal", + if app.stop_requested { + "Stopping\u{2026}" + } else if app.removal_mode == RemovalMode::OwnerCleanup + { + "Cancel owner command" + } else { + "Stop after this item" + }, + ButtonVariant::Outline, + cx, + ) + .debug_selector(|| "stop-removal".into()) + .semantic_disabled(app.stop_requested) + .on_click(cx.listener(|this, _, window, cx| { + this.stop_removal(cx); + window.focus(&this.focus, cx); + })) + .into_any_element(), + ), + ), + &theme, + )) +} + +// ── done ──────────────────────────────────────────────────────────────── + +pub fn done( + app: &Disktree, + toasts: Option, + window: &Window, + cx: &gpui_kit::Context<'_, Disktree>, +) -> Div { + let theme = cx.omarchy().clone(); + let totals = app.run_list.totals(); + let owner_cleanup = app.removal_mode == RemovalMode::OwnerCleanup; + let mut subtitle = if owner_cleanup { + format!("{} cleanup steps succeeded", totals.removed) + } else { + format!("{} removed", totals.removed) + }; + if totals.failed_all() > 0 { + let _ = write!(subtitle, " \u{b7} {} failed", totals.failed_all()); + } + let skipped = totals.total - totals.removed - totals.failed; + if skipped > 0 { + let _ = write!(subtitle, " \u{b7} {skipped} not reached"); + } + let chose_skip = app + .cleanup_results + .iter() + .filter(|report| { + report.outcome == disktree_core::cleanup::Outcome::Skipped + }) + .count(); + if owner_cleanup && chose_skip > 0 { + let _ = write!(subtitle, " \u{b7} {chose_skip} skipped by you"); + } + subtitle.push_str(" \u{b7} "); + subtitle.push_str(mode_phrase(app.removal_mode, true)); + + // Rescan is offered while none runs: it is how the sharing figures + // catch up, and nothing else on this screen starts one. + let rescan = (app.scan.is_none()).then(|| { + button("done-rescan", "Rescan", ButtonVariant::Outline, cx) + .debug_selector(|| "done-rescan".into()) + .on_click(cx.listener(|this, _, window, cx| { + this.screen = Screen::Explore; + this.start_scan(cx); + window.focus(&this.focus, cx); + })) + .into_any_element() + }); + div() + .flex() + .flex_col() + .flex_1() + .min_h_0() + .child(screen_header("Done", &subtitle, &theme, cx)) + .child(body(app, Phase::Done, &totals, toasts, window, cx)) + .child(screen_footer( + dialog_footer( + [], + rescan, + // An acknowledgement, the default: Enter and Escape press it. + Some( + button("continue", "Done", ButtonVariant::Primary, cx) + .debug_selector(|| "continue".into()) + .on_click(cx.listener(|this, _, window, cx| { + this.screen = Screen::Explore; + cx.notify(); + window.focus(&this.focus, cx); + })) + .into_any_element(), + ), + ), + &theme, + )) +} + +// ── shared ────────────────────────────────────────────────────────────── + +/// The list on the left and the figures on the right, or the figures +/// under the list in a window too narrow for both, as review does. +fn body( + app: &Disktree, + phase: Phase, + totals: &Totals, + toasts: Option, + window: &Window, + cx: &gpui_kit::Context<'_, Disktree>, +) -> Div { + let theme = cx.omarchy().clone(); + let compact = window.viewport_size().width.as_f32() + / window.rem_size().as_f32() + < REVIEW_COLUMNS_REMS; + let budget = folder_budget( + window, + if compact { + ROW_FIXED_COMPACT_REMS + } else { + ROW_FIXED_REMS + }, + ); + + let sidebar = sidebar(app, phase, totals, &theme, cx) + .when(compact, |panel| panel.w_full().max_h(relative(0.45))); + div() + .relative() + .flex() + .flex_row() + .when(compact, gpui_kit::Styled::flex_col) + .gap(space::LG) + .p(space::LG) + .flex_1() + .min_h_0() + .child(list_column(app, phase, totals, budget, compact, &theme, cx)) + .child(sidebar) + .children(toasts) +} + +/// How many caption characters a row's folder line has to itself, in a +/// list beside the summary panel or, in a narrow window, across it. +/// `fixed` is what the row's other lanes take, in rems. +pub fn folder_budget(window: &Window, fixed: f32) -> usize { + let width = + window.viewport_size().width.as_f32() / window.rem_size().as_f32(); + let list = if width < REVIEW_COLUMNS_REMS { + width + } else { + width - size::REVIEW_SUMMARY.0 + }; + // At least a name or two, however narrow: the row clips the rest. + ((list - fixed) / (text::CAPTION.0 * CAPTION_ADVANCE_EMS)).max(16.0) + as usize +} + +/// The folder `path` is in, as a person reads it, shortened to `budget`. +pub fn folder_line( + app: &Disktree, + path: &std::path::Path, + budget: usize, +) -> String { + let style = app.path_style(); + style.parent(path).map_or_else(String::new, |parent| { + crate::run_list::elide_middle( + &app.display_path(parent), + style.separator(), + budget, + ) + }) +} + +fn list_column( + app: &Disktree, + phase: Phase, + totals: &Totals, + budget: usize, + compact: bool, + theme: &Theme, + cx: &gpui_kit::Context<'_, Disktree>, +) -> Div { + let note = if app.removal_mode == RemovalMode::OwnerCleanup { + format!( + "Cleanup steps: {} succeeded, {} failed; scope allocation is not freed space", + totals.removed, totals.failed + ) + } else { + match phase { + Phase::Running => "in the order they are removed".to_string(), + Phase::Done if totals.failed == 1 => { + "1 could not be removed".to_string() + } + Phase::Done if totals.failed > 0 => { + format!("{} could not be removed", totals.failed) + } + Phase::Done => String::new(), + } + }; + // Only the rows in view are built: this screen redraws with every + // report and every free-space sample, and a run can be thousands long. + // Every row is two lines, so the list can be uniform. + let rows = gpui_kit::uniform_list( + "run-rows", + app.run_list.items.len(), + cx.processor( + move |this: &mut Disktree, + range: std::ops::Range, + _, + cx: &mut gpui_kit::Context<'_, Disktree>| { + let theme = cx.omarchy().clone(); + let app = &*this; + let current = (phase == Phase::Running) + .then(|| app.run_list.current()) + .flatten(); + range + .filter_map(|index| { + let item = app.run_list.items.get(index)?; + let state = match &item.status { + Status::Removed => Row::Removed, + Status::Failed(reason) => Row::Failed(reason), + Status::Waiting if current == Some(index) => { + Row::Current + } + Status::Waiting if phase == Phase::Done => { + Row::Skipped + } + Status::Waiting => Row::Waiting, + }; + let folder = + folder_line(app, &item.target.path, budget); + Some(row( + index, item, state, folder, compact, app, &theme, + cx, + )) + }) + .collect::>() + }, + ), + ) + .track_scroll(&app.run_scroll) + .size_full(); + let list = div() + .id("run-list") + .debug_selector(|| "run-list".into()) + .role(gpui_kit::Role::List) + .aria_label(if app.removal_mode == RemovalMode::OwnerCleanup { + format!("{} cleanup steps; {} succeeded; {} failed", totals.total, totals.removed, totals.failed) + } else { format!( + "{} items to remove; {} removed; {} failed", totals.total, totals.removed, totals.failed + ) }) + .flex() + .flex_col() + .flex_1() + .min_h_0() + .overflow_hidden() + .border_1() + .border_color(theme.border) + .bg(theme.inset) + // The next poll reads where this left the item in hand, so the + // list has scrolled by then whichever handler runs first. + .on_scroll_wheel(cx.listener(|this, _, _, cx| { + this.run_list.scrolled_by_hand = true; + cx.notify(); + })) + .child(rows); + + let cohorts = app.ledger.cohorts(); + div() + .flex() + .flex_col() + .gap(space::XS) + .flex_1() + .min_w_0() + .min_h_0() + .child( + div() + .flex() + .flex_row() + .items_baseline() + .gap(space::SM) + .child(widgets::eyebrow( + format!( + "{} {}", + totals.total, + if totals.total == 1 { "item" } else { "items" } + ), + cx, + )) + .child(div().flex_1()) + .child( + div() + .text_size(text::CAPTION) + .text_color( + if phase == Phase::Done && totals.failed > 0 { + theme.danger + } else { + theme.secondary + }, + ) + .child(note), + ), + ) + .child( + div() + .relative() + .flex() + .flex_col() + .flex_1() + .min_h_0() + .child(list) + .children( + (phase == Phase::Running && !app.run_list.follow) + .then(|| follow_pill(app, totals, theme, cx)), + ), + ) + .when(phase == Phase::Done && !cohorts.is_empty(), |column| { + column.child( + div() + .flex_shrink_0() + .pt(space::SM) + .child(ledger_table(cohorts, theme, cx)), + ) + }) +} + +/// Where the item in hand sits against the list's viewport: `Equal` when +/// any of it shows, `Less` above it, `Greater` below. `None` before the +/// list is first laid out. Worked out from the rows' one height, so a row +/// need not have been drawn to be placed. +pub fn focus_place(app: &Disktree) -> Option { + let row = app.run_list.focus()?; + let count = app.run_list.items.len(); + let state = app.run_scroll.0.borrow(); + let size = state.last_item_size?; + if count == 0 { + return None; + } + let height = size.contents.height / count as f32; + let top = -state.base_handle.offset().y; + let bottom = top + size.item.height; + let row_top = height * row as f32; + Some(if row_top + height <= top { + std::cmp::Ordering::Less + } else if row_top >= bottom { + std::cmp::Ordering::Greater + } else { + std::cmp::Ordering::Equal + }) +} + +/// "↓ Follow the removal · 3 of 8", while following is paused: the live +/// log's pill. A click brings the item in hand back and follows it again. +fn follow_pill( + app: &Disktree, + totals: &Totals, + theme: &Theme, + cx: &gpui_kit::Context<'_, Disktree>, +) -> Div { + let above = focus_place(app) == Some(std::cmp::Ordering::Less); + let label = format!( + "{} Follow the removal \u{b7} {} of {}", + if above { '\u{2191}' } else { '\u{2193}' }, + totals.removed + totals.failed, + totals.total + ); + div() + .absolute() + .bottom(space::LG) + .left_0() + .right_0() + .flex() + .justify_center() + .child( + div() + .id("follow-removal") + .debug_selector(|| "follow-removal".into()) + // It floats over the list: without this the row beneath + // raised its path tooltip over the pill. A scroll still + // reaches the list, as it would anywhere over it. + .block_mouse_except_scroll() + .role(gpui_kit::Role::Button) + .aria_label(label.clone()) + .px(space::LG) + .py(space::XS) + .border_1() + .border_color(theme.accent) + .bg(theme.surface) + .shadow_lg() + .cursor_pointer() + .text_color(theme.accent) + .font_weight(FontWeight::SEMIBOLD) + .child(label) + .on_click(cx.listener(|this, _, _, cx| { + this.follow_removal(); + cx.notify(); + })), + ) +} + +/// One item: a checkbox that fills in as it goes, its kind's colour, its +/// name over the folder it is in, why it is listed, its size and what +/// happened to it. Lanes are fixed so sizes line up down the list. +#[allow( + clippy::too_many_arguments, + reason = "a row is drawn from the run, the theme and its own layout" +)] +fn row( + index: usize, + item: &Item, + state: Row<'_>, + folder: String, + compact: bool, + app: &Disktree, + theme: &Theme, + cx: &gpui_kit::App, +) -> Stateful
{ + let accent = palette::category_accent(theme, item.category); + let kind = item.kind(); + let full = app.display_path(&item.target.path); + let label = + state.label(app.removal_mode, app.cleanup_actions.get(index).copied()); + let name = app + .path_style() + .file_name(&item.target.path) + .map_or_else(|| full.clone(), |name| name.to_string_lossy().into()); + let second = match state { + Row::Failed(reason) => { + div().text_color(theme.warning).child(reason.to_string()) + } + _ => div().text_color(theme.secondary).child(folder), + }; + let row = div() + .id(ElementId::Name(SharedString::from(format!( + "run-row-{index}" + )))) + .debug_selector(move || format!("run-row-{index}")) + .role(gpui_kit::Role::ListItem) + .aria_label(format!( + "{full}; {}; {}{label}", + human_bytes(item.target.bytes), + kind.map_or_else(String::new, |kind| format!("{kind}; ")) + )) + .relative() + // A virtualized row is only as wide as its content otherwise, and + // the size and status lanes would wander with the kind chip. + .w_full() + .flex() + .flex_row() + .flex_shrink_0() + .items_center() + .gap(space::MD) + .px(space::MD) + .py(space::SM) + .border_b_1() + .border_color(theme.divider()) + .when(state.dimmed(), |row| row.opacity(0.55)) + .when(state == Row::Current, |row| { + row.bg(theme.accent.opacity(0.1)).child( + div() + .absolute() + .left_0() + .top_0() + .bottom_0() + .w(px(2.)) + .bg(theme.accent), + ) + }) + .child(checkbox(state, theme)) + .child(div().flex_shrink_0().w(px(2.)).h(space::XL).bg(accent)) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .child( + div() + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .text_color(if matches!(state, Row::Failed(_)) { + theme.danger + } else { + theme.bright + }) + .child(name), + ) + .child( + second + .text_size(text::CAPTION) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis(), + ), + ) + .children( + kind.map(|kind| widgets::chip(kind, accent, cx).flex_shrink_0()), + ) + .child( + // Comparable numbers right-align. + div() + .w(size::SIZE_LANE) + .flex_shrink_0() + .flex() + .justify_end() + .text_color(theme.bright) + .child(human_bytes(item.target.bytes)), + ) + .when(!compact, |row| { + row.child( + div() + .w(size::SIZE_LANE) + .flex_shrink_0() + .flex() + .justify_end() + .text_size(text::CAPTION) + .text_color(state.color(theme)) + .child(label), + ) + }); + with_tooltip(row, full) +} + +/// A drawn checkbox, not a glyph: an outline while waiting, a dot in the +/// accent while in hand, filled green with a check once removed, red with +/// a cross when it failed. +fn checkbox(state: Row<'_>, theme: &Theme) -> Div { + let color = state.color(theme); + let ink = palette::ink_on(theme.background, color, 4.5); + let mark = match state { + Row::Removed => Some(gpui_omarchy::IconName::Check), + Row::Failed(_) => Some(gpui_omarchy::IconName::X), + _ => None, + }; + let filled = mark.is_some(); + div() + .flex_shrink_0() + .size(icon::MD) + .flex() + .items_center() + .justify_center() + .border_1() + .border_color(if filled || state == Row::Current { + color + } else { + theme.control_border() + }) + .when(filled, |box_| box_.bg(color)) + .children(mark.map(|mark| { + gpui_omarchy::icon(mark).size(icon::SM).text_color(ink) + })) + .when(state == Row::Current, |box_| { + box_.child(div().size(space::XS).bg(color)) + }) +} + +/// What the run has done and what it is worth, beside the list: while it +/// runs, progress and the figures so far against the whole; once it is +/// done, the result. +fn sidebar( + app: &Disktree, + phase: Phase, + totals: &Totals, + theme: &Theme, + cx: &gpui_kit::Context<'_, Disktree>, +) -> Stateful
{ + let rule = || div().flex_shrink_0().h(px(1.)).bg(theme.divider()); + let observed = observed(app, phase); + let mut panel = div() + .id("run-summary") + .debug_selector(|| "run-summary".into()) + .flex() + .flex_col() + .gap(space::LG) + .w(size::REVIEW_SUMMARY) + .flex_shrink_0() + .min_h_0() + .overflow_y_scroll() + .p(space::LG) + .border_1() + .border_color(theme.border) + .bg(theme.surface); + + if phase == Phase::Running { + let settled = totals.removed + totals.failed; + let fraction = if totals.total == 0 { + 0.0 + } else { + settled as f32 / totals.total as f32 + }; + let now = app.run_list.current().map(|index| { + let item = &app.run_list.items[index]; + let style = app.path_style(); + let name = style.file_name(&item.target.path).map_or_else( + || app.display_path(&item.target.path), + |name| name.to_string_lossy().into_owned(), + ); + div() + .flex() + .flex_row() + .gap(space::XS) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .whitespace_nowrap() + .overflow_hidden() + .child("Now") + .child( + div() + .text_color(theme.accent) + .overflow_hidden() + .text_ellipsis() + .child(name), + ) + }); + panel = panel.child( + div() + .flex() + .flex_col() + .gap(space::XS) + .child(widgets::eyebrow("Progress", cx)) + .child(big_figure( + settled.to_string(), + format!("of {} items", totals.total), + theme.bright, + theme, + )) + .child(widgets::bar( + fraction, + if app.removal_mode == RemovalMode::Permanent { + theme.danger + } else { + theme.accent + }, + cx, + )) + .children(now), + ); + panel = panel.child(rule()); + } + + // The three figures. While it runs each is what has finished, against + // what the whole run would come to. + let of = |done: String, all: String| match phase { + Phase::Running => format!("{done} / {all}"), + Phase::Done => done, + }; + let latest = app.ledger.cohorts().last(); + let (reported, private) = match (phase, latest) { + // Done reads the ledger: its private part is estimated over the + // whole run, which counts a clone shared only inside it once. + (Phase::Done, Some(cohort)) => (cohort.reported, cohort.private), + _ => (totals.reported_done, totals.private_done), + }; + let private_text = private.map_or_else( + || "unknown".to_string(), + |private| { + of( + human_bytes(private), + totals.private_all.map_or_else( + || "?".into(), + |all| format!("\u{2248} {}", human_bytes(all)), + ), + ) + }, + ); + let mut figures = div() + .flex() + .flex_col() + .gap(space::SM) + .child(widgets::eyebrow( + if phase == Phase::Running { + "Freed so far" + } else { + "Freed" + }, + cx, + )) + .children(observed.map(|delta| { + let (number, unit) = widgets::split_size(&signed_bytes(delta)); + big_figure( + number, + format!("{unit} observed"), + if delta >= 0 { + theme.success + } else { + theme.warning + }, + theme, + ) + })); + if phase == Phase::Done { + figures = figures.child(figure_row( + if app.removal_mode == RemovalMode::OwnerCleanup { + "Commands succeeded" + } else { + "Removed" + }, + None, + format!("{} of {}", totals.removed, totals.total), + theme.bright, + theme, + )); + } + figures = figures + .child(figure_row( + "Reported", + Some(if app.removal_mode == RemovalMode::OwnerCleanup { + "scan allocation of successful command scopes; not freed bytes" + } else { + "listed size of what went" + }), + of(human_bytes(reported), human_bytes(totals.reported_all)), + theme.bright, + theme, + )) + .child(figure_row( + "Private", + Some("the scan\u{2019}s estimate of theirs alone"), + private_text, + theme.bright, + theme, + )) + .child(figure_row( + "Observed", + Some("free space now, less at the start"), + observed.map_or_else(|| "\u{2014}".into(), signed_bytes), + match observed { + Some(delta) if delta < 0 => theme.warning, + Some(_) => theme.success, + None => theme.secondary, + }, + theme, + )); + panel = panel.child(figures).child(rule()); + + if let Some(volume) = app.space { + panel = panel.child( + div() + .flex() + .flex_col() + .gap(space::SM) + .child(widgets::eyebrow("Disk", cx)) + .child(widgets::space_meter(volume, 0, cx)), + ); + } + if phase == Phase::Done && app.scan.is_some() { + panel = panel.child(widgets::meter_row( + "re-scanning", + format!("{} files", widgets::human_count(app.progress.files)), + 0.0, + theme.accent, + cx, + )); + } + // One line per marked path, the skipped ones included, so every path + // the person decided has a result. + panel + .children( + app.cleanup_results + .iter() + .map(|report| caption(result_line(app, report), theme)), + ) + .child(caption(note(app, phase), theme)) +} + +/// One cleanup step's result: the path, how it ended and, when it did not +/// succeed, why. A failed owner command says that nothing else was deleted. +fn result_line( + app: &Disktree, + report: &disktree_core::cleanup::Report, +) -> String { + use disktree_core::cleanup::{Action, Outcome}; + let mut line = format!( + "{} \u{b7} {}", + app.display_path(&report.path), + report.outcome_label() + ); + if let (Some(problem), Some(error)) = (report.problem, &report.error) + && report.outcome != Outcome::Succeeded + { + let _ = write!(line, " \u{b7} {}: {error}", problem.label()); + } + if report.action == Action::Owner + && matches!(report.outcome, Outcome::Failed | Outcome::Cancelled) + { + line.push_str( + ". Nothing else was deleted; deleting these files instead \ + needs its own choice in a new review", + ); + } + line +} + +/// What the mode means for the figures above it. +const fn note(app: &Disktree, phase: Phase) -> &'static str { + match (phase, app.removal_mode) { + (Phase::Running, RemovalMode::Trash) => { + "Moving to the trash. The space comes back once the trash is \ + emptied, so until then observed stays near zero." + } + (Phase::Running, RemovalMode::Permanent) => { + "Deleting permanently; nothing removed can be recovered. Stop \ + finishes the item in hand first." + } + (Phase::Running, RemovalMode::OwnerCleanup) => { + "Running each chosen step in turn. Stop cancels the current owner command, which may already have changed its cache, and leaves the rest not reached. A failed step never deletes anything else." + } + (Phase::Done, _) if app.scan.is_some() => { + "Rescanning so the numbers on screen match the disk again." + } + (Phase::Done, RemovalMode::Trash) => { + "In the trash, the space comes back once it is emptied. What \ + was removed stays in the treemap, greyed out, until you \ + rescan." + } + (Phase::Done, RemovalMode::Permanent) => { + "What was removed stays in the treemap, greyed out, until you \ + rescan; it cannot be marked again." + } + (Phase::Done, RemovalMode::OwnerCleanup) => { + "A succeeded command exited successfully; it does not mean its whole scope is gone. Reported is scope allocation; observed is the measured free-space change. Open files, APFS clones and snapshots can retain blocks. A failed or cancelled owner command deleted nothing else: inspect it, then decide again in a new review." + } + } +} + +/// Free space gained since the run started: sampled live while it runs, +/// and as the ledger measured it once it is done. +fn observed(app: &Disktree, phase: Phase) -> Option { + match phase { + Phase::Done => app + .ledger + .cohorts() + .last() + .and_then(crate::ledger::Cohort::observed), + Phase::Running => { + let before = app.run_free_before?; + let now = app.space?.available; + Some(now.cast_signed().saturating_sub(before.cast_signed())) + } + } +} + +/// A large number with a small unit after it. +fn big_figure(number: String, unit: String, color: Hsla, theme: &Theme) -> Div { + div() + .flex() + .flex_row() + .items_baseline() + .gap(space::XS) + .child( + div() + .text_size(text::TITLE) + .font_weight(FontWeight::SEMIBOLD) + .text_color(color) + .child(number), + ) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.foreground) + .child(unit), + ) +} + +/// A figure: its name, what it means, and its value on the right. +fn figure_row( + label: &'static str, + meaning: Option<&'static str>, + value: String, + color: Hsla, + theme: &Theme, +) -> Div { + div() + .flex() + .flex_row() + .items_start() + .gap(space::SM) + .text_size(text::CAPTION) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .child(div().text_color(theme.foreground).child(label)) + .children(meaning.map(|meaning| { + div().text_color(theme.secondary).child(meaning) + })), + ) + .child( + div() + .flex_shrink_0() + .whitespace_nowrap() + .text_color(color) + .child(value), + ) +} + +fn caption(text_: impl Into, theme: &Theme) -> Div { + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(text_.into()) +} diff --git a/crates/disktree-app/src/safety.rs b/crates/disktree-app/src/safety.rs new file mode 100644 index 00000000..cecb687c --- /dev/null +++ b/crates/disktree-app/src/safety.rs @@ -0,0 +1,275 @@ +//! What Settings › Safety saved: the removal limit and what Review asks +//! before going past it. MCP cannot change either, and an agent is held +//! to a limit even when the window's is off. + +use std::path::Path; + +use disktree_core::removal_limit::Limit; + +const FILE: &str = "removal-limit-percent"; +const CONFIRM_FILE: &str = "over-limit-confirm"; +/// Saved in place of a percent when the person turned the limit off. +const OFF: &str = "off"; +/// What Settings saved for no limit before Off existed. +const LEGACY_OFF: &str = "100"; + +/// What Review asks before a removal past the limit, after Mark anyway. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Confirm { + /// Type "delete 20% of my disk": reading it is the point. + #[default] + Phrase, + /// Tick a box that says the same. + Tick, + /// Nothing more: Mark anyway was the confirmation. + Nothing, +} + +impl Confirm { + pub const ALL: [Self; 3] = [Self::Phrase, Self::Tick, Self::Nothing]; + + pub const fn label(self) -> &'static str { + match self { + Self::Phrase => "Type a phrase", + Self::Tick => "Tick a box", + Self::Nothing => "No second step", + } + } + + const fn word(self) -> &'static str { + match self { + Self::Phrase => "phrase", + Self::Tick => "tick", + Self::Nothing => "none", + } + } +} + +/// The window's removal policy. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Policy { + /// `None` when the person turned the limit off for the window. + pub limit: Option, + pub confirm: Confirm, +} + +/// The default limit, on: off is only ever the person's own choice. +impl Default for Policy { + fn default() -> Self { + Self { + limit: Some(Limit::default()), + confirm: Confirm::default(), + } + } +} + +impl Policy { + /// The limit an agent is held to: the window's, or the default when + /// the window's is off. An agent can never confirm past a limit for + /// the person, so turning it off for the window must not lift it. + pub fn agent_limit(self) -> Limit { + self.limit.unwrap_or_default() + } +} + +/// The limit an agent's removal is held to; see [`Policy::agent_limit`]. +pub fn load(dir: Option<&Path>) -> Result { + load_policy(dir).map(Policy::agent_limit) +} + +/// Both settings. A file that cannot be read or makes no sense refuses +/// removal rather than falling back to something laxer. +pub fn load_policy(dir: Option<&Path>) -> Result { + let Some(dir) = dir else { + return Ok(Policy::default()); + }; + let limit = match read(&dir.join(FILE))? { + None => Some(Limit::default()), + // 100% was the last choice before Off existed and meant the same + // for the window; read as Off, an agent keeps the default. + Some(text) if text == OFF || text == LEGACY_OFF => None, + Some(text) => Some( + text.parse::() + .map_err(|_| "Invalid removal limit in Settings > Safety") + .and_then(|percent| { + Limit::new(percent).map_err( + |_| "Invalid removal limit in Settings > Safety", + ) + })?, + ), + }; + let confirm = match read(&dir.join(CONFIRM_FILE))? { + None => Confirm::default(), + Some(text) => Confirm::ALL + .into_iter() + .find(|confirm| confirm.word() == text) + .ok_or("Invalid over-limit confirmation in Settings > Safety")?, + }; + Ok(Policy { limit, confirm }) +} + +fn read(path: &Path) -> Result, String> { + match std::fs::read_to_string(path) { + Ok(text) => Ok(Some(text.trim().to_owned())), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(format!("Cannot read Settings > Safety: {error}")), + } +} + +/// Set once Settings › Safety saves, so the main window reads the policy +/// again rather than judging marks by the one it read at start. +pub struct Saved; +impl gpui_kit::Global for Saved {} + +#[cfg(test)] +pub fn save(dir: Option<&Path>, limit: Limit) -> Result<(), String> { + save_limit(dir, Some(limit)) +} + +/// Save the limit, or `None` to turn it off for the window. +pub fn save_limit( + dir: Option<&Path>, + limit: Option, +) -> Result<(), String> { + let text = + limit.map_or_else(|| OFF.to_owned(), |l| l.percent().to_string()); + write(dir, FILE, &text) +} + +pub fn save_confirm( + dir: Option<&Path>, + confirm: Confirm, +) -> Result<(), String> { + write(dir, CONFIRM_FILE, confirm.word()) +} + +/// Write beside, then rename, so a reader never sees half a setting. +fn write(dir: Option<&Path>, file: &str, text: &str) -> Result<(), String> { + let dir = dir.ok_or("No settings directory is available")?; + std::fs::create_dir_all(dir).map_err(|error| error.to_string())?; + let pending = dir.join(format!("{file}.new")); + std::fs::write(&pending, format!("{text}\n")) + .map_err(|error| error.to_string())?; + std::fs::rename(pending, dir.join(file)).map_err(|error| error.to_string()) +} + +/// The share of a volume `bytes` is, in whole percent rounded up, so +/// "20%" never undersells what goes. At most 100. +pub fn share_percent(bytes: u64, capacity: u64) -> u8 { + if capacity == 0 { + return 100; + } + let percent = (u128::from(bytes) * 100).div_ceil(u128::from(capacity)); + u8::try_from(percent.min(100)).unwrap_or(100) +} + +/// What Review asks the person to type for a removal of `percents` of +/// disks in `mode`, one share per disk past the limit. The verb is the +/// mode's, so the phrase is read for how much, how, and how many disks: +/// "delete 20% of my disk", "trash 20% and 19% of my disks". +pub fn phrase( + percents: &[u8], + mode: disktree_core::removal::RemovalMode, +) -> String { + let verb = match mode { + disktree_core::removal::RemovalMode::Permanent => "delete", + disktree_core::removal::RemovalMode::Trash => "trash", + disktree_core::removal::RemovalMode::OwnerCleanup => "clean", + }; + let disks = if percents.len() > 1 { + "my disks" + } else { + "my disk" + }; + let shares = series(percents.iter().map(|percent| format!("{percent}%"))); + format!("{verb} {shares} of {disks}") +} + +/// `items` as a reader lists them: "a", "a and b", "a, b and c". +pub fn series(items: impl IntoIterator) -> String { + let mut items: Vec = items.into_iter().collect(); + let Some(last) = items.pop() else { + return String::new(); + }; + if items.is_empty() { + last + } else { + format!("{} and {last}", items.join(", ")) + } +} + +/// Whether `typed` says `phrase`: case and the spaces around and between +/// words are forgiven, nothing else. +pub fn matches(typed: &str, phrase: &str) -> bool { + let words = |text: &str| { + text.split_whitespace() + .map(str::to_lowercase) + .collect::>() + }; + words(typed) == words(phrase) +} + +#[cfg(test)] +mod tests { + use super::*; + use disktree_core::removal::RemovalMode; + + #[test] + fn defaults_persist_and_invalid_configuration_refuses_removal() { + let temp = tempfile::tempdir().expect("settings"); + let dir = Some(temp.path()); + assert_eq!(load(dir).expect("default").percent(), 5); + assert_eq!(load_policy(dir).expect("default"), Policy::default()); + save(dir, Limit::new(10).expect("10%")).expect("save"); + assert_eq!(load(dir).expect("saved").percent(), 10); + std::fs::write(temp.path().join(FILE), "0").expect("invalid setting"); + assert!(load(dir).is_err()); + std::fs::write(temp.path().join(CONFIRM_FILE), "maybe") + .expect("invalid setting"); + save(dir, Limit::default()).expect("save"); + assert!(load_policy(dir).is_err(), "an unknown confirmation refuses"); + } + + #[test] + fn off_lifts_the_windows_limit_but_never_an_agents() { + let temp = tempfile::tempdir().expect("settings"); + let dir = Some(temp.path()); + save_limit(dir, None).expect("off"); + save_confirm(dir, Confirm::Tick).expect("tick"); + let policy = load_policy(dir).expect("saved"); + assert_eq!(policy.limit, None); + assert_eq!(policy.confirm, Confirm::Tick); + assert_eq!(load(dir).expect("agent").percent(), 5); + std::fs::write(temp.path().join(FILE), "100\n").expect("legacy"); + assert_eq!(load_policy(dir).expect("legacy").limit, None); + assert_eq!(load(dir).expect("agent").percent(), 5); + } + + #[test] + fn the_share_rounds_up_and_the_phrase_says_it() { + assert_eq!(share_percent(181, 926), 20); + assert_eq!(share_percent(200, 1000), 20, "exact stays exact"); + assert_eq!(share_percent(201, 1000), 21); + assert_eq!(share_percent(5, 0), 100, "no capacity is the worst case"); + assert_eq!(share_percent(u64::MAX, 1), 100); + let typed = phrase(&[20], RemovalMode::Permanent); + assert_eq!(typed, "delete 20% of my disk"); + assert_eq!( + phrase(&[20, 19], RemovalMode::Trash), + "trash 20% and 19% of my disks" + ); + assert_eq!( + phrase(&[20, 19, 7], RemovalMode::Permanent), + "delete 20%, 19% and 7% of my disks" + ); + assert_eq!(series(Vec::new()), ""); + assert!(matches(" Delete 20% of my DISK ", &typed)); + assert!(!matches("delete 2% of my disk", &typed)); + assert!(!matches("trash 20% of my disk", &typed)); + assert!(!matches("", &typed)); + assert_eq!( + phrase(&[20], RemovalMode::OwnerCleanup), + "clean 20% of my disk" + ); + } +} diff --git a/crates/disktree-app/src/semantics.rs b/crates/disktree-app/src/semantics.rs new file mode 100644 index 00000000..9823bfa4 --- /dev/null +++ b/crates/disktree-app/src/semantics.rs @@ -0,0 +1,227 @@ +//! Small semantic surfaces for text that GPUI does not expose implicitly. + +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::{ + Div, InteractiveElement as _, Role, Stateful, + StatefulInteractiveElement as _, div, +}; + +pub fn text( + id: impl Into, + label: impl Into, +) -> Stateful
{ + let label = label.into(); + // AT-SPI derives a static label's name from its value, unlike macOS AX. + div() + .id(id) + .role(Role::Label) + .aria_label(label.clone()) + .when(cfg!(target_os = "linux"), |text| { + text.aria_value(label) + .a11y_synthetic_children(|b| b.parent_node().set_read_only()) + }) +} + +pub fn status(id: &'static str, label: String) -> Stateful
{ + // The macOS adapter announces live values, rather than label changes. + div() + .id(id) + .role(Role::Status) + .aria_label(label.clone()) + .aria_value(label) + .a11y_synthetic_children(|b| { + let node = b.parent_node(); + node.set_live(gpui_kit::accesskit::Live::Polite); + node.set_read_only(); + }) +} + +impl crate::state::Disktree { + pub fn accessibility_status(&mut self) -> String { + use crate::state::Screen; + use disktree_core::size::human_bytes; + if self.scan_error.is_some() || !self.is_indexing() { + self.accessible_progress = None; + } + // Review and removal remain the foreground workflow while a previous + // scan is cancelled or failed, or a completion refresh runs behind it. + let phase = match self.screen { + Screen::Explore => { + if self.awaiting_root { + return "Choose a source, then a root. No scan has started." + .into(); + } + if let Some(error) = &self.scan_error { + return format!( + "Scan failed: {error}. Scan again to retry." + ); + } + if self.is_indexing() { + return format!( + "{} Escape cancels. Live overview is incomplete and cannot be marked.", + self.accessibility_scan_progress() + ); + } + if self.progress.cancelled { + "Scan cancelled" + } else { + "Scan complete" + } + } + Screen::Review => "Review marked paths", + Screen::Running => "Removal running", + Screen::Done => "Removal finished", + }; + let background = if self.screen == Screen::Explore { + String::new() + } else if let Some(error) = &self.scan_error { + format!(" Previous scan failed: {error}.") + } else if self.is_indexing() { + format!(" Background scan. {}", self.accessibility_scan_progress()) + } else if self.progress.cancelled { + " Previous scan cancelled.".into() + } else { + String::new() + }; + let volume = self.space.map_or_else( + || "Volume space unavailable".to_owned(), + |s| { + format!( + "Volume {} free of {} total", + human_bytes(s.available), + human_bytes(s.total) + ) + }, + ); + format!( + "{phase}. {}. {} marked paths. {volume}.{background} {}{}", + self.current_path().display(), + self.marks.len(), + if self.remote.is_some() { + "SSH read-only. Space is a scan snapshot. " + } else { + "" + }, + self.notice() + .map_or_else(String::new, |(message, _)| message) + ) + } + + fn accessibility_scan_progress(&mut self) -> String { + let now = std::time::Instant::now(); + if let Some((at, label)) = &self.accessible_progress + && now.duration_since(*at) < std::time::Duration::from_secs(2) + { + return label.clone(); + } + let label = format!( + "Scanning {}. Busy; progress is indeterminate. {} files, {} indexed.", + self.scan_root.display(), + self.progress.files, + disktree_core::size::human_bytes(self.progress.bytes) + ); + self.accessible_progress = Some((now, label.clone())); + label + } +} + +/// The pinned button removes Click when disabled but omits the native state. +/// Synthetic parent metadata is a supported GPUI path to supply that state. +pub trait AccessibleButton: Sized { + fn semantic_disabled(self, disabled: bool) -> Self; +} + +impl AccessibleButton for gpui_omarchy::Button { + fn semantic_disabled(self, disabled: bool) -> Self { + self.disabled(disabled).a11y_synthetic_children(move |b| { + if disabled { + b.parent_node().set_disabled(); + } + }) + } +} + +/// Cycle inside a modal even though GPUI's global tab order includes its +/// painted background. A full cycle without an eligible stop leaves focus +/// on the modal container, rather than looping or escaping it. +pub fn advance_focus( + window: &mut gpui_kit::Window, + cx: &mut gpui_kit::App, + reverse: bool, + scope: Option<&gpui_kit::FocusHandle>, +) { + let mut first: Option = None; + loop { + if reverse { + window.focus_prev(cx); + } else { + window.focus_next(cx); + } + let Some(scope) = scope else { return }; + if scope.contains_focused(window, cx) { + return; + } + if first + .as_ref() + .is_some_and(|handle| handle.is_focused(window)) + { + window.focus(scope, cx); + return; + } + if first.is_none() { + first = window.focused(cx); + if first.is_none() { + window.focus(scope, cx); + return; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use gpui_kit::{Element as _, accesskit}; + + #[test] + fn current_status_and_text_have_stable_named_roles() { + for (element, role, label) in [ + ( + text("source-instructions", "Choose a root"), + Role::Label, + "Choose a root", + ), + ( + status("current-status", "Scan cancelled".into()), + Role::Status, + "Scan cancelled", + ), + ] { + assert_eq!(element.a11y_role(), Some(role)); + let mut node = accesskit::Node::new(role); + element.write_a11y_info(&mut node); + assert_eq!(node.label(), Some(label)); + } + } + + #[test] + fn status_review_current_updates_supply_an_announced_value() { + for label in ["Scanning Fixtures", "Scan failed", "Scan complete"] { + let element = status("current-status", label.into()); + let mut node = accesskit::Node::new(Role::Status); + element.write_a11y_info(&mut node); + assert_eq!(node.label(), Some(label)); + assert_eq!(node.value(), Some(label)); + } + } + + #[test] + fn status_review_mark_updates_supply_an_announced_value() { + let label = "1 marked path; 1024 listed bytes"; + let element = status("marked-summary", label.into()); + let mut node = accesskit::Node::new(Role::Status); + element.write_a11y_info(&mut node); + assert_eq!(node.label(), Some(label)); + assert_eq!(node.value(), Some(label)); + } +} diff --git a/crates/disktree-app/src/settings.rs b/crates/disktree-app/src/settings.rs new file mode 100644 index 00000000..8f556b01 --- /dev/null +++ b/crates/disktree-app/src/settings.rs @@ -0,0 +1,1813 @@ +//! The Settings window: its own window, one at a time, as in PwrRoute, +//! PwrGit and PwrSnap. A nav on the left and panes of cards: Updates, +//! Safety, Agents (MCP), Diagnostics and About. No General pane until +//! there is something to put in it: Power Efficiency and the view settings +//! stay in the strip, where they are used. Design: "Menus and Help +//! Windows" in the PwrDisk Claude Design project, turn 3; Agents (MCP) in +//! "Notices, Sticky Headers and Agents (MCP)", as PwrSnap's Local Agents. +//! +//! Updates is the panel the main window used to draw, moved here with its +//! rows, its names and its keys (↑↓ and Enter pick a channel, C checks, R +//! restarts). Restart to update goes through the main window, which knows +//! whether a removal is running and refuses to cut one short. + +use crate::semantics::{AccessibleButton as _, text as readable}; +use disktree_core::path_style::PathStyle; +use disktree_core::removal_limit::Limit; + +use crate::safety::Confirm; +use std::path::PathBuf; + +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::{ + AnyElement, App, ClipboardItem, Context, Div, ElementId, FocusHandle, + FontWeight, InteractiveElement as _, IntoElement, KeyDownEvent, + ParentElement as _, Render, Role, SharedString, Stateful, + StatefulInteractiveElement as _, Styled as _, Window, WindowHandle, div, + img, +}; +use gpui_omarchy::{ + ActiveTheme as _, ButtonVariant, ChoiceItem, Theme, button, button_group, +}; + +use crate::aux_window::{self, Spec}; +use crate::build_info::BuildInfo; +use crate::chrome::Drags; +use crate::diagnostics::{self, Diagnostics}; +use crate::state::Disktree; +use crate::ui::{size, space, text}; +use crate::update_channel::{Slot, UpdateSettings}; +use crate::updater; + +pub use settings_actions::OpenSettings; + +#[allow( + clippy::derive_partial_eq_without_eq, + reason = "GPUI's actions! macro writes the derives, not us" +)] +mod settings_actions { + use gpui_kit::actions; + + actions!( + disktree, + [ + /// Open the Settings window, or bring it forward. + OpenSettings, + ] + ); +} + +/// The element id of the window's root, for tests. +pub const ROOT_ID: &str = "settings-root"; +pub const CHECK_ID: &str = "updates-check"; +pub const RESTART_ID: &str = "updates-restart"; +pub const COPY_DIAGNOSTICS_ID: &str = "diagnostics-copy"; +pub const COPY_BUILD_ID: &str = "about-copy-build"; +pub const COPY_PROMPT_ID: &str = "agents-copy-prompt"; +/// How long a copy button says "Copied": PwrSnap's and PwrAgnt's 1.5 s. +pub const COPY_FEEDBACK: std::time::Duration = + std::time::Duration::from_millis(1500); +/// About's header: the icon, the name and version, the build line. +pub const ABOUT_HEADER_ID: &str = "about-header"; +pub const ABOUT_BUILD_LINE_ID: &str = "about-build-line"; + +const SPEC: Spec = Spec { + title: "PwrDisk Settings", + size: (1000.0, 680.0), + // PwrGit's Settings minimum. + min: (760.0, 520.0), +}; + +/// The nav's sections, in order. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Pane { + Updates, + Diagnostics, + Safety, + Agents, + About, +} + +impl Pane { + pub const ALL: [Self; 5] = [ + Self::Updates, + Self::Safety, + Self::Agents, + Self::Diagnostics, + Self::About, + ]; + + pub const fn label(self) -> &'static str { + match self { + Self::Updates => "Updates", + Self::Diagnostics => "Diagnostics", + Self::Safety => "Safety", + Self::Agents => "Agents (MCP)", + Self::About => "About", + } + } + + /// The nav's heading above this pane, as the family's Settings group + /// them: what PwrDisk does, then help with it. + pub const fn group(self) -> &'static str { + match self { + Self::Updates | Self::Safety | Self::Agents => "App", + Self::Diagnostics | Self::About => "Support", + } + } + + /// The nav item's element id. + pub const fn nav_id(self) -> &'static str { + match self { + Self::Updates => "settings-nav-updates", + Self::Diagnostics => "settings-nav-diagnostics", + Self::Safety => "settings-nav-safety", + Self::Agents => "settings-nav-agents", + Self::About => "settings-nav-about", + } + } +} + +pub fn install(cx: &mut App) { + cx.on_action(|_: &OpenSettings, cx| { + // Settings… reopens on the pane last shown; a first open starts on + // Updates, the one with something to set. + cx.defer(|cx| { + let pane = aux_window::find::(cx, |_| true) + .and_then(|handle| handle.read(cx).ok().map(|view| view.pane)) + .unwrap_or(Pane::Updates); + open(pane, cx); + }); + }); +} + +/// Opens Settings on `pane`, or brings it forward and switches there. +pub fn open(pane: Pane, cx: &mut App) { + let existing = aux_window::find::(cx, |_| true); + if let Some(handle) = existing { + let _ = handle.update(cx, |view, _, cx| view.show(pane, cx)); + } + if aux_window::activate(existing, cx) { + return; + } + open_window(pane, cx); +} + +/// A new Settings window, for `open` and the tests. +pub fn open_window( + pane: Pane, + cx: &mut App, +) -> Option> { + aux_window::open(&SPEC, cx, |window, cx| { + let view = SettingsWindow::new(pane, cx); + window.focus(&view.focus, cx); + view + }) +} + +/// Redraws Settings › Agents (MCP) when the agent connected to the main +/// window changes. Only that pane: nothing else there follows the agent. +pub fn agents_changed(cx: &mut App) { + if let Some(handle) = aux_window::find::(cx, |_| true) { + let _ = handle.update(cx, |view, _, cx| { + if view.pane == Pane::Agents { + cx.notify(); + } + }); + } +} + +/// Redraws Settings when the updater's state moves (`updater::install`). +/// Never for a download's percent, which Settings does not show: this +/// collects the diagnostics again. +pub fn refresh(cx: &mut App) { + #[cfg(test)] + REFRESHES.set(REFRESHES.get() + 1); + if let Some(handle) = aux_window::find::(cx, |_| true) { + let _ = handle.update(cx, |view, _, cx| { + view.diagnostics = diagnostics::collect(cx); + cx.notify(); + }); + } +} + +#[cfg(test)] +thread_local! { + /// How many times [`refresh`] ran, for the test that a download's + /// percent does not rebuild Settings. + pub static REFRESHES: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +/// The window's view. +pub struct SettingsWindow { + pub pane: Pane, + /// The channel row the keys are on. + pub updates_row: usize, + /// Where the channel pick is saved: the settings folder; tests point + /// it at a temporary one. + pub updates_dir: Option, + pub diagnostics: Diagnostics, + /// The copy button that last copied, which says "Copied" for + /// [`COPY_FEEDBACK`]. + copied: Option<&'static str>, + /// Puts "Copied" back to "Copy"; a newer copy replaces it, so an older + /// click cannot cut the newer one's short. + copied_reset: Option>, + /// Agents (MCP)'s commands: the executable does not move while it + /// runs, so they are built once rather than on every redraw. + connect: Vec, + /// Why the last pick could not be saved. + pub note: Option, + /// The saved removal limit, as Safety shows it: read when the window + /// opens, whenever Safety is shown and after a pick is saved, never + /// while drawing, which runs on every frame. + pub safety: Result, + focus: FocusHandle, + pub pane_scroll: gpui_kit::ScrollHandle, + strip_drag: bool, +} + +impl Drags for SettingsWindow { + fn strip_drag(&mut self) -> &mut bool { + &mut self.strip_drag + } +} + +impl SettingsWindow { + pub fn new(pane: Pane, cx: &Context<'_, Self>) -> Self { + let installed = updater::installed_version(); + let updates_dir = updater::settings_dir(); + Self { + pane, + updates_row: updater::selection().resolve(&installed).index(), + safety: crate::safety::load_policy(updates_dir.as_deref()), + updates_dir, + diagnostics: diagnostics::collect(cx), + copied: None, + copied_reset: None, + connect: crate::agent::connect_commands( + &std::env::current_exe() + .unwrap_or_else(|_| PathBuf::from("pwrdisk")), + ), + note: None, + focus: cx.focus_handle(), + pane_scroll: gpui_kit::ScrollHandle::new(), + strip_drag: false, + } + } + + fn show(&mut self, pane: Pane, cx: &mut Context<'_, Self>) { + self.pane = pane; + self.copied = None; + self.diagnostics = diagnostics::collect(cx); + if pane == Pane::Safety { + self.reload_safety(); + } + cx.notify(); + } + + /// The copy button that says "Copied" now, if any. + #[cfg(test)] + pub const fn copied(&self) -> Option<&'static str> { + self.copied + } + + /// Read the saved removal limit again. + fn reload_safety(&mut self) { + self.safety = crate::safety::load_policy(self.updates_dir.as_deref()); + #[cfg(test)] + work::SAFETY_LOADS.set(work::SAFETY_LOADS.get() + 1); + } + + fn copy( + &mut self, + id: &'static str, + text: String, + cx: &mut Context<'_, Self>, + ) { + cx.write_to_clipboard(ClipboardItem::new_string(text)); + self.copied = Some(id); + self.copied_reset = Some(cx.spawn(async move |this, cx| { + cx.background_executor().timer(COPY_FEEDBACK).await; + let _ = this.update(cx, |this, cx| { + this.copied = None; + cx.notify(); + }); + })); + cx.notify(); + } + + /// Follow `slot` for updates from now on, and save the pick. + pub fn pick(&mut self, slot: Slot, cx: &mut Context<'_, Self>) { + self.updates_row = slot.index(); + self.note = updater::set_selection( + UpdateSettings::picked(slot), + self.updates_dir.as_deref(), + ) + .err() + .map(|error| { + format!("Updates follow {slot} until PwrDisk quits: {error}") + }); + self.diagnostics = diagnostics::collect(cx); + cx.notify(); + } + + /// Whether the main window would let a restart through now. + fn can_restart(cx: &App) -> bool { + cx.windows() + .into_iter() + .filter_map(|window| window.downcast::()) + .filter_map(|main| main.read(cx).ok()) + .all(Disktree::can_restart_to_update) + } + + /// Restart into the download, through the main window: it refuses + /// while a removal runs, and says so in a toast. + fn restart(cx: &mut App) { + let main = cx + .windows() + .into_iter() + .find_map(|window| window.downcast::()); + match main { + Some(main) => { + let _ = main.update(cx, |app, window, cx| { + window.activate_window(); + app.restart_to_update(cx); + }); + } + None => updater::restart_in_background(), + } + } + + fn on_key(&mut self, event: &KeyDownEvent, cx: &mut Context<'_, Self>) { + let keystroke = &event.keystroke; + if keystroke.modifiers.control + && matches!(keystroke.key.as_str(), "pageup" | "pagedown") + { + let index = Pane::ALL + .iter() + .position(|pane| *pane == self.pane) + .unwrap_or(0); + let step = if keystroke.key == "pageup" { + Pane::ALL.len() - 1 + } else { + 1 + }; + self.show(Pane::ALL[(index + step) % Pane::ALL.len()], cx); + return; + } + if keystroke.modifiers.platform || keystroke.modifiers.control { + return; + } + let rows = Slot::ALL.len(); + match keystroke.key.as_str() { + _ if self.pane != Pane::Updates => {} + // The channels are a grid, Stable over Beta and Latest beside + // Prerelease: up and down change the train, left and right the + // track. + "down" | "j" | "up" | "k" => { + self.updates_row = (self.updates_row + 2) % rows; + cx.notify(); + } + "right" | "l" | "left" | "h" => { + self.updates_row ^= 1; + cx.notify(); + } + "enter" | "space" => self.pick(Slot::ALL[self.updates_row], cx), + "c" if !updater::state().checking => { + updater::check_in_background(updater::Trigger::Manual); + cx.notify(); + } + "r" => { + let installed = updater::installed_version(); + let slot = updater::selection().resolve(&installed); + let state = updater::state(); + if !state.restarting + && updater::ready(&state, &installed, slot).is_some() + { + cx.defer(Self::restart); + } + } + _ => {} + } + } +} + +impl Render for SettingsWindow { + fn render( + &mut self, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) -> impl IntoElement { + crate::ui::sync_scale(window, cx); + let theme = cx.omarchy().clone(); + // When compact the panes wrap in a row above the content instead of + // taking a column beside it, and the group headings, which only + // make sense in a column, step out. + let compact = window.viewport_size().width.as_f32() + / window.rem_size().as_f32() + < crate::ui::COMPACT_WINDOW_REMS; + // Grouped, with the pane shown marked by an accent bar, as the + // family's Settings windows have it; square, as Omarchy draws. + let mut nav = div() + .id("settings-panes") + .role(gpui_kit::Role::TabList) + .aria_label("Settings panes") + .flex() + .flex_col() + .gap(space::XXS) + .w(size::SETTINGS_NAV) + .flex_shrink_0() + .px(space::SM) + .pb(space::SM) + .border_r_1() + .border_color(theme.divider()) + .bg(theme.inset) + .when(compact, |nav| { + nav.pt(space::SM).flex_row().flex_wrap().w_full() + }); + let mut group = ""; + for &pane in &Pane::ALL { + if pane.group() != group && !compact { + group = pane.group(); + nav = nav.child( + div() + .px(space::SM) + .pt(space::MD) + .pb(space::XXS) + .font_family(theme.mono_font.clone()) + .text_size(text::CAPTION) + .font_weight(FontWeight::SEMIBOLD) + .text_color(theme.secondary) + .child(SharedString::from(group.to_uppercase())), + ); + } + let on = pane == self.pane; + // The accent bar marks the pane shown, so focus gets the + // app's full outline on a wrapper instead: recolouring the + // bar would hide focus on the shown pane and make any other + // focused row look shown too. + nav = nav.child( + div() + .id(pane.nav_id()) + .role(gpui_kit::Role::Tab) + .aria_label(pane.label()) + .aria_selected(on) + .focusable() + .tab_stop(true) + .h(size::SETTINGS_NAV_ROW) + .border_1() + .border_color(theme.inset) + .focus_visible(|style| style.border_color(theme.accent)) + .debug_selector(move || pane.nav_id().into()) + .cursor_pointer() + .child( + div() + .size_full() + .flex() + .items_center() + .px(space::SM) + .border_l_2() + .border_color(if on { + theme.accent + } else { + theme.inset + }) + .when(on, |item| { + item.bg(theme.accent.opacity(0.14)) + .text_color(theme.bright) + }) + .hover(|item| item.bg(theme.hover_fill())) + .child(pane.label()), + ) + .on_key_down(cx.listener( + move |this, event: &KeyDownEvent, _, cx| { + if matches!( + event.keystroke.key.as_str(), + "enter" | "space" + ) { + this.show(pane, cx); + cx.stop_propagation(); + } + }, + )) + .on_click(cx.listener(move |this, _, _, cx| { + this.show(pane, cx); + })), + ); + } + let pane = match self.pane { + Pane::Updates => self.updates(&theme, cx), + Pane::Diagnostics => self.diagnostics_pane(&theme, cx), + Pane::Safety => self.safety_pane(&theme, window, cx), + Pane::Agents => self.agents_pane(&theme, cx), + Pane::About => self.about(&theme, cx), + }; + let body = div() + .id(ROOT_ID) + .debug_selector(|| ROOT_ID.into()) + .track_focus(&self.focus) + .tab_group() + .tab_stop(false) + .on_key_down(cx.listener( + |this, event: &KeyDownEvent, window, cx| { + // Tab is the frame's; see `aux_window::frame`. + if !event.keystroke.modifiers.control + && matches!( + event.keystroke.key.as_str(), + "pageup" | "pagedown" | "home" | "end" + ) + && crate::ui::scroll_key( + &event.keystroke.key, + &this.pane_scroll, + window.rem_size(), + ) + { + cx.stop_propagation(); + cx.notify(); + return; + } + this.on_key(event, cx); + }, + )) + .flex() + .flex_row() + .when(compact, gpui_kit::Styled::flex_col) + .flex_1() + .min_h_0() + .child(nav) + .child( + div() + .id("settings-scroll") + .debug_selector(|| "settings-scroll".into()) + .min_h_0() + .track_scroll(&self.pane_scroll) + .flex_1() + .min_w_0() + .overflow_y_scroll() + .child( + div() + .flex() + .flex_col() + .gap(space::LG) + .px(space::XL) + .py(space::XL) + .max_w(size::SETTINGS_PANE) + .child(pane), + ), + ); + aux_window::frame(&["Settings"], div(), body, window, cx) + } +} + +/// The removal limits Settings › Safety offers, in percent of a volume; +/// `None` is Off, for the window only. 100% was the last choice before Off +/// existed, and said the same less plainly. +const LIMITS: [Option; 6] = + [Some(1), Some(5), Some(10), Some(25), Some(50), None]; + +const APPLIES_TO: &str = "Trash may be recoverable until it is emptied; \ + restoring is not guaranteed. A permanent deletion cannot be undone \ + through PwrDisk. An agent must have the exact paths and mode confirmed \ + every time."; + +/// What no setting lifts, said where the settings are so a refusal is +/// never a surprise. +#[cfg(target_os = "macos")] +const PROTECTED: &str = "/Users and each folder in it, your home and any \ + folder holding it; /System, /Library, /private, /usr, /opt/homebrew \ + and the other system trees; mount points and the scanned root."; +#[cfg(windows)] +const PROTECTED: &str = "The profiles folder and each profile in it, your \ + home and any folder holding it; Windows and Program Files; mount \ + points, drive roots and the scanned root."; +#[cfg(target_os = "linux")] +const PROTECTED: &str = "/home and each folder in it, your home and any \ + folder holding it; /usr, /etc, /boot and the other system trees; \ + mount points and the scanned root."; +#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))] +const PROTECTED: &str = "Your home and any folder holding it; /usr, /etc, \ + /boot and the other system trees; mount points and the scanned root."; + +const AGENTS: &str = "Agents over MCP stop at the limit, at 5% when it is \ + Off, and can never mark a protected folder or confirm for you."; + +// ── panes ─────────────────────────────────────────────────────────────── + +impl SettingsWindow { + fn safety_pane( + &self, + theme: &Theme, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) -> Div { + let current = &self.safety; + // One choice of six, so one control: the segments the review + // screen uses for Trash or permanent, saved as soon as one is + // picked. Six buttons read as six commands. + let picked = current.as_ref().ok().and_then(|policy| { + LIMITS.iter().position(|&percent| { + percent == policy.limit.map(Limit::percent) + }) + }); + let entity = cx.entity().downgrade(); + let rows = + div() + .debug_selector(|| "safety-limit".into()) + .child(button_group( + "safety-limit", + LIMITS + .iter() + .map(|percent| { + percent.map_or_else( + || ChoiceItem::new("off", "Off"), + |percent| { + ChoiceItem::new( + percent.to_string(), + format!("{percent}%"), + ) + }, + ) + }) + .collect(), + picked, + move |index, window, cx| { + let _ = entity.update(cx, |this, cx| { + this.note = LIMITS[index] + .map(Limit::new) + .transpose() + .and_then(|limit| { + crate::safety::save_limit( + this.updates_dir.as_deref(), + limit, + ) + }) + .err(); + // Read back what was written, so the pane + // shows the file and not the click. + this.reload_safety(); + cx.set_global(crate::safety::Saved); + // Back to the window, as the other panes' + // controls do, so Tab keeps walking panes. + window.focus(&this.focus, cx); + cx.notify(); + }); + }, + window, + cx, + )); + let confirmed = current.as_ref().ok().and_then(|policy| { + Confirm::ALL + .iter() + .position(|&confirm| confirm == policy.confirm) + }); + let entity = cx.entity().downgrade(); + let confirm = div().debug_selector(|| "safety-confirm".into()).child( + button_group( + "safety-confirm", + Confirm::ALL + .iter() + .map(|confirm| { + ChoiceItem::new(confirm.label(), confirm.label()) + }) + .collect(), + confirmed, + move |index, window, cx| { + let _ = entity.update(cx, |this, cx| { + this.note = crate::safety::save_confirm( + this.updates_dir.as_deref(), + Confirm::ALL[index], + ) + .err(); + this.reload_safety(); + cx.set_global(crate::safety::Saved); + window.focus(&this.focus, cx); + cx.notify(); + }); + }, + window, + cx, + ), + ); + let caption = |id: &'static str, text: &'static str| { + readable(id, text) + .text_color(theme.foreground) + .child(text) + .into_any_element() + }; + let mut body = div() + .flex() + .flex_col() + .gap(space::LG) + .child(head( + "Safety", + "Removal limit", + "Each operation is re-measured before anything is removed, \ + from the window and from an agent over MCP.", + None, + theme, + )) + .child( + card_plain(theme) + .child(field( + "Per operation", + Some( + "Measured data, as a share of each volume's \ + capacity. The default is 5%. Past it, Mark \ + needs Mark anyway.", + ), + vec![rows.into_any_element()], + theme, + )) + .child(field( + "Over the limit", + Some( + "What Review asks after Mark anyway, before \ + anything is removed.", + ), + vec![confirm.into_any_element()], + theme, + )) + .child(field( + "Always protected", + Some("Never offered for removal. Not a setting."), + vec![caption("safety-protected", PROTECTED)], + theme, + )) + .child(field( + "Agents", + Some("Marks and removals over MCP."), + vec![caption("safety-agents", AGENTS)], + theme, + )) + .child(field( + "Applies to", + Some("Trash and permanent deletion."), + vec![caption("safety-applies", APPLIES_TO)], + theme, + )), + ); + if let Err(reason) = current { + body = body.child( + readable("safety-error", reason.clone()) + .role(Role::Alert) + .text_color(theme.warning) + .child(reason.clone()), + ); + } + if let Some(note) = &self.note { + body = body.child(alert_note(note, theme)); + } + body + } + + /// How to connect an agent over MCP, who is connected, and what an + /// agent may do. The main window's link answers the agent; this pane + /// only reads who it is. + fn agents_pane(&self, theme: &Theme, cx: &Context<'_, Self>) -> Div { + let (connected, status) = cx + .windows() + .into_iter() + .filter_map(|window| window.downcast::()) + .find_map(|main| main.read(cx).ok().map(Disktree::agent_status)) + .unwrap_or_else(|| { + (false, "No PwrDisk window is open.".to_owned()) + }); + let mut connect = card("Connect", None, theme); + for way in &self.connect { + connect = connect.child(field( + way.label, + None, + vec![self.copy_row(way.id, &way.text, theme, cx)], + theme, + )); + } + div() + .flex() + .flex_col() + .gap(space::LG) + .child(head( + "App", + "Agents (MCP)", + "Let Claude Code, Codex or any MCP client scan, explore and \ + mark with PwrDisk, and this window follows along. Removing \ + stays yours.", + None, + theme, + )) + .child(card("Connection", None, theme).child(field( + "Status", + None, + vec![ + readable("agents-status", status.clone()) + .debug_selector(|| "agents-status".into()) + .flex() + .flex_row() + .gap(space::XS) + .child( + div() + .text_color(if connected { + theme.success + } else { + theme.secondary + }) + .child("\u{25cf}"), + ) + .child( + div() + .text_color(theme.foreground) + .child(status), + ) + .into_any_element(), + ], + theme, + ))) + .child(connect) + .child(card("First prompt", None, theme).child(field( + "Ask it", + Some("A proposal first: it marks only once you agree."), + vec![self.copy_row( + COPY_PROMPT_ID, + crate::agent::FIRST_PROMPT, + theme, + cx, + )], + theme, + ))) + .child( + card("What an agent may do", None, theme) + .child(field( + "Look and mark", + None, + vec![value_text( + "Scan, walk the tree, mark what could go, and \ + open the review screen." + .to_owned(), + )], + theme, + )) + .child(field( + "Remove", + None, + vec![value_text( + "Only after you confirm the exact paths and \ + mode, within the limit in Safety. Removing \ + from the review screen stays yours." + .to_owned(), + )], + theme, + )), + ) + } + + fn updates(&self, theme: &Theme, cx: &Context<'_, Self>) -> Div { + use crate::updater::Installation; + + let installed = updater::installed_version(); + let selection = updater::selection(); + let slot = selection.resolve(&installed); + let state = updater::state(); + let ready = updater::ready(&state, &installed, slot); + let installation = updater::installation(); + // Only a copy Velopack installed checks on its own. + let on_its_own = match installation { + Installation::Velopack { .. } => "PwrDisk also checks on its own.", + Installation::NotInstalled { .. } => { + "This copy never checks on its own." + } + }; + let lede = match installation { + Installation::Velopack { .. } => { + "Checks GitHub Releases at startup and every six hours. A \ + download installs when you restart or quit." + } + Installation::NotInstalled { .. } => { + "Not installed from the DMG, Setup.exe or the MSI, so this \ + copy does not update itself. The channel still says which \ + releases a check reads." + } + }; + + // Stable over Beta, Latest beside Prerelease: the grid the family's + // Updates panes use. + let mut grid = div() + .flex() + .flex_col() + .gap(space::XS) + .px(space::MD) + .pt(space::SM) + .pb(space::SM) + .border_t_1() + .border_color(theme.divider()); + for (train, pair) in Slot::ALL.chunks(2).enumerate() { + let mut row = div().flex().flex_row().gap(space::XS); + for (track, &choice) in pair.iter().enumerate() { + let index = train * 2 + track; + row = row.child(self.slot_tile(index, choice, slot, theme, cx)); + } + grid = grid.child(row); + } + let follows = if selection.is_inferred() { + "Follows this build until you pick one." + } else { + "Picked, and saved with the other settings." + }; + let channel = card( + "Release channel", + Some( + readable("channel-purpose", "Which releases a check reads") + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child("Which releases a check reads") + .into_any_element(), + ), + theme, + ) + .child(grid) + .child( + readable("channel-follows", follows) + .px(space::MD) + .pb(space::SM) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(follows), + ); + + let chip = ready.as_ref().map(|held| { + chip(format!("{} ready", held.version), theme.warning, theme) + .into_any_element() + }); + let checked = if state.checking { + "Checking now".to_owned() + } else { + state.last.as_ref().map_or_else( + || "Not checked yet this session".to_owned(), + |(when, _)| { + let then = when + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |since| { + i64::try_from(since.as_secs()).unwrap_or(i64::MAX) + }); + format!( + "Checked {}", + crate::widgets::ago(crate::state::now_seconds(), then) + ) + }, + ) + }; + let mut actions = div().flex().flex_row().gap(space::SM).child( + button(CHECK_ID, "Check now", ButtonVariant::Outline, cx) + .debug_selector(|| CHECK_ID.into()) + .semantic_disabled(state.checking) + .on_click(cx.listener(|_, _, _, cx| { + updater::check_in_background(updater::Trigger::Manual); + cx.notify(); + })), + ); + if let Some(held) = &ready { + let verb = if held.switch_back { "switch" } else { "update" }; + let label = if state.restarting { + "Restarting\u{2026}".to_owned() + } else { + format!("Restart to {verb} to {}", held.version) + }; + actions = actions.child( + button(RESTART_ID, label, ButtonVariant::Primary, cx) + .debug_selector(|| RESTART_ID.into()) + // As the panel had it: never while a removal runs, which an + // exit would stop partway through the marked list; and once + // pressed, until it fails. + .semantic_disabled(state.restarting || !Self::can_restart(cx)) + .on_click(|_, _, cx| cx.defer(Self::restart)), + ); + } + let status = status_line(&state, ready.as_ref()); + let this_copy = card("This copy", chip, theme) + .child(field_with( + "Status", + Some(checked.into()), + vec![ + readable("updates-status", status.clone()) + .debug_selector(|| "updates-status".into()) + .child(status) + .into_any_element(), + ], + theme, + )) + .child(field( + "Check now", + Some(on_its_own), + vec![actions.into_any_element()], + theme, + )); + + let mut pane = div() + .flex() + .flex_col() + .gap(space::LG) + .child(head( + "Updates", + &format!("PwrDisk {installed}"), + lede, + None, + theme, + )) + .child(channel) + .child(this_copy); + if let Some(note) = &self.note { + pane = pane.child(alert_note(note, theme)); + } + // Omarchy's apps list their keys; on macOS and Windows the keys + // still work, and the help overlay names them. + if crate::chrome::Platform::current() == crate::chrome::Platform::Linux + { + pane = pane.child(hint( + "\u{2191}\u{2193}\u{2190}\u{2192} and enter pick a channel \ + \u{b7} c checks \u{b7} r restarts into a download \u{b7} \ + Ctrl+PageUp/PageDown switches panes", + theme, + )); + } + pane + } + + /// One channel in the grid: picked, under the keys, or neither. + fn slot_tile( + &self, + index: usize, + choice: Slot, + current: Slot, + theme: &Theme, + cx: &Context<'_, Self>, + ) -> gpui_kit::Stateful
{ + let picked = choice == current; + let keyed = index == self.updates_row; + div() + .id(ElementId::Name(format!("update-slot-{index}").into())) + .debug_selector(move || format!("update-slot-{index}")) + .role(Role::RadioButton) + .aria_label(format!("{choice}: {}", slot_purpose(choice))) + .aria_toggled(if picked { + gpui_kit::accesskit::Toggled::True + } else { + gpui_kit::accesskit::Toggled::False + }) + .focusable() + // One stop for the group, on the channel picked, as a radio + // group takes Tab; the arrows move within it. + .tab_stop(picked) + .on_key_down(cx.listener( + move |this, event: &KeyDownEvent, window, cx| { + match event.keystroke.key.as_str() { + "enter" | "space" => { + this.updates_row = index; + this.pick(choice, cx); + cx.stop_propagation(); + } + "up" | "down" | "left" | "right" => { + this.updates_row = index; + this.on_key(event, cx); + window.focus(&this.focus, cx); + cx.stop_propagation(); + } + _ => {} + } + }, + )) + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(space::XXS) + .px(space::MD) + .py(space::SM) + .border_1() + .border_color(if picked { + theme.accent + } else if keyed { + theme.border + } else { + theme.divider() + }) + .when(picked, |tile| tile.bg(theme.accent.opacity(0.10))) + .when(keyed && !picked, |tile| tile.bg(theme.hover_fill())) + .hover(|tile| tile.bg(theme.hover_fill())) + .cursor_pointer() + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .child( + div() + .flex_1() + .font_weight(FontWeight::SEMIBOLD) + .text_color(theme.bright) + .child(choice.to_string()), + ) + .when(picked, |name| { + name.child(chip("Selected".into(), theme.accent, theme)) + }), + ) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(slot_purpose(choice)), + ) + .on_click(cx.listener(move |this, _, _, cx| { + this.updates_row = index; + this.pick(choice, cx); + })) + } + + fn diagnostics_pane(&self, theme: &Theme, cx: &Context<'_, Self>) -> Div { + let model = &self.diagnostics; + let report = model.report(); + let copy = self.copy_button(COPY_DIAGNOSTICS_ID, "Copy", report, cx); + let mut pane = div().flex().flex_col().gap(space::LG).child(head( + "Support", + "Diagnostics", + "What this copy runs with. Copy carries these lines and \ + nothing else: no scanned path ever appears here. Help \u{203a} \ + Copy Diagnostics Info copies the same.", + Some(copy.into_any_element()), + theme, + )); + let mut this_copy = card("This copy", None, theme).child(field( + "Version", + None, + vec![value_text(model.version_line())], + theme, + )); + // Paths and Session have their own cards below. + for section in model + .sections + .iter() + .filter(|section| !matches!(section.title, "Paths" | "Session")) + { + for fact in §ion.facts { + this_copy = this_copy.child(field( + fact.label, + None, + vec![value_text(fact.value.clone())], + theme, + )); + } + } + pane = pane.child(this_copy); + + let home = std::env::home_dir(); + let shown = |path: &Option| { + path.as_deref().map_or_else( + || "None".to_owned(), + |path| { + crate::marks::display_path( + path, + home.as_deref(), + PathStyle::Native, + ) + }, + ) + }; + let settings_dir = model.settings_dir.clone(); + let log = model.log.clone(); + pane = pane.child( + card("Files", None, theme) + .child(field( + "Settings folder", + Some("The release channel and the power preset."), + vec![ + command_box(shown(&settings_dir), theme) + .into_any_element(), + button( + "diagnostics-open-settings", + "Open settings folder", + ButtonVariant::Secondary, + cx, + ) + .debug_selector(|| "diagnostics-open-settings".into()) + .semantic_disabled( + !settings_dir + .as_deref() + .is_some_and(std::path::Path::exists), + ) + .on_click(move |_, _, cx| { + if let Some(dir) = &settings_dir { + cx.open_with_system(dir); + } + }) + .into_any_element(), + ], + theme, + )) + .child(field( + "Log", + Some( + "Scans, removals and updates, never a scanned path. \ + Help \u{203a} Logs follows it live.", + ), + vec![ + command_box(shown(&log), theme).into_any_element(), + button( + "diagnostics-open-logs", + "Open Logs", + ButtonVariant::Secondary, + cx, + ) + .debug_selector(|| "diagnostics-open-logs".into()) + .semantic_disabled(log.is_none()) + .on_click(|_, _, cx| { + cx.defer(crate::logs_window::open); + }) + .into_any_element(), + ], + theme, + )), + ); + if let Some(session) = model + .sections + .iter() + .find(|section| section.title == "Session") + { + pane = pane.child(session.facts.iter().fold( + card("This session", None, theme), + |card, fact| { + card.child(field( + fact.label, + None, + vec![value_text(fact.value.clone())], + theme, + )) + }, + )); + } + pane + } + + fn about(&self, theme: &Theme, cx: &Context<'_, Self>) -> Div { + let build = BuildInfo::current(); + let channel = updater::selection() + .resolve(&updater::installed_version()) + .to_string(); + let header = card_frame(theme) + .debug_selector(|| ABOUT_HEADER_ID.into()) + .flex_row() + .items_center() + .gap(space::MD) + .p(space::MD) + .child( + img(crate::chrome::MARK.clone()) + .size(size::ABOUT_ICON) + .flex_shrink_0(), + ) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .gap(space::XXS) + .child( + readable("version", format!("PwrDisk {}", build.version)) + .role(Role::Heading) + .text_size(text::HEADING) + .font_weight(FontWeight::BOLD) + .text_color(theme.bright) + .child(format!("PwrDisk {}", build.version)), + ) + // One line, as the design draws it: a long branch + // name ends in an ellipsis rather than wrapping. + // The label keeps the whole line for assistive + // technology when the painted one is cut short. + .child( + readable("build", build.header_line(&channel)) + .debug_selector(|| ABOUT_BUILD_LINE_ID.into()) + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(build.header_line(&channel)), + ), + ) + .when(!build.is_release(), |row| { + row.child(chip("Dev build".into(), theme.warning, theme)) + }) + .child(self.copy_button( + COPY_BUILD_ID, + "Copy build info", + build.report(), + cx, + )); + let mut source = Vec::new(); + if let Some(checkout) = &build.checkout { + source.push(self.copy_row( + "about-copy-checkout", + checkout, + theme, + cx, + )); + } + match (build.is_release(), &build.tag, &build.branch) { + (true, Some(tag), _) => { + source.push(self.copy_row("about-copy-branch", tag, theme, cx)); + } + (_, _, Some(branch)) => { + source.push(self.copy_row( + "about-copy-branch", + branch, + theme, + cx, + )); + } + _ => source.push(value_text( + "Detached HEAD: the commit names it.".to_owned(), + )), + } + match &build.commit { + Some(commit) => { + source.push(self.copy_row( + "about-copy-commit", + commit, + theme, + cx, + )); + } + None => source.push(value_text( + "No commit recorded: this copy was built outside a git \ + checkout." + .to_owned(), + )), + } + if let Some(line) = build.commit_line() { + source.push( + readable("commit-details", line.clone()) + .text_color(theme.secondary) + .child(line) + .into_any_element(), + ); + } + if let Some(line) = build.changes_line() { + source.push( + readable("build-changes", line.clone()) + .text_color(theme.warning) + .child(line) + .into_any_element(), + ); + } + let docs = div() + .flex() + .flex_row() + .flex_wrap() + .gap(space::SM) + .child( + button( + "about-license", + "View license", + ButtonVariant::Secondary, + cx, + ) + .debug_selector(|| "about-license".into()) + .on_click(|_, window, cx| { + window.dispatch_action( + Box::new(crate::help::ViewLicense), + cx, + ); + }), + ) + .child( + button( + "about-notices", + "Third-party notices", + ButtonVariant::Secondary, + cx, + ) + .debug_selector(|| "about-notices".into()) + .on_click(|_, window, cx| { + window.dispatch_action( + Box::new(crate::help::ThirdPartyNotices), + cx, + ); + }), + ) + .child( + button( + "about-changelog", + "Changelog", + ButtonVariant::Secondary, + cx, + ) + .debug_selector(|| "about-changelog".into()) + .on_click(|_, window, cx| { + window.dispatch_action( + Box::new(crate::help::OpenChangelog), + cx, + ); + }), + ); + let repository = crate::help::REPOSITORY + .trim_start_matches("https://") + .to_owned(); + div() + .flex() + .flex_col() + .gap(space::LG) + .child(head( + "PwrDisk", + "About", + "Finds what is eating a volume and removes what you mark, \ + with the free space live on screen. A fork of disktree, in \ + the Pwr family with PwrRoute, PwrGit and PwrAgnt.", + None, + theme, + )) + .child(header) + .child( + card("This copy", None, theme) + .child(field( + "Source", + Some("Read by git when this copy was built."), + source, + theme, + )) + .child(field( + "License", + Some("MIT. Includes disktree, by Tobi L\u{fc}tke."), + vec![docs.into_any_element()], + theme, + )), + ) + .child( + card("Project", None, theme) + .child(field( + "Source", + None, + vec![ + mono(repository.clone(), theme).into_any_element(), + ], + theme, + )) + .child(field( + "Issues", + None, + vec![ + mono(format!("{repository}/issues"), theme) + .into_any_element(), + ], + theme, + )), + ) + } + + fn copy_button( + &self, + id: &'static str, + label: &'static str, + text: String, + cx: &Context<'_, Self>, + ) -> impl IntoElement { + let label = if self.copied == Some(id) { + "Copied" + } else { + label + }; + // Several buttons read "Copy", so each is named for what it + // copies, and "Copied" says so too. + let name = match id { + COPY_DIAGNOSTICS_ID => "Copy diagnostics report", + "about-copy-checkout" => "Copy checkout path", + "about-copy-branch" => "Copy branch or tag", + "about-copy-commit" => "Copy commit", + "agents-copy-command" => "Copy the command line", + "agents-copy-claude" => "Copy the Claude Code command", + "agents-copy-codex" => "Copy the Codex command", + "agents-copy-json" => "Copy the MCP client JSON", + COPY_PROMPT_ID => "Copy the first prompt", + _ => label, + }; + let name = if self.copied == Some(id) { + format!("Copied: {name}") + } else { + name.to_owned() + }; + button(id, label, ButtonVariant::Secondary, cx) + .accessibility_label(name) + .debug_selector(move || id.into()) + .on_click(cx.listener(move |this, _, _, cx| { + this.copy(id, text.clone(), cx); + })) + } + + /// A value in a command box with its own Copy. + fn copy_row( + &self, + id: &'static str, + value: &str, + theme: &Theme, + cx: &Context<'_, Self>, + ) -> AnyElement { + command_box(value.to_owned(), theme) + .id(ElementId::Name(format!("{id}-row").into())) + .child(self.copy_button(id, "Copy", value.to_owned(), cx)) + .into_any_element() + } +} + +/// What each release channel slot is for, in the family's words. +/// The answer to Check now, in the family's words: "You're up to date +/// (0.14.0).", "Update ready: 0.15.0. Restart to install." +fn status_line( + state: &updater::State, + ready: Option<&updater::Held>, +) -> String { + use crate::updater::Outcome; + if state.checking { + return "Checking\u{2026}".to_owned(); + } + match (&state.last, ready) { + (None, _) => "Not checked yet.".to_owned(), + (_, Some(held)) if held.switch_back => { + format!("{} is downloaded. Restart to switch.", held.version) + } + (_, Some(held)) => { + format!("Update ready: {}. Restart to install.", held.version) + } + (Some((_, outcome)), None) => match outcome { + Outcome::UpToDate(version) => { + format!("You're up to date ({version}).") + } + Outcome::Failed(why) => format!("Update check failed: {why}"), + Outcome::NotInstalled(_) => { + "This copy doesn't update itself.".to_owned() + } + Outcome::NothingPublished(slot) => { + format!("Nothing is published on {slot} yet.") + } + other => other.to_string(), + }, + } +} + +const fn slot_purpose(slot: Slot) -> &'static str { + use crate::update_channel::{Track, Train}; + match (slot.train, slot.track) { + (Train::Stable, Track::Latest) => "Releases promoted after a check", + (Train::Stable, Track::Prerelease) => "Candidates for the next one", + (Train::Beta, Track::Latest) => "Beta builds off main", + (Train::Beta, Track::Prerelease) => "The newest alpha; may not work", + } +} + +// ── the pane's parts ──────────────────────────────────────────────────── + +/// The pane's head: an eyebrow, the title, what the pane is for, and an +/// action at the end. +fn head( + eyebrow: &str, + title: &str, + lede: &'static str, + action: Option, + theme: &Theme, +) -> Stateful
{ + let title = SharedString::from(title.to_owned()); + div() + .id("settings-heading") + .role(Role::Group) + .aria_label(title.clone()) + .flex() + .flex_col() + .gap(space::XS) + .child( + div() + .flex() + .flex_row() + .items_end() + .gap(space::MD) + .child( + div() + .flex() + .flex_col() + .flex_1() + .gap(space::XXS) + .child( + div() + .font_family(theme.mono_font.clone()) + .text_size(text::CAPTION) + .font_weight(FontWeight::BOLD) + .text_color(theme.accent) + .child(SharedString::from( + eyebrow.to_uppercase(), + )), + ) + .child( + readable("pane-title", title.clone()) + .role(Role::Heading) + .text_size(text::HEADING) + .font_weight(FontWeight::BOLD) + .text_color(theme.bright) + .child(title), + ), + ) + .children(action), + ) + .child( + readable("pane-description", lede) + .max_w(size::SETTINGS_LEDE) + .text_color(theme.secondary) + .child(lede), + ) +} + +/// A card: a raised heading strip with something at its end, then rows, +/// each of which draws the rule above it. +fn card( + title: &'static str, + trailing: Option, + theme: &Theme, +) -> Stateful
{ + card_frame(theme) + .id(title) + .role(Role::Group) + .aria_label(title) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(space::MD) + .px(space::MD) + .py(space::SM) + .bg(theme.surface) + .child( + readable("card-heading", title) + .role(Role::Heading) + .flex_1() + .font_weight(FontWeight::BOLD) + .text_color(theme.bright) + .child(title), + ) + .children(trailing), + ) +} + +/// A card with no heading strip: its first row's rule is the card's top +/// edge, so the card draws none of its own. +fn card_plain(theme: &Theme) -> Div { + card_frame(theme).border_t_0() +} + +fn card_frame(theme: &Theme) -> Div { + div() + .flex() + .flex_col() + .border_1() + .border_color(theme.divider()) + .bg(theme.inset) +} + +/// A labelled row: the label and what it is for on the left, the values +/// at the right, one under the other, as the family's Settings rows sit. +fn field( + label: &'static str, + sub: Option<&'static str>, + values: Vec, + theme: &Theme, +) -> Stateful
{ + field_with(label, sub.map(SharedString::from), values, theme) +} + +fn field_with( + label: &'static str, + sub: Option, + values: Vec, + theme: &Theme, +) -> Stateful
{ + div() + .id(label) + .role(Role::Group) + .aria_label(label) + .flex() + .flex_row() + .items_center() + .flex_wrap() + .gap(space::LG) + .px(space::MD) + .py(space::SM) + .border_t_1() + .border_color(theme.divider()) + .child( + div() + .flex() + .flex_col() + .gap(space::XXS) + .w(size::SETTINGS_LABEL) + .flex_shrink_0() + .child( + readable("field-label", label) + .font_weight(FontWeight::SEMIBOLD) + .text_color(theme.bright) + .child(label), + ) + .children(sub.map(|sub| { + readable("field-description", sub.clone()) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(sub) + })), + ) + .child( + div() + .flex() + .flex_col() + // Buttons keep their own width; a command box spans it. + .items_end() + .gap(space::SM) + .flex_1() + // At least half the row, so a narrow window wraps the + // values below their label rather than crushing them. + .min_w(gpui_kit::relative(0.5)) + .text_color(theme.bright) + .children(values), + ) +} + +/// A value to copy, in monospace on the window's ground. +fn command_box(value: String, theme: &Theme) -> Div { + div() + .w_full() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .pl(space::SM) + .pr(space::XS) + .py(space::XXS) + .border_1() + .border_color(theme.divider()) + .bg(theme.background) + .child( + readable("command-value", value.clone()) + .flex_1() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .font_family(theme.mono_font.clone()) + .text_color(theme.bright) + .child(value), + ) +} + +fn mono(value: String, theme: &Theme) -> Stateful
{ + readable("project-url", value.clone()) + .font_family(theme.mono_font.clone()) + .text_color(theme.foreground) + .child(value) +} + +fn chip(label: String, color: gpui_kit::Hsla, theme: &Theme) -> Div { + div() + .px(space::SM) + .border_1() + .border_color(color) + .text_color(color) + .font_family(theme.mono_font.clone()) + .text_size(text::CAPTION) + .child(label) +} + +fn hint(text_: &'static str, theme: &Theme) -> Stateful
{ + readable("settings-hint", text_) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(text_) +} + +/// A value read out as text, not just painted. +fn value_text(value: String) -> AnyElement { + readable("value", value.clone()) + .child(value) + .into_any_element() +} + +/// A failed save or pick, announced as it appears. +fn alert_note(note: &str, theme: &Theme) -> Stateful
{ + readable("settings-note", note.to_owned()) + .role(Role::Alert) + .text_color(theme.warning) + .child(note.to_owned()) +} + +/// What Settings did, counted for the tests that hold it to doing it once. +#[cfg(test)] +pub mod work { + use std::cell::Cell; + + thread_local! { + /// Reads of the saved removal limit. + pub static SAFETY_LOADS: Cell = const { Cell::new(0) }; + } +} diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs index efb9730a..9dc77875 100644 --- a/crates/disktree-app/src/state.rs +++ b/crates/disktree-app/src/state.rs @@ -4,15 +4,17 @@ //! decisions — what is selected, what a mark means, what a key does, when to //! re-scan — live here so they can be reasoned about in one place. -use std::cell::Cell; +use std::cell::{Cell, RefCell}; +use std::ops::Range; use std::path::{Path, PathBuf}; use std::rc::Rc; -use std::sync::Arc; +use std::sync::{Arc, Weak}; use std::time::{Duration, Instant}; use disktree_core::access::file_table_readable; -use disktree_core::filter::{Keep, Matches, filter}; +use disktree_core::filter::{Keep, Matches, filter_with, find_ignoring_case}; use disktree_core::insights::{Candidate, worth_a_look}; +use disktree_core::path_style::PathStyle; use disktree_core::removal::{ Plan, RemovalEvent, RemovalHandle, RemovalMode, Target, TrashBackend, detect_trash_backend, plan, @@ -21,7 +23,7 @@ use disktree_core::scan::{Known, ScanHandle, ScanOptions, ScanSnapshot}; use disktree_core::space::{ SpaceInfo, device_for, space_info, volume_root_for, }; -use disktree_core::tree::{Metric, Node, path_of}; +use disktree_core::tree::{Metric, Node, Tree, path_of}; use disktree_core::treemap::{ LayoutOptions, Rect, Tile, TileKind, hit, layout_filtered, }; @@ -31,12 +33,12 @@ use gpui_kit::{ MouseDownEvent, MouseMoveEvent, NavigationDirection, Pixels, Point, Render, ScrollDelta, ScrollWheelEvent, Size, Window, px, size, }; -use gpui_omarchy::Status; -use rustc_hash::{FxHashMap, FxHashSet}; +use gpui_omarchy::{ActiveTheme as _, Status}; +use rustc_hash::FxHashSet; -use crate::git::GitState; +use crate::git_store::{self, Ask, GitProbe, GitStore, Wanted}; -use crate::marks::{Marks, display_path, is_hidden}; +use crate::marks::{Marks, is_hidden}; use crate::treemap_view::{Mosaic, TileDeco}; /// What a tile's colour says. @@ -103,6 +105,22 @@ pub fn panel_width(pointer_x: f32, viewport: f32, rem: f32) -> f32 { /// How many "worth a look" findings the panel lists. const INSIGHT_LIMIT: usize = 6; +/// The menu bar's Undo, as each system spells it; `u` works everywhere. +pub const UNDO_KEYS: &str = if cfg!(target_os = "macos") { + "\u{2318}Z" +} else { + "Ctrl+Z" +}; + +/// Who started a removal, which decides the limit its worker is held to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Remover { + /// The window's limit, raised only by Review's confirmation. + Person, + /// The agent limit, which nothing in the window raises. + Agent, +} + /// Which screen the app is showing. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Screen { @@ -313,13 +331,30 @@ pub struct History { /// through, and small enough that pruning after a scan costs nothing. const HISTORY_DEPTH: usize = 100; -/// Result of the removal run, summarised for the final screen. -#[derive(Clone, Debug, Default)] -pub struct RunSummary { - pub total: usize, - pub removed: u64, - pub bytes: u64, - pub failed: usize, +/// Scan-derived display estimates; never cached removal authorization. +#[derive(Default)] +struct AccountingCache { + tree: Weak, + root: PathBuf, + // Total and scanned-volume subsets only: bounded by the current marks. + estimates: Vec<(Vec, disktree_core::sharing::Estimate)>, +} + +/// What the scan made of each marked path, for Review's rows. Resolving a +/// path indexes every directory it passes through, which is too much to +/// repeat on every frame of a list of marks; this keeps the answer until +/// the tree changes. Bounded by the paths marked against one tree. +#[derive(Default)] +struct KindCache { + tree: Weak, + root: PathBuf, + kinds: rustc_hash::FxHashMap< + PathBuf, + ( + disktree_core::classify::Category, + Option, + ), + >, } /// Everything the app knows and everything it can do. @@ -338,23 +373,50 @@ pub struct Disktree { pub options: ScanOptions, pub power_choice: Option, pub power_settings_path: Option, + pub removal_settings_dir: Option, /// The Power Efficiency menu, when open: the row the arrow keys are on, /// as an index into [`crate::power::PowerEfficiency::ALL`]. pub power_menu: Option, /// The pointer is on the menu's button. A press there is the button's /// to toggle, not a press outside the menu that closes it first. pub power_hover: bool, + /// The ⋮ menu, when open: the row the arrow keys are on, as an index + /// into [`crate::toolbar::BarFit::more_items`]. + pub more_menu: Option, + /// The pointer is on ⋮, as [`Self::power_hover`] is for its button. + pub more_hover: bool, + /// How much of the explore bar fit when it was last drawn, which says + /// what ⋮ holds. + pub bar_fit: crate::toolbar::BarFit, pub cpu_threads: usize, - pub tree: Option>, + pub tree: Option>, pub scan: Option, pub scan_epoch: u64, pub progress: ScanSnapshot, + /// Sampled progress is announced at most once every two seconds. Errors + /// and phase changes bypass this cache; sampled paths are never announced. + pub accessible_progress: Option<(Instant, String)>, pub scan_error: Option, pub screen: Screen, /// Path from the scanned root to the directory currently drawn. pub crumbs: Vec, pub selected: Option>, + /// A bounded, semantic alternative to the painted mosaic. + pub file_list: bool, + pub file_page: usize, + pub file_scroll: gpui_kit::ScrollHandle, + pub file_focus: FocusHandle, + restore_file_focus: bool, + pub review_page: usize, + pub review_scroll: gpui_kit::ScrollHandle, + /// The side panel's lists, measured to pin their headers. + pub panel_scroll: gpui_kit::ScrollHandle, + /// Their sections' bounds as last laid out: a change asks for one more + /// frame, so the pinned header follows the new layout. + pub panel_layout: std::rc::Rc< + std::cell::RefCell>>, + >, pub hovered: Option>, pub history: History, /// The history button under the pointer, `true` for `<`: its card is @@ -362,13 +424,19 @@ pub struct Disktree { pub history_hover: Option, /// The pointer moved more recently than the keyboard navigated. Then the /// tile under the pointer is what Space, X and Enter act on; after an - /// arrow or Tab it is the keyboard selection again. + /// arrow or n it is the keyboard selection again. pub pointer_active: bool, + /// A press of the click sequence under way (a double or triple click) + /// already opened a level. Its later presses land on the level it + /// opened, so they are ignored rather than opening another. + click_opened: bool, pub view: View, /// The in-flight layout transition, if a level was just entered or left. pub transition: Option, pub layout_options: LayoutOptions, cache: Option, + accounting: RefCell, + kinds: RefCell, /// Mouse position in treemap-local pixels, for hit-testing and the tooltip. pub pointer: Option>, @@ -377,31 +445,91 @@ pub struct Disktree { pub treemap_size: Rc>>, pub marks: Marks, + /// Paths removed since the scan. They stay in the tree, drawn as + /// removed, until the next scan, and cannot be marked again. + pub removed: Marks, + /// What Unmark all took, so one key or ⌘Z can put it back. Dropped + /// wherever the marks stop meaning this machine's paths. + pub unmarked: Option>, + /// The review footer's Export menu is open. + pub export_menu_open: bool, + /// Whether it was open when the press that may close it began, so + /// pressing its button toggles instead of reopening. + pub export_menu_was_open: bool, pub removal_mode: RemovalMode, + pub cleanup_review: Option, + pub cleanup_results: Vec, + /// What each step of the running cleanup does, in run-list order. + pub cleanup_actions: Vec, + /// Where owners are looked for instead of PwrDisk's PATH. Only tests + /// set it, so their checks find fixture executables and nothing else. + pub cleanup_path: Option, pub trash_backend: TrashBackend, /// The permanent-deletion alert dialog is open. Trash needs no dialog: it /// is reversible, so it commits directly. pub confirm_open: bool, /// Focus owner for the alert dialog while it is open. pub confirm_focus: FocusHandle, + pub overlay_return: Option, + pub app_menu_index: usize, + pub menu_scroll: gpui_kit::ScrollHandle, + pub help_scroll: gpui_kit::ScrollHandle, + pub source_roots_focus: FocusHandle, /// Focus to move on the next occasion a window is in hand. Key handling /// has no window, and opening or closing the dialog must move focus. pub focus_request: Option, - /// What the titlebar says, so it is only set when it changes. + /// What the titlebar says, so it is only set when it changes. The strip + /// paints no title, but the Window menu, Mission Control, the taskbar + /// and Waybar still read it. window_title: String, + /// The left button went down on the title strip and has not moved yet: + /// the first motion starts a window move. + pub strip_drag: bool, + /// A window frame to draw instead of asking the platform. The + /// window-harness tests pin one per layout: their window has no + /// compositor to ask. + pub chrome_pin: Option, + /// How far the content sits inside the window, from this frame's + /// [`crate::chrome::Frame`]: what turns a pointer position into one in + /// the root's coordinates. + pub content_edges: gpui_kit::Edges, /// The window's `rem` in pixels, read each frame. The mosaic is laid out /// in pixels, so its header band and label thresholds are scaled by this /// to follow interface zoom like the rest of the interface. pub rem: f32, pub run: Option, + /// Stop was asked for: the removal ends after the current item. + pub stop_requested: bool, pub run_epoch: u64, - pub run_summary: RunSummary, - pub run_log: Vec<(PathBuf, Result<(), String>)>, + /// Every target of the latest run and what happened to it: what + /// Removing and Done draw, and the run's only record of its outcome. + pub run_list: crate::run_list::RunList, + pub run_scroll: gpui_kit::UniformListScrollHandle, + /// Free bytes on the scanned volume as the latest run started, for + /// what it has freed so far. + pub run_free_before: Option, pub space: Option, /// Free space before the removal, for the honest "what did it actually /// free" number rather than the sum of what was marked. pub space_baseline: Option, - pub notice: Option<(String, Status)>, + /// Rescan once the running removal finishes: Remove & rescan. + pub rescan_after_removal: bool, + /// What each removal since the last scan freed. + pub ledger: crate::ledger::Ledger, + /// Scans that finished and replaced the tree. What the ledger is + /// counted against: `scan_epoch` also moves when a scan starts or is + /// cancelled, and a cancelled widening keeps the tree it had. + pub scans_done: u64, + /// The running removal as it started. + run_start: Option, + /// Toasts over the lower left of the screen's content: the updater's + /// answers and the window's notices, which run out. + pub toasts: crate::toasts::Toasts, + /// Wakes when the next toast runs out. + pub toast_timer: Option>, + /// What the updater has said as of its last change: the live card, the + /// ready release and whether it was put away. + pub update_watch: crate::toasts::UpdateWatch, pub find: String, pub find_open: bool, @@ -410,7 +538,31 @@ pub struct Disktree { pub matches: Option>, /// Enter was pressed: the mosaic lays out only the matches. pub filter_applied: bool, - filter_epoch: u64, + /// Bumped whenever what the mosaic lays out may have changed: a search + /// or the legend. + pub filter_epoch: u64, + /// The legend's chips: what kinds, ages and reclaimable space to show. + pub legend: crate::legend::LegendFilter, + /// What the legend keeps, from the scanned root down. Laid out in + /// place of the tree whenever no search is applied. + pub legend_matches: Option>, + /// Bumped per legend change; only the newest result is kept. + pub legend_epoch: u64, + /// The legend's filter is being worked out off the UI thread. + pub legend_pending: bool, + /// What each legend chip would keep of the whole scan, for the sizes + /// beside the chips and which of them fit on the row. Worked out off + /// the UI thread once per tree, not per filter. + pub legend_shares: Option>, + /// Bumped per tree; only the newest shares are kept. + pub(crate) shares_epoch: u64, + /// The legend's "+N" menu: the chips the row has no room for. + pub legend_menu_open: bool, + /// The pointer is over the "+N" button, whose own press toggles the + /// menu; a press anywhere else closes it. + pub legend_more_hover: bool, + /// The legend chip under the pointer, which shows its "only" pill. + pub legend_hover: Option, /// Bumped per keystroke; only the newest search's result is kept. find_epoch: u64, /// A search is running off the UI thread. @@ -418,18 +570,43 @@ pub struct Disktree { /// Enter was pressed before the search finished: apply on arrival. apply_pending: bool, pub show_help: bool, + /// Off macOS, the strip's menu: the menu bar's template as one + /// dropdown (`app_menu::menus`), since there is no global menu bar. + pub app_menu_open: bool, pub show_selection: bool, + /// A short panel folds the selection's figures into one summary line; + /// this is whether the person has opened it. It stays open for the + /// session, whatever is selected, so it is not undone by every arrow. + pub selection_details: bool, pub focus: FocusHandle, + /// The app is quitting: what this window holds is left to the system, + /// which takes a process's memory back whole when it exits. + quitting: bool, + _on_quit: gpui_kit::Subscription, + /// Settings › Safety saved: read the policy again before the next + /// mark is judged. + _on_safety: gpui_kit::Subscription, /// A trail crumb's sibling menu, when open. pub crumb_menu: Option, pub color_mode: ColorMode, /// The largest things worth clearing, recomputed when a scan lands. pub insights: Vec, - /// What git knows about each checkout that has been selected; `None` - /// once asked and found not to be one. - pub git: FxHashMap>, - git_pending: FxHashSet, + /// What git knows about the checkouts looked at, and which to ask + /// next: see `git_store`. + pub git: GitStore, + /// Runs one probe, off the UI thread. Tests count calls with a fake. + pub git_probe: GitProbe, + /// Draws again when a dwell, a token or a stale answer comes due, so + /// a pointer resting still is still answered. + git_wake: Option<(Instant, gpui_kit::Task<()>)>, + /// When the pointer came to the tile it is on: a hover asks git only + /// once it has stayed `git_store::DWELL`. + hover_since: Option, + /// Whether the directory the panel describes is a checkout, by path. + /// Finding out is a `stat`, and the panel draws on every frame, so it + /// is asked again only when the selection or the tree changes. + checkout: Option<(PathBuf, bool)>, /// The device the scanned volume is mounted from. pub device: Option, /// Whether macOS lets this process read everything: asked once, since a @@ -454,10 +631,32 @@ pub struct Disktree { pub volumes_loading: bool, pub awaiting_root: bool, pub volumes_source: Option, + /// The chooser's source switch is on SSH host: the host field shows, + /// and nothing is listed until Connect. + pub picker_ssh: bool, pub volumes_error: Option, pub picker_error: Option, pub picker_host: Option>, pub picker_path: Option>, + /// Settings › Safety as last read; see [`Self::policy`]. + pub safety_policy: RefCell>, + /// The guards' answer for the last path asked about. + pub refusal_cache: RefCell, + /// The path whose Mark ▾ menu is open, which holds Mark anyway. Kept + /// by path so a menu never stays open over another selection. + pub mark_menu: Option, + /// Review's field for the over-limit phrase, made when first shown. + pub over_phrase: Option>, + /// The shares and mode the over-limit box was ticked for: a tick says + /// "20% of this disk, to the trash", and means nothing once any of it + /// changes. + pub over_ticked: Option, + /// How Review finds the disk a marked path is on. A field so a test + /// can stand in two disks where its fixture has one. + pub disk_probe: crate::mark_guard::DiskProbe, + /// The probe's answers for Review's frames; see + /// [`Self::removal_gate`]. + pub disk_cache: RefCell, roots_job: Option, volume_epoch: u64, pub volumes: Vec, @@ -471,6 +670,8 @@ pub struct Disktree { pub scan_elapsed: Option, /// Unix seconds when the tree landed: the "now" ages are measured from. pub scanned_at: i64, + /// The agent link, once a listener is attached; see [`crate::agent`]. + pub agent: Option, } impl Disktree { @@ -537,13 +738,18 @@ impl Disktree { options, power_choice: None, power_settings_path: crate::power::settings_path(), + removal_settings_dir: crate::updater::settings_dir(), power_menu: None, power_hover: false, + more_menu: None, + more_hover: false, + bar_fit: crate::toolbar::BarFit::default(), cpu_threads: crate::power::cpu_threads(), tree: None, scan: None, scan_epoch: 0, progress: ScanSnapshot::default(), + accessible_progress: None, scan_error: None, screen: Screen::Explore, crumbs: Vec::new(), @@ -552,17 +758,34 @@ impl Disktree { history: History::default(), history_hover: None, pointer_active: false, + click_opened: false, view: View::default(), transition: None, + file_list: false, + file_page: 0, + file_scroll: gpui_kit::ScrollHandle::new(), + // Explicit handles own tab metadata; element styles do not override it. + file_focus: cx.focus_handle().tab_stop(true), + restore_file_focus: false, + review_page: 0, + review_scroll: gpui_kit::ScrollHandle::new(), + panel_scroll: gpui_kit::ScrollHandle::new(), + panel_layout: std::rc::Rc::default(), layout_options: LayoutOptions { max_depth: depth.clamp(1, 6), ..LayoutOptions::default() }, cache: None, + accounting: RefCell::new(AccountingCache::default()), + kinds: RefCell::new(KindCache::default()), pointer: None, treemap_origin: Rc::new(Cell::new(Point::new(px(0.), px(0.)))), treemap_size: Rc::new(Cell::new(size(px(0.), px(0.)))), marks: Marks::default(), + removed: Marks::default(), + unmarked: None, + export_menu_open: false, + export_menu_was_open: false, // Reversible by default whenever this machine has a trash: the // permanent path stays one choice away, behind a dialog. removal_mode: if trash_backend.is_available() { @@ -571,34 +794,68 @@ impl Disktree { RemovalMode::Permanent }, trash_backend, + cleanup_review: None, + cleanup_results: vec![], + cleanup_actions: vec![], + cleanup_path: None, confirm_open: false, confirm_focus: cx.focus_handle(), + overlay_return: None, + app_menu_index: 0, + menu_scroll: gpui_kit::ScrollHandle::new(), + help_scroll: gpui_kit::ScrollHandle::new(), + source_roots_focus: cx.focus_handle().tab_stop(true), focus_request: None, window_title: String::new(), + strip_drag: false, + chrome_pin: None, + content_edges: gpui_kit::Edges::default(), rem: crate::ui::BASE_REM, run: None, + stop_requested: false, run_epoch: 0, - run_summary: RunSummary::default(), - run_log: Vec::new(), + run_list: crate::run_list::RunList::default(), + run_scroll: gpui_kit::UniformListScrollHandle::new(), + run_free_before: None, space, space_baseline: None, - notice: None, + rescan_after_removal: false, + ledger: crate::ledger::Ledger::default(), + scans_done: 0, + run_start: None, + toasts: crate::toasts::Toasts::default(), + toast_timer: None, + update_watch: crate::toasts::UpdateWatch::default(), find: String::new(), find_open: false, matches: None, filter_applied: false, filter_epoch: 0, + legend: crate::legend::LegendFilter::default(), + legend_matches: None, + legend_epoch: 0, + legend_pending: false, + legend_shares: None, + shares_epoch: 0, + legend_menu_open: false, + legend_more_hover: false, + legend_hover: None, find_epoch: 0, finding: false, apply_pending: false, show_help: false, + app_menu_open: false, show_selection: true, + selection_details: false, focus: cx.focus_handle(), crumb_menu: None, color_mode: ColorMode::Kind, insights: Vec::new(), - git: FxHashMap::default(), - git_pending: FxHashSet::default(), + git: GitStore::new(cx.background_executor().now()), + git_probe: default_git_probe(), + git_wake: None, + hover_since: None, + checkout: None, device: None, full_disk_access: None, administrator: disktree_core::access::administrator(), @@ -609,10 +866,18 @@ impl Disktree { volumes_loading: false, awaiting_root: !start, volumes_source: None, + picker_ssh: false, volumes_error: None, picker_error: None, picker_host: None, picker_path: None, + safety_policy: RefCell::new(None), + refusal_cache: RefCell::new(None), + mark_menu: None, + over_phrase: None, + over_ticked: None, + disk_probe: crate::mark_guard::disk_of, + disk_cache: RefCell::default(), roots_job: None, volume_epoch: 0, volumes: Vec::new(), @@ -622,6 +887,20 @@ impl Disktree { scan_root: PathBuf::new(), scan_elapsed: None, scanned_at: now_seconds(), + agent: None, + quitting: false, + // GPUI runs quit hooks before it drops the windows, so the flag + // is set by the time `Drop` reads it. + _on_quit: cx.on_app_quit(|this, _| { + this.quitting = true; + std::future::ready(()) + }), + _on_safety: cx.observe_global::( + |this, cx| { + this.safety_policy.replace(None); + cx.notify(); + }, + ), }; if local && start { tree.device = device_for(&tree.root_path); @@ -652,7 +931,7 @@ impl Disktree { #[cfg(test)] pub fn with_tree( root_path: PathBuf, - tree: Node, + tree: Tree, options: ScanOptions, depth: u32, cx: &mut Context<'_, Self>, @@ -663,10 +942,17 @@ impl Disktree { scan.cancel(); } app.scan_epoch += 1; - app.marks.refresh(&app.root_path, &tree, app.options.metric); + app.marks.refresh( + &app.root_path, + tree.root(), + app.options.metric, + app.path_style(), + ); app.tree = Some(Arc::new(tree)); app.cache = None; app.refresh_insights(); + app.refresh_shares(cx); + app.refresh_legend(cx); app.select_largest(cx); app } @@ -674,6 +960,8 @@ impl Disktree { /// Scan a different root from scratch. Marks are kept; a mark outside /// the new root is shown as kept back, never removed. pub fn set_root(&mut self, root: PathBuf, cx: &mut Context<'_, Self>) { + // Accepting a new source removes its originating chooser control. + self.overlay_return = None; if self.remote.is_some() { self.root_path = root; self.remote_disk = false; @@ -709,6 +997,8 @@ impl Disktree { if !self.root_path.starts_with(&above) || self.root_path == above { return; } + // The worker's root changes immediately, even within a sampled report. + self.accessible_progress = None; if let Some(scan) = &self.scan { scan.cancel(); } @@ -743,6 +1033,7 @@ impl Disktree { self.volumes_open = true; self.picker_host = None; self.picker_path = None; + self.picker_ssh = self.remote.is_some(); self.focus_request = Some(FocusTarget::Dialog); self.load_volume_source(self.remote.clone(), cx); } @@ -837,6 +1128,11 @@ impl Disktree { cx: &mut Context<'_, Self>, ) { self.volumes_loading = false; + // A path typed while the list loaded keeps its row selected. + let typed = self + .picker_path + .as_ref() + .is_some_and(|input| !input.read(cx).value().is_empty()); match result { Ok((mut volumes, home)) => { if let Some(home) = home @@ -852,6 +1148,9 @@ impl Disktree { ); } self.volumes = volumes; + if typed { + self.volume_highlight = self.volumes.len(); + } } Err(error) => self.volumes_error = Some(error.to_string()), } @@ -883,10 +1182,15 @@ impl Disktree { let path = cx.new(|cx| { InputState::new(window, cx).placeholder("/absolute/path") }); - cx.subscribe(&path, |this, _, event, cx| { - if matches!(event, InputEvent::PressEnter { .. }) { - this.choose_picker_path(cx); + cx.subscribe(&path, |this, _, event, cx| match event { + InputEvent::PressEnter { .. } => this.choose_picker_path(cx), + // Typing or clicking in the Directory row selects it, so + // Scan and Enter act on what was just typed. + InputEvent::Change | InputEvent::Focus => { + this.volume_highlight = this.volumes.len(); + cx.notify(); } + InputEvent::Blur => {} }) .detach(); self.picker_path = Some(path); @@ -905,10 +1209,56 @@ impl Disktree { window: &mut Window, cx: &mut Context<'_, Self>, ) { + self.picker_ssh = false; if let Some(host) = self.picker_host.clone() { host.update(cx, |host, cx| host.set_value("", window, cx)); } - self.load_volume_source(None, cx); + // This computer's list is already there unless a host replaced it. + if self.volumes_source.is_some() || self.volumes_error.is_some() { + self.load_volume_source(None, cx); + } + cx.notify(); + } + + /// The source switch's SSH side: show the host field and put the + /// cursor in it. Nothing is listed until Connect. + pub fn choose_ssh_source( + &mut self, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) { + self.picker_ssh = true; + if let Some(host) = &self.picker_host { + let focus = gpui_kit::Focusable::focus_handle(host.read(cx), cx); + window.focus(&focus, cx); + } + cx.notify(); + } + + /// The Directory row's Choose…: the system's folder picker, and a scan + /// of what it returns, through the same checks as a typed path. + pub fn browse_picker_path(&self, cx: &Context<'_, Self>) { + if self.volumes_source.is_some() { + return; + } + let chosen = cx.prompt_for_paths(gpui_kit::PathPromptOptions { + files: false, + directories: true, + multiple: false, + prompt: Some("Scan".into()), + }); + cx.spawn(async move |this, cx| { + let Ok(Ok(Some(paths))) = chosen.await else { + return; + }; + let Some(path) = paths.into_iter().next() else { + return; + }; + let _ = this.update(cx, |this, cx| { + this.choose_source_root(path, cx); + }); + }) + .detach(); } pub fn connect_picker(&mut self, cx: &mut Context<'_, Self>) { @@ -948,7 +1298,12 @@ impl Disktree { cx.notify(); return; } - if !path.is_absolute() { + let absolute = if self.volumes_source.is_some() { + disktree_core::remote::is_remote_absolute(&path) + } else { + path.is_absolute() + }; + if !absolute { self.picker_error = Some("Enter an absolute directory path.".into()); cx.notify(); @@ -969,11 +1324,13 @@ impl Disktree { if self.remote != self.volumes_source { // Absolute paths only identify marks within one machine. self.marks.clear(); + self.removed.clear(); + self.unmarked = None; self.history = History::default(); self.remote_identity = None; self.remote_platform.clear(); self.git.clear(); - self.git_pending.clear(); + self.checkout = None; self.space = None; self.space_baseline = None; self.disk_root = None; @@ -1006,7 +1363,13 @@ impl Disktree { cx.notify(); } + /// Scan the highlighted row: a listed mount, or the Directory row + /// after them. pub fn choose_volume(&mut self, cx: &mut Context<'_, Self>) { + if self.volume_highlight >= self.volumes.len() { + self.choose_picker_path(cx); + return; + } if let Some(point) = self .volumes .get(self.volume_highlight) @@ -1022,11 +1385,9 @@ impl Disktree { step: i32, cx: &mut Context<'_, Self>, ) { - if self.volumes.is_empty() { - return; - } - let len = self.volumes.len(); - let at = self.volume_highlight; + // The Directory row follows the mounts. + let len = self.volumes.len() + 1; + let at = self.volume_highlight.min(len - 1); // Picker steps are ±1, but wrap either way without casting the length // down to a narrower type. let next = match step.signum() { @@ -1044,7 +1405,7 @@ impl Disktree { let Some(disk) = self.disk_root.clone() else { return; }; - if disk == self.root_path { + if self.path_style().same(&disk, &self.root_path) { self.go_to(Vec::new(), cx); } else { self.widen_to(disk, cx); @@ -1055,37 +1416,129 @@ impl Disktree { fn refresh_insights(&mut self) { self.scanned_at = now_seconds(); self.insights = self.tree.as_deref().map_or_else(Vec::new, |tree| { - worth_a_look(tree, self.scanned_at, INSIGHT_LIMIT) + worth_a_look(tree.root(), self.scanned_at, INSIGHT_LIMIT) }); + self.forget_removed_insights(); } - /// Ask git about `path` once, off the UI thread, if it is a checkout. - pub fn ensure_git(&mut self, path: &Path, cx: &Context<'_, Self>) { - if self.remote.is_some() - || self.git.contains_key(path) - || self.git_pending.contains(path) - { + /// Drop suggestions a removal since the scan already took, and take + /// what went out of those it took part of. + fn forget_removed_insights(&mut self) { + if self.removed.is_empty() { return; } - let path = path.to_path_buf(); - self.git_pending.insert(path.clone()); - let epoch = self.scan_epoch; - let task = cx.background_executor().spawn({ - let path = path.clone(); - async move { crate::git::state(&path) } + let style = self.path_style(); + let mut insights = std::mem::take(&mut self.insights); + insights.retain_mut(|candidate| { + let Some(path) = self.path_at(&candidate.crumbs) else { + return false; + }; + if self.was_removed(&path) { + return false; + } + candidate.bytes = candidate + .bytes + .saturating_sub(self.removed.below(&path, style)); + candidate.bytes > 0 }); - cx.spawn(async move |this, cx| { - let state = task.await; + self.insights = insights; + } + + /// Whether `path` is the top of a checkout, going to the disk only + /// when it is not the path asked about last. + pub fn checkout_at(&mut self, path: &Path) -> bool { + if let Some((known, checkout)) = &self.checkout + && known == path + { + return *checkout; + } + let checkout = crate::git::is_checkout(path); + self.checkout = Some((path.to_path_buf(), checkout)); + checkout + } + + /// What [`Self::checkout_at`] last found for `path`, without asking: + /// for drawing code, which only reads the window's state. + pub fn known_checkout(&self, path: &Path) -> bool { + matches!(&self.checkout, Some((known, true)) if known == path) + } + + /// The panel shows the checkout at `path`: say so to the git store, + /// and start what it lets run. A selection asks at once; a hover only + /// once the pointer has rested on it for `git_store::DWELL`. + /// + /// While the window is not `active` a known answer is left as it is, + /// stale or not, and nothing is set to wake for it: a checkout left + /// selected behind other windows would otherwise be walked by git every + /// `FRESH_FOR`. Activation draws the window again, which refreshes it. + pub fn want_git( + &mut self, + path: &Path, + active: bool, + cx: &Context<'_, Self>, + ) { + if self.remote.is_some() || (!active && self.git.answered(path)) { + return; + } + let now = cx.background_executor().now(); + let hovering = self.pointer_active + && self.hovered.is_some() + && self.hovered != self.selected; + let ask = if hovering { + let settled = self.hover_since.unwrap_or(now) + git_store::DWELL; + if now < settled { + self.wake_git(settled, cx); + return; + } + Ask::Dwell + } else { + Ask::Direct + }; + match self.git.want(path, ask, now) { + Wanted::Refused { retry_at } => self.wake_git(retry_at, cx), + // Only the selection refreshes, so only it wakes for that. + Wanted::Answered { stale_at } if ask == Ask::Direct => { + self.wake_git(stale_at, cx); + } + Wanted::Answered { .. } | Wanted::Pending => {} + } + self.run_git(cx); + } + + /// Start every probe the store lets run now. + fn run_git(&mut self, cx: &Context<'_, Self>) { + let now = cx.background_executor().now(); + for job in self.git.next_jobs(now) { + let answer = (self.git_probe)(&job.path, &job.cancel); + cx.spawn(async move |this, cx| { + let answer = + answer.recv().await.unwrap_or(git_store::Probe::Unreadable); + let _ = this.update(cx, |this, cx| { + let now = cx.background_executor().now(); + if this.git.finish(&job, answer, now) { + cx.notify(); + } + this.run_git(cx); + }); + }) + .detach(); + } + } + + /// Draw again at `at`, unless a wake already comes sooner. + fn wake_git(&mut self, at: Instant, cx: &Context<'_, Self>) { + if self.git_wake.as_ref().is_some_and(|(due, _)| *due <= at) { + return; + } + let wait = at.saturating_duration_since(cx.background_executor().now()); + let task = cx.spawn(async move |this, cx| { + cx.background_executor().timer(wait).await; let _ = this.update(cx, |this, cx| { - if this.scan_epoch != epoch || this.remote.is_some() { - return; - } - this.git_pending.remove(&path); - this.git.insert(path, state); + this.git_wake = None; cx.notify(); }); - }) - .detach(); + }); + self.git_wake = Some((at, task)); } /// Select the largest entry of the current root, so the selection line, the @@ -1108,6 +1561,7 @@ impl Disktree { /// were the whole one: a first scan leaves the panel saying it stopped, /// and a widening scan leaves the tree it started from on screen. pub fn cancel_scan(&mut self, cx: &mut Context<'_, Self>) { + self.accessible_progress = None; self.scan_preview = None; if self.remote_scan.take().is_some() { self.scan_epoch += 1; @@ -1124,11 +1578,34 @@ impl Disktree { // The poller stops at its next tick instead of taking the result. self.scan_epoch += 1; self.progress = scan.progress.snapshot(); + self.progress.cancelled = true; + self.progress.finished = true; self.scan_elapsed = self.scan_started.map(|started| started.elapsed()); self.scan_root.clone_from(&self.root_path); cx.notify(); } + /// One line in the diagnostic log for a scan that ended: its kind, the + /// files and the time, or that it failed. Never the root or the error's + /// text, which can name a path. + fn log_scan_outcome(&self, kind: &str) { + let elapsed = self + .scan_started + .map_or(0.0, |started| started.elapsed().as_secs_f64()); + match (&self.scan_error, &self.tree) { + (Some(_), _) => log::warn!( + target: "pwrdisk::scan", + "{kind} scan failed after {elapsed:.1} s" + ), + (None, Some(tree)) => log::info!( + target: "pwrdisk::scan", + "{kind} scan finished: {} files in {elapsed:.1} s", + tree.root().files + ), + (None, None) => {} + } + } + /// Changing resource policy leaves the current scan and result intact; /// rescan, navigation to a new root and restart use the new fixed budget. pub fn set_power_efficiency( @@ -1146,7 +1623,7 @@ impl Disktree { self.options.threads = preset.policy(self.cpu_threads); self.power_choice = Some(preset); let label = preset.label(self.cpu_threads); - self.notice = Some(match self.power_settings_path.as_deref() { + let (message, status) = match self.power_settings_path.as_deref() { Some(path) => match crate::power::save(path, preset) { Ok(()) => ( format!("{label} from the next scan; r rescans now"), @@ -1167,10 +1644,65 @@ impl Disktree { ), Status::Warning, ), - }); + }; + // A preference that was not saved is a failure to read later. + if status == Status::Success { + self.say(message, status, cx); + } else { + self.say_until_closed(message, status, cx); + } + } + + /// The review screen, once something is marked; until then the notice + /// says how to mark. + pub fn open_review(&mut self, cx: &mut Context<'_, Self>) { + if self.marks.is_empty() { + self.say( + "mark something first: space marks the selected tile", + Status::Warning, + cx, + ); + } else { + self.reread_disks(); + self.screen = Screen::Review; + if self.remote.is_none() + && self.marks.items().iter().any(|target| { + disktree_core::cleanup::inspection_reason(&target.path) + .is_some() + }) + { + self.removal_mode = RemovalMode::OwnerCleanup; + } + self.focus_request = Some(FocusTarget::Root); + } cx.notify(); } + /// Whether Restart to update may exit now: never while a removal runs, + /// which an exit would stop partway through the marked list. + pub const fn can_restart_to_update(&self) -> bool { + self.run.is_none() + } + + /// Install the downloaded release and start again, from the toast, + /// the strip's chip or Settings. Refused while a removal runs, which + /// the notice then says. Velopack exits the process without the quit + /// hooks, so the window's frame is saved here first. A restart that + /// fails comes back through the updater's state (`toasts.rs`). + pub fn restart_to_update(&mut self, cx: &mut Context<'_, Self>) { + if !self.can_restart_to_update() { + self.say( + "Restart to update once the removal has finished", + Status::Warning, + cx, + ); + cx.notify(); + return; + } + crate::window_frame::save(); + crate::updater::restart_in_background(); + } + /// Open the Power Efficiency menu on the current preset, or close it. pub fn toggle_power_menu(&mut self, cx: &mut Context<'_, Self>) { use crate::power::PowerEfficiency; @@ -1231,8 +1763,22 @@ impl Disktree { true } + /// `i`, the Hidden files checkbox and its ⋮ row: rescan with or without + /// hidden entries. + pub fn toggle_hidden(&mut self, cx: &mut Context<'_, Self>) { + self.options.include_hidden = !self.options.include_hidden; + self.start_scan(cx); + } + + /// `d`, the Apparent size checkbox and its ⋮ row. + pub fn toggle_apparent(&mut self, cx: &mut Context<'_, Self>) { + self.options.apparent_size = !self.options.apparent_size; + self.start_scan(cx); + } + /// Start a fresh scan, abandoning any walk still in progress. pub fn start_scan(&mut self, cx: &mut Context<'_, Self>) { + self.accessible_progress = None; if self.awaiting_root { self.open_volumes(cx); return; @@ -1253,6 +1799,10 @@ impl Disktree { self.remember(); } discard(self.tree.take()); + // Its crumbs were the old tree's; the new one gets its own. + self.legend_matches = None; + self.legend_epoch += 1; + self.file_page = 0; self.crumbs.clear(); self.selected = None; self.hovered = None; @@ -1260,7 +1810,8 @@ impl Disktree { self.cache = None; self.insights.clear(); self.git.clear(); - self.git_pending.clear(); + // Every new tree arrives through here, removal's rescan included. + self.checkout = None; self.clear_filter(); self.scan_started = Some(Instant::now()); self.scan_elapsed = None; @@ -1311,15 +1862,21 @@ impl Disktree { pub(crate) fn update_remote_identity( &mut self, identity: Option, + cx: &mut Context<'_, Self>, ) { // A stable SSH alias can be repointed to a different machine. // Old marks must not acquire that machine's freshly captured guard. + if self.remote_identity != identity { + self.unmarked = None; + self.removed.clear(); + } if self.remote_identity != identity && !self.marks.is_empty() { self.marks.clear(); - self.notice = Some(( - "Remote identity changed; previous marks were cleared.".into(), + self.say_until_closed( + "Remote identity changed; previous marks were cleared.", Status::Warning, - )); + cx, + ); } self.remote_identity = identity; } @@ -1354,18 +1911,23 @@ impl Disktree { self.disk_root = snapshot.header.disk_root; self.space = snapshot.header.space; self.remote_platform = snapshot.header.platform; - self.update_remote_identity(snapshot.header.identity); + self.update_remote_identity(snapshot.header.identity, cx); self.device = self.remote.as_ref().map(|host| { format!("{host} · read-only · space at scan") }); let node = snapshot.tree; self.marks.refresh( &self.root_path, - &node, + node.root(), self.options.metric, + self.path_style(), ); self.tree = Some(Arc::new(node)); + self.scans_done += 1; + self.removed.clear(); self.refresh_insights(); + self.refresh_shares(cx); + self.refresh_legend(cx); self.select_largest(cx); self.scan_elapsed = self.scan_started.map(|t| t.elapsed()); } @@ -1373,6 +1935,7 @@ impl Disktree { self.scan_error = Some(error.to_string()); } } + self.log_scan_outcome("SSH"); self.remote_scan = None; self.scan_preview = None; self.progress.finished = true; @@ -1411,10 +1974,19 @@ impl Disktree { self.file_table = file_table_readable(&self.root_path); } let metric = self.options.metric; - self.marks.refresh(&self.root_path, &node, metric); + self.marks.refresh( + &self.root_path, + node.root(), + metric, + self.path_style(), + ); discard(self.tree.replace(Arc::new(node))); + self.scans_done += 1; + self.removed.clear(); self.cache = None; self.refresh_insights(); + self.refresh_shares(cx); + self.refresh_legend(cx); self.scan_elapsed = self.scan_started.map(|started| started.elapsed()); if let Some(from) = came_from { @@ -1430,9 +2002,11 @@ impl Disktree { self.keep_selection_valid(); self.prune_history(); self.select_largest(cx); + self.finish_pending_show(cx); } Err(error) => self.scan_error = Some(error.to_string()), } + self.log_scan_outcome("local"); self.scan = None; self.scan_preview = None; self.progress.finished = true; @@ -1444,11 +2018,11 @@ impl Disktree { let Some(tree) = &self.tree else { return; }; - if tree.resolve(&self.crumbs).is_none() { + if tree.root().resolve(&self.crumbs).is_none() { self.crumbs.clear(); } if let Some(selected) = self.selected.clone() - && tree.resolve(&selected).is_none() + && tree.root().resolve(&selected).is_none() { self.selected = None; } @@ -1499,24 +2073,78 @@ impl Disktree { self.scan.is_some() || self.remote_scan.is_some() } - pub fn tree(&self) -> Option<&Node> { - self.tree.as_deref() + /// Byte coverage is an estimate: clones, hardlinks, snapshots and access + /// errors prevent it from measuring how much enumeration time remains. + pub fn scan_fraction(&self) -> Option { + if !self.is_indexing() + || self.options.apparent_size + || !self.options.one_filesystem + || !self.options.include_hidden + || self.options.follow_links + || self.options.max_depth.is_some() + || self.scan_finalizing() + { + return None; + } + let used = if self.remote.is_some() { + self.remote_progress.volume_used + } else { + self.progress.volume_used + }?; + (used > 0).then(|| { + (self.progress.bytes as f64 / used as f64).clamp(0.0, 0.99) as f32 + }) + } + + pub fn scan_finalizing(&self) -> bool { + if self.remote.is_some() { + self.remote_progress.stage + == disktree_core::remote_progress::Stage::Finalizing + } else { + self.progress.finalizing + } + } + + pub fn tree(&self) -> Option> { + self.tree.as_deref().map(Tree::root) } /// The node the treemap is currently rooted at. - pub fn current(&self) -> Option<&Node> { + pub fn current(&self) -> Option> { self.tree .as_ref() - .and_then(|tree| tree.resolve(&self.crumbs)) + .and_then(|tree| tree.root().resolve(&self.crumbs)) } - pub fn node_at(&self, crumbs: &[usize]) -> Option<&Node> { - self.tree.as_ref().and_then(|tree| tree.resolve(crumbs)) + pub fn node_at(&self, crumbs: &[usize]) -> Option> { + self.tree + .as_ref() + .and_then(|tree| tree.root().resolve(crumbs)) } pub fn path_at(&self, crumbs: &[usize]) -> Option { let tree = self.tree.as_ref()?; - Some(path_of(&self.root_path, tree, crumbs)) + Some(path_of( + &self.root_path, + tree.root(), + crumbs, + self.path_style(), + )) + } + + /// The path rules of the machine on screen: an SSH host is Unix, so its + /// paths are POSIX on every client. + pub const fn path_style(&self) -> PathStyle { + PathStyle::of(self.remote.is_some()) + } + + /// `path` shortened under the scanned machine's home, in its separators. + pub fn display_path(&self, path: &Path) -> String { + crate::marks::display_path( + path, + self.home.as_deref(), + self.path_style(), + ) } /// Path of the directory currently drawn. @@ -1529,28 +2157,35 @@ impl Disktree { /// The trail, from `/`: the directories above the scanned root, which /// widen the scan, then the root and the path into the tree. pub fn breadcrumbs(&self) -> Vec<(String, Crumb)> { - let mut trail: Vec<(String, Crumb)> = self - .root_path - .ancestors() + let style = self.path_style(); + let mut trail: Vec<(String, Crumb)> = style + .ancestors(&self.root_path) .skip(1) .collect::>() .into_iter() .rev() - .map(|path| (crumb_label(path), Crumb::Above(path.to_path_buf()))) + .map(|path| { + (crumb_label(path, style), Crumb::Above(path.to_path_buf())) + }) .collect(); - trail.push((crumb_label(&self.root_path), Crumb::Tree(Vec::new()))); + trail.push(( + crumb_label(&self.root_path, style), + Crumb::Tree(Vec::new()), + )); let Some(tree) = &self.tree else { return trail; }; let mut crumbs: Vec = Vec::new(); for &index in &self.crumbs { - let Some(node) = - tree.resolve(&crumbs).and_then(|node| node.child(index)) + let Some(node) = tree + .root() + .resolve(&crumbs) + .and_then(|node| node.child(index)) else { break; }; crumbs.push(index); - trail.push((node.name.to_string(), Crumb::Tree(crumbs.clone()))); + trail.push((node.name().to_string(), Crumb::Tree(crumbs.clone()))); } trail } @@ -1563,12 +2198,12 @@ impl Disktree { return (Vec::new(), 0); }; let mut rows: Vec = node - .children + .children() .iter() .enumerate() .map(|(index, child)| Sibling { index, - name: child.name.to_string(), + name: child.name().to_string(), value: child.value(metric), category: child.category, is_dir: child.is_dir(), @@ -1686,6 +2321,50 @@ impl Disktree { self.enter(target, from, cx); } + /// What a click on `crumbs` opens: the child of the directory on screen + /// that holds it, one level down however deep the tile is drawn. A + /// click aims at a tile, and a tile can be several levels down; going + /// straight there skipped the levels between. + pub fn click_target(&self, crumbs: &[usize]) -> Option> { + let depth = self.crumbs.len(); + if crumbs.len() <= depth || !crumbs.starts_with(&self.crumbs) { + return None; + } + let target = crumbs[..=depth].to_vec(); + self.node_at(&target) + .is_some_and(|node| node.is_dir() && !node.children().is_empty()) + .then_some(target) + } + + /// Whether a click on the hovered tile would open a level: it is the + /// selection, and something holds it. The pointer says so. + pub fn click_opens_hovered(&self) -> bool { + self.hovered.as_deref().is_some_and(|hovered| { + self.selected.as_deref() == Some(hovered) + && self.click_target(hovered).is_some() + }) + } + + /// Open one level toward `crumbs`, keeping it selected when it lies + /// deeper, so the next click on it opens the next level. Returns whether + /// a level opened. + fn open_toward( + &mut self, + crumbs: &[usize], + cx: &mut Context<'_, Self>, + ) -> bool { + let Some(target) = self.click_target(crumbs) else { + return false; + }; + let from = self.tile_body(&target).map(|rect| self.view.project(rect)); + self.enter(target, from, cx); + if crumbs.len() > self.crumbs.len() && crumbs.starts_with(&self.crumbs) + { + self.selected = Some(crumbs.to_vec()); + } + true + } + /// Go inside one child of the current root, so that it fills the viewport. /// /// `from` is where the child was on screen, when the caller knows it. @@ -1707,10 +2386,11 @@ impl Disktree { let Some(node) = self.node_at(&target) else { return; }; - if !node.is_dir() || node.children.is_empty() { + if !node.is_dir() || node.children().is_empty() { return; } self.remember(); + self.file_page = 0; self.selected = Some(target.clone()); self.crumbs = target; self.forget_hover(); @@ -1724,7 +2404,8 @@ impl Disktree { area.width.as_f32().max(1.0), area.height.as_f32().max(1.0), ); - self.transition = Some(LayoutTransition::new(src, dst)); + self.transition = (!prefers_reduced_motion(cx)) + .then(|| LayoutTransition::new(src, dst)); cx.notify(); } @@ -1755,7 +2436,7 @@ impl Disktree { .map(|length| hovered[..length].to_vec()) .find(|crumbs| { self.node_at(crumbs).is_some_and(|node| { - node.is_dir() && !node.children.is_empty() + node.is_dir() && !node.children().is_empty() }) && self.tile_body(crumbs).is_some() }) } @@ -1775,6 +2456,7 @@ impl Disktree { /// the new level simply lands. fn ascend_to(&mut self, ancestor: Vec, cx: &mut Context<'_, Self>) { self.remember(); + self.file_page = 0; // The region we are looking at now, and where it sits in the layout // we are going back to. let area = self.treemap_size.get(); @@ -1785,10 +2467,13 @@ impl Disktree { self.cache = None; self.selected = Some(ancestor); self.view = View::IDENTITY; - self.transition = self - .tile_body(&child_crumbs) - .filter(|rect| rect.w > 1.0 && rect.h > 1.0) - .map(|dst| LayoutTransition::new(src, dst)); + self.transition = if prefers_reduced_motion(cx) { + None + } else { + self.tile_body(&child_crumbs) + .filter(|rect| rect.w > 1.0 && rect.h > 1.0) + .map(|dst| LayoutTransition::new(src, dst)) + }; cx.notify(); } @@ -1810,6 +2495,7 @@ impl Disktree { // A reveal in the directory on screen goes nowhere. if crumbs != self.crumbs { self.remember(); + self.file_page = 0; } self.crumbs.clone_from(&crumbs); self.selected = Some(crumbs); @@ -1827,7 +2513,12 @@ impl Disktree { return; } let here = self.current_path(); - if self.history.back.last() != Some(&here) { + if self + .history + .back + .last() + .is_none_or(|last| !self.path_style().same(last, &here)) + { self.history.back.push(here); } if self.history.back.len() > HISTORY_DEPTH { @@ -1914,7 +2605,7 @@ impl Disktree { fn travel(&mut self, target: Vec, cx: &mut Context<'_, Self>) { let enterable = self .node_at(&target) - .is_some_and(|node| node.is_dir() && !node.children.is_empty()); + .is_some_and(|node| node.is_dir() && !node.children().is_empty()); if target.len() > self.crumbs.len() && target.starts_with(&self.crumbs) && enterable @@ -2037,6 +2728,10 @@ impl Disktree { /// Select the next sibling by rank, which is next-largest by the active /// metric. Scanning a directory for space is exactly this walk. pub fn cycle_sibling(&mut self, step: isize, cx: &mut Context<'_, Self>) { + if self.file_list { + self.file_step(step, cx); + return; + } self.pointer_active = false; let siblings = self.ranked_siblings(); if siblings.is_empty() { @@ -2072,7 +2767,7 @@ impl Disktree { let Some(node) = self.node_at(&parent) else { return Vec::new(); }; - (0..node.children.len()) + (0..node.children().len()) .map(|index| { let mut crumbs = parent.clone(); crumbs.push(index); @@ -2087,11 +2782,11 @@ impl Disktree { return; }; if crumbs.is_empty() { - self.notice = Some(( - "the scanned root cannot be removed; open a directory first" - .into(), + self.say( + "the scanned root cannot be removed; open a directory first", Status::Warning, - )); + cx, + ); cx.notify(); return; } @@ -2108,50 +2803,84 @@ impl Disktree { &mut self, crumbs: &[usize], cx: &mut Context<'_, Self>, + ) { + self.toggle_mark_checked(crumbs, false, cx); + } + + /// [`Self::toggle_mark`], with `anyway` for the inspector's Mark + /// anyway: a new mark past the limit is made only with it, and a + /// protected path never is. + pub fn toggle_mark_checked( + &mut self, + crumbs: &[usize], + anyway: bool, + cx: &mut Context<'_, Self>, ) { let Some(target) = self.target_at(crumbs) else { return; }; - self.notice = None; - if !self.marks.contains(&target.path) + self.clear_notice(cx); + if self.was_removed(&target.path) { + self.say( + format!( + "{} was removed; rescan to see the disk as it is now", + self.display_path(&target.path) + ), + Status::Warning, + cx, + ); + cx.notify(); + return; + } + if !self.marks.contains(&target.path, self.path_style()) && let Some(ancestor) = self.marked_ancestor(&target.path) { - self.notice = Some(( + self.say( format!( "{} goes with the marked {}; unmark that to keep it", - display_path(&target.path, self.home.as_deref()), - display_path(&ancestor, self.home.as_deref()) + self.display_path(&target.path), + self.display_path(&ancestor) ), Status::Warning, - )); + cx, + ); cx.notify(); return; } + if !self.marks.contains(&target.path, self.path_style()) { + // Judged afresh: the inspector's cached answer may predate a + // mount or a link changing under the path. + self.refusal_cache.replace(None); + let check = self.mark_check(&target); + let refused = match check { + crate::mark_guard::MarkCheck::OverLimit(_) => !anyway, + crate::mark_guard::MarkCheck::Protected(_) => true, + crate::mark_guard::MarkCheck::Allowed => false, + }; + if refused { + if let Some(notice) = self.mark_refusal_notice(&target, &check) + { + self.warn(notice, cx); + } + return; + } + } let path = target.path.clone(); - if self.marks.toggle(target) { + let style = self.path_style(); + if self.marks.toggle(target, self.path_style()) { self.space_baseline = self.space_baseline.or(self.space); - let inside: Vec = self - .marks - .items() - .iter() - .filter(|item| { - item.path != path && item.path.starts_with(&path) - }) - .map(|item| item.path.clone()) - .collect(); - for inner in &inside { - self.marks.remove(inner); - } - if !inside.is_empty() { - self.notice = Some(( + let inside = self.marks.absorb(&path, style); + if inside > 0 { + self.say( format!( "{} now covers {} mark{} inside it", - display_path(&path, self.home.as_deref()), - inside.len(), - if inside.len() == 1 { "" } else { "s" } + self.display_path(&path), + inside, + if inside == 1 { "" } else { "s" } ), Status::Neutral, - )); + cx, + ); } } cx.notify(); @@ -2160,37 +2889,127 @@ impl Disktree { /// The marked directory `path` is inside, if any; never `path` itself. pub fn marked_ancestor(&self, path: &Path) -> Option { self.marks - .items() - .iter() - .filter(|item| item.path != path && path.starts_with(&item.path)) - .map(|item| item.path.clone()) - .min_by_key(|ancestor| ancestor.as_os_str().len()) + .ancestor(path, self.path_style()) + .map(Path::to_path_buf) } pub fn target_at(&self, crumbs: &[usize]) -> Option { let node = self.node_at(crumbs)?; let path = self.path_at(crumbs)?; + // A directory part of which was removed frees only the rest. + let bytes = node + .bytes + .saturating_sub(self.removed.below(&path, self.path_style())); Some(Target { - hidden: is_hidden(&path), + hidden: is_hidden(&path, self.path_style()), path, - bytes: node.bytes, + bytes, is_dir: node.is_dir(), }) } pub fn unmark(&mut self, path: &Path, cx: &mut Context<'_, Self>) { - self.marks.remove(path); + self.marks.remove(path, self.path_style()); cx.notify(); } + /// Review's Unmark all, or `!`. Marks live only in memory, so what goes + /// is kept for [`Self::undo_unmark`] rather than asked about first. pub fn clear_marks(&mut self, cx: &mut Context<'_, Self>) { + if self.marks.is_empty() { + return; + } + let taken = self.marks.items().to_vec(); + let count = taken.len(); self.marks.clear(); - self.notice = None; + self.unmarked = Some(taken); + // Export and Unmark all are disabled now; neither may keep focus. + self.focus_request = Some(FocusTarget::Root); + // Undo on the card as well as on the keys: the card is where the + // eye is when the list empties. + self.show_toast( + crate::toasts::Toast { + actions: vec![crate::toasts::Action::Undo], + ..crate::toasts::notice( + format!("Unmarked {count} \u{b7} u or {UNDO_KEYS} to undo"), + Status::Neutral, + ) + }, + cx, + ); + } + + /// Put back what Unmark all took. Marks made since stay; a path that + /// is marked again, or now goes with a marked directory, is skipped. + /// Only where marks are edited: during a removal they are the running + /// list's, and are cleared when it ends. + pub fn undo_unmark(&mut self, cx: &mut Context<'_, Self>) { + if !matches!(self.screen, Screen::Explore | Screen::Review) { + return; + } + let Some(taken) = self.unmarked.take() else { + return; + }; + let style = self.path_style(); + let mut restored = 0; + for target in taken { + if self.marks.contains(&target.path, style) + || self.marks.ancestor(&target.path, style).is_some() + { + continue; + } + let path = target.path.clone(); + self.marks.toggle(target, style); + self.marks.absorb(&path, style); + restored += 1; + } + self.say( + if restored == 0 { + "Nothing to put back: those paths are marked again".into() + } else { + format!("Marked {restored} again") + }, + Status::Neutral, + cx, + ); + cx.notify(); + } + + /// The Removing screen's Stop, or Escape: the worker finishes the item + /// in hand and starts no other. + pub fn stop_removal(&mut self, cx: &mut Context<'_, Self>) { + let Some(run) = &self.run else { + return; + }; + run.cancel(); + self.stop_requested = true; + self.say( + if self.removal_mode == RemovalMode::OwnerCleanup { + "cancelling the current step; an owner command may have partly cleaned its cache" + } else { + "stopping after the current item" + }, + Status::Warning, + cx, + ); cx.notify(); } /// The plan the review screen shows and the removal runs. pub fn plan(&self) -> Plan { + if self.remote.is_none() + && self.removal_mode == RemovalMode::OwnerCleanup + && let Ok(approved) = self.cleanup_approved() + { + return approved.plan.clone(); + } + self.selection_plan() + } + + /// Only marked paths: owner execution scopes must never widen exports. + pub(crate) fn selection_plan(&self) -> Plan { + #[cfg(test)] + crate::marks::work::PLANS.set(crate::marks::work::PLANS.get() + 1); if self.remote.is_some() { // Never judge remote paths against this machine's filesystem. // This is an export selection, not an executable removal plan. @@ -2200,8 +3019,7 @@ impl Disktree { .items() .iter() .filter(|target| { - target.path != self.root_path - && target.path.starts_with(&self.root_path) + self.path_style().is_below(&target.path, &self.root_path) }) .cloned() .collect(); @@ -2210,7 +3028,61 @@ impl Disktree { // this computer's mounts or project an unmeasured saving. return selection; } - plan(self.marks.items(), &self.root_path) + let mut plan = plan(self.marks.items(), &self.root_path); + if let Some(tree) = &self.tree { + let mut cached = self.accounting.borrow_mut(); + if !cached.tree.ptr_eq(&Arc::downgrade(tree)) + || cached.root != self.root_path + { + *cached = AccountingCache { + tree: Arc::downgrade(tree), + root: self.root_path.clone(), + estimates: Vec::new(), + }; + } + let mut resolver = crate::marks::Resolver::new( + &self.root_path, + tree.root(), + PathStyle::Native, + ); + let mut next = Vec::new(); + plan.estimate_selection(|targets| { + let paths: Vec<_> = + targets.iter().map(|target| target.path.clone()).collect(); + let value = cached + .estimates + .iter() + .find(|(old, _)| *old == paths) + .map_or_else( + || { + let nodes: Vec<_> = targets + .iter() + .filter_map(|target| { + resolver + .resolve(&target.path) + .map(|(_, node)| node) + }) + .collect(); + if let [node] = nodes.as_slice() { + node.sharing().estimate.unwrap_or( + disktree_core::sharing::Estimate { + lower: node.bytes, + upper: node.bytes, + partial: false, + }, + ) + } else { + disktree_core::sharing::estimate(nodes) + } + }, + |(_, value)| *value, + ); + next.push((paths, value)); + value + }); + cached.estimates = next; + } + plan } // ── layout and hit-testing ────────────────────────────────────────── @@ -2221,19 +3093,22 @@ impl Disktree { /// to draw, and the marked/hidden/selected state of every tile is decided /// here, where the tree and the marks are both at hand. pub fn prepare(&mut self) -> Mosaic { + #[cfg(test)] + crate::marks::work::FRAMES.set(crate::marks::work::FRAMES.get() + 1); let metric = self.options.metric; let view = self.view; let hovered = self.hovered.clone(); let selected = self.selected.clone(); - // Marks are paths; the mosaic thinks in crumbs. Resolve once per frame - // rather than building a path for every tile. - let mut marked: FxHashSet> = FxHashSet::default(); - for item in self.marks.items() { - if let Some(crumbs) = self.crumbs_for_path(&item.path) { - marked.insert(crumbs); - } - } + let style = self.path_style(); + let marked = self.tree.as_ref().map_or_else( + || Arc::new(FxHashSet::default()), + |tree| self.marks.crumbs(&self.root_path, tree, metric, style), + ); + let removed = self.tree.as_ref().map_or_else( + || Arc::new(FxHashSet::default()), + |tree| self.removed.crumbs(&self.root_path, tree, metric, style), + ); let Some(tiles) = self.layout().map(<[Tile]>::to_vec) else { return Mosaic { @@ -2249,6 +3124,8 @@ impl Disktree { let mut decorations = Vec::with_capacity(tiles.len()); let mut labels = Vec::new(); for tile in &tiles { + #[cfg(test)] + crate::marks::work::TILES.set(crate::marks::work::TILES.get() + 1); let crumbs = tile.crumbs(); let node = match &tile.kind { TileKind::Node { crumbs } => self.node_at(crumbs), @@ -2261,19 +3138,43 @@ impl Disktree { (now - node.map_or(now, |n| n.modified)) / 86_400; crate::palette::age_bucket(days) }); - let filtered = match self.matches.as_deref().map(|m| m.keep(crumbs)) - { + // A search being typed dims what it does not match; otherwise + // the legend says which folders hold more than is shown. + let keep = self + .matches + .as_deref() + .or(self.legend_matches.as_deref()) + .map(|matches| match node { + Some(node) => matches.keep_at(crumbs, node), + None => matches.keep(crumbs), + }); + let filtered = match keep { None | Some(Some(Keep::Whole)) => Filtered::Shown, Some(Some(Keep::Partial { .. })) => Filtered::Holds, Some(None) => Filtered::Out, }; + // A partly shown folder is laid out by what passed, so its label + // says that and what it holds in all: "48G of 196G". + let partial = + self.layout_filter().and_then(|matches| { + match matches.keep(crumbs) { + Some(Keep::Partial { bytes, files }) => { + Some((bytes, files)) + } + _ => None, + } + }); let is_marked = marked.contains(crumbs); // Everything inside a marked directory goes with it, so it is // drawn marked too. let is_covered = !marked.is_empty() && (1..crumbs.len()) .any(|length| marked.contains(&crumbs[..length])); - decorations.push(TileDeco { + // Removed since the scan, itself or with a directory holding it. + let is_removed = !removed.is_empty() + && (1..=crumbs.len()) + .any(|length| removed.contains(&crumbs[..length])); + let decoration = TileDeco { rect: self.animated_rect(tile.rect), depth: tile.depth, category, @@ -2283,9 +3184,11 @@ impl Disktree { unreadable: node.is_some_and(|n| n.read_error), marked: is_marked, covered: is_covered, + removed: is_removed, hovered: hovered.as_deref() == Some(crumbs), selected: selected.as_deref() == Some(crumbs), - }); + }; + decorations.push(decoration.clone()); // Labels are chosen in screen space: zooming in makes room for more // of them, which is the point of zooming in. @@ -2304,26 +3207,58 @@ impl Disktree { let Some(node) = self.node_at(crumbs) else { continue; }; + // State is said without colour, and without spending + // the label's width on it: a marked name, and every name + // inside it, is struck through, and a name the find text + // matches has the matching part underlined. Words would + // repeat on every tile in a mark or a search and push + // narrow names out of their tiles. Only "unreadable", + // which is rare, keeps a prefix. + let unreadable = if node.read_error { "! " } else { "" }; + // A tile the filter left out holds no match: skip the + // search for it. + let found = self + .matches + .as_deref() + .filter(|_| filtered != Filtered::Out) + .and_then(|matches| { + find_ignoring_case(node.name(), &matches.needle) + }) + .map(|range| { + range.start + unreadable.len() + ..range.end + unreadable.len() + }); labels.push(Label { - text: node.name.to_string(), + text: format!("{unreadable}{}", node.name()), + found, rect: self.animated_rect(tile.rect), header: tile .header .map(|header| self.animated_rect(header)), depth: tile.depth, - dim: filtered == Filtered::Out, + dim: filtered == Filtered::Out || is_removed, marked: is_marked || is_covered, - size_text: crate::widgets::short_value(node, metric), + size_text: partial.map_or_else( + || crate::widgets::short_value(node, metric), + |(bytes, files)| { + crate::widgets::short_share( + node, bytes, files, metric, + ) + }, + ), + decoration: decoration.clone(), }); } TileKind::Others { count, .. } => labels.push(Label { text: format!("+{count} more"), + found: None, rect: self.animated_rect(tile.rect), header: None, depth: tile.depth, dim: self.matches.is_some(), marked: false, size_text: String::new(), + decoration: decoration.clone(), }), } } @@ -2342,6 +3277,17 @@ impl Disktree { } } + /// Whether the node at `crumbs` is marked, or inside a marked directory + /// and so removed with it. The trail strikes such a crumb, as the + /// mosaic strikes such a tile's name. + pub fn goes_with_a_mark(&self, crumbs: &[usize]) -> bool { + let style = self.path_style(); + self.path_at(crumbs).is_some_and(|path| { + self.marks.contains(&path, style) + || self.marks.ancestor(&path, style).is_some() + }) + } + /// Crumbs for an absolute path, if the tree still contains it. #[allow( clippy::unnecessary_wraps, @@ -2350,16 +3296,18 @@ impl Disktree { pub fn crumbs_for_path(&self, path: &Path) -> Option> { // The path is relative to the scanned root, so the walk starts there, // not at the directory currently drawn. - let relative = path.strip_prefix(&self.root_path).ok()?; + // Names are split by the scanned machine's rules, so a Unix host's + // `a\b` stays one name on a Windows client. + let relative = self.path_style().relative(&self.root_path, path)?; let tree = self.tree.clone()?; - let mut node: &Node = &tree; + let mut node = tree.root(); let mut crumbs = Vec::new(); - for component in relative.components() { - let name = component.as_os_str().to_string_lossy(); - let index = node - .children - .iter() - .position(|child| child.name.as_ref() == name)?; + for name in relative { + let index = node.children().iter().position(|child| { + #[cfg(test)] + crate::marks::work::step(); + child.name() == name + })?; crumbs.push(index); node = node.child(index)?; } @@ -2395,10 +3343,9 @@ impl Disktree { let stale = self.cache.as_ref().is_none_or(|cache| cache.key != key); if stale { let tree = self.tree.clone()?; - let node = tree.resolve(&self.crumbs)?; + let node = tree.root().resolve(&self.crumbs)?; let rect = Rect::new(0.0, 0.0, key.width, key.height); - let filter = - self.matches.as_deref().filter(|_| self.filter_applied); + let filter = self.layout_filter(); let tiles = layout_filtered( node, &key.crumbs, @@ -2412,6 +3359,16 @@ impl Disktree { self.cache.as_ref().map(|cache| cache.tiles.as_slice()) } + /// What the mosaic lays out instead of the whole tree: an applied + /// search, which already keeps to the legend, or else the legend. + pub fn layout_filter(&self) -> Option<&Matches> { + if self.filter_applied { + self.matches.as_deref() + } else { + self.legend_matches.as_deref() + } + } + /// Base-space rect of the tile at `crumbs`, if it is currently drawn. #[cfg(test)] pub fn tile_rect(&mut self, crumbs: &[usize]) -> Option { @@ -2503,16 +3460,34 @@ impl Disktree { let directory = self.current_path(); let selected = self.selected.as_deref().and_then(|c| self.path_at(c)); self.options.metric = self.options.metric.toggled(); - if let Some(tree) = &self.tree { - let mut tree = (**tree).clone(); - disktree_core::tree::aggregate(&mut tree, self.options.metric); - discard(self.tree.replace(Arc::new(tree))); + if let Some(tree) = self.tree.take() { + // The window is usually the tree's only owner, and then it is + // reordered where it lies. A copy of 20 million nodes took 0.8 + // to 0.9 s and briefly held the whole tree twice, 3.2 GiB more + // on such a scan, where reordering took 0.1 to 0.2 s. A find or + // a widening walk still reading it gets its own copy, as before. + // Either way it becomes a new `Arc`, so a removal preview bound + // to the old order lapses as it did. + let mut tree = Arc::try_unwrap(tree).unwrap_or_else(|shared| { + let copy = (*shared).clone(); + // The other reader may let go first; then this is the last + // reference, and it must not be freed on this thread. + discard(Some(shared)); + copy + }); + // Totals and sharing do not depend on the metric; only the order + // of children does. + disktree_core::tree::reorder(&mut tree, self.options.metric); + self.tree = Some(Arc::new(tree)); let metric = self.options.metric; + let style = self.path_style(); self.marks.refresh( &self.root_path, - self.tree.as_ref().unwrap(), + self.tree.as_ref().unwrap().root(), metric, + style, ); + self.marks.discount(&self.removed, style); } self.crumbs = self.crumbs_for_path(&directory).unwrap_or_default(); self.selected = selected.and_then(|path| self.crumbs_for_path(&path)); @@ -2520,6 +3495,12 @@ impl Disktree { self.crumb_menu = None; self.transition = None; self.refresh_insights(); + self.refresh_shares(cx); + // Every crumb moved, so the legend's result points at other + // children now; drop it rather than lay it out until the new one + // comes back. + self.legend_matches = None; + self.refresh_legend(cx); self.clear_filter(); self.cache = None; cx.notify(); @@ -2552,14 +3533,39 @@ impl Disktree { // ── removal ───────────────────────────────────────────────────────── /// The review screen's commit: move to the trash at once, or ask first for - /// a permanent deletion, which cannot be undone. - pub fn commit(&mut self, cx: &mut Context<'_, Self>) { - if self.remote.is_some() || self.plan().is_empty() { + /// a permanent deletion, which cannot be undone. `rescan` is Remove & + /// rescan; without it the tree drops what went and stays. + pub fn commit(&mut self, rescan: bool, cx: &mut Context<'_, Self>) { + // A cleanup is checked, then decided, before anything else: until + // then there is nothing to confirm. + if self.removal_mode == RemovalMode::OwnerCleanup + && self.remote.is_none() + { + if self.cleanup_ready().is_err() { + self.prepare_cleanup(cx); + return; + } + if let Err(reason) = self.cleanup_approved() { + self.say(reason, Status::Warning, cx); + cx.notify(); + return; + } + } + let plan = self.plan(); + if self.remote.is_some() || plan.is_empty() { return; } + // Past the limit the second confirmation comes first, before the + // permanent dialog asks about recoverability; `begin_removal` + // checks it again on the way to the worker. + if let Err(notice) = self.removal_limit(&plan, cx) { + self.warn(notice, cx); + return; + } + self.rescan_after_removal = rescan; match self.removal_mode { RemovalMode::Trash => self.begin_removal(cx), - RemovalMode::Permanent => { + RemovalMode::Permanent | RemovalMode::OwnerCleanup => { self.confirm_open = true; self.focus_request = Some(FocusTarget::Dialog); cx.notify(); @@ -2569,6 +3575,7 @@ impl Disktree { /// The alert dialog's `Delete`. pub fn confirm_delete(&mut self, cx: &mut Context<'_, Self>) { + self.overlay_return = None; self.confirm_open = false; self.focus_request = Some(FocusTarget::Root); self.begin_removal(cx); @@ -2588,9 +3595,42 @@ impl Disktree { window: &mut Window, cx: &mut Context<'_, Self>, ) { + let navigation_visible = self.screen == Screen::Explore + && !self.awaiting_root + && self.tree.is_some(); + let list_visible = self.file_list && navigation_visible; + // Both navigation views leave the focus tree during a rescan. Their + // persistent parent must own Escape until navigation is available. + if !navigation_visible && self.file_focus.is_focused(window) { + self.restore_file_focus = true; + window.focus(&self.focus, cx); + } + if self.screen != Screen::Explore { + self.restore_file_focus = false; + } else if navigation_visible + && std::mem::take(&mut self.restore_file_focus) + && self.focus.is_focused(window) + && self.focus_request.is_none() + { + window.focus(&self.file_focus, cx); + } match self.focus_request.take() { - Some(FocusTarget::Root) => window.focus(&self.focus, cx), - Some(FocusTarget::Dialog) => window.focus(&self.confirm_focus, cx), + Some(FocusTarget::Root) => { + let target = self.overlay_return.take().unwrap_or_else(|| { + if list_visible { + self.file_focus.clone() + } else { + self.focus.clone() + } + }); + window.focus(&target, cx); + } + Some(FocusTarget::Dialog) => { + if self.overlay_return.is_none() { + self.overlay_return = window.focused(cx); + } + window.focus(&self.confirm_focus, cx); + } None => {} } } @@ -2602,58 +3642,169 @@ impl Disktree { &mut self, event: &KeyDownEvent, window: &mut Window, + cx: &mut Context<'_, Self>, ) -> bool { - let keystroke = &event.keystroke; - if !(keystroke.modifiers.control || keystroke.modifiers.platform) { - return false; + if crate::ui::zoom_interface(event, window, cx) { + self.cache = None; + true + } else { + false } - let steps = crate::ui::ZOOM_STEPS; - let current = window.rem_size().as_f32() / crate::ui::BASE_REM; - let index = steps - .iter() - .position(|step| (step - current).abs() < 0.01) - .unwrap_or(2); - let next = match keystroke.key.as_str() { - "=" | "+" => (index + 1).min(steps.len() - 1), - "-" => index.saturating_sub(1), - "0" => 2, - _ => return false, - }; - window.set_rem_size(px(crate::ui::BASE_REM * steps[next])); - self.cache = None; - true } + /// Start the person's removal of what is marked, held to the window's + /// limit or to the shares Review confirmed past it. pub fn begin_removal(&mut self, cx: &mut Context<'_, Self>) { + self.start_removal(Remover::Person, None, cx); + } + + /// Start an agent's confirmed removal, held to the agent limit + /// whatever the window's limit and Review's confirmation say. A cache + /// cleanup runs the agent's confirmed decisions, never the window's. + pub(crate) fn begin_agent_removal( + &mut self, + cleanup: Option, + cx: &mut Context<'_, Self>, + ) { + self.start_removal(Remover::Agent, cleanup, cx); + } + + fn start_removal( + &mut self, + by: Remover, + agent_cleanup: Option, + cx: &mut Context<'_, Self>, + ) { if self.remote.is_some() { return; } - let plan = self.plan(); + let cleanup = if self.removal_mode == RemovalMode::OwnerCleanup { + let approved = match by { + Remover::Person => self.cleanup_approved().cloned(), + Remover::Agent => agent_cleanup.ok_or_else(|| { + "Cache cleanup needs confirmed decisions".to_string() + }), + }; + match approved { + Ok(approved) => Some(approved), + Err(reason) => { + self.say(reason, Status::Warning, cx); + cx.notify(); + return; + } + } + } else { + None + }; + // Deleting files directly is its own intent: in the window it needs + // its own tick in the confirmation, whatever else was confirmed. + if by == Remover::Person + && cleanup + .as_ref() + .is_some_and(|approved| approved.file_steps() > 0) + && !self.cleanup_files_ticked() + { + self.say( + "Tick \u{201c}Delete these files myself\u{201d} to delete files without their owner", + Status::Warning, + cx, + ); + cx.notify(); + return; + } + let plan = cleanup + .as_ref() + .map_or_else(|| self.plan(), |approved| approved.plan.clone()); + if self.removal_mode != RemovalMode::OwnerCleanup + && let Some((target, reason)) = + plan.targets.iter().find_map(|target| { + disktree_core::cleanup::inspection_reason(&target.path) + .map(|reason| (target, reason)) + }) + { + self.say( + format!( + "{}: {reason}. Choose Cache cleanup to decide what happens to it.", + target.path.display() + ), + Status::Warning, + cx, + ); + cx.notify(); + return; + } if plan.is_empty() { - self.notice = Some(("nothing is marked".into(), Status::Warning)); + self.say("nothing is marked", Status::Warning, cx); cx.notify(); return; } + let limit = match by { + Remover::Person => self.removal_limit(&plan, cx), + Remover::Agent => self.agent_removal_limit(&plan), + }; + let limit = match limit { + Ok(limit) => limit, + Err(reason) => { + self.say_until_closed(reason, Status::Warning, cx); + cx.notify(); + return; + } + }; // This window quits once the prompt is answered yes, and quitting // would stop a permanent delete halfway. if self.restarting { - self.notice = Some(( - "not while restarting as administrator".into(), + self.say( + "not while restarting as administrator", Status::Warning, - )); + cx, + ); cx.notify(); return; } - self.space_baseline = self.space.or(self.space_baseline); + // The window's decisions are consumed: a retry needs a new check + // and new consent, even when a command fails. + if by == Remover::Person && cleanup.is_some() { + self.cleanup_review = None; + } + // Measured now rather than read from the ticker, which can be a + // second old: the observed figure is only as good as its baseline. + let before = space_info(&self.root_path).ok().or(self.space); + self.space_baseline = before.or(self.space_baseline); + self.ledger.begin(self.scans_done); + self.run_start = Some(crate::ledger::Start { + mode: self.removal_mode, + before: before.map(|space| space.available), + started: std::time::SystemTime::now(), + }); self.run_epoch += 1; let epoch = self.run_epoch; - self.run_summary = RunSummary { - total: plan.targets.len(), - ..RunSummary::default() - }; - self.run_log.clear(); + self.run_list = + crate::run_list::RunList::new(self.run_items(&plan.targets)); + self.track_agent_removal(); + self.run_scroll = gpui_kit::UniformListScrollHandle::new(); + self.run_free_before = before.map(|space| space.available); + self.cleanup_results.clear(); + self.cleanup_actions = + cleanup.as_ref().map_or_else(Vec::new, |approved| { + (0..approved.steps.len()) + .map(|index| approved.action(index)) + .collect() + }); + self.stop_requested = false; + // A confirmation is for this removal only: the next one past the + // limit asks again, even for the same share and mode. + self.over_phrase = None; + self.over_ticked = None; self.screen = Screen::Running; - self.run = Some(disktree_core::removal::spawn(plan, self.removal_mode)); + self.run = Some(if let Some(approved) = cleanup { + disktree_core::removal::spawn_cleanup(approved, limit) + } else { + disktree_core::removal::spawn_limited( + plan, + self.removal_mode, + limit, + ) + }); Self::poll_removal(epoch, cx); cx.notify(); } @@ -2686,50 +3837,313 @@ impl Disktree { if epoch != self.run_epoch { return false; } + if self.run.is_none() { + return false; + } + let mut finished = false; + // Only a report, the end, or a change in following redraws: the + // tick itself changes nothing on screen. + let mut changed = self.update_follow(); let Some(run) = &self.run else { return false; }; - let mut finished = false; while let Some(event) = run.poll() { + changed = true; match event { - RemovalEvent::Start { total } => self.run_summary.total = total, - RemovalEvent::Item { - path, - bytes, - outcome, - } => { - if outcome.is_ok() { - self.run_summary.removed += 1; - self.run_summary.bytes += bytes; - } else { - self.run_summary.failed += 1; + RemovalEvent::Cleanup(report) => { + self.cleanup_results.push(report); + } + // The list was built from the plan, so it already holds + // the total the worker announces. + RemovalEvent::Start { .. } => {} + RemovalEvent::Item { path, outcome, .. } => { + if self.run_list.settle(&path, &outcome).is_some() { + self.scroll_to_focus(); } - self.run_log.push((path, outcome)); } RemovalEvent::Done { removed, bytes, failed, } => { - self.run_summary.removed = removed; - self.run_summary.bytes = bytes; - self.run_summary.failed = failed; + // Counts only: the paths removed are the user's. + log::info!( + target: "pwrdisk::removal", + "removal finished: {removed} removed, {bytes} bytes, \ + {failed} failed" + ); + // The worker's own tally, kept only to check the list: + // a report the list could not place would show here. + let totals = self.run_list.totals(); + if ( + totals.removed as u64, + totals.reported_done, + totals.failed_all(), + ) != (removed, bytes, failed) + { + log::warn!( + target: "pwrdisk::removal", + "the run's list counts {} removed, {} bytes, \ + {} failed; the worker counted otherwise", + totals.removed, + totals.reported_done, + totals.failed_all() + ); + } finished = true; } } } if finished { self.run = None; + let removed = self.record_cohort(); + self.record_removal(); self.marks.clear(); + self.unmarked = None; self.screen = Screen::Done; - // The tree on screen is now wrong; start over rather than leaving - // numbers that include what was just removed. - self.start_scan(cx); + // What went stays drawn, as removed, until a scan: a rescan + // of a whole disk takes minutes and is asked for, never implied. + if self.removal_mode == RemovalMode::OwnerCleanup { + // Owner success does not mean the cache directory vanished. + // Partial failure can change it too. A fresh tree is required. + self.rescan_after_removal = true; + } else { + self.note_removed(removed); + } + if std::mem::take(&mut self.rescan_after_removal) { + self.start_scan(cx); + } + } + self.update_agent_removal(finished); + if changed { + cx.notify(); } - cx.notify(); !finished } + /// Whether a scroll by hand paused following, or one back to the item + /// in hand resumed it: following goes on while that row is in view, + /// as the live log does near its end. + /// Returns whether following changed. + pub fn update_follow(&mut self) -> bool { + let was = self.run_list.follow; + let place = crate::run_view::focus_place(self); + if std::mem::take(&mut self.run_list.scrolled_by_hand) { + if let Some(place) = place { + self.run_list.follow = place == std::cmp::Ordering::Equal; + } + } else if place == Some(std::cmp::Ordering::Equal) { + self.run_list.follow = true; + } + self.run_list.follow != was + } + + /// The pill's click: follow the item in hand again, from here. A wheel + /// turn not yet read by a poll is part of what the click answers. + pub fn follow_removal(&mut self) { + self.run_list.follow = true; + self.run_list.scrolled_by_hand = false; + self.scroll_to_focus(); + } + + /// Bring the item in hand into view, while following. + pub fn scroll_to_focus(&self) { + if self.run_list.follow + && let Some(focus) = self.run_list.focus() + { + // The least movement that shows it, as the log scrolls. + self.run_scroll + .scroll_to_item(focus, gpui_kit::ScrollStrategy::Nearest); + } + } + + /// What the scan made of each path, for Review's rows: its kind and + /// why it can be had back, default where the tree does not have it. + pub fn kinds_of<'a>( + &self, + paths: impl IntoIterator, + ) -> Vec<( + disktree_core::classify::Category, + Option, + )> { + let Some(tree) = &self.tree else { + return paths.into_iter().map(|_| Default::default()).collect(); + }; + let mut cached = self.kinds.borrow_mut(); + if !cached.tree.ptr_eq(&Arc::downgrade(tree)) + || cached.root != self.root_path + { + *cached = KindCache { + tree: Arc::downgrade(tree), + root: self.root_path.clone(), + kinds: rustc_hash::FxHashMap::default(), + }; + } + // Built only on a miss: a page already seen costs a hash lookup + // per row. + let mut resolver = None; + paths + .into_iter() + .map(|path| { + if let Some(kind) = cached.kinds.get(path) { + return *kind; + } + let resolver = resolver.get_or_insert_with(|| { + crate::marks::Resolver::new( + &self.root_path, + tree.root(), + self.path_style(), + ) + }); + let kind = resolver + .resolve(path) + .map_or_else(Default::default, |(_, node)| { + (node.category, node.reclaim) + }); + cached.kinds.insert(path.to_path_buf(), kind); + kind + }) + .collect() + } + + /// Add the run that just finished to the ledger. Returns what it + /// removed. + fn record_cohort(&mut self) -> Vec { + let Some(start) = self.run_start.take() else { + return Vec::new(); + }; + let removed: Vec<_> = self.run_list.removed().cloned().collect(); + let private = if start.mode == RemovalMode::OwnerCleanup { + None + } else { + self.private_estimate(&removed) + }; + let totals = self.run_list.totals(); + self.ledger.push(crate::ledger::Cohort { + mode: start.mode, + removed: totals.removed as u64, + failed: totals.failed_all(), + reported: totals.reported_done, + private, + before: start.before, + after: space_info(&self.root_path) + .ok() + .map(|space| space.available), + started: start.started, + finished: std::time::SystemTime::now(), + }); + removed + } + + /// Keep what a removal took, so the tree shows it as gone and it is + /// never marked again before a scan. + fn note_removed(&mut self, removed: Vec) { + let style = self.path_style(); + for target in removed { + if self.was_removed(&target.path) { + continue; + } + let path = target.path.clone(); + self.removed.toggle(target, style); + self.removed.absorb(&path, style); + } + self.forget_removed_insights(); + } + + /// Whether `path` was removed since the scan, itself or with a + /// directory holding it. + pub fn was_removed(&self, path: &Path) -> bool { + let style = self.path_style(); + self.removed.contains(path, style) + || self.removed.ancestor(path, style).is_some() + } + + /// Whether the scan can say what is private: not in an apparent-size + /// scan, nor on macOS without clone metadata. + const fn private_known(&self) -> bool { + !(self.options.apparent_size + || (cfg!(target_os = "macos") && !self.options.apfs_clone_metadata)) + } + + /// The run's list as it starts: each target with what the scan says it + /// is and what it holds alone. A target the tree no longer has keeps + /// its marked size and no kind. + fn run_items( + &self, + targets: &[disktree_core::removal::Target], + ) -> Vec { + let private_known = self.private_known() + && self.removal_mode != RemovalMode::OwnerCleanup; + let mut resolver = self.tree.as_ref().map(|tree| { + crate::marks::Resolver::new( + &self.root_path, + tree.root(), + self.path_style(), + ) + }); + targets + .iter() + .map(|target| { + let node = resolver + .as_mut() + .and_then(|resolver| resolver.resolve(&target.path)) + .map(|(_, node)| node); + crate::run_list::Item { + target: target.clone(), + category: node + .map(|node| node.category) + .unwrap_or_default(), + reclaim: node.and_then(|node| node.reclaim), + // As `private_estimate` reads one node, and never more + // than was reported for it. + private: node.filter(|_| private_known).map(|node| { + node.sharing() + .estimate + .map_or(node.bytes, |estimate| estimate.lower) + .min(target.bytes) + }), + status: crate::run_list::Status::Waiting, + } + }) + .collect() + } + + /// What the scan saw as only these targets', estimated as review does, + /// from the tree they were removed from. Unknown where review's is. + fn private_estimate( + &self, + targets: &[disktree_core::removal::Target], + ) -> Option { + if !self.private_known() { + return None; + } + let tree = self.tree.as_ref()?; + let mut resolver = crate::marks::Resolver::new( + &self.root_path, + tree.root(), + PathStyle::Native, + ); + let nodes: Vec<_> = targets + .iter() + .filter_map(|target| { + resolver.resolve(&target.path).map(|(_, node)| node) + }) + .collect(); + let estimate = match nodes.as_slice() { + [] => 0, + [node] => node + .sharing() + .estimate + .map_or(node.bytes, |estimate| estimate.lower), + _ => disktree_core::sharing::estimate(nodes).lower, + }; + // The scan's figures still hold what an earlier removal took from + // inside these targets; their reported bytes already leave it out, + // and nothing private can exceed what is reported. + let reported = targets.iter().map(|target| target.bytes).sum(); + Some(estimate.min(reported)) + } + /// Descend to a path found by the search field. /// Recompute what the find text matches in the directory on screen. /// @@ -2751,9 +4165,11 @@ impl Disktree { }; self.finding = true; let base = self.crumbs.clone(); + let rule = self.legend_rule(); let task = cx.background_executor().spawn(async move { - tree.resolve(&base) - .and_then(|node| filter(node, &base, &needle)) + tree.root().resolve(&base).and_then(|node| { + filter_with(node, &base, &needle, rule.as_ref()) + }) }); cx.spawn(async move |this, cx| { let found = task.await; @@ -2785,10 +4201,11 @@ impl Disktree { return; }; if matches.count == 0 { - self.notice = Some(( + self.say( format!("nothing here matches {}", matches.needle), Status::Warning, - )); + cx, + ); cx.notify(); return; } @@ -2804,12 +4221,12 @@ impl Disktree { .iter() .filter(|(_, keep)| **keep == Keep::Whole) .filter_map(|(crumbs, _)| { - let node = tree.as_deref()?.resolve(crumbs)?; + let node = tree.as_deref()?.root().resolve(crumbs)?; Some((node.bytes, crumbs)) }) .max_by_key(|(bytes, _)| *bytes) .map(|(_, crumbs)| crumbs.clone()); - self.notice = None; + self.clear_notice(cx); cx.notify(); } @@ -2843,6 +4260,45 @@ impl Disktree { self.screen == Screen::Explore && !self.confirm_open && !self.volumes_open + && !self.show_help + } + + pub const fn has_modal(&self) -> bool { + self.confirm_open || self.volumes_open || self.show_help + } + + pub fn open_help(&mut self, cx: &mut Context<'_, Self>) { + if !self.has_modal() { + // A modal must not leave another keyboard owner behind it. + self.crumb_menu = None; + self.power_menu = None; + self.more_menu = None; + self.app_menu_open = false; + self.export_menu_open = false; + self.show_help = true; + self.focus_request = Some(FocusTarget::Dialog); + cx.notify(); + } + } + + pub fn close_help(&mut self, cx: &mut Context<'_, Self>) { + self.show_help = false; + self.focus_request = Some(FocusTarget::Root); + cx.notify(); + } + + pub fn toggle_app_menu(&mut self, cx: &mut Context<'_, Self>) { + if self.has_modal() { + return; + } + self.app_menu_open = !self.app_menu_open; + self.app_menu_index = 0; + self.focus_request = Some(if self.app_menu_open { + FocusTarget::Dialog + } else { + FocusTarget::Root + }); + cx.notify(); } /// Ask for a directory and scan it: an app opened from the Dock has no @@ -2878,8 +4334,7 @@ impl Disktree { .detach(); } - /// Save what the plan would act on as a list of paths, one per line, - /// wherever the user chooses: for a script, or for later. + /// Save marked paths, one per line, without widening to owner scopes. pub fn save_delete_list(&mut self, cx: &mut Context<'_, Self>) { self.save_export(false, cx); } @@ -2889,31 +4344,27 @@ impl Disktree { } fn save_export(&mut self, script: bool, cx: &mut Context<'_, Self>) { - let plan = self.plan(); - if plan.is_empty() { - self.notice = Some(("nothing to save".into(), Status::Warning)); - cx.notify(); - return; - } - let list = if script { - self.delete_script(&plan.targets) - } else { - disktree_core::export::delete_list(&plan.targets) + let (list, count) = match self.export_text(script) { + Ok(export) => export, + Err(reason) => { + self.say(reason, Status::Warning, cx); + cx.notify(); + return; + } }; - let count = plan.targets.len(); let directory = std::env::home_dir().unwrap_or_else(|| PathBuf::from(".")); let filename = if script { - "disktree-delete.sh" + "pwrdisk-delete.sh" } else { - "disktree-delete-list.txt" + "pwrdisk-delete-list.txt" }; let chosen = cx.prompt_for_new_path(&directory, Some(filename)); cx.spawn(async move |this, cx| { let Ok(Ok(Some(path))) = chosen.await else { return; }; - let notice = match std::fs::write(&path, list) { + let (message, status) = match std::fs::write(&path, list) { Ok(()) => ( format!( "saved {count} {} to {}", @@ -2928,48 +4379,74 @@ impl Disktree { ), }; let _ = this.update(cx, |this, cx| { - this.notice = Some(notice); - cx.notify(); + this.say(message, status, cx); }); }) .detach(); } - fn delete_script(&self, targets: &[Target]) -> String { + /// Both save and copy use this boundary before opening a prompt or + /// changing the clipboard. A raw script cannot stand in for an owner. + pub(crate) fn export_text( + &self, + script: bool, + ) -> Result<(String, usize), String> { + let plan = self.selection_plan(); + if plan.is_empty() { + return Err("nothing selected for export".into()); + } + if !script { + return Ok(( + disktree_core::export::delete_list(&plan.targets), + plan.targets.len(), + )); + } + if self.removal_mode == RemovalMode::OwnerCleanup + || (self.remote.is_none() + && plan.targets.iter().any(|target| { + disktree_core::cleanup::inspection_reason(&target.path) + .is_some() + })) + { + return Err("Cache selections require owner cleanup or inspection; a raw deletion script cannot replace owner cleanup".into()); + } let identity = if self.remote.is_some() { self.remote_identity.clone() } else { disktree_core::identity::HostIdentity::current() }; - disktree_core::export::delete_script_for( - targets, + let text = disktree_core::export::delete_script_for( + &plan.targets, &self.root_path, self.remote.as_deref(), identity.as_ref(), - ) + ); + Ok((text, plan.targets.len())) } pub fn copy_delete_script(&mut self, cx: &mut Context<'_, Self>) { - let plan = self.plan(); - if plan.is_empty() { - self.notice = Some(("nothing to copy".into(), Status::Warning)); - } else { - let script = self.delete_script(&plan.targets); - cx.write_to_clipboard(gpui_kit::ClipboardItem::new_string(script)); - self.notice = Some(( - "copied delete script; previews by default, checks host before deletion".into(), - Status::Success, - )); + match self.export_text(true) { + Ok((script, _)) => { + cx.write_to_clipboard(gpui_kit::ClipboardItem::new_string( + script, + )); + self.say( + "copied delete script; previews by default, checks host before deletion", + Status::Success, + cx, + ); + } + Err(reason) => self.say(reason, Status::Warning, cx), } cx.notify(); } /// Copy instructions for a coding agent to free the space by removing - /// what the plan would act on, after checking each path. + /// the marked paths, after checking each path. pub fn copy_agent_prompt(&mut self, cx: &mut Context<'_, Self>) { - let plan = self.plan(); + let plan = self.selection_plan(); if plan.is_empty() { - self.notice = Some(("nothing to copy".into(), Status::Warning)); + self.say("nothing to copy", Status::Warning, cx); cx.notify(); return; } @@ -2999,14 +4476,15 @@ impl Disktree { } cx.write_to_clipboard(gpui_kit::ClipboardItem::new_string(prompt)); let count = plan.targets.len(); - self.notice = Some(( + self.say( format!( "copied a prompt for your agent: {count} {}, {}", if count == 1 { "path" } else { "paths" }, disktree_core::size::human_bytes(plan.bytes()) ), Status::Success, - )); + cx, + ); cx.notify(); } @@ -3022,13 +4500,11 @@ impl Disktree { }; // GPUI's reveal cannot report failure, so check what it can't. if std::fs::symlink_metadata(&path).is_err() { - self.notice = Some(( - format!( - "{} is no longer on disk", - crate::marks::display_path(&path, self.home.as_deref()) - ), + self.say( + format!("{} is no longer on disk", self.display_path(&path)), Status::Warning, - )); + cx, + ); cx.notify(); return; } @@ -3078,21 +4554,40 @@ impl Disktree { return; } + // The legend's "+N" menu closes before Escape clears the legend. + if self.legend_menu_open + && key == "escape" + && self.screen == Screen::Explore + { + self.legend_menu_open = false; + cx.notify(); + return; + } if self.crumb_menu.is_some() && self.on_menu_key(key, cx) { return; } if self.power_menu.is_some() && self.on_power_key(key, cx) { return; } + if self.more_menu.is_some() && self.on_more_key(key, cx) { + return; + } - if self.show_help { - if matches!(key, "escape" | "?" | "/" | "q") { - self.show_help = false; + if self.app_menu_open { + if key == "escape" { + self.app_menu_open = false; + self.focus_request = Some(FocusTarget::Root); cx.notify(); } return; } + if self.show_help { + if matches!(key, "escape" | "?" | "/" | "q") { + self.close_help(cx); + } + return; + } // The search field takes the keyboard while it is open. It is a field // of three keys on purpose: no editor state to keep in sync with the // tree, and Escape always means "give the keyboard back". @@ -3128,17 +4623,13 @@ impl Disktree { Screen::Explore if alt && key == "left" => self.go_back(cx), Screen::Explore if alt && key == "right" => self.go_forward(cx), Screen::Explore => self.on_explore_key(key, control, shift, cx), - Screen::Review => self.on_review_key(key, cx), + // No review key is a Ctrl chord, and Edit's rows replay those + // (Select All is ctrl-a), so a chord must not act as its letter. + Screen::Review if !control => self.on_review_key(key, shift, cx), + Screen::Review => {} Screen::Running => { - if key == "escape" - && let Some(run) = &self.run - { - run.cancel(); - self.notice = Some(( - "stopping after the current item".into(), - Status::Warning, - )); - cx.notify(); + if key == "escape" { + self.stop_removal(cx); } } Screen::Done => { @@ -3156,6 +4647,29 @@ impl Disktree { control: bool, shift: bool, cx: &mut Context<'_, Self>, + ) { + if self.file_list && !control { + match key { + "n" => self.file_step(if shift { -1 } else { 1 }, cx), + "up" | "k" => self.file_step(-1, cx), + "down" | "j" => self.file_step(1, cx), + "pageup" => self.file_step(-100, cx), + "pagedown" => self.file_step(100, cx), + "right" | "l" => self.descend(cx), + "left" | "h" => self.ascend(cx), + _ => self.on_file_shared_key(key, control, shift, cx), + } + return; + } + self.on_file_shared_key(key, control, shift, cx); + } + + fn on_file_shared_key( + &mut self, + key: &str, + control: bool, + shift: bool, + cx: &mut Context<'_, Self>, ) { // Keys that act on "the current tile" start from the pointer when it // moved last. @@ -3164,7 +4678,7 @@ impl Disktree { "space" | "x" | "enter" - | "tab" + | "n" | "left" | "right" | "up" @@ -3192,12 +4706,21 @@ impl Disktree { "down" | "j" if !control => { self.move_selection(Direction::Down, cx); } + // Shift-U, not `u`: plain `u` goes up a level, as backspace. + // Updates is Settings › Updates now, in its own window. + "u" if shift && !control => cx.defer(|cx| { + crate::settings::open(crate::settings::Pane::Updates, cx); + }), "backspace" | "u" if !control => self.ascend(cx), // A filter is the first thing Escape takes away. "escape" if self.matches.is_some() => self.clear_filter(), "escape" if self.scan.is_some() || self.remote_scan.is_some() => { self.cancel_scan(cx); } + // Then the legend's, before Escape goes back to moving around. + "escape" if self.legend.is_active() => { + self.clear_legend(None, cx); + } "escape" => { if self.selected.is_some() { self.selected = None; @@ -3208,19 +4731,10 @@ impl Disktree { } "space" => self.toggle_mark_selected(cx), "x" if !control => self.toggle_mark_selected(cx), - "tab" => self.cycle_sibling(if shift { -1 } else { 1 }, cx), - "c" if !control => { - if self.marks.is_empty() { - self.notice = Some(( - "mark something first: space marks the selected tile" - .into(), - Status::Warning, - )); - } else { - self.screen = Screen::Review; - } - cx.notify(); + "n" if !control => { + self.cycle_sibling(if shift { -1 } else { 1 }, cx); } + "c" if !control => self.open_review(cx), "[" => self.adjust_depth(-1, cx), "]" => self.adjust_depth(1, cx), "-" => { @@ -3248,32 +4762,51 @@ impl Disktree { "r" if !control => self.start_scan(cx), "g" if !control => self.go_to_disk(cx), "v" if !control && !shift => self.open_volumes(cx), - "i" if !control => { - self.options.include_hidden = !self.options.include_hidden; - self.start_scan(cx); - } - "d" if !control => { - self.options.apparent_size = !self.options.apparent_size; - self.start_scan(cx); - } + "i" if !control => self.toggle_hidden(cx), + "d" if !control => self.toggle_apparent(cx), "p" if !control => { self.show_selection = !self.show_selection; cx.notify(); } "o" if !control => self.reveal_target(cx), "?" => { - self.show_help = true; - cx.notify(); + self.open_help(cx); + } + // A bare letter quitting is Omarchy's habit, kept there; macOS + // and Windows quit with ⌘Q and Alt+F4, and q would throw away + // marks by surprise. + "q" if !control + && crate::chrome::Platform::current() + == crate::chrome::Platform::Linux => + { + cx.quit(); } - "q" if !control => cx.quit(), _ => {} } } - fn on_review_key(&mut self, key: &str, cx: &mut Context<'_, Self>) { + fn on_review_key( + &mut self, + key: &str, + shift: bool, + cx: &mut Context<'_, Self>, + ) { if self.remote.is_some() && matches!(key, "m" | "p" | "enter") { return; } + // The open Export menu shows each row's key: those keys run the + // row and close it, as a click would; Escape only closes it. + if self.export_menu_open { + let row = matches!(key, "s" | "a" | "e" | "y"); + if row || key == "escape" { + self.export_menu_open = false; + self.focus_request = Some(FocusTarget::Root); + cx.notify(); + } + if !row { + return; + } + } if key == "e" { self.save_delete_script(cx); return; @@ -3281,10 +4814,12 @@ impl Disktree { match key { "escape" => { self.screen = Screen::Explore; + self.focus_request = Some(FocusTarget::Root); cx.notify(); } - "enter" => self.commit(cx), + "enter" => self.commit(shift, cx), "!" => self.clear_marks(cx), + "u" => self.undo_unmark(cx), "p" => { self.removal_mode = RemovalMode::Permanent; cx.notify(); @@ -3297,8 +4832,7 @@ impl Disktree { "a" => self.copy_agent_prompt(cx), "y" => self.copy_delete_script(cx), "?" => { - self.show_help = true; - cx.notify(); + self.open_help(cx); } _ => {} } @@ -3342,6 +4876,9 @@ impl Disktree { self.pointer_active = true; let previous = self.hovered.clone(); self.hovered = self.tile_at(local.x.as_f32(), local.y.as_f32()); + if self.hovered != previous { + self.hover_since = Some(cx.background_executor().now()); + } // The cursor tooltip is positioned from `pointer`, so a move *within* // one tile still has to repaint — otherwise the tooltip sticks where // the tile was first entered until the hover target changes. @@ -3370,10 +4907,17 @@ impl Disktree { let crumbs = self.tile_at(x, y); match event.button { + // A later press of a double or triple click. One gesture opens + // at most one level: once a press of it has opened, the view + // has changed under the pointer, and acting on what is there + // now would open a second level nobody aimed at. MouseButton::Left if event.click_count >= 2 => { + if self.click_opened { + return; + } if let Some(crumbs) = crumbs { - self.select(Some(crumbs), cx); - self.descend(cx); + self.select(Some(crumbs.clone()), cx); + self.click_opened = self.open_toward(&crumbs, cx); } } MouseButton::Left @@ -3384,15 +4928,18 @@ impl Disktree { } } MouseButton::Left => { - let activate = crumbs.as_ref().is_some_and(|crumbs| { - self.selected.as_ref() == Some(crumbs) - && self.node_at(crumbs).is_some_and(Node::is_dir) - }); - if activate { - // A second click on the selection opens it, like a file - // manager, without needing a double click. - self.descend(cx); - return; + self.click_opened = false; + // A second click on the selection opens it, like a file + // manager, without needing a double click. + if let Some(crumbs) = crumbs + .as_ref() + .filter(|crumbs| self.selected.as_ref() == Some(*crumbs)) + { + let crumbs = crumbs.clone(); + self.click_opened = self.open_toward(&crumbs, cx); + if self.click_opened { + return; + } } self.select(crumbs, cx); } @@ -3454,14 +5001,21 @@ impl Disktree { } /// Advance the layout transition, if one is running. - pub fn tick_transition(&mut self, window: &Window) { - if let Some(transition) = self.transition { - let (_, running) = transition.sample(Rect::default()); - if running { - window.request_animation_frame(); - } else { - self.transition = None; - } + pub fn tick_transition(&mut self, window: &Window, cx: &mut gpui_kit::App) { + let Some(transition) = self.transition else { + return; + }; + // Asked only mid-flight: the answer is a platform call, and no other + // frame has motion to drop. + if prefers_reduced_motion(cx) { + self.transition = None; + return; + } + let (_, running) = transition.sample(Rect::default()); + if running { + window.request_animation_frame(); + } else { + self.transition = None; } } @@ -3475,6 +5029,15 @@ impl Disktree { } } +/// Base 0.6.6 follows Linux portal changes, but reads macOS/Windows only +/// when asked. Re-sample before a transition starts and on each of its +/// frames so a running app honors an OS toggle too. Base preserves explicit +/// application overrides. +pub fn prefers_reduced_motion(cx: &mut gpui_kit::App) -> bool { + gpui_kit::base::apply_system_reduce_motion(cx); + cx.reduce_motion() +} + /// A direction for geometric selection movement. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Direction { @@ -3538,6 +5101,9 @@ impl Direction { #[derive(Clone, Debug)] pub struct Label { pub text: String, + /// The bytes of `text` the find text matched: underlined, so a match + /// reads as one without its colour. + pub found: Option>, /// Base-space rectangle; the view transform is applied while painting. pub rect: Rect, /// The band this label belongs in, when its tile reserved one. A parent's @@ -3547,8 +5113,11 @@ pub struct Label { pub depth: u32, /// Filtered out while typing: drawn quietly. pub dim: bool, + /// Marked, or inside a mark: struck through, in the marked ink. pub marked: bool, pub size_text: String, + /// The exact fill state is needed for contrast after filtering/marking. + pub decoration: TileDeco, } /// How many labels one frame will shape. @@ -3561,8 +5130,8 @@ const HEADER_REMS: f32 = 1.375; const HEADER_INNER_REMS: f32 = 1.0; /// A trail step's label: the directory's own name, or `/` for the root. -fn crumb_label(path: &Path) -> String { - path.file_name().map_or_else( +fn crumb_label(path: &Path, style: PathStyle) -> String { + style.file_name(path).map_or_else( || path.display().to_string(), |name| name.to_string_lossy().into_owned(), ) @@ -3605,10 +5174,11 @@ impl Disktree { Ok(()) => cx.quit(), Err(error) => { this.restarting = false; - this.notice = Some(( + this.say_until_closed( format!("still not an administrator: {error}"), Status::Warning, - )); + cx, + ); cx.notify(); } }); @@ -3673,13 +5243,58 @@ pub fn now_seconds() -> i64 { }) } -/// Let go of a tree off the UI thread: freeing a disk's millions of nodes -/// takes a good part of a second, and nothing waits on it. -fn discard(tree: Option>) { - if let Some(tree) = tree { +/// Closing the window or quitting drops the app, and with it the tree. +/// Freed in place, a home directory's tens of millions of nodes held the +/// main thread for seconds after Quit, long enough for macOS to call the +/// app not responding. On quit nothing is freed at all: the process is +/// about to exit and the system takes its memory back without walking +/// the nodes. A window closed while the app stays hands them to a +/// background thread. The find results (an entry per match and ancestor) +/// and a finished scan not yet taken from its channel can be as large, +/// so they go with the tree. +impl Drop for Disktree { + fn drop(&mut self) { + let held = (self.tree.take(), self.matches.take(), self.scan.take()); + if self.quitting { + std::mem::forget(held); + } else { + discard(Some(held)); + } + } +} + +/// Git, on a thread of its own per probe. +#[cfg(not(test))] +fn default_git_probe() -> GitProbe { + Arc::new(|path, cancel| { + crate::git::probe_on_thread( + path, + git_store::PROBE_LIMIT, + cancel.clone(), + ) + }) +} + +/// In the window tests, an answer at once and no git: a probe's own thread +/// would wake GPUI's deterministic test executor from outside it. Tests +/// that count probes put in their own (`tests::count_probes`); `git.rs` +/// tests the real one. +#[cfg(test)] +fn default_git_probe() -> GitProbe { + Arc::new(|_, _| git_store::ready(git_store::Probe::Unreadable)) +} + +/// Let go of a tree, or anything holding one, off the UI thread: freeing +/// a disk's millions of nodes takes from a good part of a second to many, +/// and nothing waits on it. +fn discard(held: Option) { + if let Some(held) = held { + #[cfg(test)] + crate::marks::work::DISCARDED + .set(crate::marks::work::DISCARDED.get() + 1); // When no thread can be made, the closure is dropped here instead, // and the tree is freed in place rather than taking the window down. - let _ = std::thread::Builder::new().spawn(move || drop(tree)); + let _ = std::thread::Builder::new().spawn(move || drop(held)); } } @@ -3713,29 +5328,38 @@ impl Render for Disktree { window: &mut Window, cx: &mut Context<'_, Self>, ) -> impl gpui_kit::IntoElement { + #[cfg(test)] + crate::marks::work::RENDERS.set(crate::marks::work::RENDERS.get() + 1); + if crate::ui::sync_scale(window, cx) { + self.cache = None; + } self.rem = window.rem_size().as_f32(); - self.tick_transition(window); + self.tick_transition(window, cx); // The titlebar names the directory on screen, however it got there: // a key, a click, a rescan or a folder chosen from the menu. let title = if self.awaiting_root { - "disktree · Choose a source".into() + "PwrDisk · Choose a source".into() } else { format!( - "disktree{} · {}", + "PwrDisk{} · {}", self.remote.as_ref().map_or_else(String::new, |host| { format!(" · {host} · read-only") }), - crate::marks::display_path( - &self.current_path(), - self.home.as_deref() - ) + self.display_path(&self.current_path()) ) }; if title != self.window_title { window.set_window_title(&title); self.window_title = title; } - crate::views::root(self, window, cx) + let frame = self + .chrome_pin + .clone() + .unwrap_or_else(|| crate::chrome::Frame::detect(window, cx)); + self.content_edges = frame.content_edges(); + let root = crate::views::root(self, &frame, window, cx); + let theme = cx.omarchy().clone(); + crate::chrome::client_frame(&frame, root, window, &theme) } } diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rs index 0520e4cb..190f0d6f 100644 --- a/crates/disktree-app/src/tests.rs +++ b/crates/disktree-app/src/tests.rs @@ -7,6 +7,7 @@ use std::path::{Path, PathBuf}; +use disktree_core::path_style::PathStyle; use disktree_core::removal::RemovalMode; use disktree_core::scan::{ScanOptions, scan}; use disktree_core::space::{SpaceInfo, Volume}; @@ -19,6 +20,61 @@ use gpui_omarchy::Theme; use crate::state::{Disktree, Screen}; +/// Native filesystem callbacks cannot run on GPUI's deterministic scheduler. +/// +/// `gpui_omarchy::init` watches `$HOME` even without an Omarchy theme. Its +/// callback wakes the deterministic executor from a foreign thread. The +/// control initializers are private in gpui-omarchy 0.1.3, so mirror their +/// bindings here and apply a fixed theme without creating a watcher at all. +fn init(cx: &mut gpui_kit::App) { + use gpui_kit::base::actions::{Cancel, Confirm, SelectLeft, SelectRight}; + use gpui_kit::{KeyBinding, NoAction}; + use gpui_omarchy::focus::{Next, Previous}; + + gpui_kit::base::init(cx); + cx.bind_keys([ + KeyBinding::new( + if cfg!(target_os = "macos") { + "cmd-c" + } else { + "ctrl-c" + }, + gpui_kit::base::input::Copy, + Some("OmarchyFocusScope"), + ), + KeyBinding::new("tab", Next, Some("OmarchyFocusScope")), + KeyBinding::new("shift-tab", Previous, Some("OmarchyFocusScope")), + KeyBinding::new("left", SelectLeft, Some("OmarchyOptionGroup")), + KeyBinding::new("h", SelectLeft, Some("OmarchyOptionGroup")), + KeyBinding::new("right", SelectRight, Some("OmarchyOptionGroup")), + KeyBinding::new("l", SelectRight, Some("OmarchyOptionGroup")), + KeyBinding::new( + "enter", + Confirm { secondary: false }, + Some("OmarchyOptionGroup"), + ), + KeyBinding::new( + "space", + Confirm { secondary: false }, + Some("OmarchyOptionGroup"), + ), + KeyBinding::new("enter", NoAction, Some("OmarchyPopoverContent")), + KeyBinding::new("space", NoAction, Some("OmarchyPopoverContent")), + KeyBinding::new( + "enter", + Confirm { secondary: false }, + Some("OmarchyDatePicker"), + ), + KeyBinding::new( + "space", + Confirm { secondary: false }, + Some("OmarchyDatePicker"), + ), + KeyBinding::new("escape", Cancel, Some("OmarchyDatePicker")), + ]); + Theme::tokyo_night().apply(cx); +} + /// A small tree on disk: two directories, a nested file, and a hidden one. /// /// The hidden directory holds the largest file, which is both the common case @@ -39,6 +95,155 @@ fn fixture() -> tempfile::TempDir { temp } +#[gpui_kit::test] +fn artifact_assessments_render_and_vm_data_stays_out_of_cleanup_filters( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + for path in [ + "target/debug/deps/libapp.rlib", + "guest.utm/cache/state", + "guest.vmss", + ] { + let path = temp.path().join(path); + std::fs::create_dir_all(path.parent().expect("parent")).unwrap(); + std::fs::write(path, vec![b'x'; 200_000]).unwrap(); + } + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1440.), px(900.))); + for (path, shown, absent) in [ + ( + "target/debug/deps", + "artifact-suggested", + "artifact-detected", + ), + ("guest.utm", "artifact-detected", "artifact-suggested"), + ("guest.vmss", "artifact-detected", "artifact-suggested"), + ] { + update(&view, cx, |app, cx| { + let (crumbs, _) = + app.tree().unwrap().descend(Path::new(path)).unwrap(); + app.selected = Some(crumbs); + app.hovered = None; + app.pointer_active = false; + app.show_selection = true; + cx.notify(); + }); + draw(cx); + assert!(cx.debug_bounds(shown).is_some(), "{path}"); + assert!(cx.debug_bounds(absent).is_none(), "{path}"); + // The status is a chip of its own, not a run of caption text. + let status: &'static str = + Box::leak(format!("{shown}-status").into_boxed_str()); + assert!(cx.debug_bounds(status).is_some(), "{path}"); + } + click_on(cx, "legend-reclaimable"); + cx.run_until_parked(); + let drawn = laid_out(&view, cx); + assert!(drawn.iter().any(|name| name == "deps"), "{drawn:?}"); + assert!( + !drawn.iter().any(|name| name.starts_with("guest")), + "{drawn:?}" + ); + assert!(read(&view, cx, |app| app.marks.is_empty())); +} + +/// Review repeats the VM caution where removal is approved, and only on +/// VM data: a suggested build cache carries its kind alone. +#[gpui_kit::test] +fn review_cautions_on_marked_vm_data_only(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + for path in ["target/debug/deps/libapp.rlib", "guest.vmss"] { + let path = temp.path().join(path); + std::fs::create_dir_all(path.parent().expect("parent")).unwrap(); + std::fs::write(path, vec![b'x'; 200_000]).unwrap(); + } + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1440.), px(900.))); + let vm = temp.path().join("guest.vmss"); + mark_paths( + &view, + cx, + &[temp.path().join("target/debug/deps"), vm.clone()], + ); + update(&view, cx, |app, cx| { + app.screen = Screen::Review; + cx.notify(); + }); + draw(cx); + let at = read(&view, cx, |app| { + app.marks.items().iter().position(|item| item.path == vm) + }) + .expect("the VM file is marked"); + let caution = |index: usize| -> &'static str { + Box::leak(format!("review-caution-{index}").into_boxed_str()) + }; + assert!(cx.debug_bounds(caution(at)).is_some(), "VM row cautions"); + assert!(cx.debug_bounds(caution(1 - at)).is_none(), "cache row"); + // A reminder, not a gate: both stay in the plan. + assert_eq!(read(&view, cx, |app| app.plan().targets.len()), 2); +} + +#[gpui_kit::test] +fn artifact_guidance_scrolls_above_the_pinned_free_space_meter( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let output = temp.path().join("target/debug/deps"); + std::fs::create_dir_all(&output).unwrap(); + std::fs::write(output.join("libapp.rlib"), vec![b'x'; 200_000]).unwrap(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + let (crumbs, _) = app + .tree() + .unwrap() + .descend(Path::new("target/debug/deps")) + .unwrap(); + app.selected = Some(crumbs); + app.hovered = None; + app.pointer_active = false; + app.show_selection = true; + app.space = Some(SpaceInfo { + total: 1000, + free: 350, + available: 350, + }); + cx.notify(); + }); + for (width, height, rem) in + [(1200., 600., 16.), (1400., 600., 24.), (1440., 900., 16.)] + { + cx.simulate_resize(gpui_kit::size(px(width), px(height))); + cx.update(|window, _| window.set_rem_size(px(rem))); + draw(cx); + draw(cx); + let disk = cx.debug_bounds("disk-section").unwrap(); + assert!(disk.bottom() <= px(height), "{disk:?}"); + assert!(disk.size.height >= px(rem * 4.0), "{disk:?}"); + let scroll = cx.debug_bounds("side-panel-scroll").unwrap(); + assert!(scroll.size.height > px(0.), "{scroll:?}"); + assert!(scroll.bottom() <= disk.origin.y, "{scroll:?}, {disk:?}"); + let guidance = cx.debug_bounds("artifact-suggested").unwrap(); + // Scroll just far enough to read the final guidance line without + // moving the meter, even when the selection exceeds the viewport. + let distance = (guidance.bottom() - scroll.bottom()).max(px(0.)); + cx.simulate_event(gpui_kit::ScrollWheelEvent { + position: scroll.center(), + delta: gpui_kit::ScrollDelta::Pixels(Point::new(px(0.), -distance)), + modifiers: gpui_kit::Modifiers::none(), + touch_phase: gpui_kit::TouchPhase::Moved, + }); + draw(cx); + let scrolled = cx.debug_bounds("artifact-suggested").unwrap(); + assert!(scrolled.bottom() <= scroll.bottom(), "{scrolled:?}"); + assert!(scrolled.bottom() > scroll.origin.y, "{scrolled:?}"); + assert_eq!(disk, cx.debug_bounds("disk-section").unwrap()); + } +} + /// Apparent sizes, so the assertions are about the tree and not about how the /// filesystem rounds a small file up to a block. fn options() -> ScanOptions { @@ -58,19 +263,171 @@ fn view_over<'a>( let tree = scan(root, options()).expect("scan the fixture"); let root_path = root.to_path_buf(); let (view, cx) = cx.add_window_view(move |_, cx| { - Disktree::with_tree(root_path.clone(), tree, options(), 3, cx) + let mut app = + Disktree::with_tree(root_path.clone(), tree, options(), 3, cx); + app.removal_settings_dir = None; + app }); let focus = view.read_with(cx, |app, _| app.focus.clone()); cx.update(|window, cx| window.focus(&focus, cx)); (view, cx) } +/// The fixture as an SSH session holds it. Remote paths are POSIX on every +/// client, so the root must be `/`-rooted: the temporary directory itself on +/// Unix, which keeps "nothing on disk changed" checks meaningful, and a Unix +/// path on Windows, whose temporary directory is `C:\…`. +fn remote_view_over<'a>( + temp: &Path, + cx: &'a mut TestAppContext, +) -> (Entity, &'a mut Window, PathBuf) { + let root = if cfg!(unix) { + temp.to_path_buf() + } else { + PathBuf::from("/srv/fixture") + }; + let tree = scan(temp, options()).expect("scan the fixture"); + let root_path = root.clone(); + let (view, cx) = cx.add_window_view(move |_, cx| { + Disktree::with_tree(root_path.clone(), tree, options(), 3, cx) + }); + let focus = view.read_with(cx, |app, _| app.focus.clone()); + cx.update(|window, cx| window.focus(&focus, cx)); + (view, cx, root) +} + fn draw(cx: &mut Window) { cx.update(|window, cx| { window.draw(cx).clear(cx); }); } +#[cfg(target_os = "macos")] +#[gpui_kit::test] +fn private_service_stores_draw_unavailable_and_partial_figures( + cx: &mut TestAppContext, +) { + use disktree_core::macos_services::{Usage, usage}; + use disktree_core::tree::{Draft, Metric, NodeKind, Tree, aggregate}; + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + assert!(cx.debug_bounds("macos-services").is_none()); + update(&view, cx, |app, cx| { + // Replace the fixture's tree without starting a real system scan. + let mut history = Draft::directory(".fseventsd"); + history.read_error = true; + let mut index = Draft::directory(".Spotlight-V100"); + index + .children + .push(Draft::entry("store", NodeKind::File, 8192)); + index.read_error = true; + let mut data = Draft::directory("Data"); + data.children = vec![history, index]; + let mut volumes = Draft::directory("Volumes"); + volumes.children.push(data); + let mut system = Draft::directory("System"); + system.children.push(volumes); + let mut root = Draft::directory("/"); + root.children.push(system); + let mut root = Tree::from(root); + aggregate(&mut root, Metric::Bytes); + disktree_core::classify::classify(&mut root); + app.tree = Some(std::sync::Arc::new(root)); + app.root_path = PathBuf::from("/"); + app.selected = None; + app.hovered = None; + app.options = ScanOptions::default(); + app.progress.errors = 2; + app.progress.service_errors = 2; + app.full_disk_access = Some(false); + cx.notify(); + }); + draw(cx); + assert!(cx.debug_bounds("macos-services").is_some()); + assert!(cx.debug_bounds("privacy-hint").is_none()); + read(&view, cx, |app| { + let tree = app.tree().expect("fixture tree"); + let data = Path::new(disktree_core::space::MACOS_DATA_VOLUME); + assert_eq!( + usage(&app.root_path, tree, &app.options, &data.join(".fseventsd")), + Usage::Unavailable + ); + assert_eq!( + usage( + &app.root_path, + tree, + &app.options, + &data.join(".Spotlight-V100") + ), + Usage::Incomplete(8192) + ); + }); + update(&view, cx, |app, cx| { + app.remote = Some("fixture-host".into()); + cx.notify(); + }); + draw(cx); + assert!(cx.debug_bounds("macos-services").is_none()); + update(&view, cx, |app, cx| { + app.remote = None; + app.selected = app.tree().and_then(|tree| { + tree.find(".Spotlight-V100").map(|(crumbs, _)| crumbs) + }); + cx.notify(); + }); + draw(cx); + // The guards refuse a service store, so it is never offered: the + // inspector says why, and Space marks nothing and says so. + assert!(cx.debug_bounds("mark-guard").is_some()); + press(cx, "space"); + assert!(read(&view, cx, |app| app.marks.is_empty())); + assert!(read(&view, cx, |app| { + app.notice() + .is_some_and(|(notice, _)| notice.contains("macOS manages")) + })); +} + +#[cfg(target_os = "macos")] +#[gpui_kit::test] +fn unreadable_service_stores_stay_quiet_without_hiding_other_privacy_errors( + cx: &mut TestAppContext, +) { + use disktree_core::tree::{Draft, Tree}; + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + let mut tree = Draft::directory(".fseventsd"); + tree.read_error = true; + app.tree = Some(std::sync::Arc::new(Tree::from(tree))); + app.root_path = PathBuf::from("/System/Volumes/Data/.fseventsd"); + app.selected = None; + app.hovered = None; + app.progress.errors = 1; + app.progress.service_errors = 1; + cx.notify(); + }); + for access in [None, Some(false), Some(true)] { + update(&view, cx, |app, cx| { + app.full_disk_access = access; + cx.notify(); + }); + draw(cx); + assert!(cx.debug_bounds("macos-services").is_none()); + assert!(cx.debug_bounds("privacy-hint").is_none()); + } + update(&view, cx, |app, cx| { + app.full_disk_access = Some(false); + app.progress.errors += 1; + cx.notify(); + }); + draw(cx); + assert!(cx.debug_bounds("privacy-hint").is_some()); + assert!(cx.debug_bounds("macos-services").is_none()); +} + fn press(cx: &mut Window, keys: &str) { cx.simulate_keystrokes(keys); draw(cx); @@ -96,7 +453,7 @@ fn read( fn remote_indexing_draws_live_activity_and_the_sampled_directory( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); update(&view, cx, |app, _| { @@ -126,7 +483,7 @@ fn remote_indexing_draws_live_activity_and_the_sampled_directory( #[gpui_kit::test] fn loading_values_and_paths_do_not_move_the_sidebar(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); update(&view, cx, |app, _| { @@ -153,9 +510,12 @@ fn loading_values_and_paths_do_not_move_the_sidebar(cx: &mut TestAppContext) { assert!(cx.debug_bounds("scan-preview").is_some()); assert!(cx.debug_bounds("scan-reading").is_none()); update(&view, cx, |app, _| { + app.options.apparent_size = false; + app.progress.volume_used = Some(1000); app.progress.files = 99_999_999; app.progress.bytes = u64::MAX / 2; app.remote = Some("fixture-only".into()); + app.remote_progress.volume_used = Some(1000); app.remote_progress.directory = Some(PathBuf::from( "/a/very/long/directory/whose/text/must/not/move/the/layout", )); @@ -164,6 +524,12 @@ fn loading_values_and_paths_do_not_move_the_sidebar(cx: &mut TestAppContext) { assert_eq!(panel, cx.debug_bounds("indexing-progress").unwrap()); assert_eq!(files, cx.debug_bounds("indexing-files").unwrap()); assert_eq!(path, cx.debug_bounds("scan-directory").unwrap()); + update(&view, cx, |app, _| { + app.remote = None; + app.progress.finalizing = true; + }); + draw(cx); + assert_eq!(panel, cx.debug_bounds("indexing-progress").unwrap()); let preview = cx.debug_bounds("scan-preview").unwrap(); cx.simulate_click(preview.center(), gpui_kit::Modifiers::none()); press(cx, "space"); @@ -177,11 +543,140 @@ fn loading_values_and_paths_do_not_move_the_sidebar(cx: &mut TestAppContext) { assert!(read(&view, cx, |app| app.scan_preview.is_none())); } +#[gpui_kit::test] +fn scan_percentage_is_bounded_and_rejects_incompatible_totals( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, _| { + app.scan = Some(disktree_core::scan::ScanHandle::spawn( + temp.path().into(), + options(), + )); + app.options.apparent_size = false; + app.progress.volume_used = Some(1000); + for (bytes, expected) in [(0, 0.0), (450, 0.45), (2000, 0.99)] { + app.progress.bytes = bytes; + assert!((app.scan_fraction().unwrap() - expected).abs() < 0.001); + } + let allocated = app.options.clone(); + for incompatible in [ + ScanOptions { + apparent_size: true, + ..allocated + }, + ScanOptions { + one_filesystem: false, + ..allocated + }, + ScanOptions { + include_hidden: false, + ..allocated + }, + ScanOptions { + follow_links: true, + ..allocated + }, + ScanOptions { + max_depth: Some(1), + ..allocated + }, + ] { + app.options = incompatible; + assert!(app.scan_fraction().is_none()); + } + app.options = allocated; + app.progress.finalizing = true; + assert!(app.scan_fraction().is_none()); + app.progress.finalizing = false; + app.progress.volume_used = None; + assert!(app.scan_fraction().is_none()); + app.remote = Some("fixture-only".into()); + app.remote_progress.volume_used = Some(1000); + assert!((app.scan_fraction().unwrap() - 0.99).abs() < 0.001); + app.remote_progress.stage = + disktree_core::remote_progress::Stage::Finalizing; + assert!(app.scan_fraction().is_none()); + app.remote = None; + app.scan = None; + app.progress.volume_used = Some(1000); + assert!(app.scan_fraction().is_none()); + }); +} + +#[gpui_kit::test] +fn indexing_keeps_free_space_visible_in_short_zoomed_windows( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, _| { + app.tree = None; + app.scan = Some(disktree_core::scan::ScanHandle::spawn( + temp.path().into(), + options(), + )); + app.options.apparent_size = false; + app.progress.volume_used = Some(1000); + app.progress.bytes = 650; + app.space = Some(SpaceInfo { + total: 1000, + free: 350, + available: 350, + }); + }); + for (width, height, rem) in + [(1200., 700., 20.), (1400., 600., 24.), (1440., 900., 16.)] + { + cx.simulate_resize(gpui_kit::size(px(width), px(height))); + cx.update(|window, _| window.set_rem_size(px(rem))); + draw(cx); + draw(cx); + let disk = cx.debug_bounds("disk-section").unwrap(); + assert!( + disk.bottom() <= px(height), + "{width}×{height}, {rem}: {disk:?}" + ); + assert!(disk.size.height >= px(rem * 4.0), "{disk:?}"); + let scroll = cx.debug_bounds("side-panel-scroll").unwrap(); + assert!(scroll.bottom() <= disk.origin.y, "{scroll:?}, {disk:?}"); + let progress = cx.debug_bounds("indexing-progress").unwrap(); + cx.simulate_event(gpui_kit::ScrollWheelEvent { + position: scroll.center(), + delta: gpui_kit::ScrollDelta::Pixels(Point::new( + px(0.), + px(-1000.), + )), + modifiers: gpui_kit::Modifiers::none(), + touch_phase: gpui_kit::TouchPhase::Moved, + }); + draw(cx); + let scrolled = cx.debug_bounds("indexing-progress").unwrap(); + if progress.bottom() > scroll.bottom() { + assert!(scrolled.origin.y < progress.origin.y); + } + // The stop button is the last progress row; it must be reachable. + assert!( + scrolled.bottom() <= scroll.bottom(), + "{width}×{height}, rem {rem}: {scrolled:?}, viewport {scroll:?}" + ); + assert!(scrolled.bottom() > scroll.origin.y, "{scrolled:?}"); + assert_eq!(disk, cx.debug_bounds("disk-section").unwrap()); + update(&view, cx, |app, _| app.progress.finalizing = true); + draw(cx); + assert_eq!(disk, cx.debug_bounds("disk-section").unwrap()); + update(&view, cx, |app, _| app.progress.finalizing = false); + } +} + #[gpui_kit::test] fn narrow_indexing_keeps_a_preview_and_compact_progress_in_bounds( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); update(&view, cx, |app, _| { @@ -216,13 +711,13 @@ fn narrow_indexing_keeps_a_preview_and_compact_progress_in_bounds( fn startup_chooser_never_scans_before_explicit_acceptance( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let (view, cx) = cx.add_window_view(|_, cx| Disktree::choose(options(), 3, None, cx)); cx.run_until_parked(); draw(cx); assert!(cx.debug_bounds("choose-root-idle").is_some()); - assert!(cx.debug_bounds("source-host").is_some()); + assert!(cx.debug_bounds("source-switch").is_some()); read(&view, cx, |app| { assert!(app.awaiting_root); assert_eq!(app.scan_epoch, 0); @@ -236,9 +731,22 @@ fn startup_chooser_never_scans_before_explicit_acceptance( && app.scan.is_none())); } +#[gpui_kit::test] +fn title_brand_opens_source_picker(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + let brand = cx.debug_bounds("strip-brand").expect("title brand"); + cx.simulate_click(brand.center(), gpui_kit::Modifiers::none()); + draw(cx); + assert!(read(&view, cx, |app| app.volumes_open)); + assert!(cx.debug_bounds("source-picker").is_some()); +} + #[gpui_kit::test] fn entering_a_directory_scans_only_that_explicit_root(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); + cx.update(init); let selected = fixture(); let other = fixture(); let (view, cx) = @@ -279,11 +787,12 @@ fn entering_a_directory_scans_only_that_explicit_root(cx: &mut TestAppContext) { fn invalid_ssh_input_does_not_start_a_scan_or_change_the_source( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let (view, cx) = cx.add_window_view(|_, cx| Disktree::choose(options(), 3, None, cx)); cx.run_until_parked(); draw(cx); + choose_ssh(cx); let input = cx.debug_bounds("source-host").expect("host editor"); cx.simulate_click(input.center(), gpui_kit::Modifiers::none()); cx.simulate_input("invalid host"); @@ -302,17 +811,18 @@ fn invalid_ssh_input_does_not_start_a_scan_or_change_the_source( fn switching_from_remote_to_local_clears_machine_specific_marks( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); let target = fixture(); - let (view, cx) = view_over(temp.path(), cx); + let (view, cx, root) = remote_view_over(temp.path(), cx); + let junk = PathStyle::Posix.join(&root, "junk"); update(&view, cx, |app, cx| { app.remote = Some("old-source".into()); app.remote_identity = Some(disktree_core::identity::HostIdentity { hostname: "old-source".into(), machine_id: None, }); - let crumbs = app.crumbs_for_path(&temp.path().join("junk")).unwrap(); + let crumbs = app.crumbs_for_path(&junk).unwrap(); app.select(Some(crumbs), cx); app.toggle_mark_selected(cx); assert!(!app.marks.is_empty()); @@ -330,12 +840,12 @@ fn switching_from_remote_to_local_clears_machine_specific_marks( fn chooser_fits_a_small_window_at_large_interface_zoom( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let (_, cx) = cx.add_window_view(|_, cx| Disktree::choose(options(), 3, None, cx)); cx.run_until_parked(); cx.simulate_resize(gpui_kit::size(px(900.), px(600.))); - for rem in [16., 28.] { + for rem in [16., 28., 32.] { cx.update(|window, _| window.set_rem_size(px(rem))); draw(cx); let bounds = cx @@ -355,13 +865,14 @@ fn chooser_fits_a_small_window_at_large_interface_zoom( #[gpui_kit::test] fn editing_a_host_never_retargets_an_existing_scan(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); update(&view, cx, Disktree::open_volumes); cx.run_until_parked(); draw(cx); let before = read(&view, cx, |app| app.scan_epoch); + choose_ssh(cx); let input = cx.debug_bounds("source-host").unwrap(); cx.simulate_click(input.center(), gpui_kit::Modifiers::none()); cx.simulate_input("new-host-not-connected"); @@ -380,7 +891,7 @@ fn editing_a_host_never_retargets_an_existing_scan(cx: &mut TestAppContext) { fn a_directory_error_can_be_corrected_without_reconnecting( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); let (view, cx) = cx.add_window_view(|_, cx| Disktree::choose(options(), 3, None, cx)); @@ -400,7 +911,7 @@ fn a_directory_error_can_be_corrected_without_reconnecting( fn stale_local_discovery_cannot_overwrite_a_new_source_error( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let (view, cx) = cx.add_window_view(|_, cx| Disktree::choose(options(), 3, None, cx)); // The old discovery is still queued. The new host fails validation @@ -426,8 +937,18 @@ fn stale_local_discovery_cannot_overwrite_a_new_source_error( fn remote_root_acceptance_never_stats_the_path_locally( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); + // A Unix host sends a POSIX root on every client. Its absence here + // proves that accepting it skips local directory validation. + let remote_root = if cfg!(unix) { + temp.path().join("only-on-the-remote-host") + } else { + PathBuf::from("/srv/pwrdisk-fixture/only-on-the-remote-host") + }; + assert!( + PathStyle::Posix.is_absolute(&remote_root) && !remote_root.exists() + ); let (view, cx) = view_over(temp.path(), cx); update(&view, cx, |app, cx| { let crumbs = app.crumbs_for_path(&temp.path().join("junk")).unwrap(); @@ -440,7 +961,7 @@ fn remote_root_acceptance_never_stats_the_path_locally( app.finish_volume_listing( Ok(( vec![Volume { - point: PathBuf::from("/only-on-the-remote-host"), + point: remote_root.clone(), device: Some("/dev/remote-disk".into()), space: None, }], @@ -453,7 +974,8 @@ fn remote_root_acceptance_never_stats_the_path_locally( update(&view, cx, |app, cx| { app.choose_volume(cx); assert_eq!(app.remote.as_deref(), Some("-test-fixture")); - assert_eq!(app.root_path, PathBuf::from("/only-on-the-remote-host")); + assert_eq!(app.root_path, remote_root); + assert!(app.picker_error.is_none()); assert!(app.marks.is_empty() && app.remote_identity.is_none()); assert!( app.tree.is_none() @@ -472,31 +994,33 @@ fn remote_root_acceptance_never_stats_the_path_locally( fn repointing_an_ssh_alias_never_reuses_old_machine_marks( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); - let (view, cx) = view_over(temp.path(), cx); + let (view, cx, root) = remote_view_over(temp.path(), cx); + let junk = PathStyle::Posix.join(&root, "junk"); update(&view, cx, |app, cx| { let old = disktree_core::identity::HostIdentity { hostname: "same-name".into(), machine_id: Some("machine-a".into()), }; app.remote = Some("stable-alias".into()); - app.update_remote_identity(Some(old.clone())); - let crumbs = app.crumbs_for_path(&temp.path().join("junk")).unwrap(); + app.update_remote_identity(Some(old.clone()), cx); + let crumbs = app.crumbs_for_path(&junk).unwrap(); app.select(Some(crumbs), cx); app.toggle_mark_selected(cx); - app.update_remote_identity(Some(old.clone())); + app.update_remote_identity(Some(old.clone()), cx); assert!(!app.marks.is_empty(), "same machine keeps its marks"); - app.update_remote_identity(Some( - disktree_core::identity::HostIdentity { + app.update_remote_identity( + Some(disktree_core::identity::HostIdentity { hostname: old.hostname, machine_id: Some("machine-b".into()), - }, - )); + }), + cx, + ); assert!(app.marks.is_empty(), "same alias is not proof of identity"); app.toggle_mark_selected(cx); assert!(!app.marks.is_empty()); - app.update_remote_identity(None); + app.update_remote_identity(None, cx); assert!(app.marks.is_empty(), "lost identity also fails closed"); }); } @@ -505,12 +1029,13 @@ fn repointing_an_ssh_alias_never_reuses_old_machine_marks( fn remote_review_never_deletes_even_through_direct_actions( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); - let (view, cx) = view_over(temp.path(), cx); + let (view, cx, root) = remote_view_over(temp.path(), cx); + let junk = PathStyle::Posix.join(&root, "junk"); update(&view, cx, |app, cx| { app.remote = Some("dev".into()); - let crumbs = app.crumbs_for_path(&temp.path().join("junk")).unwrap(); + let crumbs = app.crumbs_for_path(&junk).unwrap(); app.select(Some(crumbs), cx); app.toggle_mark_selected(cx); app.screen = Screen::Review; @@ -520,7 +1045,7 @@ fn remote_review_never_deletes_even_through_direct_actions( press(cx, "p"); press(cx, "m"); update(&view, cx, |app, cx| { - app.commit(cx); + app.commit(false, cx); app.confirm_delete(cx); app.begin_removal(cx); assert!(!app.confirm_open); @@ -546,7 +1071,7 @@ fn remote_review_never_deletes_even_through_direct_actions( fn a_failed_remote_scan_stops_showing_the_reading_screen( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); update(&view, cx, |app, _| { @@ -563,7 +1088,7 @@ fn a_failed_remote_scan_stops_showing_the_reading_screen( #[gpui_kit::test] fn the_window_draws_a_treemap_with_tiles(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); draw(cx); @@ -587,7 +1112,7 @@ fn the_window_draws_a_treemap_with_tiles(cx: &mut TestAppContext) { fn the_first_scan_shows_what_it_is_doing_then_the_treemap( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); let root = temp.path().to_path_buf(); // Through the real constructor, so this is the path every first run takes. @@ -608,7 +1133,7 @@ fn the_first_scan_shows_what_it_is_doing_then_the_treemap( app.layout().map(<[Tile]>::len).unwrap_or_default(), app.selected.is_some(), app.tree().is_some_and(|tree| { - tree.children.iter().any(|c| c.name.starts_with('.')) + tree.children().iter().any(|c| c.name().starts_with('.')) }), ) }); @@ -622,7 +1147,7 @@ fn the_first_scan_shows_what_it_is_doing_then_the_treemap( #[gpui_kit::test] fn keys_walk_the_tree_and_mark_what_is_selected(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); draw(cx); @@ -631,7 +1156,7 @@ fn keys_walk_the_tree_and_mark_what_is_selected(cx: &mut TestAppContext) { let (selected, name) = read(&view, cx, |app| { ( app.selected.clone(), - app.node_at(&[0]).map(|node| node.name.to_string()), + app.node_at(&[0]).map(|node| node.name().to_string()), ) }); assert_eq!(selected, Some(vec![0])); @@ -662,7 +1187,7 @@ fn keys_walk_the_tree_and_mark_what_is_selected(cx: &mut TestAppContext) { fn a_permanent_deletion_asks_in_an_alert_dialog_then_removes( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); draw(cx); @@ -674,9 +1199,9 @@ fn a_permanent_deletion_asks_in_an_alert_dialog_then_removes( let junk = app .tree() .and_then(|tree| { - tree.children + tree.children() .iter() - .position(|child| &*child.name == "junk") + .position(|child| child.name() == "junk") .map(|index| vec![index]) }) .expect("the junk directory"); @@ -719,7 +1244,7 @@ fn a_permanent_deletion_asks_in_an_alert_dialog_then_removes( assert!(finished, "the removal finished"); draw(cx); - let summary = read(&view, cx, |app| app.run_summary.clone()); + let summary = read(&view, cx, |app| app.run_list.totals()); assert_eq!(summary.removed, 1, "{summary:?}"); assert_eq!(summary.failed, 0, "{summary:?}"); assert!( @@ -744,7 +1269,7 @@ fn a_permanent_deletion_asks_in_an_alert_dialog_then_removes( fn a_parents_name_gets_its_own_band_above_its_children( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); draw(cx); @@ -794,7 +1319,7 @@ fn a_parents_name_gets_its_own_band_above_its_children( #[gpui_kit::test] fn hovering_reports_the_tile_under_the_pointer(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); draw(cx); @@ -840,9 +1365,154 @@ fn hovering_reports_the_tile_under_the_pointer(cx: &mut TestAppContext) { assert_eq!(hovered.as_deref(), Some(biggest.as_slice())); } +/// Press the left button over the drawn tile for `path`, as the +/// `count`th press of a click sequence, and draw the frame after it. +fn press_on( + view: &Entity, + cx: &mut Window, + path: &Path, + count: usize, +) { + let at = update(view, cx, |app, _| { + let crumbs = app.crumbs_for_path(path).expect("a path in the tree"); + let rect = app.tile_rect(&crumbs).expect("the tile is drawn"); + let screen = app.view.project(rect); + let (x, y) = (screen.x + screen.w / 2.0, screen.y + screen.h / 2.0); + assert_eq!( + app.tile_at(x, y), + Some(crumbs), + "the press lands on that tile" + ); + let origin = app.treemap_origin.get(); + Point::new(origin.x + px(x), origin.y + px(y)) + }); + cx.simulate_event(gpui_kit::MouseDownEvent { + button: gpui_kit::MouseButton::Left, + position: at, + modifiers: gpui_kit::Modifiers::none(), + click_count: count, + first_mouse: false, + }); + cx.simulate_event(gpui_kit::MouseUpEvent { + button: gpui_kit::MouseButton::Left, + position: at, + modifiers: gpui_kit::Modifiers::none(), + click_count: count, + }); + draw(cx); +} + +/// Where the window is and what is selected, as paths. +fn place(view: &Entity, cx: &Window) -> (PathBuf, Option) { + read(view, cx, |app| { + ( + app.current_path(), + app.selected + .as_deref() + .and_then(|crumbs| app.path_at(crumbs)), + ) + }) +} + +#[gpui_kit::test] +fn a_double_click_on_a_nested_tile_opens_one_level(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + let more = temp.path().join("junk/deeper/more.bin"); + + // Press 1 selects the deepest tile under the pointer and opens nothing. + press_on(&view, cx, &more, 1); + assert_eq!( + place(&view, cx), + (temp.path().to_path_buf(), Some(more.clone())) + ); + + // Press 2 opens one level toward it, not the three it is drawn down. + press_on(&view, cx, &more, 2); + assert_eq!( + place(&view, cx), + (temp.path().join("junk"), Some(more.clone())), + "one level, with the tile still selected" + ); + + // A triple click is still the same gesture. + press_on(&view, cx, &more, 3); + assert_eq!(place(&view, cx).0, temp.path().join("junk")); + + // A new click on the selection opens the next level. + press_on(&view, cx, &more, 1); + assert_eq!( + place(&view, cx), + (temp.path().join("junk/deeper"), Some(more)) + ); +} + +#[gpui_kit::test] +fn a_double_click_on_the_selection_opens_one_level(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + let more = temp.path().join("junk/deeper/more.bin"); + + // Click once: it is selected, and the hover card says what a second + // click does. + press_on(&view, cx, &more, 1); + let opens = update(&view, cx, |app, _| { + app.hovered = app.selected.clone(); + app.click_opens_hovered() + }); + assert!(opens, "a click on the selection opens"); + + // Then double-click it. Press 1 opens a level; press 2 lands on the + // level press 1 opened and used to open whatever was under it there. + press_on(&view, cx, &more, 1); + assert_eq!(place(&view, cx).0, temp.path().join("junk")); + let at_junk = read(&view, cx, |app| app.crumbs.clone()); + cx.simulate_event(gpui_kit::MouseDownEvent { + button: gpui_kit::MouseButton::Left, + position: read(&view, cx, |app| { + let origin = app.treemap_origin.get(); + let size = app.treemap_size.get(); + Point::new( + origin.x + size.width / 2.0, + origin.y + size.height / 2.0, + ) + }), + modifiers: gpui_kit::Modifiers::none(), + click_count: 2, + first_mouse: false, + }); + draw(cx); + assert_eq!( + read(&view, cx, |app| app.crumbs.clone()), + at_junk, + "the second press of the gesture is ignored" + ); +} + +#[gpui_kit::test] +fn a_click_on_a_file_at_the_top_selects_it_and_opens_nothing( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + std::fs::write(temp.path().join("top.bin"), vec![b'x'; 150_000]) + .expect("write"); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + let top = temp.path().join("top.bin"); + press_on(&view, cx, &top, 1); + press_on(&view, cx, &top, 2); + press_on(&view, cx, &top, 1); + assert_eq!(place(&view, cx), (temp.path().to_path_buf(), Some(top))); +} + #[gpui_kit::test] fn right_click_selects_the_tile_and_reveals_it(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); draw(cx); @@ -890,10 +1560,7 @@ fn right_click_selects_the_tile_and_reveals_it(cx: &mut TestAppContext) { draw(cx); let (selected, notice) = read(&view, cx, |app| { - ( - app.selected.clone(), - app.notice.as_ref().map(|(text, _)| text.clone()), - ) + (app.selected.clone(), app.notice().map(|(text, _)| text)) }); assert_eq!(selected, Some(target), "the clicked tile is selected"); assert!( @@ -902,11 +1569,62 @@ fn right_click_selects_the_tile_and_reveals_it(cx: &mut TestAppContext) { ); } +#[gpui_kit::test] +fn find_field_never_draws_over_the_legend(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (_view, cx) = view_over(temp.path(), cx); + draw(cx); + press(cx, "/"); + // Matches bring the longest hint, "enter shows only these". + cx.simulate_input("BLOB"); + cx.run_until_parked(); + // The minimum window width up to a wide one, at 100%, 150% and 200%. + for width in [900., 1100., 1440.] { + for rem in [16., 24., 32.] { + cx.simulate_resize(gpui_kit::size(px(width), px(900.))); + cx.update(|window, _| window.set_rem_size(px(rem))); + draw(cx); + let at = format!("{width}x900 at rem {rem}"); + let field = cx.debug_bounds("find-field").expect("find drawn"); + let legend = cx.debug_bounds("legend").expect("legend drawn"); + // Half a pixel for rounding where two edges meet. The field + // clips what it holds, so its own bounds are what is drawn. + // The legend has its own row under the field's. + assert!( + field.bottom() <= legend.top() + px(0.5) + || field.right() <= legend.left() + px(0.5), + "{at}: field {field:?} overlaps legend {legend:?}" + ); + assert!( + field.right() <= px(width) + px(0.5), + "{at}: the field stays in the window: {field:?}" + ); + } + } + // Where the overlap was seen, and narrower: the whole hint reads, and + // the legend, on its own row now, is still drawn. + for width in [1000., 1440.] { + cx.simulate_resize(gpui_kit::size(px(width), px(900.))); + cx.update(|window, _| window.set_rem_size(px(16.))); + draw(cx); + let hint = cx.debug_bounds("find-hint").expect("hint drawn"); + let field = cx.debug_bounds("find-field").expect("find drawn"); + let legend = cx.debug_bounds("legend").expect("legend drawn"); + assert!( + hint.size.width > px(100.) + && hint.right() <= field.right() + px(0.5), + "{width}: the whole hint fits in the field: {hint:?} {field:?}" + ); + assert!(legend.size.width > px(0.), "{width}: legend {legend:?}"); + } +} + #[gpui_kit::test] fn typing_filters_live_and_enter_shows_only_the_matches( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); draw(cx); @@ -916,7 +1634,7 @@ fn typing_filters_live_and_enter_shows_only_the_matches( tiles .iter() .filter_map(|tile| app.node_at(tile.crumbs())) - .map(|node| node.name.to_string()) + .map(|node| node.name().to_string()) .collect::>() }) }; @@ -930,9 +1648,9 @@ fn typing_filters_live_and_enter_shows_only_the_matches( let (count, applied, keep_filtered) = read(&view, cx, |app| { let matches = app.matches.as_deref().expect("matching as it is typed"); let keep = app.tree().and_then(|tree| { - tree.children + tree.children() .iter() - .position(|child| &*child.name == "keep") + .position(|child| child.name() == "keep") }); ( matches.count, @@ -945,6 +1663,30 @@ fn typing_filters_live_and_enter_shows_only_the_matches( assert!(keep_filtered, "keep holds no blob"); // Dimmed, not hidden: a non-match is still drawn while typing. assert!(names_drawn(&view, cx).contains(&"deeper".to_string())); + // A match says so without colour (WCAG 1.4.1): the part of its name the + // find text matched is underlined, whatever case it was typed in. A + // non-match keeps its plain name, with no word added to every tile. + let mosaic = update(&view, cx, |app, _| app.prepare()); + let matched: Vec<_> = mosaic + .labels + .iter() + .filter_map(|label| Some((label, label.found.clone()?))) + .collect(); + assert!(!matched.is_empty(), "a blob is labelled"); + for (label, found) in &matched { + assert_eq!(label.text, "blob.bin"); + assert_eq!(&label.text[found.clone()], "blob"); + } + let unmatched: Vec<_> = mosaic + .labels + .iter() + .filter(|label| label.found.is_none()) + .map(|label| label.text.as_str()) + .collect(); + assert!( + unmatched.iter().all(|text| !text.starts_with('[')), + "{unmatched:?}" + ); // Enter: only the matches, and the largest selected for marking. press(cx, "enter"); @@ -975,7 +1717,7 @@ fn typing_filters_live_and_enter_shows_only_the_matches( #[gpui_kit::test] fn the_help_overlay_opens_and_closes(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); draw(cx); @@ -986,1374 +1728,9671 @@ fn the_help_overlay_opens_and_closes(cx: &mut TestAppContext) { assert!(!read(&view, cx, |app| app.show_help)); } +/// No dialog draws the treemap's hover card behind it. #[gpui_kit::test] -fn the_volume_picker_opens_moves_and_closes(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); +fn the_tooltip_hides_under_an_overlay(cx: &mut TestAppContext) { + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); draw(cx); + let origin = read(&view, cx, |app| app.treemap_origin.get()); + let at = origin + Point::new(px(40.), px(40.)); + cx.simulate_mouse_move(at, None, gpui_kit::Modifiers::default()); + draw(cx); + assert!(cx.debug_bounds("cursor-tooltip").is_some(), "a tooltip"); + + // The overlays' backdrop takes the mouse, so the treemap drops its + // hover; the volumes and delete dialogs leave it, and rely on the rule. + let dialogs: [OpenOverlay; 2] = + [|app| app.show_help = true, |app| app.volumes_open = true]; + for open in dialogs { + update(&view, cx, |app, cx| { + open(app); + cx.notify(); + }); + draw(cx); + assert!(cx.debug_bounds("cursor-tooltip").is_none(), "hidden"); + update(&view, cx, |app, cx| { + app.show_help = false; + app.volumes_open = false; + cx.notify(); + }); + cx.simulate_mouse_move(at, None, gpui_kit::Modifiers::default()); + draw(cx); + assert!(cx.debug_bounds("cursor-tooltip").is_some(), "back"); + } +} - // The picker lists volumes and draws them without panicking; Escape - // leaves the scan where it was. - press(cx, "v"); - assert!(read(&view, cx, |app| app.volumes_open)); +/// Help › Connect an AI Agent (MCP)… opens Settings › Agents (MCP), and +/// leaves the main window as it was. +#[gpui_kit::test] +fn the_menu_opens_settings_agents(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); draw(cx); - assert!(cx.debug_bounds("disktree-root").is_some()); - let before = read(&view, cx, |app| app.root_path.clone()); - press(cx, "down"); - press(cx, "up"); - press(cx, "escape"); - assert!(!read(&view, cx, |app| app.volumes_open)); - assert_eq!(read(&view, cx, |app| app.root_path.clone()), before); + cx.dispatch_action(crate::app_menu::ConnectAgent); + cx.run_until_parked(); + assert_eq!(settings_pane(cx), Some(crate::settings::Pane::Agents)); + assert!(read(&view, cx, |app| !app.has_modal())); } -/// Enter must reach the picker even when its dialog owns keyboard focus. +/// The pane Settings shows, if it is open. +fn settings_pane(cx: &mut VisualTestContext) -> Option { + cx.update(|_, cx| { + crate::aux_window::find::(cx, |_| true) + .and_then(|handle| handle.read(cx).ok().map(|view| view.pane)) + }) +} + +/// Opens one overlay, for the cases of `overlays_fit_a_short_window`. +type OpenOverlay = fn(&mut Disktree); + +/// A window shorter than an overlay keeps the card, and its Done, inside +/// the window: the list scrolls instead of spilling past the bottom. #[gpui_kit::test] -fn enter_in_the_focused_volume_picker_scans_the_selected_root( +fn overlays_fit_a_short_window(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(900.), px(420.))); + let cases: [(&str, OpenOverlay); 1] = + [("help-overlay", |app| app.show_help = true)]; + for (card, open) in cases { + update(&view, cx, |app, cx| { + app.show_help = false; + open(app); + cx.notify(); + }); + draw(cx); + draw(cx); + let window = cx.update(|window, _| window.viewport_size()); + let bounds = cx.debug_bounds(card).expect("card drawn"); + let done = cx.debug_bounds("overlay-done").expect("Done drawn"); + assert!( + bounds.bottom() <= window.height, + "{card} ends at {:?}, past {:?}", + bounds.bottom(), + window.height + ); + assert!(done.bottom() <= bounds.bottom(), "{card}: Done inside"); + } +} + +#[gpui_kit::test] +fn audit_help_contains_navigation_and_restores_keyboard_operation( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); - let target = temp.path().join("junk"); let (view, cx) = view_over(temp.path(), cx); - update(&view, cx, |app, _| { - app.volumes = vec![disktree_core::space::Volume { - point: target.clone(), - device: None, - space: None, - }]; - app.volume_highlight = 0; - app.volumes_open = true; + press(cx, "n"); + let selected = read(&view, cx, |app| app.selected.clone()); + let root = read(&view, cx, |app| app.crumbs.clone()); + press(cx, "?"); + for key in ["right", "enter", "space", "c", "tab", "shift-tab"] { + press(cx, key); + } + read(&view, cx, |app| { + assert!(app.show_help); + assert_eq!(app.selected, selected); + assert_eq!(app.crumbs, root); + assert!(app.marks.is_empty()); + assert_eq!(app.screen, Screen::Explore); }); - let focus = read(&view, cx, |app| app.confirm_focus.clone()); - cx.update(|window, cx| window.focus(&focus, cx)); + press(cx, "escape"); + let focus = read(&view, cx, |app| app.focus.clone()); + assert!(cx.update(|window, _| focus.is_focused(window))); + press(cx, "space"); + assert_eq!(read(&view, cx, |app| app.marks.len()), 1); +} + +#[gpui_kit::test] +fn audit_source_picker_contains_shortcuts_and_restores_focus( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); draw(cx); - assert!(!read(&view, cx, Disktree::can_start_over)); - press(cx, "enter"); - assert!(!read(&view, cx, |app| app.volumes_open)); - assert_eq!(read(&view, cx, |app| app.root_path.clone()), target); - finish_scan(&view, cx); - assert!(read(&view, cx, |app| app.tree().is_some())); + let root = read(&view, cx, |app| app.root_path.clone()); + let epoch = read(&view, cx, |app| app.scan_epoch); + press(cx, "v"); + for key in ["space", "c", "/", "r", "tab", "shift-tab"] { + press(cx, key); + } + read(&view, cx, |app| { + assert!(app.volumes_open); + assert_eq!(app.screen, Screen::Explore); + assert_eq!(app.root_path, root); + assert_eq!(app.scan_epoch, epoch); + assert!(app.marks.is_empty()); + assert!(!app.find_open); + }); + press(cx, "escape"); + let focus = read(&view, cx, |app| app.focus.clone()); + assert!(cx.update(|window, _| focus.is_focused(window))); + press(cx, "tab"); + assert!(read(&view, cx, |app| app.selected.is_some())); } #[gpui_kit::test] -fn the_volume_picker_is_centred_and_still_dismisses_from_outside( +fn audit_confirmation_contains_shortcuts_and_cancel_restores_review( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); - // Fixed rows, so this is about where the popup lands and not about which - // disks the machine running the test happens to have. update(&view, cx, |app, cx| { - app.volumes = vec![ - Volume { - point: PathBuf::from("/one"), - device: Some("/dev/one".into()), - space: Some(SpaceInfo { - total: 1_000, - free: 500, - available: 400, - }), - }, - Volume { - point: PathBuf::from("/two"), - device: None, - space: None, - }, - ]; - app.volumes_open = true; - cx.notify(); + app.removal_mode = RemovalMode::Permanent; + let junk = app.tree().unwrap().find("junk").unwrap().0; + app.select(Some(junk.clone()), cx); + app.toggle_mark(&junk, cx); }); - draw(cx); + press(cx, "c"); + // Only the harness opens this dialog; no confirmation action is sent. + press(cx, "enter"); + for key in ["c", "r", "p", "m", "!", "tab", "shift-tab"] { + press(cx, key); + } + read(&view, cx, |app| { + assert!(app.confirm_open); + assert_eq!(app.screen, Screen::Review); + assert_eq!(app.removal_mode, RemovalMode::Permanent); + assert_eq!(app.marks.len(), 1); + assert!(app.run.is_none()); + }); + let dialog = read(&view, cx, |app| app.confirm_focus.clone()); + assert!(cx.update(|window, cx| dialog.contains_focused(window, cx))); + press(cx, "escape"); + let focus = read(&view, cx, |app| app.focus.clone()); + assert!(cx.update(|window, _| focus.is_focused(window))); + assert!(!read(&view, cx, |app| app.confirm_open)); + assert!(temp.path().join("junk/blob.bin").exists()); + assert!(temp.path().join("keep/notes.txt").exists()); +} - let viewport = cx.update(|window, _| window.viewport_size()); - let rows = cx.debug_bounds("volume-rows").expect("the rows are drawn"); - let centre = rows.center(); - assert!( - (centre.x - viewport.width / 2.0).abs() < px(4.), - "the popup is not centred across: {centre:?} in {viewport:?}" - ); +/// Settings › Updates draws, keeps the panel's keys and saves the channel +/// picked. A test binary is no Velopack install, so it offers no restart; +/// nothing reaches the network. +#[gpui_kit::test] +fn settings_updates_picks_a_channel_and_keeps_the_keys( + cx: &mut TestAppContext, +) { + use crate::settings::{Pane, SettingsWindow}; + use crate::update_channel::{Slot, UpdateSettings}; + + cx.update(init); + let saved_in = tempfile::TempDir::new().expect("tempdir"); + let (view, cx) = cx.add_window_view(|window, cx| { + let view = SettingsWindow::new(Pane::Updates, cx); + window.focus(&cx.focus_handle(), cx); + view + }); + let root = cx.update(|_, cx| { + view.update(cx, |view, cx| { + view.updates_dir = Some(saved_in.path().to_path_buf()); + cx.focus_handle() + }) + }); + drop(root); + draw(cx); + let focus = cx.update(|window, cx| { + let _ = window; + view.read(cx).pane + }); + assert_eq!(focus, Pane::Updates); + assert!(cx.debug_bounds(crate::settings::ROOT_ID).is_some()); + assert!(cx.debug_bounds("update-slot-3").is_some()); + assert!(cx.debug_bounds(crate::settings::CHECK_ID).is_some()); assert!( - (centre.y - viewport.height / 2.0).abs() < px(150.), - "the popup is not centred down: {centre:?} in {viewport:?}" + cx.debug_bounds(crate::settings::RESTART_ID).is_none(), + "nothing is downloaded, so there is nothing to restart into" ); - // The wrapper that centres the popup must not swallow the backdrop's - // clicks: a click in the corner, outside the popup, still closes it. + // The keys, as the in-window panel had them, once the pane has focus. + let slot = cx.debug_bounds("update-slot-0").expect("first row"); + cx.simulate_click(slot.center(), gpui_kit::Modifiers::none()); + draw(cx); + // Latest sits beside Prerelease in the grid. + press(cx, "right"); + press(cx, "enter"); + assert_eq!( + crate::updater::selection().resolve("0.12.0"), + Slot::STABLE_PRERELEASE + ); + let saved = + std::fs::read_to_string(saved_in.path().join("update-channel.json")) + .expect("the pick is saved"); + assert!(saved.contains("\"prerelease\""), "{saved}"); + + // Ctrl+PageDown walks the panes; every one draws. Safety saves only in the fixture. + press(cx, "ctrl-pagedown"); + // One control of six equal segments, 1 5 10 25 50 100: 10% is third. + let limits = cx.debug_bounds("safety-limit").expect("the limit control"); cx.simulate_click( - gpui_kit::point(px(4.), px(4.)), + gpui_kit::point( + limits.origin.x + limits.size.width * 2.5 / 6., + limits.center().y, + ), gpui_kit::Modifiers::none(), ); draw(cx); + assert_eq!( + crate::safety::load(Some(saved_in.path())) + .expect("saved limit") + .percent(), + 10 + ); + press(cx, "ctrl-pagedown"); + assert_eq!( + view.read_with(cx, |settings, _| settings.pane), + Pane::Agents + ); + assert!(cx.debug_bounds("agents-status").is_some()); + press(cx, "ctrl-pagedown"); assert!( - !read(&view, cx, |app| app.volumes_open), - "clicking outside the picker closes it" + cx.debug_bounds(crate::settings::COPY_DIAGNOSTICS_ID) + .is_some() ); + press(cx, "ctrl-pagedown"); + assert_eq!(view.read_with(cx, |settings, _| settings.pane), Pane::About); + // The header leads the pane, and its Copy build info sits at the + // right of the same card. + let header = cx + .debug_bounds(crate::settings::ABOUT_HEADER_ID) + .expect("About's header"); + let copy = cx + .debug_bounds(crate::settings::COPY_BUILD_ID) + .expect("Copy build info"); + assert!(header.contains(©.center()), "{header:?} {copy:?}"); + assert!(copy.center().x > header.center().x, "{header:?} {copy:?}"); + let line = cx + .debug_bounds(crate::settings::ABOUT_BUILD_LINE_ID) + .expect("the build line"); + assert!(header.contains(&line.center()), "{header:?} {line:?}"); + assert!(line.right() < copy.left(), "{line:?} {copy:?}"); + let notices = cx.debug_bounds("about-notices").expect("the notices"); + assert!(header.bottom() < notices.top(), "{header:?} {notices:?}"); + + // The selection is process-wide; leave the default for other tests. + let _ = crate::updater::set_selection(UpdateSettings::default(), None); } +/// Settings › Safety reads the saved limit when the pane opens and after +/// a pick is saved, not on every frame, and shows the pick once saved. #[gpui_kit::test] -fn showing_a_tile_that_is_gone_says_so_instead(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); - let temp = fixture(); - let (view, cx) = view_over(temp.path(), cx); +fn settings_safety_reads_the_limit_once_and_shows_a_saved_pick( + cx: &mut TestAppContext, +) { + use crate::settings::{Pane, SettingsWindow, work}; + use disktree_core::removal_limit::Limit; + + cx.update(init); + let saved_in = tempfile::TempDir::new().expect("tempdir"); + crate::safety::save( + Some(saved_in.path()), + Limit::new(25).expect("a limit"), + ) + .expect("save the starting limit"); + let (view, cx) = cx.add_window_view(|window, cx| { + let view = SettingsWindow::new(Pane::Updates, cx); + window.focus(&cx.focus_handle(), cx); + view + }); + cx.update(|_, cx| { + view.update(cx, |view, _| { + view.updates_dir = Some(saved_in.path().to_path_buf()); + }); + }); + let shown = |cx: &mut Window| { + view.read_with(cx, |view, _| { + view.safety + .as_ref() + .ok() + .and_then(|policy| policy.limit.map(Limit::percent)) + }) + }; draw(cx); + work::SAFETY_LOADS.set(0); + click_on(cx, Pane::Safety.nav_id()); + assert_eq!(view.read_with(cx, |view, _| view.pane), Pane::Safety); + for _ in 0..5 { + draw(cx); + } + assert_eq!(shown(cx), Some(25)); + assert_eq!(work::SAFETY_LOADS.get(), 1, "opening the pane reads it"); - // The selection is .cache, the largest; take it away behind the tree. - std::fs::remove_dir_all(temp.path().join(".cache")).expect("remove"); - press(cx, "o"); - let notice = read(&view, cx, |app| app.notice.clone()); - let (message, _) = notice.expect("a notice"); - assert!(message.contains("no longer on disk"), "{message}"); + // 1 5 10 25 50 100: 10% is the third segment. + let limits = cx.debug_bounds("safety-limit").expect("the limit control"); + cx.simulate_click( + gpui_kit::point( + limits.origin.x + limits.size.width * 2.5 / 6., + limits.center().y, + ), + gpui_kit::Modifiers::none(), + ); + for _ in 0..5 { + draw(cx); + } + assert_eq!(shown(cx), Some(10), "the pane shows the pick once saved"); + assert_eq!(work::SAFETY_LOADS.get(), 2, "and read it back once"); + assert_eq!( + crate::safety::load(Some(saved_in.path())) + .expect("saved limit") + .percent(), + 10 + ); } -#[gpui_kit::test] -fn command_chords_are_not_read_as_plain_letters(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); - let temp = fixture(); - let (view, cx) = view_over(temp.path(), cx); - draw(cx); +/// Three checkouts side by side: each a worktree's `.git` file and some +/// data, largest first, so the first is selected when the window opens. +fn checkouts() -> tempfile::TempDir { + let temp = tempfile::TempDir::new().expect("tempdir"); + for (name, bytes) in + [("alpha", 300_000), ("beta", 200_000), ("gamma", 100_000)] + { + let dir = temp.path().join(name); + std::fs::create_dir_all(&dir).expect("mkdir"); + std::fs::write(dir.join(".git"), "gitdir: elsewhere").expect("write"); + std::fs::write(dir.join("data.bin"), vec![b'x'; bytes]).expect("write"); + } + temp +} - // ⌘P and ⌘D are the menu bar's or nobody's; read as `p` and `d` they - // would hide the selection and re-scan. - let shown = read(&view, cx, |app| app.show_selection); - press(cx, "cmd-p cmd-d"); - assert_eq!(read(&view, cx, |app| app.show_selection), shown); - assert!(read(&view, cx, |app| app.options.apparent_size)); - press(cx, "p"); - assert_eq!(read(&view, cx, |app| app.show_selection), !shown); +/// Give the window a probe that counts its runs and gives `answer` for +/// every checkout, in place of git. Anything the real one started is +/// forgotten. +fn count_probes( + view: &Entity, + cx: &mut Window, + answer: crate::git_store::Probe, +) -> std::sync::Arc { + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + let runs = Arc::new(AtomicUsize::new(0)); + update(view, cx, |app, _| { + let counter = runs.clone(); + app.git_probe = Arc::new(move |_, _| { + counter.fetch_add(1, Ordering::SeqCst); + crate::git_store::ready(answer.clone()) + }); + app.git.clear(); + }); + cx.run_until_parked(); + runs } -#[gpui_kit::test] -fn the_treemap_zooms_with_the_wheel_and_resets(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); - let temp = fixture(); - let (view, cx) = view_over(temp.path(), cx); - draw(cx); +fn clean_checkout() -> crate::git::GitState { + crate::git::GitState { + changed: Some(0), + unpushed: Some(0), + ..crate::git::GitState::default() + } +} - let middle = read(&view, cx, |app| { - let size = app.treemap_size.get(); - Point::new(size.width / 2.0, size.height / 2.0) - }); - update(&view, cx, |app, cx| { - app.zoom_at(middle.x.as_f32(), middle.y.as_f32(), 1.5, false, cx); +/// Move the pointer onto the drawn tile for the directory `path`: onto its +/// name band when it has children, where no child tile is. +fn hover_on(view: &Entity, cx: &mut Window, path: &Path) { + let at = update(view, cx, |app, _| { + let crumbs = app.crumbs_for_path(path).expect("a path in the tree"); + let tile = app + .layout() + .and_then(|tiles| { + tiles.iter().find(|tile| tile.crumbs() == crumbs).cloned() + }) + .expect("the tile is drawn"); + let screen = app.view.project(tile.header.unwrap_or(tile.rect)); + let (x, y) = (screen.x + screen.w / 2.0, screen.y + screen.h / 2.0); + assert_eq!(app.tile_at(x, y), Some(crumbs), "the pointer is on it"); + let origin = app.treemap_origin.get(); + Point::new(origin.x + px(x), origin.y + px(y)) }); - let zoomed = read(&view, cx, |app| app.view.scale); - assert!(zoomed > 1.0, "scale after zooming: {zoomed}"); + cx.simulate_mouse_move(at, None, gpui_kit::Modifiers::default()); + draw(cx); +} - press(cx, "0"); - assert!((read(&view, cx, |app| app.view.scale) - 1.0).abs() < f32::EPSILON); +fn probe_runs(runs: &std::sync::atomic::AtomicUsize) -> usize { + runs.load(std::sync::atomic::Ordering::SeqCst) } -/// Both appearances Omarchy ships must draw: the palette is derived from the -/// theme, so a light theme is a real second configuration. +/// Sweeping the pointer across checkouts runs no git; resting on one runs +/// it once, and the panel shows the answer. #[gpui_kit::test] -fn both_appearances_draw(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); - let temp = fixture(); +fn a_sweep_over_checkouts_asks_nothing_and_a_rest_asks_once( + cx: &mut TestAppContext, +) { + use crate::git_store::{DWELL, Probe, Shown}; + + cx.update(init); + let temp = checkouts(); let (view, cx) = view_over(temp.path(), cx); - for theme in [Theme::tokyo_night(), Theme::flexoki_light()] { - view.update(cx, |_, cx| { - theme.clone().apply(cx); - cx.notify(); - }); - draw(cx); - assert!(cx.debug_bounds("disktree-root").is_some()); + cx.simulate_resize(gpui_kit::size(px(1400.), px(900.))); + // Nothing selected, so only the pointer chooses what the panel shows. + press(cx, "escape"); + assert_eq!(read(&view, cx, |app| app.selected.clone()), None); + let runs = count_probes(&view, cx, Probe::Known(clean_checkout())); + + for name in ["alpha", "beta", "gamma", "alpha", "beta"] { + hover_on(&view, cx, &temp.path().join(name)); + cx.run_until_parked(); } -} + assert_eq!(probe_runs(&runs), 0, "a sweep asks nothing"); -/// A view built without a scan keeps working: the screens must not assume a -/// walk is in flight. + // The pointer stays on beta. + cx.executor().advance_clock(DWELL); + cx.run_until_parked(); + draw(cx); + cx.run_until_parked(); + assert_eq!(probe_runs(&runs), 1, "resting asks once"); + let beta = temp.path().join("beta"); + assert!(read(&view, cx, |app| { + app.git.shown(&beta) == Shown::Answer(&Probe::Known(clean_checkout())) + })); + + // Resting longer asks nothing more. + for _ in 0..3 { + cx.executor().advance_clock(DWELL); + cx.run_until_parked(); + draw(cx); + cx.run_until_parked(); + } + assert_eq!(probe_runs(&runs), 1); +} + +/// Selecting a checkout runs git once at once; selecting it again reads +/// the answer instead. #[gpui_kit::test] -fn a_view_without_flags_or_marks_still_draws(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); - let temp = fixture(); +fn selecting_a_checkout_asks_once_and_then_reads_the_answer( + cx: &mut TestAppContext, +) { + use crate::git_store::Probe; + + cx.update(init); + let temp = checkouts(); let (view, cx) = view_over(temp.path(), cx); - update(&view, cx, |app, cx| { - app.screen = Screen::Review; - cx.notify(); - }); + cx.simulate_resize(gpui_kit::size(px(1400.), px(900.))); + let runs = count_probes(&view, cx, Probe::Known(clean_checkout())); + let alpha = temp.path().join("alpha"); + let beta = temp.path().join("beta"); + let crumbs = |path: &Path| { + read(&view, cx, |app| app.crumbs_for_path(path)).expect("in the tree") + }; + let (alpha_at, beta_at) = (crumbs(&alpha), crumbs(&beta)); + assert_eq!( + read(&view, cx, |app| app.selected.clone()), + Some(alpha_at.clone()), + "the largest is selected" + ); + + for _ in 0..5 { + draw(cx); + cx.run_until_parked(); + } + assert_eq!(probe_runs(&runs), 1, "five frames, one probe"); + + let select = |at: &Vec, cx: &mut Window| { + let at = at.clone(); + update(&view, cx, move |app, cx| { + app.selected = Some(at); + cx.notify(); + }); + draw(cx); + cx.run_until_parked(); + }; + select(&beta_at, cx); + assert_eq!(probe_runs(&runs), 2, "another checkout, another probe"); + select(&alpha_at, cx); draw(cx); - assert!(cx.debug_bounds("disktree-root").is_some()); + cx.run_until_parked(); + assert_eq!(probe_runs(&runs), 2, "alpha's answer is remembered"); +} - update(&view, cx, |app, cx| { - app.screen = Screen::Running; - cx.notify(); - }); +/// A checkout left selected is not asked again while the window is in +/// the background, however stale its answer gets; it is refreshed once +/// when the window comes back. +#[gpui_kit::test] +fn a_background_window_leaves_a_stale_answer_until_it_is_active( + cx: &mut TestAppContext, +) { + use crate::git_store::{FRESH_FOR, Probe}; + + cx.update(init); + let temp = checkouts(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1400.), px(900.))); + // A test window opens in the background; bring it to the front. + cx.update(|window, _| window.activate_window()); + let runs = count_probes(&view, cx, Probe::Known(clean_checkout())); draw(cx); + cx.run_until_parked(); + assert!(cx.update(|window, _| window.is_window_active())); + assert_eq!(probe_runs(&runs), 1, "the selection is asked about"); - update(&view, cx, |app, cx| { - app.screen = Screen::Done; - cx.notify(); - }); + cx.deactivate_window(); + for _ in 0..5 { + cx.executor().advance_clock(FRESH_FOR); + cx.run_until_parked(); + draw(cx); + cx.run_until_parked(); + } + assert_eq!(probe_runs(&runs), 1, "nobody is looking"); + + cx.update(|window, _| window.activate_window()); + cx.run_until_parked(); draw(cx); - assert!(cx.debug_bounds("disktree-root").is_some()); + cx.run_until_parked(); + assert_eq!(probe_runs(&runs), 2, "back in front, it is refreshed"); + draw(cx); + cx.run_until_parked(); + assert_eq!(probe_runs(&runs), 2, "once"); } -/// The removal mode is a choice with two independent channels: the key and the -/// button both have to reach the same state. +/// A checkout git could not read within its limit is drawn as such, and +/// not asked again on the frames that follow. #[gpui_kit::test] -fn the_review_screen_switches_removal_mode(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); +fn a_timed_out_checkout_is_drawn_and_not_asked_again(cx: &mut TestAppContext) { + use crate::git_store::{Probe, Shown}; + + cx.update(init); + let temp = checkouts(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1400.), px(900.))); + let runs = count_probes(&view, cx, Probe::TimedOut); + for _ in 0..5 { + draw(cx); + cx.run_until_parked(); + } + assert_eq!(probe_runs(&runs), 1); + let alpha = temp.path().join("alpha"); + assert!(read(&view, cx, |app| { + app.git.shown(&alpha) == Shown::Answer(&Probe::TimedOut) + })); +} + +/// The side panel asks whether the selection is a checkout once per +/// selection, not on every frame it draws. +#[gpui_kit::test] +fn the_panel_checks_for_a_checkout_once_per_selection(cx: &mut TestAppContext) { + cx.update(init); let temp = fixture(); + // Opening the window draws its first frame, so count from before it. + crate::git::CHECKS.set(0); let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1400.), px(900.))); + for _ in 0..5 { + draw(cx); + } + assert!( + cx.debug_bounds("side-panel-scroll").is_some(), + "the panel is shown" + ); + assert_eq!(read(&view, cx, |app| app.selected.clone()), Some(vec![0])); + assert_eq!(crate::git::CHECKS.get(), 1, "five frames, one check"); + + // Another directory is another question, asked once. update(&view, cx, |app, cx| { - app.marks.toggle(disktree_core::removal::Target { - path: temp.path().join("junk"), - bytes: 300_000, - is_dir: true, - hidden: false, - }); - app.screen = Screen::Review; + app.selected = Some(vec![1]); cx.notify(); }); - draw(cx); + for _ in 0..5 { + draw(cx); + } + let next_is_dir = read(&view, cx, |app| { + app.node_at(&[1]) + .is_some_and(disktree_core::index::Node::is_dir) + }); + assert!(next_is_dir, "the fixture's second entry is a directory"); + assert_eq!(crate::git::CHECKS.get(), 2); - press(cx, "m"); - assert_eq!(read(&view, cx, |app| app.removal_mode), RemovalMode::Trash); - press(cx, "p"); - assert_eq!( - read(&view, cx, |app| app.removal_mode), - RemovalMode::Permanent + // With nothing selected the panel describes the scan root, which is + // never asked about: not even its `.git`, let alone `git status`. + std::fs::create_dir(temp.path().join(".git")).expect("mkdir .git"); + press(cx, "escape"); + for _ in 0..5 { + draw(cx); + } + assert_eq!(read(&view, cx, |app| app.selected.clone()), None); + assert_eq!(crate::git::CHECKS.get(), 2, "the root is not checked"); + // `git` fills only when a background ask finishes; let any finish. + cx.run_until_parked(); + let root = temp.path().to_path_buf(); + assert!( + read(&view, cx, |app| { + app.git.shown(&root) == crate::git_store::Shown::Asking + }), + "no git status" ); - press(cx, "!"); - assert!(read(&view, cx, |app| app.marks.is_empty())); } -/// `a` on the review screen copies a prompt for an agent naming the marked -/// path, and removes nothing. +/// Shift-U, which opened the Updates panel, opens Settings › Updates in +/// its own window now; the main window is left as it was. #[gpui_kit::test] -fn the_review_screen_copies_the_list_as_an_agent_prompt( - cx: &mut TestAppContext, -) { - cx.update(gpui_omarchy::init); +fn shift_u_opens_settings_updates(cx: &mut TestAppContext) { + cx.update(init); let temp = fixture(); - let junk = temp.path().join("junk"); let (view, cx) = view_over(temp.path(), cx); - update(&view, cx, |app, cx| { - app.marks.toggle(disktree_core::removal::Target { - path: junk.clone(), - bytes: 300_000, - is_dir: true, - hidden: false, - }); - app.screen = Screen::Review; - cx.notify(); + draw(cx); + let crumbs = read(&view, cx, |app| app.crumbs.clone()); + press(cx, "shift-u"); + cx.run_until_parked(); + let settings = cx.update(|_, cx| { + crate::aux_window::find::(cx, |_| true) + .and_then(|handle| handle.read(cx).ok().map(|view| view.pane)) + }); + assert_eq!(settings, Some(crate::settings::Pane::Updates)); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), crumbs); +} + +/// Help's documents draw from what this build ships, and Copy puts the +/// whole document on the clipboard. +#[gpui_kit::test] +fn help_documents_draw_and_copy(cx: &mut TestAppContext) { + use crate::doc_window::{Doc, DocWindow}; + + cx.update(init); + for doc in [Doc::Changelog, Doc::License, Doc::ThirdPartyNotices] { + let (_, cx) = cx.add_window_view(move |_, cx| DocWindow::new(doc, cx)); + draw(cx); + assert!(cx.debug_bounds("title-strip").is_some(), "{doc:?}"); + let copy = cx + .debug_bounds(crate::doc_window::COPY_ID) + .unwrap_or_else(|| panic!("{doc:?} has Copy")); + cx.simulate_click(copy.center(), gpui_kit::Modifiers::none()); + draw(cx); + let copied = cx + .read_from_clipboard() + .and_then(|item| item.text()) + .unwrap_or_default(); + assert_eq!(copied, doc.source(), "{doc:?}"); + } +} + +/// A contrived `main.log` in a temporary folder, and the Logs window over +/// it at its opening size. Nothing is remembered: there is no settings +/// file. +fn logs_over<'a>( + cx: &'a mut TestAppContext, + text: &str, +) -> ( + tempfile::TempDir, + std::path::PathBuf, + Entity, + &'a mut Window, +) { + cx.update(init); + let dir = tempfile::TempDir::new().expect("tempdir"); + let path = dir.path().join("main.log"); + std::fs::write(&path, text).expect("write the log"); + let log = path.clone(); + let (view, cx) = cx.add_window_view(move |window, cx| { + crate::logs_window::LogsWindow::new(Some(log), None, window, cx) }); + cx.simulate_resize(gpui_kit::size( + gpui_kit::px(1120.0), + gpui_kit::px(720.0), + )); + draw(cx); draw(cx); + (dir, path, view, cx) +} - press(cx, "a"); - let copied = cx - .read_from_clipboard() +fn append_log(path: &std::path::Path, text: &str) { + let mut file = std::fs::OpenOptions::new() + .append(true) + .open(path) + .expect("open the log"); + std::io::Write::write_all(&mut file, text.as_bytes()).expect("append"); +} + +/// One poll of the file, as the window's timer runs it. +fn poll_logs(cx: &mut Window) { + cx.executor() + .advance_clock(std::time::Duration::from_millis(500)); + cx.run_until_parked(); + draw(cx); +} + +fn click_on(cx: &mut Window, selector: &'static str) { + draw(cx); + let bounds = cx + .debug_bounds(selector) + .unwrap_or_else(|| panic!("{selector} is drawn")); + cx.simulate_click(bounds.center(), gpui_kit::Modifiers::none()); + draw(cx); +} + +fn clipboard(cx: &Window) -> String { + cx.read_from_clipboard() .and_then(|item| item.text()) - .expect("a prompt on the clipboard"); - assert!(copied.contains("free up disk space"), "{copied}"); - assert!( - copied.contains(&format!("- {}", junk.display())), - "{copied}" + .unwrap_or_default() +} + +/// Logs reads the file, filters by level and by search, steps through the +/// matches, wraps long lines rather than clip them, follows lines written +/// after it opened (or counts them while paused), and copies the lines +/// picked in the gutter exactly as the file has them. +#[gpui_kit::test] +fn logs_follow_the_file_and_filter(cx: &mut TestAppContext) { + use crate::log_view::Level; + use crate::logs_window::{ + LIVE_ID, MARK_ID, NEXT_ID, PILL_ID, PREV_ID, SINCE_MARK_ID, WRAP_ID, + }; + + let long = format!( + "2026-10-30T00:00:02.000-04:00 WARN pwrdisk::updater: GitHub said \ + 403 {}", + "and kept saying so ".repeat(30) ); - assert!(junk.exists(), "nothing was removed"); - let notice = read(&view, cx, |app| app.notice.clone()); - assert!( - notice.is_some_and(|(message, _)| message.contains("copied")), - "the copy is confirmed" + let started = + "2026-10-30T00:00:01.000-04:00 INFO pwrdisk: started PwrDisk"; + let workers = + "2026-10-30T00:00:03.000-04:00 DEBUG pwrdisk::scan: 8 workers"; + let failed = "2026-10-30T00:00:04.000-04:00 ERROR pwrdisk::scan: \ + local scan failed after 0.2 s"; + let (_dir, path, view, cx) = + logs_over(cx, &format!("{started}\n{long}\n{workers}\n{failed}\n")); + let visible = + |cx: &mut Window| cx.update(|_, cx| view.read(cx).view.visible().len()); + assert!(cx.debug_bounds("logs-count").is_some()); + // Debug starts off; its toggle shows it. + assert_eq!(visible(cx), 3); + click_on(cx, "logs-level-debug"); + assert_eq!(visible(cx), 4); + click_on(cx, "logs-level-debug"); + + // Wrap is on: the long line takes several rows, the short one one, and + // its rows cover it at word boundaries within the room it has. + let row = cx.debug_bounds("log-row-1").expect("line 1").size.height; + let tall = cx.debug_bounds("log-row-2").expect("line 2").size.height; + assert!(tall >= row * 3.0, "{tall:?} vs {row:?}"); + let (segments, len) = cx.update(|window, cx| { + let logs = view.read(cx); + let raw = logs.view.lines[1].raw().clone(); + (logs.segments(&raw, window, cx), raw.len()) + }); + assert!(segments.len() >= 3, "{segments:?}"); + assert_eq!(segments.first().map(|s| s.start), Some(0)); + assert_eq!(segments.last().map(|s| s.end), Some(len)); + assert!(segments.windows(2).all(|pair| pair[0].end == pair[1].start)); + // Off, every line is one row, and the text scrolls sideways. + click_on(cx, WRAP_ID); + assert!(!cx.update(|_, cx| view.read(cx).wrap)); + let unwrapped = cx.debug_bounds("log-row-2").expect("line 2").size.height; + assert_eq!(unwrapped, row); + let at = cx.debug_bounds("log-row-2").expect("line 2").center(); + cx.simulate_event(gpui_kit::ScrollWheelEvent { + position: at, + delta: gpui_kit::ScrollDelta::Pixels(gpui_kit::point( + gpui_kit::px(-120.0), + gpui_kit::px(0.0), + )), + ..Default::default() + }); + draw(cx); + assert!(cx.update(|_, cx| view.read(cx).h_offset) > 0.0); + click_on(cx, WRAP_ID); + + // A search filters, and Enter, Shift-Enter and the chevrons step + // through what it found. + let search = cx.update(|_, cx| view.read(cx).search_state()); + cx.update(|window, cx| { + search.update(cx, |search, cx| search.focus(window, cx)); + }); + cx.simulate_input("pwrdisk"); + draw(cx); + let active = + |cx: &mut Window| cx.update(|_, cx| view.read(cx).view.active()); + assert!(!cx.update(|_, cx| view.read(cx).live), "a search pauses"); + assert_eq!(cx.update(|_, cx| view.read(cx).view.match_count()), 3); + assert_eq!(active(cx), Some(1)); + cx.simulate_keystrokes("enter"); + assert_eq!(active(cx), Some(2)); + cx.simulate_keystrokes("shift-enter shift-enter"); + assert_eq!(active(cx), Some(4)); + click_on(cx, NEXT_ID); + assert_eq!(active(cx), Some(1)); + click_on(cx, PREV_ID); + assert_eq!(active(cx), Some(4)); + // Esc clears it, and every line is back. + cx.update(|window, cx| { + search.update(cx, |search, cx| search.focus(window, cx)); + }); + cx.simulate_keystrokes("escape"); + draw(cx); + assert!(!cx.update(|_, cx| view.read(cx).view.searching())); + assert_eq!(visible(cx), 3); + click_on(cx, LIVE_ID); + assert!(cx.update(|_, cx| view.read(cx).live)); + + // Lines picked in the gutter copy as the file has them; Select All + // takes every line shown. + click_on(cx, "log-number-1"); + let gutter = cx.debug_bounds("log-number-4").expect("line 4's number"); + cx.simulate_click(gutter.center(), gpui_kit::Modifiers::shift()); + draw(cx); + assert_eq!(cx.update(|_, cx| view.read(cx).selection), Some((1, 4))); + cx.simulate_keystrokes("ctrl-c"); + assert_eq!(clipboard(cx), format!("{started}\n{long}\n{failed}\n")); + click_on(cx, "log-number-4"); + cx.simulate_keystrokes("ctrl-c"); + assert_eq!(clipboard(cx), format!("{failed}\n")); + cx.simulate_keystrokes("ctrl-a ctrl-c"); + assert_eq!(clipboard(cx), format!("{started}\n{long}\n{failed}\n")); + cx.simulate_keystrokes("escape"); + assert_eq!(cx.update(|_, cx| view.read(cx).selection), None); + + // A line written later is read on the next poll. + let refused = "2026-10-30T00:00:05.000-04:00 ERROR pwrdisk::removal: \ + removal finished: 0 removed, 0 bytes, 1 failed"; + append_log(&path, &format!("{refused}\n")); + poll_logs(cx); + assert_eq!(visible(cx), 4); + assert_eq!(cx.update(|_, cx| view.read(cx).view.count(Level::Error)), 2); + + // Paused, new lines are counted on the pill, which follows again. + click_on(cx, LIVE_ID); + append_log(&path, &format!("{started}\n{refused}\n")); + poll_logs(cx); + assert_eq!(cx.update(|_, cx| view.read(cx).new_lines), 2); + click_on(cx, PILL_ID); + assert!(cx.update(|_, cx| view.read(cx).live)); + + // The mark selects what came after it, and that grows with the log. + click_on(cx, MARK_ID); + assert!(cx.debug_bounds("log-mark").is_some()); + append_log(&path, &format!("{started}\n")); + poll_logs(cx); + click_on(cx, SINCE_MARK_ID); + assert_eq!(cx.update(|_, cx| view.read(cx).selection), Some((8, 8))); + append_log(&path, &format!("{refused}\n")); + poll_logs(cx); + assert_eq!(cx.update(|_, cx| view.read(cx).selection), Some((8, 9))); + cx.simulate_keystrokes("ctrl-c"); + assert_eq!(clipboard(cx), format!("{started}\n{refused}\n")); +} + +/// A rotation reads the files again, even when it leaves `main.log` empty: +/// what was shown pointed into the old file, and drawing it would index +/// past the end. +#[gpui_kit::test] +fn logs_survive_a_rotation_to_an_empty_file(cx: &mut TestAppContext) { + let (dir, path, view, cx) = logs_over( + cx, + "2026-10-30T00:00:01.000-04:00 WARN pwrdisk: one\n\ + 2026-10-30T00:00:02.000-04:00 ERROR pwrdisk: two\n", + ); + assert_eq!(cx.update(|_, cx| view.read(cx).view.visible().len()), 2); + // Paused, with a line waiting behind the pill. + view.update(cx, |logs, cx| logs.set_live(false, cx)); + append_log(&path, "2026-10-30T00:00:02.500-04:00 INFO pwrdisk: more\n"); + poll_logs(cx); + assert_eq!(cx.update(|_, cx| view.read(cx).new_lines), 1); + + std::fs::rename(&path, dir.path().join("main.old.log")).expect("rotate"); + std::fs::write(&path, "").expect("a new main.log"); + poll_logs(cx); + // The old file's lines, from main.old.log, and nothing past them; + // the pill counted lines of a reading that is gone. + assert_eq!(cx.update(|_, cx| view.read(cx).view.visible().len()), 3); + assert_eq!(cx.update(|_, cx| view.read(cx).new_lines), 0); + view.update(cx, |logs, cx| logs.set_live(true, cx)); + // A real rotation only ever moves a main.log with lines in it: an + // empty file swapped for another empty one may keep its inode (Linux) + // or have none (Windows), and there is nothing to notice then. + append_log( + &path, + "2026-10-30T00:00:03.000-04:00 INFO pwrdisk: three\n", ); + poll_logs(cx); + assert_eq!(cx.update(|_, cx| view.read(cx).view.visible().len()), 4); + std::fs::write(dir.path().join("main.old.log"), "").expect("emptied"); + std::fs::write(&path, "").expect("truncated"); + poll_logs(cx); + assert_eq!(cx.update(|_, cx| view.read(cx).view.visible().len()), 0); + assert!(cx.debug_bounds("logs-count").is_some()); } +/// Restart to update never exits while a removal runs, wherever it is +/// asked from (Settings goes through the main window): it says why. #[gpui_kit::test] -fn remote_review_copies_host_guarded_script_and_prompt( - cx: &mut TestAppContext, -) { - cx.update(gpui_omarchy::init); +fn restart_to_update_waits_for_a_removal(cx: &mut TestAppContext) { + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); update(&view, cx, |app, cx| { - app.remote = Some("dev-alias".into()); - app.remote_identity = Some(disktree_core::identity::HostIdentity { - hostname: "actual-server".into(), - machine_id: Some("abcdefabcdefabcdefabcdefabcdefab".into()), - }); - app.marks.toggle(disktree_core::removal::Target { - path: temp.path().join("junk"), - bytes: 300_000, - is_dir: true, - hidden: false, - }); - app.screen = Screen::Review; - cx.notify(); + app.run = Some(disktree_core::removal::spawn( + disktree_core::removal::Plan::default(), + RemovalMode::Trash, + )); + assert!(!app.can_restart_to_update()); + app.restart_to_update(cx); }); - draw(cx); - press(cx, "y"); - let script = cx - .read_from_clipboard() - .and_then(|item| item.text()) - .expect("script on clipboard"); - assert!(script.contains("actual-server")); - assert!(script.contains("/etc/machine-id")); - assert!(script.contains("Wrong hostname")); - assert!(script.contains("ssh -T")); - assert!(script.contains("PREVIEW ONLY")); - press(cx, "a"); - let prompt = cx - .read_from_clipboard() - .and_then(|item| item.text()) - .expect("prompt on clipboard"); - assert!(prompt.contains("actual-server")); - assert!(prompt.contains("abcdefabcdefabcdefabcdefabcdefab")); - assert!(prompt.contains("MANDATORY HOST CHECK")); - assert!(temp.path().join("junk/blob.bin").exists()); + let notice = read(&view, cx, Disktree::notice); + assert!( + notice.is_some_and(|(text, _)| text.contains("removal")), + "restart refused while removing" + ); + update(&view, cx, |app, _| app.run = None); } -/// Escape in the alert dialog cancels: the dialog closes, the review screen -/// stays, and nothing on disk changes. +/// Off macOS the strip carries the menu button, and its dropdown lists the +/// menu bar's template; Escape closes it. #[gpui_kit::test] -fn escape_in_the_delete_dialog_cancels(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); +fn the_strip_menu_lists_the_menus_off_macos(cx: &mut TestAppContext) { + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); - update(&view, cx, |app, cx| { - app.removal_mode = RemovalMode::Permanent; - app.marks.toggle(disktree_core::removal::Target { - path: temp.path().join("junk"), - bytes: 300_000, - is_dir: true, - hidden: false, + for (name, frame) in window_frames() { + update(&view, cx, |app, cx| { + app.chrome_pin = Some(frame.clone()); + cx.notify(); }); - app.screen = Screen::Review; - cx.notify(); - }); + draw(cx); + let mac = frame.platform == crate::chrome::Platform::MacOs; + assert_eq!( + cx.debug_bounds("app-menu-button").is_some(), + !mac, + "{name}" + ); + } + let button = cx.debug_bounds("app-menu-button").expect("menu button"); + cx.simulate_click(button.center(), gpui_kit::Modifiers::none()); draw(cx); - - press(cx, "enter"); - assert!(read(&view, cx, |app| app.confirm_open)); + assert!(read(&view, cx, |app| app.app_menu_open)); + assert!(cx.debug_bounds("app-menu").is_some()); + // The first group's first row: File › Open Folder…. + assert!(cx.debug_bounds("app-menu-0-0").is_some()); press(cx, "escape"); - assert!(!read(&view, cx, |app| app.confirm_open), "Escape cancels"); - assert_eq!(read(&view, cx, |app| app.screen), Screen::Review); - assert!(temp.path().join("junk").exists()); - assert_eq!( - read(&view, cx, |app| app.marks.len()), - 1, - "the list is kept" - ); + assert!(!read(&view, cx, |app| app.app_menu_open)); + assert!(cx.debug_bounds("app-menu").is_none()); } -/// With a trash on the machine, the reversible path is the default and -/// commits without a dialog; the permanent one is a deliberate choice. +/// Copy Diagnostics Info writes the report, with the main window's +/// session and no path it scanned, and says so in a toast. #[gpui_kit::test] -fn the_trash_is_the_default_when_there_is_one(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); +fn copy_diagnostics_info_names_no_scanned_path(cx: &mut TestAppContext) { + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); - let (mode, available) = read(&view, cx, |app| { - (app.removal_mode, app.trash_backend.is_available()) - }); - if available { - assert_eq!(mode, RemovalMode::Trash); - } else { - assert_eq!(mode, RemovalMode::Permanent); - } + draw(cx); + // As the menu runs it: after the dispatch that asked. + cx.update(|_, cx| cx.defer(crate::help::copy_diagnostics)); + cx.run_until_parked(); + let report = cx + .read_from_clipboard() + .and_then(|item| item.text()) + .unwrap_or_default(); + assert!( + report.starts_with("PwrDisk diagnostics, collected "), + "{report}" + ); + assert!(report.contains("\n[Session]\nScan: local"), "{report}"); + let root = temp.path().display().to_string(); + assert!(!report.contains(&root), "{report}"); + let notice = read(&view, cx, Disktree::notice); + assert!( + notice.is_some_and(|(text, _)| text.starts_with("Diagnostics copied")), + "the main window says it copied" + ); } -/// `ctrl =` / `ctrl -` / `ctrl 0` change the window's rem, which every size -/// in the app is expressed in, and the mosaic's header band follows it. #[gpui_kit::test] -fn interface_zoom_scales_the_rem_and_the_header_band(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); +fn the_volume_picker_opens_moves_and_closes(cx: &mut TestAppContext) { + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); draw(cx); - let rem = - |cx: &mut Window| cx.update(|window, _| window.rem_size().as_f32()); - let base = rem(cx); - let band = |view: &Entity, cx: &mut Window| { - update(view, cx, |app, _| { - app.layout(); - app.layout_options.header - }) - }; - let base_band = band(&view, cx); - press(cx, "ctrl-="); - let zoomed = rem(cx); - assert!(zoomed > base, "{zoomed} after zooming in from {base}"); - let zoomed_band = band(&view, cx); - assert!( - (zoomed_band / base_band - zoomed / base).abs() < 0.01, - "the band scales with the rem: {base_band} -> {zoomed_band}" - ); - - press(cx, "ctrl--"); - press(cx, "ctrl--"); - assert!(rem(cx) < base, "zooming out goes below the default"); - press(cx, "ctrl-0"); - assert!((rem(cx) - base).abs() < 0.01, "ctrl 0 resets"); -} - -/// The crumbs of the directory named `name` directly inside `parent`. -fn child_crumbs(app: &Disktree, parent: &[usize], name: &str) -> Vec { - let node = app.node_at(parent).expect("the parent"); - let index = node - .children - .iter() - .position(|child| &*child.name == name) - .unwrap_or_else(|| panic!("no {name}")); - let mut crumbs = parent.to_vec(); - crumbs.push(index); - crumbs + // The picker lists volumes and draws them without panicking; Escape + // leaves the scan where it was. + press(cx, "v"); + assert!(read(&view, cx, |app| app.volumes_open)); + draw(cx); + assert!(cx.debug_bounds("disktree-root").is_some()); + let before = read(&view, cx, |app| app.root_path.clone()); + press(cx, "down"); + press(cx, "up"); + press(cx, "escape"); + assert!(!read(&view, cx, |app| app.volumes_open)); + assert_eq!(read(&view, cx, |app| app.root_path.clone()), before); } -/// Regression: the wheel magnified toward the deepest directory under the -/// pointer, then went into the *top-level* one containing it, so the screen -/// after the descent was never the area that was zoomed into. +/// Enter must reach the picker even when its dialog owns keyboard focus. #[gpui_kit::test] -fn the_wheel_goes_into_the_directory_it_zoomed_into(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); +fn enter_in_the_focused_volume_picker_scans_the_selected_root( + cx: &mut TestAppContext, +) { + cx.update(init); let temp = fixture(); + // Accepting a local root canonicalizes it, and the temporary directory + // is behind a link on macOS (/var -> /private/var) and a short 8.3 name + // on Windows runners, so compare against the resolved path. + let target = dunce::canonicalize(temp.path().join("junk")).unwrap(); let (view, cx) = view_over(temp.path(), cx); - draw(cx); - - // Point at the middle of junk/deeper's contents: a directory one level - // below a top-level one. - let (deeper, point) = update(&view, cx, |app, _| { - let junk = child_crumbs(app, &[], "junk"); - let deeper = child_crumbs(app, &junk, "deeper"); - let body = app.tile_body(&deeper).expect("deeper is drawn"); - (deeper, (body.x + body.w / 2.0, body.y + body.h / 2.0)) + update(&view, cx, |app, _| { + app.volumes = vec![disktree_core::space::Volume { + point: target.clone(), + device: None, + space: None, + }]; + app.volume_highlight = 0; + app.volumes_open = true; }); - - let mut entered = None; - for _ in 0..40 { - let crumbs = update(&view, cx, |app, cx| { - let (x, y) = app.view.unproject(point.0, point.1); - let screen = app - .view - .project(disktree_core::treemap::Rect::new(x, y, 0.0, 0.0)); - app.zoom_at(screen.x, screen.y, 1.15, true, cx); - app.crumbs.clone() - }); - draw(cx); - if !crumbs.is_empty() { - entered = Some(crumbs); - break; - } - } + let focus = read(&view, cx, |app| app.confirm_focus.clone()); + cx.update(|window, cx| window.focus(&focus, cx)); + draw(cx); + assert!(!read(&view, cx, Disktree::can_start_over)); + press(cx, "enter"); + assert!(!read(&view, cx, |app| app.volumes_open)); assert_eq!( - entered.as_deref(), - Some(deeper.as_slice()), - "descended into the pointed-at directory, not its top-level ancestor" + read(&view, cx, |app| app.root_path.clone()), + dunce::canonicalize(target).expect("canonical selected root") ); + finish_scan(&view, cx); + assert!(read(&view, cx, |app| app.tree().is_some())); } -/// Regression, keyboard side: Enter on a deep selection enters that -/// directory, and on a file enters the directory holding it. #[gpui_kit::test] -fn enter_opens_the_selected_directory_at_any_depth(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); +fn the_volume_picker_is_centred_and_ignores_clicks_outside( + cx: &mut TestAppContext, +) { + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); + // Fixed rows, so this is about where the popup lands and not about which + // disks the machine running the test happens to have. + update(&view, cx, |app, cx| { + app.volumes = vec![ + Volume { + point: PathBuf::from("/one"), + device: Some("/dev/one".into()), + space: Some(SpaceInfo { + total: 1_000, + free: 500, + available: 400, + }), + }, + Volume { + point: PathBuf::from("/two"), + device: None, + space: None, + }, + ]; + app.volumes_open = true; + cx.notify(); + }); draw(cx); - let deeper = update(&view, cx, |app, cx| { - let junk = child_crumbs(app, &[], "junk"); - let deeper = child_crumbs(app, &junk, "deeper"); - app.select(Some(deeper.clone()), cx); - app.descend(cx); - deeper - }); - assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); + let viewport = cx.update(|window, _| window.viewport_size()); + let rows = cx.debug_bounds("volume-rows").expect("the rows are drawn"); + let centre = rows.center(); + assert!( + (centre.x - viewport.width / 2.0).abs() < px(4.), + "the popup is not centred across: {centre:?} in {viewport:?}" + ); + assert!( + (centre.y - viewport.height / 2.0).abs() < px(150.), + "the popup is not centred down: {centre:?} in {viewport:?}" + ); - press(cx, "escape"); - press(cx, "escape"); - press(cx, "escape"); - let junk = update(&view, cx, |app, cx| { - app.go_to(Vec::new(), cx); - let junk = child_crumbs(app, &[], "junk"); - let blob = child_crumbs(app, &junk, "blob.bin"); - app.select(Some(blob), cx); - app.descend(cx); - junk - }); - assert_eq!( - read(&view, cx, |app| app.crumbs.clone()), - junk, - "a file opens its directory" + // A dialog keeps what was typed: a click in the corner, outside the + // popup, closes nothing. Cancel and Escape do. + cx.simulate_click( + gpui_kit::point(px(4.), px(4.)), + gpui_kit::Modifiers::none(), + ); + draw(cx); + assert!( + read(&view, cx, |app| app.volumes_open), + "clicking outside the picker leaves it open" ); } -/// The mark key acts on what the pointer is over when the pointer moved -/// last, and on the keyboard selection after an arrow. #[gpui_kit::test] -fn the_mark_key_follows_the_pointer_until_the_keyboard_moves( - cx: &mut TestAppContext, -) { - cx.update(gpui_omarchy::init); +fn showing_a_tile_that_is_gone_says_so_instead(cx: &mut TestAppContext) { + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); draw(cx); - // Point at junk's name band, which belongs to junk itself (its body - // belongs to its children). junk is not the default selection, .cache. - let (keep, origin, centre) = update(&view, cx, |app, _| { - let keep = child_crumbs(app, &[], "junk"); - let body = app - .layout() - .and_then(|tiles| { - tiles.iter().find(|tile| tile.crumbs() == keep.as_slice()) - }) - .and_then(|tile| tile.header) - .expect("junk is drawn with a band"); - ( - keep, - app.treemap_origin.get(), - (body.x + body.w / 2.0, body.y + body.h / 2.0), - ) - }); - assert_ne!( - read(&view, cx, |app| app.selected.clone()), - Some(keep.clone()) - ); - cx.simulate_mouse_move( - Point::new(origin.x + px(centre.0), origin.y + px(centre.1)), - None, - gpui_kit::Modifiers::default(), - ); - draw(cx); + // The selection is .cache, the largest; take it away behind the tree. + std::fs::remove_dir_all(temp.path().join(".cache")).expect("remove"); + press(cx, "o"); + let notice = read(&view, cx, Disktree::notice); + let (message, _) = notice.expect("a notice"); + assert!(message.contains("no longer on disk"), "{message}"); +} - press(cx, "space"); - let marked = read(&view, cx, |app| app.marks.items().to_vec()); - assert_eq!(marked.len(), 1); - assert!( - marked[0].path.ends_with("junk"), - "marked what the pointer is on: {:?}", - marked[0].path - ); - assert_eq!(read(&view, cx, |app| app.selected.clone()), Some(keep)); +#[gpui_kit::test] +fn command_chords_are_not_read_as_plain_letters(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); - // An arrow hands control back to the keyboard selection. - press(cx, "right"); - assert!(!read(&view, cx, |app| app.pointer_active)); + // ⌘P and ⌘D are the menu bar's or nobody's; read as `p` and `d` they + // would hide the selection and re-scan. + let shown = read(&view, cx, |app| app.show_selection); + press(cx, "cmd-p cmd-d"); + assert_eq!(read(&view, cx, |app| app.show_selection), shown); + assert!(read(&view, cx, |app| app.options.apparent_size)); + press(cx, "p"); + assert_eq!(read(&view, cx, |app| app.show_selection), !shown); } -/// Regression: after descending, tiles resolved against the scanned root -/// instead of the directory drawn, so labels, hover and marks named strangers. #[gpui_kit::test] -fn after_descending_every_tile_is_inside_the_directory_drawn( - cx: &mut TestAppContext, -) { - cx.update(gpui_omarchy::init); +fn the_treemap_zooms_with_the_wheel_and_resets(cx: &mut TestAppContext) { + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); draw(cx); - let junk = update(&view, cx, |app, cx| { - let junk = child_crumbs(app, &[], "junk"); - app.select(Some(junk.clone()), cx); - app.descend(cx); - junk + let middle = read(&view, cx, |app| { + let size = app.treemap_size.get(); + Point::new(size.width / 2.0, size.height / 2.0) }); - assert_eq!(read(&view, cx, |app| app.crumbs.clone()), junk); - draw(cx); - - let (paths, labels) = update(&view, cx, |app, _| { - let tiles = app.layout().map(<[Tile]>::to_vec).unwrap_or_default(); - let paths: Vec<_> = tiles - .iter() - .filter_map(|tile| app.path_at(tile.crumbs())) - .collect(); - let labels: Vec = app - .prepare() - .labels - .into_iter() - .map(|label| label.text) - .collect(); - (paths, labels) + update(&view, cx, |app, cx| { + app.zoom_at(middle.x.as_f32(), middle.y.as_f32(), 1.5, false, cx); }); - assert!(!paths.is_empty()); - let junk_path = temp.path().join("junk"); - for path in &paths { - assert!(path.starts_with(&junk_path), "{path:?} is outside junk"); - } - for label in &labels { - assert!( - ["blob.bin", "deeper", "more.bin"].contains(&label.as_str()) - || label.starts_with('+'), - "label {label} does not belong to junk" - ); + let zoomed = read(&view, cx, |app| app.view.scale); + assert!(zoomed > 1.0, "scale after zooming: {zoomed}"); + + press(cx, "0"); + assert!((read(&view, cx, |app| app.view.scale) - 1.0).abs() < f32::EPSILON); +} + +/// Both appearances Omarchy ships must draw: the palette is derived from the +/// theme, so a light theme is a real second configuration. +#[gpui_kit::test] +fn both_appearances_draw(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + for theme in [Theme::tokyo_night(), Theme::flexoki_light()] { + view.update(cx, |_, cx| { + theme.clone().apply(cx); + cx.notify(); + }); + draw(cx); + assert!(cx.debug_bounds("disktree-root").is_some()); } +} - // Space on the selection marks something inside junk, never elsewhere. +/// A view built without a scan keeps working: the screens must not assume a +/// walk is in flight. +#[gpui_kit::test] +fn a_view_without_flags_or_marks_still_draws(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); update(&view, cx, |app, cx| { - let blob = child_crumbs(app, &junk, "blob.bin"); - app.select(Some(blob), cx); + app.screen = Screen::Review; + cx.notify(); }); - press(cx, "space"); - let marked = read(&view, cx, |app| app.marks.items().to_vec()); - assert_eq!(marked.len(), 1); - assert_eq!(marked[0].path, junk_path.join("blob.bin")); - assert_eq!(marked[0].bytes, 200_000); + draw(cx); + assert!(cx.debug_bounds("disktree-root").is_some()); - // And the mark is drawn on the right tile: its crumbs resolve here. - let hatched = update(&view, cx, |app, _| { - app.prepare() - .tiles - .iter() - .filter(|tile| tile.marked) - .count() + update(&view, cx, |app, cx| { + app.screen = Screen::Running; + cx.notify(); }); - assert_eq!(hatched, 1, "exactly the marked tile is hatched"); + draw(cx); + + update(&view, cx, |app, cx| { + app.screen = Screen::Done; + cx.notify(); + }); + draw(cx); + assert!(cx.debug_bounds("disktree-root").is_some()); } -/// Drive the scan the view started until its outcome has been applied. -/// -/// The scan is what is waited on, not the tree: widening keeps the old tree -/// on screen while the wider root is read, so a tree being there does not -/// mean the requested scan has completed. -fn finish_scan(view: &Entity, cx: &mut Window) { - // Without a scan in flight the poller reports "stopped" at once, and the - // wait would pass without having waited for anything. +/// In a short window what does not fit in the summary is reached by +/// scrolling it. Its box ended above the footer even before the fix; its +/// content painted past the box, so the wheel checks are the guard. +#[gpui_kit::test] +fn the_review_summary_fits_a_short_window(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1100.), px(420.))); + update(&view, cx, |app, cx| { + app.marks.toggle( + disktree_core::removal::Target { + path: temp.path().join("junk"), + bytes: 300_000, + is_dir: true, + hidden: false, + }, + app.path_style(), + ); + app.screen = Screen::Review; + cx.notify(); + }); + draw(cx); + draw(cx); + let summary = cx.debug_bounds("review-summary").expect("summary"); + let footer = cx.debug_bounds("review-footer").expect("footer"); assert!( - read(view, cx, |app| app.scan.is_some()), - "no scan to finish" + summary.bottom() <= footer.top(), + "summary ends at {:?}, under the footer at {:?}", + summary.bottom(), + footer.top() + ); + // The panel's end starts below its bottom edge, and the wheel brings + // it up into view. Without scrolling it stays put and paints over the + // footer. + let end = cx.debug_bounds("review-summary-end").expect("summary end"); + assert!(end.bottom() > summary.bottom(), "starts out of view"); + cx.simulate_event(gpui_kit::ScrollWheelEvent { + position: summary.center(), + delta: gpui_kit::ScrollDelta::Pixels(gpui_kit::point( + px(0.), + px(-2000.), + )), + ..Default::default() + }); + draw(cx); + let scrolled = cx.debug_bounds("review-summary-end").expect("summary end"); + assert!(scrolled.top() < end.top(), "{scrolled:?} did not move"); + assert!( + scrolled.bottom() <= summary.bottom(), + "{scrolled:?} still past {summary:?}" ); - let epoch = read(view, cx, |app| app.scan_epoch); - for _ in 0..600 { - std::thread::sleep(std::time::Duration::from_millis(5)); - let running = update(view, cx, |app, cx| app.poll_scan_once(epoch, cx)); - if !running { - let (error, tree) = read(view, cx, |app| { - (app.scan_error.clone(), app.tree().is_some()) - }); - assert_eq!(error, None, "the scan failed"); - assert!(tree, "the scan landed without a tree"); - return; - } - } - panic!("the scan never landed"); } +/// The removal mode is a choice with two independent channels: the key and the +/// button both have to reach the same state. #[gpui_kit::test] -fn dragging_the_panel_edge_resizes_it_within_its_limits( - cx: &mut TestAppContext, -) { - use crate::state::{PANEL_MAX_REMS, PANEL_MIN_REMS, panel_width}; - use gpui_kit::{Modifiers, MouseButton}; - - cx.update(gpui_omarchy::init); +fn the_review_screen_switches_removal_mode(cx: &mut TestAppContext) { + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); - cx.simulate_resize(gpui_kit::size(px(1400.), px(900.))); + update(&view, cx, |app, cx| { + app.marks.toggle( + disktree_core::removal::Target { + path: temp.path().join("junk"), + bytes: 300_000, + is_dir: true, + hidden: false, + }, + app.path_style(), + ); + app.screen = Screen::Review; + cx.notify(); + }); draw(cx); - let handle = cx.debug_bounds("panel-handle").expect("the panel is shown"); - let start = handle.center(); - let before = read(&view, cx, |app| app.panel_rems); - // A drag starts on the first move and reports moves after it, as a real - // pointer does in many small steps. - let drag = |cx: &mut Window, from: Point, to: Point| { - cx.simulate_mouse_down(from, MouseButton::Left, Modifiers::none()); - for step in 1..=4 { - let t = step as f32 / 4.0; - let at = Point::new(from.x + (to.x - from.x) * t, to.y); - cx.simulate_mouse_move( - at, - Some(MouseButton::Left), - Modifiers::none(), + press(cx, "m"); + assert_eq!(read(&view, cx, |app| app.removal_mode), RemovalMode::Trash); + // A Ctrl chord is not its letter: Edit's rows replay them (Select All + // is ctrl-a), and ctrl-p must not choose permanent removal. + press(cx, "ctrl-p"); + assert_eq!(read(&view, cx, |app| app.removal_mode), RemovalMode::Trash); + press(cx, "p"); + assert_eq!( + read(&view, cx, |app| app.removal_mode), + RemovalMode::Permanent + ); + press(cx, "!"); + assert!(read(&view, cx, |app| app.marks.is_empty())); +} + +/// Put `paths` on the marked list, as the treemap would. +fn mark_paths(view: &Entity, cx: &mut Window, paths: &[PathBuf]) { + update(view, cx, |app, cx| { + for path in paths { + app.marks.toggle( + disktree_core::removal::Target { + path: path.clone(), + bytes: 1_000, + is_dir: true, + hidden: false, + }, + app.path_style(), ); } - cx.simulate_mouse_up(to, MouseButton::Left, Modifiers::none()); - draw(cx); - }; - - // Wider: drag the edge 160 px to the left. - let wider = Point::new(start.x - px(160.), start.y); - drag(cx, start, wider); - let after = read(&view, cx, |app| app.panel_rems); - assert!( - (after - before - 10.0).abs() < 0.5, - "160 px is 10 rem: {before} -> {after}" - ); + cx.notify(); + }); +} - // The limits, for any edge position: a minimum, a maximum, and never - // so wide that the mosaic gets less room than the panel's own minimum. - assert!((panel_width(1390., 1400., 16.) - PANEL_MIN_REMS).abs() < 1e-3); - assert!((panel_width(0., 3000., 16.) - PANEL_MAX_REMS).abs() < 1e-3); - let squeezed = panel_width(0., 800., 16.); - assert!((squeezed - (800. / 16. - PANEL_MIN_REMS)).abs() < 1e-3); - assert!((panel_width(0., 300., 16.) - PANEL_MIN_REMS).abs() < 1e-3); +fn marked(view: &Entity, cx: &Window) -> Vec { + read(view, cx, |app| { + app.marks + .items() + .iter() + .map(|item| item.path.clone()) + .collect() + }) } +/// Unmark all keeps what it took: `u`, or Edit › Undo, puts it back, +/// and a source switch forgets it, since the paths were that machine's. #[gpui_kit::test] -fn widening_reuses_the_tree_it_has_and_reads_only_the_rest( - cx: &mut TestAppContext, -) { - use crate::state::Crumb; - - cx.update(gpui_omarchy::init); +fn unmark_all_can_be_undone(cx: &mut TestAppContext) { + cx.update(init); let temp = fixture(); - let inner = temp.path().join("junk"); - let (view, cx) = view_over(&inner, cx); - update(&view, cx, |app, _| { - app.disk_root = Some(temp.path().to_path_buf()); - // Stale on purpose: the wider root, a folder, must reset it. - app.file_table = true; + let (view, cx) = view_over(temp.path(), cx); + let both = vec![temp.path().join("junk"), temp.path().join("keep")]; + mark_paths(&view, cx, &both); + update(&view, cx, |app, cx| { + app.screen = Screen::Review; + cx.notify(); }); - let before = read(&view, cx, |app| app.tree().map(|tree| tree.files)); - - // The trail runs from the top of the filesystem — "/", or a drive such - // as "C:\" — and the scanned root sits under its parents. - let trail = read(&view, cx, Disktree::breadcrumbs); - let top = temp.path().ancestors().last().expect("a top"); - assert_eq!(trail[0].0, top.display().to_string()); + click_on(cx, "unmark-all"); + assert!(marked(&view, cx).is_empty()); + let notice = read(&view, cx, Disktree::notice); assert!( - trail.contains(&( - temp.path() - .file_name() - .unwrap() - .to_string_lossy() - .into_owned(), - Crumb::Above(temp.path().to_path_buf()) - )) + notice.is_some_and(|(message, _)| message.contains("to undo")), + "the way back is said" ); + press(cx, "u"); + assert_eq!(marked(&view, cx), both); - // Written after the first scan: a memoized subtree cannot see it. - std::fs::write(inner.join("late.bin"), vec![0_u8; 4096]).expect("write"); + // The menu's Undo does the same, once. + press(cx, "!"); + assert!(marked(&view, cx).is_empty()); + cx.dispatch_action(crate::app_menu::Undo); + draw(cx); + assert_eq!(marked(&view, cx), both); + press(cx, "u"); + assert_eq!(marked(&view, cx), both, "nothing more to undo"); - press(cx, "g"); - // The old tree stays on screen while the wider one is read. - assert!(read(&view, cx, |app| app.tree().is_some())); - finish_scan(&view, cx); - assert_eq!(read(&view, cx, |app| app.root_path.clone()), temp.path()); + // Keys still reach the window after a click on Export, whose button + // Unmark all then disables: a disabled button must not keep focus. + click_on(cx, "export"); + press(cx, "escape"); + press(cx, "!"); + assert!(marked(&view, cx).is_empty()); + press(cx, "u"); + assert_eq!(marked(&view, cx), both); + + // A mark made since stays, and a path it now covers is not re-added. + press(cx, "!"); + mark_paths(&view, cx, &[temp.path().to_path_buf()]); + press(cx, "u"); + assert_eq!(marked(&view, cx), vec![temp.path().to_path_buf()]); + let notice = read(&view, cx, Disktree::notice); assert!( - !read(&view, cx, |app| app.file_table), - "the offer follows the root it widened to" + notice.is_some_and(|(message, _)| message.contains("Nothing to put")), + "no count of nothing" ); - let (reused, rest, selected) = read(&view, cx, |app| { - let tree = app.tree().expect("the wider tree"); - let junk = tree.child_named("junk").map(|node| node.files); - let selected = app - .selected - .as_deref() - .and_then(|crumbs| app.node_at(crumbs)) - .map(|node| node.name.to_string()); - (junk, tree.child_named("keep").is_some(), selected) + + // During a removal the marks are the running list's: Undo leaves + // them alone and keeps what it holds. + press(cx, "!"); + update(&view, cx, |app, cx| { + app.screen = Screen::Running; + cx.notify(); }); - assert_eq!(reused, before, "junk was reused, not walked again"); - assert!(rest, "what is outside it was walked"); - assert_eq!(selected.as_deref(), Some("junk"), "where you came from"); + cx.dispatch_action(crate::app_menu::Undo); + draw(cx); + assert!(marked(&view, cx).is_empty()); + assert!(read(&view, cx, |app| app.unmarked.is_some())); } +/// The review screen's footer: Export and Unmark all on the left, Back +/// and the commit on the right, the commit in the corner except on +/// Windows, where the default comes first. #[gpui_kit::test] -fn enter_before_the_search_lands_applies_it_when_it_does( +fn the_review_footer_puts_the_commit_with_back_on_the_right( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); + let junk = temp.path().join("junk"); let (view, cx) = view_over(temp.path(), cx); + mark_paths(&view, cx, std::slice::from_ref(&junk)); + update(&view, cx, |app, cx| { + app.screen = Screen::Review; + cx.notify(); + }); draw(cx); + let bounds = |cx: &mut Window, selector| { + cx.debug_bounds(selector) + .unwrap_or_else(|| panic!("{selector} is drawn")) + }; + let export = bounds(cx, "export"); + let unmark = bounds(cx, "unmark-all"); + let back = bounds(cx, "back"); + let commit = bounds(cx, "commit"); + assert!(export.right() <= unmark.origin.x, "{export:?} {unmark:?}"); + assert!(unmark.right() < back.origin.x.min(commit.origin.x)); + if cfg!(windows) { + assert!(commit.right() <= back.origin.x, "{commit:?} {back:?}"); + } else { + assert!(back.right() <= commit.origin.x, "{back:?} {commit:?}"); + } + // One row, along the bottom. + assert_eq!(back.center().y, commit.center().y); + assert_eq!(export.center().y, commit.center().y); + + // Export opens a menu of the four ways to hand the list on; a row + // runs and closes it, removing nothing. + click_on(cx, "export"); + assert!(cx.debug_bounds("export-menu").is_some()); + press(cx, "escape"); + assert!(cx.debug_bounds("export-menu").is_none()); + assert_eq!(read(&view, cx, |app| app.screen), Screen::Review); + // The keys the menu shows run their row and close it. + click_on(cx, "export"); + press(cx, "y"); + assert!(cx.debug_bounds("export-menu").is_none()); + assert!(clipboard(cx).contains(&junk.display().to_string())); + click_on(cx, "export"); + click_on(cx, "copy-prompt"); + assert!(cx.debug_bounds("export-menu").is_none()); + assert!( + clipboard(cx).contains(&format!("- {}", junk.display())), + "the prompt names the path" + ); + assert!(junk.exists(), "nothing was removed"); +} - press(cx, "/"); - cx.simulate_input("blob"); - cx.simulate_keystrokes("enter"); - cx.run_until_parked(); +/// While a removal runs, Stop is a button; when it ends, Done is the +/// footer's right-hand button. +#[gpui_kit::test] +fn removing_shows_stop_and_done_sits_on_the_right(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + let width = cx.update(|window, _| window.viewport_size().width); + update(&view, cx, |app, cx| { + app.screen = Screen::Running; + cx.notify(); + }); + draw(cx); + let stop = cx.debug_bounds("stop-removal").expect("a Stop button"); + assert!(stop.origin.x > width / 2., "{stop:?}"); + update(&view, cx, |app, cx| { + app.screen = Screen::Done; + cx.notify(); + }); + draw(cx); + let done = cx.debug_bounds("continue").expect("a Done button"); + assert!(done.origin.x > width / 2., "{done:?}"); + press(cx, "enter"); + assert_eq!(read(&view, cx, |app| app.screen), Screen::Explore); +} + +/// The chooser asks, so a stray click outside it neither answers nor +/// throws away what was typed: only Cancel or Escape close it. +#[gpui_kit::test] +fn a_click_outside_the_chooser_keeps_it_open(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, Disktree::open_volumes); + cx.run_until_parked(); + draw(cx); + let picker = cx.debug_bounds("source-picker").expect("the chooser"); + let outside = gpui_kit::point(picker.origin.x / 2., picker.center().y); + cx.simulate_click(outside, gpui_kit::Modifiers::none()); + draw(cx); + assert!(read(&view, cx, |app| app.volumes_open)); + click_on(cx, "source-cancel"); + assert!(!read(&view, cx, |app| app.volumes_open)); +} + +/// The source switch: SSH host shows the host field, This computer hides +/// it, and the typed directory is the list's last row, which typing +/// selects so the one Scan acts on it. +#[gpui_kit::test] +fn the_chooser_switches_source_and_scans_the_selected_row( + cx: &mut TestAppContext, +) { + cx.update(init); + let selected = fixture(); + let (view, cx) = + cx.add_window_view(|_, cx| Disktree::choose(options(), 3, None, cx)); + cx.run_until_parked(); + update(&view, cx, |app, _| { + app.volumes = vec![Volume { + point: selected.path().join("keep"), + device: None, + space: None, + }]; + app.volumes_loading = false; + }); + draw(cx); + assert!(cx.debug_bounds("source-host").is_none()); + choose_ssh(cx); + assert!(read(&view, cx, |app| app.picker_ssh)); + assert!(cx.debug_bounds("source-host").is_some()); + assert!( + cx.debug_bounds("source-path").is_none(), + "nothing to choose from before Connect" + ); + let switch = cx.debug_bounds("source-switch").expect("the switch"); + cx.simulate_click( + gpui_kit::point( + switch.origin.x + switch.size.width / 4., + switch.center().y, + ), + gpui_kit::Modifiers::none(), + ); + draw(cx); + assert!(!read(&view, cx, |app| app.picker_ssh)); + assert!(cx.debug_bounds("source-host").is_none()); + + assert_eq!(read(&view, cx, |app| app.volume_highlight), 0); + let input = cx.debug_bounds("source-path").expect("the Directory row"); + cx.simulate_click(input.center(), gpui_kit::Modifiers::none()); + cx.simulate_input(selected.path().to_str().unwrap()); + draw(cx); + assert_eq!(read(&view, cx, |app| app.volume_highlight), 1); + click_on(cx, "source-scan"); + assert_eq!( + read(&view, cx, |app| app.root_path.clone()), + dunce::canonicalize(selected.path()).unwrap() + ); + finish_scan(&view, cx); +} + +/// Click the chooser's SSH host segment. +fn choose_ssh(cx: &mut Window) { + let switch = cx.debug_bounds("source-switch").expect("the switch"); + cx.simulate_click( + gpui_kit::point( + switch.origin.x + switch.size.width * 3. / 4., + switch.center().y, + ), + gpui_kit::Modifiers::none(), + ); + draw(cx); +} + +/// `a` on the review screen copies a prompt for an agent naming the marked +/// path, and removes nothing. +#[gpui_kit::test] +fn the_review_screen_copies_the_list_as_an_agent_prompt( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let junk = temp.path().join("junk"); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + app.marks.toggle( + disktree_core::removal::Target { + path: junk.clone(), + bytes: 300_000, + is_dir: true, + hidden: false, + }, + app.path_style(), + ); + app.screen = Screen::Review; + cx.notify(); + }); + draw(cx); + + press(cx, "a"); + let copied = cx + .read_from_clipboard() + .and_then(|item| item.text()) + .expect("a prompt on the clipboard"); + assert!(copied.contains("free up disk space"), "{copied}"); + assert!( + copied.contains(&format!("- {}", junk.display())), + "{copied}" + ); + assert!(junk.exists(), "nothing was removed"); + let notice = read(&view, cx, Disktree::notice); + assert!( + notice.is_some_and(|(message, _)| message.contains("copied")), + "the copy is confirmed" + ); +} + +#[gpui_kit::test] +fn remote_review_copies_host_guarded_script_and_prompt( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx, root) = remote_view_over(temp.path(), cx); + let junk = PathStyle::Posix.join(&root, "junk"); + update(&view, cx, |app, cx| { + app.remote = Some("dev-alias".into()); + app.remote_identity = Some(disktree_core::identity::HostIdentity { + hostname: "actual-server".into(), + machine_id: Some("abcdefabcdefabcdefabcdefabcdefab".into()), + }); + app.marks.toggle( + disktree_core::removal::Target { + path: junk.clone(), + bytes: 300_000, + is_dir: true, + hidden: false, + }, + app.path_style(), + ); + app.screen = Screen::Review; + cx.notify(); + }); + draw(cx); + press(cx, "y"); + let script = cx + .read_from_clipboard() + .and_then(|item| item.text()) + .expect("script on clipboard"); + assert!(script.contains("actual-server")); + assert!(script.contains("/etc/machine-id")); + assert!(script.contains("Wrong hostname")); + assert!(script.contains("ssh -T")); + assert!(script.contains("PREVIEW ONLY")); + press(cx, "a"); + let prompt = cx + .read_from_clipboard() + .and_then(|item| item.text()) + .expect("prompt on clipboard"); + assert!(prompt.contains("actual-server")); + assert!(prompt.contains("abcdefabcdefabcdefabcdefabcdefab")); + assert!(prompt.contains("MANDATORY HOST CHECK")); + assert!(temp.path().join("junk/blob.bin").exists()); +} + +#[gpui_kit::test] +fn remote_history_keeps_literal_and_nested_names_separate( + cx: &mut TestAppContext, +) { + use disktree_core::tree::{Draft, Tree}; + cx.update(init); + let mut root = Draft::directory("srv"); + root.children.push(Draft::directory(r"a\b")); + let mut a = Draft::directory("a"); + a.children.push(Draft::directory("b")); + root.children.push(a); + root.children.push(Draft::directory("other")); + let root = Tree::from(root); + let (view, cx) = cx.add_window_view(move |_, cx| { + let mut app = + Disktree::with_tree(PathBuf::from("/srv"), root, options(), 3, cx); + app.remote = Some("fixture".into()); + app + }); + update(&view, cx, |app, cx| { + for path in [r"/srv/a\b", "/srv/a/b", "/srv/other"] { + let crumbs = app.crumbs_for_path(Path::new(path)).unwrap(); + app.go_to(crumbs, cx); + } + let paths: Vec<_> = app + .history + .back + .iter() + .map(|path| path.to_str().unwrap()) + .collect(); + assert_eq!(paths, ["/srv", r"/srv/a\b", "/srv/a/b"]); + app.go_back(cx); + assert_eq!(app.current_path().to_str(), Some("/srv/a/b")); + app.go_back(cx); + assert_eq!(app.current_path().to_str(), Some(r"/srv/a\b")); + }); + draw(cx); +} + +/// A Unix host's paths are POSIX on every client. A Windows client must not +/// join them with `\`, split a name such as `logs\old` or `a:b`, or export a +/// delete script that names a different file on the host. +#[gpui_kit::test] +fn remote_paths_keep_the_hosts_separators_on_every_client( + cx: &mut TestAppContext, +) { + use disktree_core::tree::{Draft, Metric, NodeKind, Tree, aggregate}; + + cx.update(init); + let mut root = Draft::directory("data"); + let mut logs = Draft::directory(r"logs\old"); + logs.children + .push(Draft::entry("a:b", NodeKind::File, 4_000)); + root.children.push(logs); + root.children + .push(Draft::entry("notes", NodeKind::File, 1_000)); + let mut root = Tree::from(root); + aggregate(&mut root, Metric::Bytes); + let root_path = PathBuf::from("/srv/data"); + let (view, cx) = cx.add_window_view(move |_, cx| { + let mut app = + Disktree::with_tree(root_path.clone(), root, options(), 3, cx); + app.remote = Some("dev".into()); + app + }); + let focus = read(&view, cx, |app| app.focus.clone()); + cx.update(|window, cx| window.focus(&focus, cx)); + draw(cx); + update(&view, cx, |app, cx| { + let file = Path::new(r"/srv/data/logs\old/a:b"); + let crumbs = app.crumbs_for_path(file).expect("one name, not two"); + assert_eq!(app.path_at(&crumbs).as_deref(), Some(file)); + assert!( + app.crumbs_for_path(Path::new("/srv/data/logs/old")) + .is_none() + ); + app.select(Some(crumbs), cx); + app.toggle_mark_selected(cx); + assert!(app.marks.contains(file, app.path_style())); + let labels: Vec<_> = app + .breadcrumbs() + .into_iter() + .map(|(label, _)| label) + .collect(); + assert_eq!(labels, ["/", "srv", "data"]); + app.home = Some(PathBuf::from("/srv")); + assert_eq!(app.display_path(file), r"~/data/logs\old/a:b"); + app.screen = Screen::Review; + cx.notify(); + }); + draw(cx); + press(cx, "y"); + let script = cx + .read_from_clipboard() + .and_then(|item| item.text()) + .expect("script on clipboard"); + assert!(script.contains(r"'/srv/data/logs\old/a:b'"), "{script}"); + assert!(!script.contains(r"data\logs"), "{script}"); +} + +/// Escape in the alert dialog cancels: the dialog closes, the review screen +/// stays, and nothing on disk changes. +#[gpui_kit::test] +fn escape_in_the_delete_dialog_cancels(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + app.removal_mode = RemovalMode::Permanent; + app.marks.toggle( + disktree_core::removal::Target { + path: temp.path().join("junk"), + bytes: 300_000, + is_dir: true, + hidden: false, + }, + app.path_style(), + ); + app.screen = Screen::Review; + cx.notify(); + }); + draw(cx); + + press(cx, "enter"); + assert!(read(&view, cx, |app| app.confirm_open)); + press(cx, "escape"); + assert!(!read(&view, cx, |app| app.confirm_open), "Escape cancels"); + assert_eq!(read(&view, cx, |app| app.screen), Screen::Review); + assert!(temp.path().join("junk").exists()); + assert_eq!( + read(&view, cx, |app| app.marks.len()), + 1, + "the list is kept" + ); +} + +/// With a trash on the machine, the reversible path is the default and +/// commits without a dialog; the permanent one is a deliberate choice. +#[gpui_kit::test] +fn the_trash_is_the_default_when_there_is_one(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + let (mode, available) = read(&view, cx, |app| { + (app.removal_mode, app.trash_backend.is_available()) + }); + if available { + assert_eq!(mode, RemovalMode::Trash); + } else { + assert_eq!(mode, RemovalMode::Permanent); + } +} + +/// `ctrl =` / `ctrl -` / `ctrl 0` change the window's rem, which every size +/// in the app is expressed in, and the mosaic's header band follows it. +#[gpui_kit::test] +fn interface_zoom_scales_the_rem_and_the_header_band(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + let rem = + |cx: &mut Window| cx.update(|window, _| window.rem_size().as_f32()); + let base = rem(cx); + let band = |view: &Entity, cx: &mut Window| { + update(view, cx, |app, _| { + app.layout(); + app.layout_options.header + }) + }; + let base_band = band(&view, cx); + + press(cx, "ctrl-="); + let zoomed = rem(cx); + assert!(zoomed > base, "{zoomed} after zooming in from {base}"); + let zoomed_band = band(&view, cx); + assert!( + (zoomed_band / base_band - zoomed / base).abs() < 0.01, + "the band scales with the rem: {base_band} -> {zoomed_band}" + ); + + press(cx, "ctrl--"); + press(cx, "ctrl--"); + assert!(rem(cx) < base, "zooming out goes below the default"); + press(cx, "ctrl-0"); + assert!((rem(cx) - base).abs() < 0.01, "ctrl 0 resets"); +} + +/// The crumbs of the directory named `name` directly inside `parent`. +fn child_crumbs(app: &Disktree, parent: &[usize], name: &str) -> Vec { + let node = app.node_at(parent).expect("the parent"); + let index = node + .children() + .iter() + .position(|child| child.name() == name) + .unwrap_or_else(|| panic!("no {name}")); + let mut crumbs = parent.to_vec(); + crumbs.push(index); + crumbs +} + +/// Regression: the wheel magnified toward the deepest directory under the +/// pointer, then went into the *top-level* one containing it, so the screen +/// after the descent was never the area that was zoomed into. +#[gpui_kit::test] +fn the_wheel_goes_into_the_directory_it_zoomed_into(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + + // Point at the middle of junk/deeper's contents: a directory one level + // below a top-level one. + let (deeper, point) = update(&view, cx, |app, _| { + let junk = child_crumbs(app, &[], "junk"); + let deeper = child_crumbs(app, &junk, "deeper"); + let body = app.tile_body(&deeper).expect("deeper is drawn"); + (deeper, (body.x + body.w / 2.0, body.y + body.h / 2.0)) + }); + + let mut entered = None; + for _ in 0..40 { + let crumbs = update(&view, cx, |app, cx| { + let (x, y) = app.view.unproject(point.0, point.1); + let screen = app + .view + .project(disktree_core::treemap::Rect::new(x, y, 0.0, 0.0)); + app.zoom_at(screen.x, screen.y, 1.15, true, cx); + app.crumbs.clone() + }); + draw(cx); + if !crumbs.is_empty() { + entered = Some(crumbs); + break; + } + } + assert_eq!( + entered.as_deref(), + Some(deeper.as_slice()), + "descended into the pointed-at directory, not its top-level ancestor" + ); +} + +/// Regression, keyboard side: Enter on a deep selection enters that +/// directory, and on a file enters the directory holding it. +#[gpui_kit::test] +fn enter_opens_the_selected_directory_at_any_depth(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + + let deeper = update(&view, cx, |app, cx| { + let junk = child_crumbs(app, &[], "junk"); + let deeper = child_crumbs(app, &junk, "deeper"); + app.select(Some(deeper.clone()), cx); + app.descend(cx); + deeper + }); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); + + press(cx, "escape"); + press(cx, "escape"); + press(cx, "escape"); + let junk = update(&view, cx, |app, cx| { + app.go_to(Vec::new(), cx); + let junk = child_crumbs(app, &[], "junk"); + let blob = child_crumbs(app, &junk, "blob.bin"); + app.select(Some(blob), cx); + app.descend(cx); + junk + }); + assert_eq!( + read(&view, cx, |app| app.crumbs.clone()), + junk, + "a file opens its directory" + ); +} + +/// The mark key acts on what the pointer is over when the pointer moved +/// last, and on the keyboard selection after an arrow. +#[gpui_kit::test] +fn the_mark_key_follows_the_pointer_until_the_keyboard_moves( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + + // Point at junk's name band, which belongs to junk itself (its body + // belongs to its children). junk is not the default selection, .cache. + let (keep, origin, centre) = update(&view, cx, |app, _| { + let keep = child_crumbs(app, &[], "junk"); + let body = app + .layout() + .and_then(|tiles| { + tiles.iter().find(|tile| tile.crumbs() == keep.as_slice()) + }) + .and_then(|tile| tile.header) + .expect("junk is drawn with a band"); + ( + keep, + app.treemap_origin.get(), + (body.x + body.w / 2.0, body.y + body.h / 2.0), + ) + }); + assert_ne!( + read(&view, cx, |app| app.selected.clone()), + Some(keep.clone()) + ); + cx.simulate_mouse_move( + Point::new(origin.x + px(centre.0), origin.y + px(centre.1)), + None, + gpui_kit::Modifiers::default(), + ); + draw(cx); + + press(cx, "space"); + let marked = read(&view, cx, |app| app.marks.items().to_vec()); + assert_eq!(marked.len(), 1); + assert!( + marked[0].path.ends_with("junk"), + "marked what the pointer is on: {:?}", + marked[0].path + ); + assert_eq!(read(&view, cx, |app| app.selected.clone()), Some(keep)); + + // An arrow hands control back to the keyboard selection. + press(cx, "right"); + assert!(!read(&view, cx, |app| app.pointer_active)); +} + +/// Regression: after descending, tiles resolved against the scanned root +/// instead of the directory drawn, so labels, hover and marks named strangers. +#[gpui_kit::test] +fn after_descending_every_tile_is_inside_the_directory_drawn( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + + let junk = update(&view, cx, |app, cx| { + let junk = child_crumbs(app, &[], "junk"); + app.select(Some(junk.clone()), cx); + app.descend(cx); + junk + }); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), junk); + draw(cx); + + let (paths, labels) = update(&view, cx, |app, _| { + let tiles = app.layout().map(<[Tile]>::to_vec).unwrap_or_default(); + let paths: Vec<_> = tiles + .iter() + .filter_map(|tile| app.path_at(tile.crumbs())) + .collect(); + let labels: Vec = app + .prepare() + .labels + .into_iter() + .map(|label| label.text) + .collect(); + (paths, labels) + }); + assert!(!paths.is_empty()); + let junk_path = temp.path().join("junk"); + for path in &paths { + assert!(path.starts_with(&junk_path), "{path:?} is outside junk"); + } + for label in &labels { + assert!( + ["blob.bin", "deeper", "more.bin"].contains(&label.as_str()) + || label.starts_with('+'), + "label {label} does not belong to junk" + ); + } + + // Space on the selection marks something inside junk, never elsewhere. + update(&view, cx, |app, cx| { + let blob = child_crumbs(app, &junk, "blob.bin"); + app.select(Some(blob), cx); + }); + press(cx, "space"); + let marked = read(&view, cx, |app| app.marks.items().to_vec()); + assert_eq!(marked.len(), 1); + assert_eq!(marked[0].path, junk_path.join("blob.bin")); + assert_eq!(marked[0].bytes, 200_000); + + // And the mark is drawn on the right tile: its crumbs resolve here. + let hatched = update(&view, cx, |app, _| { + app.prepare() + .tiles + .iter() + .filter(|tile| tile.marked) + .count() + }); + assert_eq!(hatched, 1, "exactly the marked tile is hatched"); +} + +/// Drive the scan the view started until its outcome has been applied. +/// +/// The scan is what is waited on, not the tree: widening keeps the old tree +/// on screen while the wider root is read, so a tree being there does not +/// mean the requested scan has completed. +fn finish_scan(view: &Entity, cx: &mut Window) { + // Without a scan in flight the poller reports "stopped" at once, and the + // wait would pass without having waited for anything. + assert!( + read(view, cx, |app| app.scan.is_some()), + "no scan to finish" + ); + let epoch = read(view, cx, |app| app.scan_epoch); + for _ in 0..600 { + std::thread::sleep(std::time::Duration::from_millis(5)); + let running = update(view, cx, |app, cx| app.poll_scan_once(epoch, cx)); + if !running { + let (error, tree) = read(view, cx, |app| { + (app.scan_error.clone(), app.tree().is_some()) + }); + assert_eq!(error, None, "the scan failed"); + assert!(tree, "the scan landed without a tree"); + return; + } + } + panic!("the scan never landed"); +} + +#[gpui_kit::test] +fn dragging_the_panel_edge_resizes_it_within_its_limits( + cx: &mut TestAppContext, +) { + use crate::state::{PANEL_MAX_REMS, PANEL_MIN_REMS, panel_width}; + use gpui_kit::{Modifiers, MouseButton}; + + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1400.), px(900.))); + draw(cx); + let handle = cx.debug_bounds("panel-handle").expect("the panel is shown"); + let start = handle.center(); + let before = read(&view, cx, |app| app.panel_rems); + + // A drag starts on the first move and reports moves after it, as a real + // pointer does in many small steps. + let drag = |cx: &mut Window, from: Point, to: Point| { + cx.simulate_mouse_down(from, MouseButton::Left, Modifiers::none()); + for step in 1..=4 { + let t = step as f32 / 4.0; + let at = Point::new(from.x + (to.x - from.x) * t, to.y); + cx.simulate_mouse_move( + at, + Some(MouseButton::Left), + Modifiers::none(), + ); + } + cx.simulate_mouse_up(to, MouseButton::Left, Modifiers::none()); + draw(cx); + }; + + // Wider: drag the edge 160 px to the left. + let wider = Point::new(start.x - px(160.), start.y); + drag(cx, start, wider); + let after = read(&view, cx, |app| app.panel_rems); + assert!( + (after - before - 10.0).abs() < 0.5, + "160 px is 10 rem: {before} -> {after}" + ); + + // The limits, for any edge position: a minimum, a maximum, and never + // so wide that the mosaic gets less room than the panel's own minimum. + assert!((panel_width(1390., 1400., 16.) - PANEL_MIN_REMS).abs() < 1e-3); + assert!((panel_width(0., 3000., 16.) - PANEL_MAX_REMS).abs() < 1e-3); + let squeezed = panel_width(0., 800., 16.); + assert!((squeezed - (800. / 16. - PANEL_MIN_REMS)).abs() < 1e-3); + assert!((panel_width(0., 300., 16.) - PANEL_MIN_REMS).abs() < 1e-3); +} + +#[gpui_kit::test] +fn widening_reuses_the_tree_it_has_and_reads_only_the_rest( + cx: &mut TestAppContext, +) { + use crate::state::Crumb; + + cx.update(init); + let temp = fixture(); + let inner = temp.path().join("junk"); + let (view, cx) = view_over(&inner, cx); + update(&view, cx, |app, _| { + app.disk_root = Some(temp.path().to_path_buf()); + // Stale on purpose: the wider root, a folder, must reset it. + app.file_table = true; + }); + let before = read(&view, cx, |app| app.tree().map(|tree| tree.files)); + + // The trail runs from the top of the filesystem — "/", or a drive such + // as "C:\" — and the scanned root sits under its parents. + let trail = read(&view, cx, Disktree::breadcrumbs); + let top = temp.path().ancestors().last().expect("a top"); + assert_eq!(trail[0].0, top.display().to_string()); + assert!( + trail.contains(&( + temp.path() + .file_name() + .unwrap() + .to_string_lossy() + .into_owned(), + Crumb::Above(temp.path().to_path_buf()) + )) + ); + + // Written after the first scan: a memoized subtree cannot see it. + std::fs::write(inner.join("late.bin"), vec![0_u8; 4096]).expect("write"); + + press(cx, "g"); + // The old tree stays on screen while the wider one is read. + assert!(read(&view, cx, |app| app.tree().is_some())); + finish_scan(&view, cx); + assert_eq!(read(&view, cx, |app| app.root_path.clone()), temp.path()); + assert!( + !read(&view, cx, |app| app.file_table), + "the offer follows the root it widened to" + ); + let (reused, rest, selected) = read(&view, cx, |app| { + let tree = app.tree().expect("the wider tree"); + let junk = tree.child_named("junk").map(|node| node.files); + let selected = app + .selected + .as_deref() + .and_then(|crumbs| app.node_at(crumbs)) + .map(|node| node.name().to_string()); + (junk, tree.child_named("keep").is_some(), selected) + }); + assert_eq!(reused, before, "junk was reused, not walked again"); + assert!(rest, "what is outside it was walked"); + assert_eq!(selected.as_deref(), Some("junk"), "where you came from"); +} + +#[gpui_kit::test] +fn enter_before_the_search_lands_applies_it_when_it_does( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + + press(cx, "/"); + cx.simulate_input("blob"); + cx.simulate_keystrokes("enter"); + cx.run_until_parked(); + draw(cx); + let (applied, count, open) = read(&view, cx, |app| { + ( + app.filter_applied, + app.matches.as_deref().map(|matches| matches.count), + app.find_open, + ) + }); + assert!(applied, "Enter was not lost to a search in flight"); + assert_eq!(count, Some(2)); + assert!(!open); +} + +#[gpui_kit::test] +fn a_crumb_lists_its_siblings_and_jumps_sideways(cx: &mut TestAppContext) { + use gpui_kit::{Modifiers, MouseButton}; + + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1400.), px(900.))); + draw(cx); + // Into junk, so the trail ends in a crumb that has siblings. + let junk = read(&view, cx, |app| { + app.tree() + .and_then(|tree| { + tree.children().iter().position(|c| c.name() == "junk") + }) + .expect("junk") + }); + update(&view, cx, |app, cx| app.go_to(vec![junk], cx)); + draw(cx); + + let last = read(&view, cx, |app| app.breadcrumbs().len() - 1); + let chevron = cx + .debug_bounds(Box::leak(format!("crumb-{last}-menu").into_boxed_str())) + .expect("the current crumb has a menu"); + cx.simulate_click(chevron.center(), Modifiers::none()); + draw(cx); + assert!( + cx.debug_bounds("sibling-menu").is_some(), + "the menu is drawn" + ); + let (names, highlighted) = read(&view, cx, |app| { + let menu = app.crumb_menu.clone().expect("open"); + let (rows, _) = app.siblings(&menu.parent); + let names: Vec = + rows.iter().map(|row| row.name.clone()).collect(); + let highlighted = names_at(&names, menu.highlighted); + (names, highlighted) + }); + assert!( + names.contains(&".cache".to_string()) + && names.contains(&"keep".to_string()) + ); + assert_eq!(highlighted, "junk", "it opens on where you are"); + + // Walk to .cache by name, not by rank: it and junk are close in size. + let target = names + .iter() + .position(|name| name == ".cache") + .expect("listed"); + let here = names + .iter() + .position(|name| name == "junk") + .expect("listed"); + let key = if target < here { "up" } else { "down" }; + for _ in 0..target.abs_diff(here) { + press(cx, key); + } + press(cx, "enter"); + let (crumbs, open) = read(&view, cx, |app| { + (app.crumbs.clone(), app.crumb_menu.is_some()) + }); + let cache = read(&view, cx, |app| { + app.tree() + .and_then(|tree| { + tree.children().iter().position(|c| c.name() == ".cache") + }) + .expect(".cache") + }); + assert_eq!(crumbs, vec![cache], "went sideways into .cache"); + assert!(!open); + + // A click outside closes it. + let chevron = cx + .debug_bounds(Box::leak(format!("crumb-{last}-menu").into_boxed_str())) + .expect("menu chevron"); + cx.simulate_click(chevron.center(), Modifiers::none()); + draw(cx); + assert!(read(&view, cx, |app| app.crumb_menu.is_some())); + cx.simulate_mouse_down( + gpui_kit::point(px(700.), px(600.)), + MouseButton::Left, + Modifiers::none(), + ); + cx.simulate_mouse_up( + gpui_kit::point(px(700.), px(600.)), + MouseButton::Left, + Modifiers::none(), + ); + draw(cx); + assert!(read(&view, cx, |app| app.crumb_menu.is_none())); +} + +fn names_at(names: &[String], index: usize) -> String { + names.get(index).cloned().unwrap_or_default() +} + +#[gpui_kit::test] +fn marking_a_directory_marks_everything_inside_it(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + let crumbs = |view: &Entity, cx: &mut Window, rel: &str| { + let path = temp.path().join(rel); + read(view, cx, |app| app.crumbs_for_path(&path)).expect(rel) + }; + let junk = crumbs(&view, cx, "junk"); + let deeper = crumbs(&view, cx, "junk/deeper"); + + // Marked inside first, then the directory around it: one mark remains, + // and it covers the inner one. + update(&view, cx, |app, cx| app.toggle_mark(&deeper, cx)); + update(&view, cx, |app, cx| app.toggle_mark(&junk, cx)); + let marks = read(&view, cx, |app| { + app.marks + .items() + .iter() + .map(|item| item.path.clone()) + .collect::>() + }); + assert_eq!( + marks, + vec![temp.path().join("junk")], + "the inner mark is absorbed" + ); + + // Every tile inside it is drawn marked: the ones below the mark are + // "covered", which paints the same fill and label. + let mosaic = update(&view, cx, |app, _| app.prepare()); + let (inside, covered) = update(&view, cx, |app, _| { + let tiles = app.layout().map(<[Tile]>::to_vec).unwrap_or_default(); + let inside: Vec = tiles + .iter() + .zip(&mosaic.tiles) + .filter(|(tile, _)| { + tile.crumbs().starts_with(&junk) && tile.crumbs() != junk + }) + .map(|(_, deco)| deco.covered) + .collect(); + (inside.len(), inside.iter().all(|covered| *covered)) + }); + assert!(inside >= 2, "blob.bin and deeper are drawn inside junk"); + assert!(covered, "every tile inside junk goes with it"); + + // The mark is not said by colour alone (WCAG 1.4.1): its name, and every + // name inside it, is struck through. The name itself is left whole, so + // a narrow tile still shows it rather than a repeated word. + let label = mosaic + .labels + .iter() + .find(|label| label.text == "junk") + .expect("junk is large enough to be labelled, under its own name"); + assert!(label.marked, "a marked name is struck through"); + assert!(label.decoration.marked, "the label paints its tile's state"); + let covered: Vec<_> = mosaic + .labels + .iter() + .filter(|label| label.decoration.covered) + .collect(); + assert!(!covered.is_empty(), "something inside junk is labelled"); + assert!( + covered.iter().all(|label| label.marked), + "what goes with a mark is struck through as going" + ); + assert!( + covered.iter().all(|label| matches!( + &*label.text, + "blob.bin" | "deeper" | "more.bin" + )), + "covered names carry no prefix: {:?}", + covered.iter().map(|label| &label.text).collect::>() + ); + assert!( + mosaic + .labels + .iter() + .filter( + |label| !label.decoration.marked && !label.decoration.covered + ) + .all(|label| !label.marked), + "nothing else is struck" + ); + // Gone inside the mark, the trail still shows it: the crumbs for junk + // and anything in it are struck, the rest are not. + let keep = crumbs(&view, cx, "keep"); + read(&view, cx, |app| { + assert!(app.goes_with_a_mark(&junk)); + assert!(app.goes_with_a_mark(&deeper)); + assert!(!app.goes_with_a_mark(&keep)); + assert!(!app.goes_with_a_mark(&[]), "the scanned root"); + }); + + // Marking something inside it is refused, and says why. + update(&view, cx, |app, cx| app.toggle_mark(&deeper, cx)); + let (count, notice) = read(&view, cx, |app| { + (app.marks.len(), app.notice().map(|(text, _)| text)) + }); + assert_eq!(count, 1); + assert!(notice.is_some_and(|text| text.contains("goes with the marked"))); + + // Unmarking the directory unmarks everything. + update(&view, cx, |app, cx| app.toggle_mark(&junk, cx)); + assert!(read(&view, cx, |app| app.marks.is_empty())); +} + +/// `<` and `>` retrace the directories visited, are disabled when there is +/// nowhere to go, and a fresh move ends what was ahead. +#[gpui_kit::test] +fn back_and_forward_retrace_where_you_have_been(cx: &mut TestAppContext) { + use gpui_kit::Modifiers; + + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1400.), px(900.))); + draw(cx); + let can = |view: &Entity, cx: &Window| { + read(view, cx, |app| (app.can_go_back(), app.can_go_forward())) + }; + assert_eq!(can(&view, cx), (false, false), "nowhere to go yet"); + + let (junk, deeper, keep) = update(&view, cx, |app, cx| { + let junk = child_crumbs(app, &[], "junk"); + let deeper = child_crumbs(app, &junk, "deeper"); + let keep = child_crumbs(app, &[], "keep"); + app.select(Some(deeper.clone()), cx); + app.descend(cx); + (junk, deeper, keep) + }); + draw(cx); + assert_eq!(can(&view, cx), (true, false)); + + // Hovering `<` shows the card for where it goes, as hovering a tile + // does: here, the scanned root. It hangs below the button, never on it. + let back = cx + .debug_bounds("history-back") + .expect("the button is drawn"); + cx.simulate_mouse_move(back.center(), None, Modifiers::none()); + draw(cx); + let card = cx.debug_bounds("history-tip").expect("the card is shown"); + assert!(card.top() >= back.bottom(), "{card:?} covers {back:?}"); + assert_eq!( + read(&view, cx, |app| app.history_target(true)), + Some((0, Vec::new())) + ); + + let click = |cx: &mut Window, selector: &'static str| { + let bounds = cx.debug_bounds(selector).expect("the button is drawn"); + cx.simulate_click(bounds.center(), Modifiers::none()); + draw(cx); + }; + click(cx, "history-back"); + assert_eq!( + read(&view, cx, |app| app.crumbs.clone()), + Vec::::new() + ); + assert_eq!(can(&view, cx), (false, true), "back at the start"); + + click(cx, "history-forward"); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); + assert_eq!(can(&view, cx), (true, false)); + + // Up a level is a move of its own, and the keys retrace it too. + press(cx, "backspace"); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), junk); + press(cx, "alt-left"); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); + press(cx, "alt-left"); + assert_eq!( + read(&view, cx, |app| app.crumbs.clone()), + Vec::::new() + ); + press(cx, "alt-right"); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); + + // Going somewhere new from the middle of the history drops what was + // ahead of it, as in a browser. + press(cx, "alt-left"); + update(&view, cx, |app, cx| app.go_to(keep, cx)); + draw(cx); + assert_eq!(can(&view, cx), (true, false), "the forward trail is gone"); + press(cx, "alt-left"); + assert_eq!( + read(&view, cx, |app| app.crumbs.clone()), + Vec::::new() + ); +} + +/// Regression: children are ordered by the metric, so switching between +/// Size and Files reorders them. The directory on screen and the selection +/// are found again by path, rather than following their old positions into +/// a sibling. +#[gpui_kit::test] +fn switching_the_metric_keeps_the_directory_and_the_selection( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = tempfile::TempDir::new().expect("tempdir"); + let root = temp.path(); + // Largest by size, but fewest files: the two swap places. + std::fs::create_dir_all(root.join("big")).expect("mkdir"); + std::fs::write(root.join("big/one.bin"), vec![b'x'; 500_000]) + .expect("write"); + std::fs::write(root.join("big/two.bin"), vec![b'x'; 1_000]).expect("write"); + for index in 0..5 { + let file = root.join(format!("many/{index}.txt")); + std::fs::create_dir_all(file.parent().expect("parent")).expect("mkdir"); + std::fs::write(&file, b"x").expect("write"); + } + let (view, cx) = view_over(root, cx); + draw(cx); + + update(&view, cx, |app, cx| { + let big = child_crumbs(app, &[], "big"); + assert_eq!(big, vec![0], "largest first by size"); + app.go_to(big.clone(), cx); + let one = child_crumbs(app, &big, "one.bin"); + app.select(Some(one), cx); + }); + draw(cx); + + update(&view, cx, |app, cx| app.set_mode(1, cx)); + draw(cx); + let (here, selected) = read(&view, cx, |app| { + ( + app.current_path(), + app.selected + .as_deref() + .and_then(|crumbs| app.path_at(crumbs)), + ) + }); + assert_eq!(here, root.join("big")); + assert_eq!(selected, Some(root.join("big/one.bin"))); + + update(&view, cx, |app, cx| app.set_mode(0, cx)); + draw(cx); + assert_eq!(read(&view, cx, Disktree::current_path), root.join("big")); +} + +/// The size/files toggle reorders the window's tree where it lies rather +/// than copying it, yet still hands out a new tree; a tree another task is +/// reading is copied and left in its old order. +#[gpui_kit::test] +fn toggling_the_metric_reorders_without_copying_the_tree( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = tempfile::tempdir().expect("tempdir"); + let root = temp.path(); + std::fs::create_dir_all(root.join("big")).expect("mkdir"); + std::fs::write(root.join("big/one.bin"), vec![b'x'; 500_000]) + .expect("write"); + for index in 0..5 { + let file = root.join(format!("many/{index}.txt")); + std::fs::create_dir_all(file.parent().expect("parent")).expect("mkdir"); + std::fs::write(&file, b"x").expect("write"); + } + let (view, cx) = view_over(root, cx); + draw(cx); + let first = |app: &Disktree| { + app.tree + .as_ref() + .expect("tree") + .root() + .children() + .at(0) + .name() + .to_string() + }; + + let (tree, children) = read(&view, cx, |app| { + let tree = app.tree.as_ref().expect("tree"); + // Where the root's children start: an in-place reorder keeps it. + let children = tree.root().children().at(0).facts(); + (std::sync::Arc::as_ptr(tree), std::ptr::from_ref(children)) + }); + assert_eq!(read(&view, cx, first), "big"); + update(&view, cx, Disktree::toggle_metric); + draw(cx); + assert_eq!(read(&view, cx, first), "many", "most files first"); + let (after, children_after) = read(&view, cx, |app| { + let tree = app.tree.as_ref().expect("tree"); + // Where the root's children start: an in-place reorder keeps it. + let children = tree.root().children().at(0).facts(); + (std::sync::Arc::as_ptr(tree), std::ptr::from_ref(children)) + }); + assert_eq!(children_after, children, "the nodes were not copied"); + assert_ne!(after, tree, "but the tree is a new one"); + + let held = read(&view, cx, |app| app.tree.clone().expect("tree")); + update(&view, cx, Disktree::toggle_metric); + draw(cx); + assert_eq!(read(&view, cx, first), "big"); + assert_eq!( + held.root().children().at(0).name(), + "many", + "a reader keeps its order" + ); +} + +/// Escape stops a first scan. What the walk found so far is not shown as a +/// tree, a late result is ignored, and `r` starts over. +#[gpui_kit::test] +fn escape_cancels_the_first_scan_and_r_starts_it_again( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let root = temp.path().to_path_buf(); + let (view, cx) = + cx.add_window_view(move |_, cx| Disktree::new(root, options(), 3, cx)); + let focus = view.read_with(cx, |app, _| app.focus.clone()); + cx.update(|window, cx| window.focus(&focus, cx)); + draw(cx); + let epoch = read(&view, cx, |app| app.scan_epoch); + + press(cx, "escape"); + let (scanning, cancelled) = read(&view, cx, |app| { + (app.scan.is_some(), app.progress.cancelled) + }); + assert!(!scanning, "the walk was dropped"); + assert!(cancelled, "the panel can say it stopped"); + std::thread::sleep(std::time::Duration::from_millis(50)); + let polling = update(&view, cx, |app, cx| app.poll_scan_once(epoch, cx)); + assert!(!polling, "the old poller stops"); + assert!(read(&view, cx, |app| app.tree().is_none())); + draw(cx); + + press(cx, "r"); + finish_scan(&view, cx); + assert!(read(&view, cx, |app| app.tree().is_some())); +} + +/// Escape stops a widening scan and keeps the tree it started from. +#[gpui_kit::test] +fn escape_cancels_widening_and_keeps_the_tree_on_screen( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let inner = temp.path().join("junk"); + let (view, cx) = view_over(&inner, cx); + update(&view, cx, |app, _| { + app.disk_root = Some(temp.path().to_path_buf()); + }); + let before = read(&view, cx, |app| app.tree().map(|tree| tree.files)); + + press(cx, "g"); + assert!(read(&view, cx, |app| app.scan.is_some())); + press(cx, "escape"); + let (scanning, root, scan_root, files) = read(&view, cx, |app| { + ( + app.scan.is_some(), + app.root_path.clone(), + app.scan_root.clone(), + app.tree().map(|tree| tree.files), + ) + }); + assert!(!scanning); + assert_eq!(root, inner); + assert_eq!(scan_root, inner, "the trail stops showing a widening"); + assert_eq!(files, before, "the tree on screen is unchanged"); +} + +/// The mouse's back and forward buttons retrace the same history as +/// alt-arrows and the header buttons, and only on the explore screen. +#[gpui_kit::test] +fn mouse_side_buttons_go_back_and_forward(cx: &mut TestAppContext) { + use gpui_kit::{Modifiers, MouseButton, NavigationDirection}; + + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1400.), px(900.))); + draw(cx); + + let (junk, deeper) = update(&view, cx, |app, cx| { + let junk = child_crumbs(app, &[], "junk"); + let deeper = child_crumbs(app, &junk, "deeper"); + app.select(Some(junk.clone()), cx); + app.descend(cx); + app.select(Some(deeper.clone()), cx); + app.descend(cx); + (junk, deeper) + }); + draw(cx); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); + + // Over the mosaic, buttons 8 and 9 step the history, as alt-arrows do. + let mosaic = cx.debug_bounds("treemap").expect("the mosaic is drawn"); + let at = mosaic.center(); + let press_button = |cx: &mut Window, button: MouseButton| { + cx.simulate_mouse_move(at, None, Modifiers::none()); + cx.simulate_mouse_down(at, button, Modifiers::none()); + cx.simulate_mouse_up(at, button, Modifiers::none()); + draw(cx); + }; + press_button(cx, MouseButton::Navigate(NavigationDirection::Back)); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), junk); + press_button(cx, MouseButton::Navigate(NavigationDirection::Forward)); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); + + // On the review screen the same press changes nothing: the marked list + // is not somewhere the history can take you back to. + update(&view, cx, |app, cx| app.toggle_mark(&junk, cx)); + press(cx, "c"); + assert_eq!(read(&view, cx, |app| app.screen), Screen::Review); + press_button(cx, MouseButton::Navigate(NavigationDirection::Back)); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); + assert_eq!(read(&view, cx, |app| app.screen), Screen::Review); +} + +/// The restart as administrator reopens the same root and options: every +/// flag it writes is one the command line reads back. +#[test] +fn restart_arguments_parse_back_to_the_same_scan() { + use disktree_core::tree::Metric; + let temp = tempfile::TempDir::new().expect("tempdir"); + let root = temp.path().join("a folder"); + std::fs::create_dir(&root).expect("mkdir"); + let root = dunce::canonicalize(&root).expect("canonical root"); + let changed = ScanOptions { + apparent_size: true, + follow_links: true, + include_hidden: false, + one_filesystem: false, + metric: Metric::Files, + threads: disktree_core::scan_threads::ScanThreads { + max_threads: 8, + adaptive: true, + retained_throughput: 0.85, + system_cpu_limit: Some(0.70), + }, + ..ScanOptions::default() + }; + for (options, depth) in [(changed, 5), (ScanOptions::default(), 1)] { + let args = crate::state::restart_args(&options, depth, &root); + let parsed = crate::parse_args(args.into_iter()).expect("parses"); + assert_eq!(parsed.root, root); + assert_eq!(parsed.depth, depth); + let got = &parsed.options; + assert_eq!(got.threads.max_threads, options.threads.max_threads); + assert_eq!(got.threads.adaptive, options.threads.adaptive); + assert!( + (got.threads.retained_throughput + - options.threads.retained_throughput) + .abs() + < f64::EPSILON + ); + assert_eq!( + got.threads.system_cpu_limit, + options.threads.system_cpu_limit + ); + assert_eq!( + ( + got.apparent_size, + got.follow_links, + got.include_hidden, + got.one_filesystem, + got.metric, + ), + ( + options.apparent_size, + options.follow_links, + options.include_hidden, + options.one_filesystem, + options.metric, + ) + ); + } +} + +#[cfg(target_os = "macos")] +#[gpui_kit::test] +fn apfs_clones_use_private_bytes_in_review_and_refresh( + cx: &mut TestAppContext, +) { + cx.update(init); + // The macOS system-tree guard deliberately refuses canonical /private. + let temp = tempfile::tempdir_in(std::env::current_dir().expect("cwd")) + .expect("tempdir in the checkout"); + let root = std::fs::canonicalize(temp.path()).expect("canonical root"); + std::fs::create_dir(root.join("copies")).expect("mkdir"); + let original = root.join("original"); + std::fs::write(&original, vec![0x5a; 8 * 1024 * 1024]).expect("write"); + assert!( + std::process::Command::new("cp") + .arg("-c") + .arg(&original) + .arg(root.join("copies/clone")) + .status() + .expect("cp -c") + .success() + ); + let options = ScanOptions::default(); + let tree = scan(&root, options.clone()).expect("scan"); + let root_for_view = root.clone(); + let (view, cx) = cx.add_window_view(move |_, cx| { + Disktree::with_tree(root_for_view.clone(), tree, options, 3, cx) + }); + draw(cx); + // The window answers a listing with the clone split `pwrdisk mcp` + // computes in process, and draws the same split for the selection. + update(&view, cx, |app, cx| { + let answer = app.answer_agent( + &disktree_link::Request::Ls { + path: root.clone(), + limit: 10, + }, + cx, + ); + let disktree_link::Response::Listing(listing) = answer else { + panic!("{answer:?}"); + }; + let tree = app.tree().expect("tree"); + let here = + disktree_link::Listing::of(&root, tree.bytes, &root, tree, 10); + assert_eq!(listing, here); + let copies = listing + .children + .iter() + .find(|child| child.name == "copies") + .and_then(|child| child.clones) + .expect("clone facts for copies"); + assert!(copies.private <= 8 * 1024, "{copies:?}"); + assert!(copies.shared >= 8 * 1024 * 1024 - 64 * 1024, "{copies:?}"); + let node = tree + .children() + .iter() + .find(|node| node.name() == "copies") + .expect("copies"); + let split = crate::views::clone_split(node).expect("a split"); + assert!(split.contains("shared with other APFS clones"), "{split}"); + }); + // The accessible file list draws the split on its rows too. + update(&view, cx, |app, _| app.file_list = true); + draw(cx); + update(&view, cx, |app, _| app.file_list = false); + update(&view, cx, |app, cx| { + let index = app + .tree() + .expect("tree") + .children() + .iter() + .position(|node| node.name() == "copies") + .expect("copies"); + app.toggle_mark(&[index], cx); + app.screen = Screen::Review; + }); + draw(cx); + read(&view, cx, |app| { + assert_eq!(app.plan().bytes(), 8 * 1024 * 1024); + assert_eq!(app.plan().reclaimable_bytes(), 0); + let state = app.agent_state(); + let estimate = state.estimate.expect("linked estimate"); + assert_eq!(estimate.paths, vec![root.join("copies")]); + assert_eq!((estimate.lower, estimate.upper), (0, Some(0))); + assert_eq!(estimate.on_volume, 0); + // The agent hears why: the listed bytes are clone blocks. + assert!(estimate.shared >= 8 * 1024 * 1024 - 64 * 1024); + }); + // Remote selections are exports: local clone metadata and mount + // attribution cannot authorize or project a remote saving. + update(&view, cx, |app, _| { + app.remote = Some("test-fixture".into()); + let selection = app.plan(); + assert_eq!(selection.targets.len(), 1); + assert_eq!(selection.reclaim(), 0); + assert_eq!(selection.unattributed(), 8 * 1024 * 1024); + assert!(app.run.is_none()); + }); + draw(cx); + update(&view, cx, |app, _| { + app.remote = None; + assert_eq!(app.plan().reclaimable_bytes(), 0); + }); + update(&view, cx, |app, _| { + app.removal_mode = RemovalMode::Permanent; + app.confirm_open = true; + }); + draw(cx); + update(&view, cx, |app, _| app.confirm_open = false); + // Separate marks complete the group. Changing tile weights must never + // turn the review's byte values into file counts. + update(&view, cx, |app, cx| { + app.options.metric = disktree_core::tree::Metric::Files; + let index = app + .tree() + .expect("tree") + .children() + .iter() + .position(|node| node.name() == "original") + .expect("original"); + app.toggle_mark(&[index], cx); + let plan = app.plan(); + assert_eq!(plan.bytes(), 16 * 1024 * 1024); + assert_eq!(plan.reclaimable_bytes(), 8 * 1024 * 1024); + assert_eq!(plan.possible_bytes(), 8 * 1024 * 1024); + let estimate = app.agent_state().estimate.expect("linked union"); + assert_eq!(estimate.lower, 8 * 1024 * 1024); + assert_eq!(estimate.upper, Some(estimate.lower)); + }); + draw(cx); + crate::marks::work::reset(); + read(&view, cx, |app| { + for _ in 0..4 { + assert_eq!(app.plan().reclaimable_bytes(), 8 * 1024 * 1024); + } + }); + assert_eq!( + crate::marks::work::RESOLUTION.get(), + 0, + "warm plans must not resolve paths again" + ); + update(&view, cx, |app, _| { + app.marks.remove(&root.join("original"), app.path_style()); + assert_eq!(app.plan().reclaimable_bytes(), 0); + app.options.metric = disktree_core::tree::Metric::Bytes; + }); + // Break sharing and refresh the same absolute-path mark. + std::fs::remove_file(root.join("copies/clone")).expect("remove clone"); + std::fs::write(root.join("copies/clone"), vec![0x31; 8 * 1024 * 1024]) + .expect("replace"); + let refreshed = scan(&root, ScanOptions::default()).expect("rescan"); + update(&view, cx, |app, _| { + app.marks.refresh( + &root, + refreshed.root(), + disktree_core::tree::Metric::Bytes, + app.path_style(), + ); + app.tree = Some(std::sync::Arc::new(refreshed.clone())); + }); + assert_eq!( + read(&view, cx, |app| app.plan().reclaimable_bytes()), + 8 * 1024 * 1024 + ); + draw(cx); +} + +#[gpui_kit::test] +fn power_efficiency_menu_saves_without_discarding_the_tree( + cx: &mut TestAppContext, +) { + use crate::power::{self, PowerEfficiency as Power}; + use gpui_kit::Modifiers; + + cx.update(init); + let temp = fixture(); + let config = tempfile::tempdir().expect("config"); + let path = config.path().join("power-efficiency"); + let (view, cx) = view_over(temp.path(), cx); + // Wide enough for the gauge to sit in the bar rather than in ⋮. + cx.simulate_resize(gpui_kit::size(px(1280.), px(800.))); + update(&view, cx, |app, _| { + app.power_settings_path = Some(path.clone()); + // Enough CPUs that every preset is offered, whatever runs the test. + app.cpu_threads = 18; + }); + let epoch = read(&view, cx, |app| app.scan_epoch); + for preset in Power::ALL { + draw(cx); + let button = cx.debug_bounds("power-efficiency").expect("control"); + cx.simulate_click(button.center(), Modifiers::none()); + draw(cx); + let choice = cx.debug_bounds(preset.key()).expect("preset"); + cx.simulate_click(choice.center(), Modifiers::none()); + draw(cx); + assert_eq!(power::load(&path).expect("saved"), preset); + read(&view, cx, |app| { + assert_eq!(app.power_choice, Some(preset)); + assert_eq!( + app.options.threads.max_threads, + preset.threads(app.cpu_threads) + ); + assert!(!app.options.threads.adaptive); + assert!(app.power_menu.is_none()); + assert_eq!(app.scan_epoch, epoch); + assert!(app.tree.is_some()); + }); + } + // Persistence failure must not masquerade as a saved preference. + update(&view, cx, |app, cx| { + app.power_settings_path = Some(config.path().to_owned()); + app.set_power_efficiency(Power::Miser, cx); + }); + assert!(read(&view, cx, |app| app.notice().as_ref().is_some_and( + |(message, _)| message.contains("could not be saved") + ))); + update(&view, cx, Disktree::start_scan); + assert_eq!(read(&view, cx, |app| app.scan_epoch), epoch + 1); +} + +#[gpui_kit::test] +fn the_power_menu_offers_only_what_the_cpus_can_tell_apart( + cx: &mut TestAppContext, +) { + use crate::power::PowerEfficiency as Power; + use gpui_kit::Modifiers; + + cx.update(init); + let temp = fixture(); + let config = tempfile::tempdir().expect("config"); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1280.), px(800.))); + update(&view, cx, |app, _| { + app.power_settings_path = Some(config.path().join("power")); + // Aggressive and Drain My Battery would both run four workers. + app.cpu_threads = 4; + app.power_choice = Some(Power::Balanced); + }); + draw(cx); + let toggle = cx.debug_bounds("power-efficiency").expect("control"); + cx.simulate_mouse_move(toggle.center(), None, Modifiers::none()); + cx.simulate_click(toggle.center(), Modifiers::none()); + draw(cx); + assert_eq!(read(&view, cx, |app| app.power_menu), Some(1)); + + // The pointer takes the highlight, and the check stays on what is saved. + let miser = cx.debug_bounds(Power::Miser.key()).expect("row"); + cx.simulate_mouse_move(miser.center(), None, Modifiers::none()); + draw(cx); + assert_eq!(read(&view, cx, |app| app.power_menu), Some(0)); + let balanced = cx.debug_bounds(Power::Balanced.key()).expect("row"); + let check = cx.debug_bounds("power-check").expect("check"); + assert!(balanced.contains(&check.center()), "check on {check:?}"); + + // A disabled row ignores the click and leaves the menu to be dismissed. + let drain = cx.debug_bounds(Power::DrainMyBattery.key()).expect("row"); + cx.simulate_click(drain.center(), Modifiers::none()); + draw(cx); + read(&view, cx, |app| { + assert_eq!(app.power_choice, Some(Power::Balanced)); + assert!(app.notice().is_none()); + }); + + // The arrows step over what is not offered, and Enter chooses. + update(&view, cx, |app, cx| { + app.power_menu = None; + app.toggle_power_menu(cx); + }); + press(cx, "down"); + assert_eq!(read(&view, cx, |app| app.power_menu), Some(1)); + press(cx, "up"); + assert_eq!(read(&view, cx, |app| app.power_menu), Some(0)); + press(cx, "enter"); + read(&view, cx, |app| { + assert_eq!(app.power_choice, Some(Power::Miser)); + assert_eq!(app.options.threads.max_threads, 2); + assert!(app.power_menu.is_none()); + }); + + // The button closes what it opened, rather than the press outside the + // menu closing it only for the click to open it again. + draw(cx); + let toggle = cx.debug_bounds("power-efficiency").expect("control"); + cx.simulate_mouse_move(toggle.center(), None, Modifiers::none()); + cx.simulate_click(toggle.center(), Modifiers::none()); + draw(cx); + assert!(read(&view, cx, |app| app.power_menu.is_some())); + cx.simulate_click(toggle.center(), Modifiers::none()); + draw(cx); + assert!(read(&view, cx, |app| app.power_menu.is_none())); +} + +/// Exercise prepare through actual window draws, including repeated renders. +#[gpui_kit::test] +fn marked_window_resolution_budget(cx: &mut TestAppContext) { + use crate::marks::work; + use disktree_core::removal::Target; + use disktree_core::tree::{Draft, Metric, NodeKind, Tree, aggregate}; + + cx.update(init); + let mut measure = |count| { + let temp = tempfile::tempdir().expect("tempdir"); + let root_path = temp.path().to_path_buf(); + let mut tree = Draft::directory("root"); + for index in 0..count { + let mut folder = Draft::directory(format!("folder-{index:05}")); + folder + .children + .push(Draft::entry("payload", NodeKind::File, 1)); + tree.children.push(folder); + } + let mut tree = Tree::from(tree); + aggregate(&mut tree, Metric::Bytes); + let (view, window) = cx.add_window_view(move |_, cx| { + Disktree::with_tree(root_path.clone(), tree, options(), 3, cx) + }); + update(&view, window, |app, _| { + for index in 0..count { + app.marks.toggle( + Target { + path: temp + .path() + .join(format!("folder-{index:05}")) + .join("payload"), + bytes: 1, + is_dir: false, + hidden: false, + }, + app.path_style(), + ); + } + }); + work::reset(); + let start = std::time::Instant::now(); + for _ in 0..4 { + update(&view, window, |_, cx| cx.notify()); + draw(window); + } + let elapsed = start.elapsed(); + let frames = work::FRAMES.get(); + let operations = work::RESOLUTION.get(); + let tiles = work::TILES.get(); + assert!(tiles > 0 && tiles <= count * 4 * frames); + work::reset(); + let warm_start = std::time::Instant::now(); + for _ in 0..4 { + update(&view, window, |_, cx| cx.notify()); + draw(window); + } + let warm_elapsed = warm_start.elapsed(); + let warm_frames = work::FRAMES.get(); + let warm_work = work::RESOLUTION.get(); + assert!(warm_frames >= 4); + assert!( + warm_work <= 64 * warm_frames, + "unchanged renders must not resolve all marks: {warm_work}" + ); + assert_eq!( + work::TILES.get() * frames, + tiles * warm_frames, + "visible tile work remains linear in frame count" + ); + eprintln!( + "warm window M={count} prepares={warm_frames} resolution={warm_work} tiles={} wall={warm_elapsed:?}", + work::TILES.get() + ); + window.update(|window, _| window.remove_window()); + assert!(frames >= 4, "budget must cover actual renders: {frames}"); + assert!(operations > 0, "resolution instrumentation must run"); + eprintln!( + "window M={count} N={} draws=4 prepares={frames} work={operations} wall={elapsed:?}", + count * 2 + ); + (operations, frames) + }; + let (small, small_frames) = measure(128); + let (large, large_frames) = measure(1024); + assert!( + large * small_frames <= small * large_frames * 16, + "8x marks/folders per frame: {small}/{small_frames} -> {large}/{large_frames}" + ); + assert!( + large <= 1024 * large_frames * 16, + "absolute work cap: {large}" + ); +} + +#[gpui_kit::test] +fn marked_tiles_follow_metric_rescan_and_mark_changes(cx: &mut TestAppContext) { + use disktree_core::removal::Target; + use std::sync::Arc; + + fn marked_paths(app: &mut Disktree) -> Vec { + let mosaic = app.prepare(); + let tiles = app.layout().expect("layout").to_vec(); + tiles + .iter() + .zip(mosaic.tiles) + .filter_map(|(tile, deco)| { + deco.marked.then(|| app.path_at(tile.crumbs())).flatten() + }) + .collect() + } + + cx.update(init); + let temp = fixture(); + let (view, window) = view_over(temp.path(), cx); + let junk = temp.path().join("junk"); + update(&view, window, |app, cx| { + app.marks.toggle( + Target { + path: junk.clone(), + bytes: 300_000, + is_dir: true, + hidden: false, + }, + app.path_style(), + ); + cx.notify(); + }); + draw(window); + assert_eq!( + update(&view, window, |app, _| marked_paths(app)), + std::slice::from_ref(&junk) + ); + update(&view, window, Disktree::toggle_metric); + draw(window); + assert_eq!( + update(&view, window, |app, _| marked_paths(app)), + std::slice::from_ref(&junk) + ); + update(&view, window, |app, cx| { + // Child lists are fixed once built: reorder through a draft. + let mut tree = app.tree.as_ref().expect("tree").root().to_draft(); + tree.children.reverse(); + app.tree = Some(Arc::new(disktree_core::tree::Tree::from(tree))); + cx.notify(); + }); + draw(window); + assert_eq!( + update(&view, window, |app, _| marked_paths(app)), + std::slice::from_ref(&junk) + ); + update(&view, window, |app, cx| app.unmark(&junk, cx)); + draw(window); + assert!(update(&view, window, |app, _| marked_paths(app)).is_empty()); +} + +/// Opt-in latency evidence, separate from deterministic CI work budgets. +#[gpui_kit::test] +#[ignore = "manual interaction timing on synthetic temporary files"] +fn marked_interaction_timings(cx: &mut TestAppContext) { + use crate::marks::work; + use disktree_core::removal::Target; + use gpui_kit::Modifiers; + + fn measure( + view: &Entity, + window: &mut Window, + action: &str, + repeat: usize, + run: impl FnOnce(&mut Window), + ) { + let before = read(view, window, |app| app.marks.len()); + work::reset(); + let start = std::time::Instant::now(); + run(window); + let elapsed = start.elapsed(); + let after = read(view, window, |app| app.marks.len()); + assert!(work::RENDERS.get() > 0, "must render the real screen"); + assert!(work::PLANS.get() > 0, "must include removal projections"); + assert_eq!(work::REFRESHES.get(), 0, "interaction must not rescan"); + eprintln!( + "interaction action={action} repeat={repeat} marks={before}->{after} renders={} prepares={} plans={} refreshes={} wall={elapsed:?}", + work::RENDERS.get(), + work::FRAMES.get(), + work::PLANS.get(), + work::REFRESHES.get(), + ); + } + + cx.update(init); + let temp = tempfile::tempdir().expect("tempdir"); + // One broad directory, kept fixed while only the number of marks grows. + // Each marked folder contains a file: descendants still make one mark. + for index in 0..1025 { + let folder = temp.path().join(format!("folder-{index:05}")); + std::fs::create_dir(&folder).expect("mkdir"); + std::fs::write(folder.join("payload"), [b'x'; 64]).expect("write"); + } + let tree = scan(temp.path(), options()).expect("scan private fixture"); + let extra_path = temp.path().join("folder-01024"); + for count in [0, 1, 8, 32, 128, 1024] { + let root_path = temp.path().to_path_buf(); + let snapshot = tree.clone(); + let (view, window) = cx.add_window_view(move |_, cx| { + Disktree::with_tree(root_path.clone(), snapshot, options(), 3, cx) + }); + window.simulate_resize(gpui_kit::size(px(1400.), px(900.))); + let focus = read(&view, window, |app| app.focus.clone()); + window.update(|window, cx| window.focus(&focus, cx)); + update(&view, window, |app, cx| { + assert!(app.space.is_some() && app.show_selection); + for index in 0..count { + app.marks.toggle( + Target { + path: temp.path().join(format!("folder-{index:05}")), + bytes: 64, + is_dir: true, + hidden: false, + }, + app.path_style(), + ); + } + cx.notify(); + }); + draw(window); + for repeat in 1..=3 { + update(&view, window, |app, cx| { + app.pointer_active = false; + app.hovered = None; + app.pointer = None; + let crumbs = + app.crumbs_for_path(&extra_path).expect("extra folder"); + app.select(Some(crumbs), cx); + }); + draw(window); + measure(&view, window, "mark-space", repeat, |window| { + press(window, "space"); + }); + assert_eq!(read(&view, window, |app| app.marks.len()), count + 1); + let at = update(&view, window, |app, _| { + let tile = app + .layout() + .expect("layout") + .iter() + .find(|tile| { + matches!( + tile.kind, + disktree_core::treemap::TileKind::Node { .. } + ) + }) + .expect("node tile") + .rect; + let rect = app.view.project(tile); + let origin = app.treemap_origin.get(); + Point::new( + origin.x + px(rect.x + rect.w / 2.), + origin.y + px(rect.y + rect.h / 2.), + ) + }); + measure(&view, window, "hover", repeat, |window| { + window.simulate_mouse_move(at, None, Modifiers::none()); + draw(window); + }); + assert!(read(&view, window, |app| app.hovered.is_some())); + measure(&view, window, "review-c", repeat, |window| { + press(window, "c"); + }); + assert_eq!(read(&view, window, |app| app.screen), Screen::Review); + press(window, "escape"); + update(&view, window, |app, cx| { + app.pointer_active = false; + app.hovered = None; + app.pointer = None; + let crumbs = + app.crumbs_for_path(&extra_path).expect("extra folder"); + app.select(Some(crumbs), cx); + }); + draw(window); + press(window, "space"); + assert_eq!(read(&view, window, |app| app.marks.len()), count); + } + window.update(|window, _| window.remove_window()); + } +} + +/// The disk root is private and empty; only the displayed tree is synthetic. +fn queue_budget_view( + count: usize, + cx: &mut TestAppContext, +) -> (tempfile::TempDir, Entity, &mut Window) { + use disktree_core::tree::{Draft, Metric, NodeKind, Tree, aggregate}; + + let temp = tempfile::tempdir().expect("tempdir"); + let root_path = temp.path().to_path_buf(); + let mut tree = Draft::directory("root"); + let mut parent = Draft::directory("container"); + for index in 0..count { + parent.children.push(Draft::entry( + format!("file-{index:05}"), + NodeKind::File, + 1, + )); + } + tree.children.push(parent); + tree.children.push(Draft::entry("keep", NodeKind::File, 1)); + let mut tree = Tree::from(tree); + aggregate(&mut tree, Metric::Bytes); + let (view, window) = cx.add_window_view(move |_, cx| { + Disktree::with_tree(root_path.clone(), tree, options(), 3, cx) + }); + (temp, view, window) +} + +#[gpui_kit::test] +fn queue_construction_budget(cx: &mut TestAppContext) { + use crate::marks::work; + + cx.update(init); + let mut measure = |count| { + let (_temp, view, window) = queue_budget_view(count, cx); + let operations = update(&view, window, |app, cx| { + work::reset(); + let start = std::time::Instant::now(); + for index in 0..count { + app.toggle_mark(&[0, index], cx); + } + assert_eq!(app.marks.len(), count); + assert_eq!( + work::FRAMES.get(), + 0, + "measure insertion before rendering" + ); + let operations = work::MARKING.get() + work::COMPACTION.get(); + assert!(operations > 0); + eprintln!( + "queue-construction M={count} work={operations} wall={:?}", + start.elapsed() + ); + operations + }); + window.update(|window, _| window.remove_window()); + operations + }; + let small = measure(128); + let large = measure(1024); + assert!(large <= small * 16, "8x marks: {small} -> {large}"); + assert!(large <= 1024 * 32, "absolute insertion budget: {large}"); +} + +#[gpui_kit::test] +fn parent_absorption_budget(cx: &mut TestAppContext) { + use crate::marks::work; + + cx.update(init); + let mut measure = |count| { + let (temp, view, window) = queue_budget_view(count, cx); + let operations = update(&view, window, |app, cx| { + let keep = app.target_at(&[1]).expect("neighbour"); + app.marks.toggle(keep.clone(), app.path_style()); + for index in 0..count { + let target = app.target_at(&[0, index]).expect("file"); + app.marks.toggle(target, app.path_style()); + } + work::reset(); + let start = std::time::Instant::now(); + app.toggle_mark(&[0], cx); + assert_eq!(app.marks.len(), 2); + assert_eq!(app.marks.items()[0], keep, "neighbour stays in order"); + assert_eq!( + app.marks.items()[1].path, + temp.path().join("container") + ); + assert_eq!(app.marks.items()[1].bytes, count as u64); + let operations = work::MARKING.get() + work::COMPACTION.get(); + assert!(operations > 0); + eprintln!( + "parent-absorption M={count} work={operations} compactions={} wall={:?}", + work::COMPACTION.get(), + start.elapsed() + ); + operations + }); + window.update(|window, _| window.remove_window()); + operations + }; + let small = measure(128); + let large = measure(1024); + assert!(large <= small * 16, "8x descendants: {small} -> {large}"); + assert!(large <= 1024 * 32, "absolute absorption budget: {large}"); +} + +fn review_status_work( + count: usize, + covered: bool, + cx: &mut TestAppContext, +) -> (usize, usize) { + use crate::marks::work; + use disktree_core::removal::Target; + + let (temp, view, window) = queue_budget_view(count, cx); + update(&view, window, |app, _| { + if covered { + let parent = app.target_at(&[0]).expect("parent"); + app.marks.toggle(parent, app.path_style()); + } + for index in 0..count { + let target = if covered { + app.target_at(&[0, index]).expect("file") + } else { + Target { + path: temp + .path() + .with_extension("outside") + .join(format!("file-{index:05}")), + bytes: 1, + is_dir: false, + hidden: false, + } + }; + app.marks.toggle(target, app.path_style()); + } + app.screen = Screen::Review; + }); + work::reset(); + let start = std::time::Instant::now(); + for _ in 0..4 { + update(&view, window, |_, cx| cx.notify()); + draw(window); + } + let elapsed = start.elapsed(); + let frames = work::RENDERS.get(); + let operations = work::REVIEW.get(); + assert!( + frames >= 4 && work::PLANS.get() >= 4, + "must render and plan Review" + ); + let rows = (count + usize::from(covered)).min(1200); + assert_eq!( + work::REVIEW_ROWS.get(), + rows * frames, + "retain the display cap" + ); + assert_eq!( + work::BLOCKED_ROWS.get(), + if covered { 0 } else { rows * frames } + ); + assert_eq!( + work::COVERED_ROWS.get(), + if covered { (rows - 1) * frames } else { 0 } + ); + assert!(operations > 0); + eprintln!( + "review-status covered={covered} M={count} work={operations} renders={frames} rows={rows} per-render={} wall={elapsed:?}", + operations / frames + ); + window.update(|window, _| window.remove_window()); + (operations, frames) +} + +fn review_status_budget(cx: &mut TestAppContext, covered: bool) { + let (small, small_frames) = review_status_work(128, covered, cx); + let (large, large_frames) = review_status_work(1024, covered, cx); + assert!( + large * small_frames <= small * large_frames * 16, + "8x status rows: {small}/{small_frames} -> {large}/{large_frames}" + ); + assert!( + large <= 1024 * large_frames * 8, + "absolute row-status budget: {large}" + ); + let (capped, capped_frames) = review_status_work(8192, covered, cx); + assert!( + capped <= 8192 * capped_frames * 8, + "status budget above row cap: {capped}" + ); +} + +#[gpui_kit::test] +fn blocked_review_status_budget(cx: &mut TestAppContext) { + cx.update(init); + review_status_budget(cx, false); +} + +#[gpui_kit::test] +fn covered_review_status_budget(cx: &mut TestAppContext) { + cx.update(init); + review_status_budget(cx, true); +} + +#[gpui_kit::test] +fn folder_queue_construction_budget(cx: &mut TestAppContext) { + use crate::marks::work; + use disktree_core::tree::{Draft, NodeKind, Tree, aggregate}; + use std::sync::Arc; + + cx.update(init); + let mut measure = |count| { + let (_temp, view, window) = queue_budget_view(count, cx); + let operations = update(&view, window, |app, cx| { + let metric = app.options.metric; + // Child lists are fixed once built: turn each file into a + // folder through a draft, then build the tree again. + let mut draft = app.tree.as_ref().expect("tree").root().to_draft(); + for child in &mut draft.children[0].children { + child.kind = NodeKind::Directory; + child + .children + .push(Draft::entry("payload", NodeKind::File, 1)); + } + let mut tree = Tree::from(draft); + aggregate(&mut tree, metric); + app.tree = Some(Arc::new(tree)); + work::reset(); + let start = std::time::Instant::now(); + for index in 0..count { + app.toggle_mark(&[0, index], cx); + } + assert_eq!(app.marks.len(), count); + assert!(app.marks.items().iter().all(|item| item.is_dir)); + assert_eq!(work::FRAMES.get(), 0); + let operations = work::MARKING.get() + work::COMPACTION.get(); + assert!(operations > 0); + eprintln!( + "folder-queue M={count} work={operations} wall={:?}", + start.elapsed() + ); + operations + }); + window.update(|window, _| window.remove_window()); + operations + }; + let small = measure(128); + let large = measure(1024); + assert!(large <= small * 16, "8x folders: {small} -> {large}"); + assert!( + large <= 1024 * 32, + "absolute folder insertion budget: {large}" + ); +} + +/// Every frame the title strip can be drawn in, as the platforms report +/// them: the window harness has no compositor to ask, so each is pinned. +fn window_frames() -> Vec<(&'static str, crate::chrome::Frame)> { + use crate::chrome::{Frame, Platform}; + use gpui_kit::{ + Decorations, Tiling, WindowButton, WindowButtonLayout, WindowControls, + }; + + let frame = |platform, decorations, layout, fullscreen| { + Frame::new( + platform, + decorations, + layout, + WindowControls::default(), + fullscreen, + ) + }; + let floating = Decorations::Client { + tiling: Tiling::default(), + }; + // Close, minimize, maximize on the left: the layout that puts the + // controls where macOS has its stoplights. + let on_the_left = WindowButtonLayout { + left: [ + Some(WindowButton::Close), + Some(WindowButton::Minimize), + Some(WindowButton::Maximize), + ], + right: [None; 3], + }; + vec![ + ( + "macOS", + frame(Platform::MacOs, Decorations::Server, None, false), + ), + ( + "macOS full screen", + frame(Platform::MacOs, Decorations::Server, None, true), + ), + ( + "Windows", + frame(Platform::Windows, Decorations::Server, None, false), + ), + ( + "Hyprland or KDE", + frame(Platform::Linux, Decorations::Server, None, false), + ), + ( + "GNOME, controls right", + frame(Platform::Linux, floating, None, false), + ), + ( + "GNOME, controls left", + frame(Platform::Linux, floating, Some(on_the_left), false), + ), + ( + "GNOME, maximized", + frame( + Platform::Linux, + Decorations::Client { + tiling: Tiling::tiled(), + }, + None, + false, + ), + ), + ] +} + +#[gpui_kit::test] +fn the_title_strip_draws_on_every_window_frame(cx: &mut TestAppContext) { + use crate::chrome::Controls; + use crate::ui::chrome; + + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + for (name, frame) in window_frames() { + for screen in [Screen::Explore, Screen::Review, Screen::Done] { + update(&view, cx, |app, cx| { + app.chrome_pin = Some(frame.clone()); + app.screen = screen; + cx.notify(); + }); + draw(cx); + + let strip = cx.debug_bounds("title-strip").expect(name); + // The band the stoplights centre in, then the divider below it. + assert_eq!( + strip.size.height, + chrome::STRIP + px(1.), + "{name}, {screen:?}" + ); + let brand = cx.debug_bounds("strip-brand").expect(name); + assert!(brand.size.width > px(0.), "{name}: the brand is drawn"); + + // The brand stays clear of the controls at either end. + match &frame.leading { + // The brand's area runs to the edge, padding and all. + Controls::None => assert_eq!(brand.left(), strip.left()), + Controls::Stoplights => assert!( + brand.left() - strip.left() >= chrome::STOPLIGHT_ZONE, + "{name}: brand at {:?}", + brand.left() - strip.left() + ), + Controls::Buttons(_) => { + let controls = + cx.debug_bounds("window-controls-leading").expect(name); + assert!(controls.left() >= strip.left()); + assert!(brand.left() >= controls.right(), "{name}"); + } + } + if let Controls::Buttons(_) = &frame.trailing { + let controls = + cx.debug_bounds("window-controls-trailing").expect(name); + assert!( + (strip.right() - controls.right()).abs() <= px(1.), + "{name}: the controls sit at the right edge" + ); + assert!(brand.right() < controls.left(), "{name}"); + } + } + } +} + +#[gpui_kit::test] +fn a_client_side_frame_keeps_a_resize_ring_until_it_is_tiled( + cx: &mut TestAppContext, +) { + use crate::ui::chrome; + + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + let frames = window_frames(); + let pin = |name: &str| { + frames + .iter() + .find(|(each, _)| *each == name) + .map(|(_, frame)| frame.clone()) + }; + + update(&view, cx, |app, cx| { + app.chrome_pin = pin("GNOME, controls right"); + cx.notify(); + }); + draw(cx); + let root = cx.debug_bounds("disktree-root").expect("root"); + let frame = cx.debug_bounds("client-frame").expect("client frame"); + // The ring, then the window's hairline border. + let inset = chrome::RESIZE_RING + px(1.); + assert_eq!(root.left() - frame.left(), inset); + assert_eq!(root.top() - frame.top(), inset); + for grip in ["grip-top", "grip-bottom-right", "grip-left"] { + assert!(cx.debug_bounds(grip).is_some(), "{grip}"); + } + + // Maximized or tiled, the compositor owns the edges: no ring, no grips. + update(&view, cx, |app, cx| { + app.chrome_pin = pin("GNOME, maximized"); + cx.notify(); + }); + draw(cx); + let root = cx.debug_bounds("disktree-root").expect("root"); + let frame = cx.debug_bounds("client-frame").expect("client frame"); + assert_eq!(root.left() - frame.left(), px(1.)); + assert_eq!(root.top() - frame.top(), px(1.)); + assert!(cx.debug_bounds("grip-top").is_none()); + + // Where the compositor draws the frame, the content is the window. + update(&view, cx, |app, cx| { + app.chrome_pin = pin("Hyprland or KDE"); + cx.notify(); + }); + draw(cx); + assert!(cx.debug_bounds("client-frame").is_none()); +} + +#[gpui_kit::test] +fn the_wordmark_gives_way_in_a_narrow_window(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + app.chrome_pin = window_frames().first().map(|(_, f)| f.clone()); + cx.notify(); + }); + let brand_width = |cx: &mut Window| { + draw(cx); + cx.debug_bounds("strip-brand").expect("brand").size.width + }; + + cx.simulate_resize(gpui_kit::size(px(1440.), px(900.))); + let wide = brand_width(cx); + cx.simulate_resize(gpui_kit::size(px(900.), px(600.))); + let narrow = brand_width(cx); + assert!( + narrow < wide / 2., + "only the mark is left at 900 pt: {narrow:?} of {wide:?}" + ); + // The trail keeps the crumb you are in. + assert!(cx.debug_bounds("title-strip").is_some()); +} + +#[gpui_kit::test] +fn a_press_on_the_strip_arms_a_move_and_a_click_disarms_it( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + app.chrome_pin = window_frames().first().map(|(_, f)| f.clone()); + cx.notify(); + }); + draw(cx); + let empty = cx.debug_bounds("strip-drag").expect("empty strip"); + let at = empty.center(); + let none = gpui_kit::Modifiers::none(); + let left = gpui_kit::MouseButton::Left; + + // A press arms the move. The move itself, on the first motion with + // the button down, cannot run here: the test platform leaves + // `start_window_move` unimplemented. + cx.simulate_mouse_down(at, left, none); + assert!(read(&view, cx, |app| app.strip_drag)); + + // Released without moving, it was a click, and leaves nothing armed + // for the next time the pointer passes over with a button held. + cx.simulate_mouse_up(at, left, none); + assert!(!read(&view, cx, |app| app.strip_drag)); + + // The keyboard still belongs to the treemap. + let focused = cx.update(|window, cx| { + let focus = view.read(cx).focus.clone(); + focus.is_focused(window) + }); + assert!(focused, "a press on the strip leaves the treemap focused"); +} + +#[gpui_kit::test] +fn the_tooltip_follows_the_pointer_inside_a_client_side_frame( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + // Floating under GNOME: the content sits inside the resize ring. + update(&view, cx, |app, cx| { + app.chrome_pin = window_frames() + .into_iter() + .find(|(name, _)| *name == "GNOME, controls right") + .map(|(_, frame)| frame); + cx.notify(); + }); + draw(cx); + let origin = read(&view, cx, |app| app.treemap_origin.get()); + let at = origin + Point::new(px(40.), px(40.)); + cx.simulate_mouse_move(at, None, gpui_kit::Modifiers::default()); + draw(cx); + + let tip = cx.debug_bounds("cursor-tooltip").expect("a tooltip"); + // Beside the pointer by the tooltip's gap, wherever the root starts. + let gap = crate::ui::space::MD.0 * crate::ui::BASE_REM; + assert_eq!( + tip.left(), + at.x + px(gap), + "{tip:?} for a pointer at {at:?}" + ); + assert_eq!(tip.top(), at.y + px(gap)); +} + +/// Only a read-only preview may be retried while its worker is preparing. +fn await_removal_preview( + ask: &mut impl FnMut( + &mut Window, + disktree_link::Request, + ) -> disktree_link::Response, + cx: &mut Window, + request: &disktree_link::Request, +) -> disktree_link::RemovalPreview { + assert!(matches!( + request, + disktree_link::Request::PrepareRemoval { .. } + )); + for _ in 0..400 { + cx.run_until_parked(); + match ask(cx, request.clone()) { + disktree_link::Response::RemovalPreview(preview) => return preview, + disktree_link::Response::Error { message } + if message.contains("preparing") => {} + response => panic!("preview refused: {response:?}"), + } + draw(cx); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("preview worker did not finish"); +} + +/// Link `view` to an agent over a real socket or pipe named after `temp`, +/// as `pwrdisk mcp` does. +#[cfg(any(unix, windows))] +fn link_agent( + view: &Entity, + temp: &Path, + cx: &mut Window, +) -> disktree_link::Link { + #[cfg(not(windows))] + let socket = temp.join("link.sock"); + #[cfg(windows)] + let socket = PathBuf::from(format!( + r"\\.\pipe\pwrdisk-test-{}", + temp.file_name().expect("temp name").to_string_lossy() + )); + let listener = + disktree_link::Listener::bind_at(&socket).expect("bind the link"); + update(view, cx, |app, cx| app.attach_agent(listener, cx)); + disktree_link::Link::connect_at(&socket).expect("connect") +} + +/// Send `request` over `link` and pump the window until it answers. The +/// client blocks on each answer, so it runs on its own thread while the +/// test pumps the window's side, as the timer task would. +#[cfg(any(unix, windows))] +fn ask_over( + view: &Entity, + link: &mut Option, + cx: &mut Window, + request: disktree_link::Request, +) -> disktree_link::Response { + let mut taken = link.take().expect("the link is at hand"); + let worker = std::thread::spawn(move || { + let response = taken.call(&request).expect("an answer"); + (taken, response) + }); + for _ in 0..400 { + update(view, cx, |app, cx| { + app.poll_agent_once(cx); + }); + if worker.is_finished() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let (returned, response) = worker.join().expect("client thread"); + *link = Some(returned); + draw(cx); + response +} + +/// Drive the window as `pwrdisk mcp` does, over the real socket: say +/// hello, mark, show, open the review, unmark, hang up. The marks land in +/// the window, the screen follows, and the header names the agent while it +/// is there. +#[cfg(any(unix, windows))] +#[gpui_kit::test] +fn an_agent_marks_shows_and_reviews_over_the_link(cx: &mut TestAppContext) { + use disktree_link::{MarkRequest, Request, Response}; + + cx.update(init); + let temp = fixture(); + let root = temp.path().to_path_buf(); + // Native approval needs ordinary output too: cache fixtures are + // inspection-only and cannot exercise successful raw removal. + std::fs::create_dir(root.join("native-output")).expect("native output"); + std::fs::write(root.join("native-output/artifact"), b"fixture") + .expect("native payload"); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + + let mut link = Some(link_agent(&view, temp.path(), cx)); + let mut ask = |cx: &mut Window, request: Request| -> Response { + ask_over(&view, &mut link, cx, request) + }; + + let refused = ask( + cx, + Request::Hello { + client: "Old MCP fixture".into(), + version: disktree_link::VERSION - 1, + }, + ); + let Response::Error { message } = refused else { + panic!("incompatible Hello must be refused"); + }; + assert!(message.contains("Incompatible PwrDisk link protocols")); + assert!(message.contains("restart/reconnect")); + assert!(message.contains("updated installation")); + assert!( + message.contains(concat!("PwrDisk GUI ", env!("CARGO_PKG_VERSION"))) + ); + let hello = ask( + cx, + Request::Hello { + client: "Claude Code".into(), + version: disktree_link::VERSION, + }, + ); + let Response::State(state) = hello else { + panic!("hello answers with the state: {hello:?}"); + }; + assert_eq!(state.root, root); + assert!(state.scanned && !state.scanning); + assert!(state.marks.is_empty()); + assert_eq!( + read(&view, cx, |app| app + .agent + .as_ref() + .and_then(|agent| agent.presence.clone()) + .map(|presence| presence.client)), + Some("Claude Code".to_string()) + ); + assert!( + cx.debug_bounds("agent-pill").is_some(), + "the header names the connected agent" + ); + + // Marking lands in the window's marks; the agent's own number is only + // a stand-in, and a wrong one is corrected from the tree. + let marked = ask( + cx, + Request::Mark { + root: root.clone(), + targets: vec![MarkRequest { + path: root.join("junk"), + bytes: 7, + is_dir: false, + }], + }, + ); + let Response::Marked { state, refused } = marked else { + panic!("mark answers with the state: {marked:?}"); + }; + assert!(refused.is_empty(), "{refused:?}"); + assert_eq!(state.marks.len(), 1); + // The window measured the mark from its own tree, not from the + // agent's number. + let measured = read(&view, cx, |app| { + app.crumbs_for_path(&root.join("junk")) + .and_then(|crumbs| app.node_at(&crumbs).map(|node| node.bytes)) + }) + .expect("junk is in the tree"); + assert_eq!(state.marks[0].bytes, measured); + assert!(state.marks[0].is_dir); + assert_ne!(measured, 7); + assert_eq!(read(&view, cx, |app| app.plan().bytes()), measured); + assert!(state.tree.is_some_and(|tree| tree.files > 0)); + + // A path the tree does not have is refused, not guessed at. + let missing = ask( + cx, + Request::Mark { + root: root.clone(), + targets: vec![MarkRequest { + path: root.join("nowhere"), + bytes: 1, + is_dir: false, + }], + }, + ); + let Response::Marked { refused, .. } = missing else { + panic!("{missing:?}"); + }; + assert_eq!(refused.len(), 1); + assert_eq!(read(&view, cx, |app| app.marks.len()), 1); + + // The agent reads the window's tree: a listing and a search. + let listed = ask( + cx, + Request::Ls { + path: root.clone(), + limit: 10, + }, + ); + let Response::Listing(listing) = listed else { + panic!("{listed:?}"); + }; + assert!(listing.children.iter().any(|child| child.name == "junk")); + assert_eq!(listing.root_bytes, listing.entry.bytes); + let outside = ask( + cx, + Request::Ls { + path: PathBuf::from("/definitely/elsewhere"), + limit: 10, + }, + ); + assert!( + matches!(outside, Response::Error { ref message } if message.contains("outside")), + "{outside:?}" + ); + let found = ask( + cx, + Request::Find(disktree_link::FindRequest { + kind: "file".into(), + name: Some("blob".into()), + limit: 5, + ..disktree_link::FindRequest::default() + }), + ); + let Response::Found(found) = found else { + panic!("{found:?}"); + }; + // Two blobs, the larger first. + assert_eq!(found.count, 2); + assert_eq!(found.matches[0].path, root.join(".cache/blob.bin")); + assert_eq!(found.matches[1].path, root.join("junk/blob.bin")); + + // A scan the agent asks for runs in the window; the state says when it + // has landed, and the marks survive it. + let rescanned = ask( + cx, + Request::Scan { + root: root.clone(), + options: disktree_link::ScanOptionsRequest::default(), + }, + ); + assert!( + matches!(rescanned, Response::State(ref s) if s.scanning), + "{rescanned:?}" + ); + finish_scan(&view, cx); + let after = ask(cx, Request::State); + let Response::State(after) = after else { + panic!("{after:?}"); + }; + assert!(!after.scanning && after.scanned); + assert_eq!(after.marks.len(), 1); + + // A path inside the mark is left alone, not toggled off or added. + ask( + cx, + Request::Mark { + root: root.clone(), + targets: vec![MarkRequest { + path: root.join("junk/deeper"), + bytes: 100_000, + is_dir: true, + }], + }, + ); + assert_eq!(read(&view, cx, |app| app.marks.len()), 1); + + // Showing a directory opens it; the view follows the agent. + let shown = ask( + cx, + Request::Show { + root: root.clone(), + path: root.join("junk/deeper"), + }, + ); + assert_eq!(shown, Response::Ok); + let (crumbs, expected) = read(&view, cx, |app| { + ( + app.crumbs.clone(), + app.crumbs_for_path(&root.join("junk/deeper")), + ) + }); + assert_eq!(Some(crumbs), expected); + + // Review opens the review screen over the marks. + assert_eq!(ask(cx, Request::Review), Response::Ok); + assert_eq!(read(&view, cx, |app| app.screen), Screen::Review); + assert!( + temp.path().join("junk/blob.bin").exists(), + "nothing removed" + ); + + // Unmarking everything empties the list and leaves the review screen. + let cleared = ask(cx, Request::Unmark { paths: vec![] }); + assert!(matches!(cleared, Response::State(ref s) if s.marks.is_empty())); + assert_eq!(read(&view, cx, |app| app.screen), Screen::Explore); + assert_eq!( + ask(cx, Request::Review), + Response::error("nothing is marked") + ); + + // Removal is a separate, explicit protocol operation, not a UI key. + ask( + cx, + Request::Mark { + root: root.clone(), + targets: vec![MarkRequest { + path: root.join("junk"), + bytes: 0, + is_dir: true, + }], + }, + ); + let preview_request = Request::PrepareRemoval { + mode: disktree_link::RemovalChoice::Permanent, + decisions: None, + files: None, + }; + assert!(matches!( + ask(cx, preview_request.clone()), + Response::Error { message } if message.contains("preparing") + )); + assert!(matches!(ask(cx, Request::State), Response::State(_))); + let preview = await_removal_preview(&mut ask, cx, &preview_request); + assert_eq!(preview.estimate.paths, preview.paths); + assert_eq!(preview.estimate.lower, 0, "apparent fixture sizes"); + assert_eq!(preview.estimate.upper, None); + assert!(preview.estimate.partial); + // Estimation must leave the pending single-use removal intent intact. + let before = ask(cx, Request::State); + let estimated = ask( + cx, + Request::Estimate { + paths: vec![root.join("junk")], + peer_scope: None, + peer_limit: 10, + }, + ); + let Response::Estimate(report) = estimated else { + panic!("estimate response"); + }; + assert_eq!(report.accepted, [root.join("junk")]); + assert!(report.reclaim.is_none(), "apparent fixture"); + assert_eq!(ask(cx, Request::State), before); + assert!(read(&view, cx, |app| app + .agent + .as_ref() + .expect("agent") + .removal_preview + .is_some())); + let confirmed = |preview: &disktree_link::RemovalPreview| { + disktree_link::ConfirmedRemoval { + rescan: false, + preview_id: preview.preview_id.clone(), + mode: preview.mode, + paths: preview.paths.clone(), + confirmation: preview.mode.confirmation().into(), + } + }; + let mut wrong = confirmed(&preview); + wrong.paths.push(root.join("keep")); + assert!(matches!( + ask(cx, Request::Remove(wrong)), + Response::Error { .. } + )); + assert!(root.join("junk/blob.bin").exists()); + // A failed attempt consumes its preview as well. + assert!(matches!( + ask(cx, Request::Remove(confirmed(&preview))), + Response::Error { .. } + )); + let changed = await_removal_preview(&mut ask, cx, &preview_request); + ask( + cx, + Request::Unmark { + paths: vec![root.join("junk")], + }, + ); + assert!(matches!( + ask(cx, Request::Remove(confirmed(&changed))), + Response::Error { .. } + )); + ask( + cx, + Request::Mark { + root: root.clone(), + targets: vec![MarkRequest { + path: root.join("junk"), + bytes: 0, + is_dir: true, + }], + }, + ); + // A capacity-policy change also requires a new preview and confirmation. + let settings = temp.path().join("fixture-settings"); + update(&view, cx, |app, _| { + app.removal_settings_dir = Some(settings.clone()); + }); + let old_policy = await_removal_preview(&mut ask, cx, &preview_request); + crate::safety::save( + Some(&settings), + disktree_core::removal_limit::Limit::new(10).expect("10%"), + ) + .expect("save"); + assert!(matches!( + ask(cx, Request::Remove(confirmed(&old_policy))), + Response::Error { .. } + )); + assert!(root.join("junk/blob.bin").exists()); + crate::safety::save( + Some(&settings), + disktree_core::removal_limit::Limit::default(), + ) + .expect("restore fixture policy"); + let preview = await_removal_preview(&mut ask, cx, &preview_request); + assert_eq!(preview.paths, [root.join("junk")]); + assert_eq!(preview.limit_percent, 5); + let started = ask(cx, Request::Remove(confirmed(&preview))); + assert!( + matches!(started, Response::State(ref state) if state.screen == "running"), + "{started:?}" + ); + assert!( + matches!( + ask(cx, Request::Remove(confirmed(&preview))), + Response::State(_) + ), + "a duplicate reports the running operation without replay" + ); + let epoch = read(&view, cx, |app| app.run_epoch); + let mut done = false; + for _ in 0..400 { + std::thread::sleep(std::time::Duration::from_millis(5)); + done = update(&view, cx, |app, cx| { + app.poll_removal_once(epoch, cx); + app.screen == Screen::Done + }); + if done { + break; + } + } + assert!(done); + assert!(!root.join("junk").exists()); + assert!(root.join("keep/notes.txt").exists()); + assert!(root.join(".cache/blob.bin").exists()); + assert_eq!(read(&view, cx, |app| app.run_list.totals().failed), 0); + + // A pending MCP form does not own native UI approval. Complete another + // exact preview through the same entry point as native confirmation. + ask( + cx, + Request::Mark { + root: root.clone(), + targets: vec![MarkRequest { + path: root.join("native-output"), + bytes: 0, + is_dir: true, + }], + }, + ); + let native = await_removal_preview( + &mut ask, + cx, + &Request::PrepareRemoval { + mode: disktree_link::RemovalChoice::Permanent, + decisions: None, + files: None, + }, + ); + update(&view, cx, |app, cx| { + app.removal_mode = RemovalMode::Permanent; + app.begin_removal(cx); + }); + let native_epoch = read(&view, cx, |app| app.run_epoch); + let Response::State(running) = ask(cx, Request::State) else { + panic!("state"); + }; + let operation = running.removal_operation.expect("native run correlated"); + assert_eq!(operation.preview_id, native.preview_id); + assert!(!operation.finished); + for _ in 0..400 { + std::thread::sleep(std::time::Duration::from_millis(5)); + if update(&view, cx, |app, cx| { + !app.poll_removal_once(native_epoch, cx) + }) { + break; + } + } + assert!(!root.join("native-output").exists()); + assert!(root.join(".cache/blob.bin").exists()); + let Response::State(completed) = + ask(cx, Request::Remove(confirmed(&native))) + else { + panic!("late request reports outcome"); + }; + let operation = completed.removal_operation.expect("completed outcome"); + assert!(operation.finished); + assert_eq!( + (operation.removed, operation.failed, operation.pending), + (1, 0, 0) + ); + assert_eq!( + read(&view, cx, |app| app.run_epoch), + native_epoch, + "no second run" + ); + assert!(root.join("keep/notes.txt").exists()); + + // Hanging up takes the name out of the header. + drop(link); + for _ in 0..400 { + let gone = update(&view, cx, |app, cx| { + app.poll_agent_once(cx); + app.agent + .as_ref() + .is_some_and(|agent| agent.presence.is_none()) + }); + if gone { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + draw(cx); + assert!(cx.debug_bounds("agent-pill").is_none(), "pill gone"); +} + +/// The panel's agent line opens Settings › Agents (MCP), which lists a +/// command for each client with the binary's own path, the bare command +/// line first, and says who is connected. +#[gpui_kit::test] +fn the_agent_line_opens_settings_agents(cx: &mut TestAppContext) { + use crate::settings::{Pane, SettingsWindow}; + + cx.update(init); + let temp = fixture(); + let (_, cx) = view_over(temp.path(), cx); + draw(cx); + assert!(cx.debug_bounds("agent-line").is_some()); + click_on(cx, "agent-line"); + cx.run_until_parked(); + assert_eq!(settings_pane(cx), Some(Pane::Agents)); + + let commands = + crate::agent::connect_commands(Path::new("/opt/disktree/disktree")); + let labels: Vec<_> = commands.iter().map(|way| way.label).collect(); + assert_eq!( + labels, + [ + "Command line", + "Claude Code", + "Codex", + "Other MCP clients (JSON)" + ] + ); + assert_eq!(commands[0].text, "\"/opt/disktree/disktree\" mcp"); + assert!( + commands[1] + .text + .starts_with("claude mcp add --scope user pwrdisk") + ); + assert!( + commands + .iter() + .all(|way| way.text.contains("/opt/disktree/disktree")) + ); + assert!(commands[3].text.contains("\"args\": [\"mcp\"]")); + + // The pane draws every row, each with its own Copy, and the status. + let (view, cx) = + cx.add_window_view(|_, cx| SettingsWindow::new(Pane::Agents, cx)); + draw(cx); + assert!(cx.debug_bounds("settings-nav-agents").is_some()); + assert!(cx.debug_bounds("agents-status").is_some()); + for way in &commands { + assert!(cx.debug_bounds(way.id).is_some(), "{} has Copy", way.label); + } + // Copy answers on its own button, for a moment, never with a toast. + click_on(cx, "agents-copy-command"); + let copied = clipboard(cx); + assert!(copied.ends_with("\" mcp"), "{copied}"); + assert!(copied.starts_with('"'), "{copied}"); + assert_eq!( + view.read_with(cx, |view, _| view.copied()), + Some("agents-copy-command") + ); + cx.executor().advance_clock(crate::settings::COPY_FEEDBACK); + cx.run_until_parked(); + assert_eq!(view.read_with(cx, |view, _| view.copied()), None); +} + +/// A window showing an SSH host answers an agent with where it is and +/// nothing more: an agent's paths are this computer's, and a mark or a +/// scan read against the host would land on the wrong machine. +#[gpui_kit::test] +fn a_window_on_an_ssh_host_refuses_the_agent(cx: &mut TestAppContext) { + use disktree_link::{MarkRequest, Request, Response, VERSION}; + + cx.update(init); + let temp = fixture(); + let (view, window) = view_over(temp.path(), cx); + let junk = temp.path().join("junk"); + let answers = update(&view, window, |app, cx| { + app.remote = Some("build-box".into()); + let hello = app.answer_agent( + &Request::Hello { + client: "test".into(), + version: VERSION, + }, + cx, + ); + let mark = app.answer_agent( + &Request::Mark { + root: temp.path().to_path_buf(), + targets: vec![MarkRequest { + path: junk.clone(), + bytes: 1, + is_dir: true, + }], + }, + cx, + ); + let review = app.answer_agent(&Request::Review, cx); + (hello, mark, review, app.marks.is_empty()) + }); + let (hello, mark, review, unmarked) = answers; + assert!( + matches!(&hello, Response::State(state) + if state.remote.as_deref() == Some("build-box")), + "{hello:?}" + ); + for refused in [mark, review] { + assert!( + matches!(&refused, Response::Error { message } + if message.contains("SSH host build-box")), + "{refused:?}" + ); + } + assert!(unmarked, "a refused mark leaves no mark behind"); +} + +/// A window still on the source chooser scans the root an agent names: +/// the request is explicit, and the chooser would otherwise reopen and +/// leave the agent waiting on a scan that never starts. +#[gpui_kit::test] +fn an_agent_scan_leaves_the_chooser(cx: &mut TestAppContext) { + use disktree_link::{Request, ScanOptionsRequest}; + + cx.update(init); + let temp = fixture(); + let (view, cx) = + cx.add_window_view(|_, cx| Disktree::choose(options(), 3, None, cx)); + cx.run_until_parked(); + update(&view, cx, |app, cx| { + assert!(app.awaiting_root); + app.answer_agent( + &Request::Scan { + root: temp.path().to_path_buf(), + options: ScanOptionsRequest::default(), + }, + cx, + ); + assert!(!app.awaiting_root); + assert!(!app.volumes_open, "the chooser is closed"); + assert!(app.scan.is_some(), "the agent's root is being scanned"); + assert_eq!(app.root_path, temp.path()); + }); + finish_scan(&view, cx); +} + +/// UI removal cannot bypass the same capacity check used by MCP. +#[gpui_kit::test] +fn removal_capacity_limit_blocks_the_entire_ui_selection( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + app.marks.toggle( + disktree_core::removal::Target { + path: temp.path().join("junk"), + bytes: u64::MAX / 4, + is_dir: true, + hidden: false, + }, + app.path_style(), + ); + app.screen = Screen::Review; + app.removal_mode = RemovalMode::Permanent; + app.begin_removal(cx); + assert_eq!(app.screen, Screen::Review); + assert!(app.run.is_none()); + assert!( + app.notice() + .as_ref() + .is_some_and(|(text, _)| text.contains("limit")) + ); + assert_eq!(app.marks.len(), 1); + }); + assert!(temp.path().join("junk/blob.bin").exists()); + assert!(temp.path().join("keep/notes.txt").exists()); + draw(cx); +} + +#[gpui_kit::test] +fn accessible_file_pages_reach_every_entry_and_share_safe_marks( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = tempfile::tempdir().expect("tempdir"); + for i in 0..235 { + std::fs::write( + temp.path().join(format!("Résumé 日本語-{i:03}.txt")), + b"fixture", + ) + .expect("file"); + } + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + app.file_list = true; + app.selected = None; + cx.notify(); + }); + draw(cx); + assert!(cx.debug_bounds("file-row-99").is_some()); + assert!(cx.debug_bounds("file-row-100").is_none()); + click_on(cx, "file-next"); + assert_eq!(read(&view, cx, |app| app.selected.clone()), Some(vec![100])); + press(cx, "pagedown"); + assert!(cx.debug_bounds("file-row-200").is_some()); + assert!(cx.debug_bounds("file-row-199").is_none()); + read(&view, cx, |app| { + assert_eq!(app.file_entries().len(), 235); + assert_eq!(app.selected.as_deref(), Some([200].as_slice())); + }); + press(cx, "space c"); + read(&view, cx, |app| { + assert_eq!(app.screen, Screen::Review); + assert_eq!(app.marks.len(), 1); + assert!( + app.marks.items()[0] + .path + .file_name() + .unwrap() + .to_string_lossy() + .contains("200") + ); + }); + press(cx, "escape"); + assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 235); +} + +#[gpui_kit::test] +fn accessible_file_navigation_uses_absolute_paths_and_filter( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + app.file_list = true; + app.selected = Some(child_crumbs(app, &[], "junk")); + cx.notify(); + }); + press(cx, "right down space"); + read(&view, cx, |app| { + assert_eq!(app.current_path(), temp.path().join("junk")); + assert!( + app.marks.items()[0] + .path + .starts_with(temp.path().join("junk")) + ); + }); + press(cx, "left / k e e p enter"); + read(&view, cx, |app| { + assert_eq!(app.file_entries().len(), 1); + }); +} + +fn paginated_fixture(count: usize) -> tempfile::TempDir { + let temp = tempfile::tempdir().expect("tempdir"); + for index in 0..count { + let prefix = if index < 150 { "match" } else { "other" }; + std::fs::write( + temp.path().join(format!("{prefix}-{index:06}.txt")), + b"fixture", + ) + .expect("file"); + } + temp +} + +fn focus_file_list(view: &Entity, cx: &mut Window) { + update(view, cx, |app, cx| { + app.file_list = true; + cx.notify(); + }); + draw(cx); + let focus = view.read_with(cx, |app, _| app.file_focus.clone()); + cx.update(|window, cx| window.focus(&focus, cx)); +} + +#[gpui_kit::test] +fn accessible_list_review_rescan_preserves_keyboard_focus( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + focus_file_list(&view, cx); + press(cx, "r"); + assert!(cx.debug_bounds("file-list").is_none()); + let root_focused = + cx.update(|window, cx| view.read(cx).focus.is_focused(window)); + press(cx, "escape"); + assert!(read(&view, cx, |app| app.scan.is_none()), "Escape cancels"); + assert!(root_focused, "the persistent root owns scan keys"); + + press(cx, "r"); + finish_scan(&view, cx); + draw(cx); + assert!(cx.debug_bounds("file-list").is_some()); + assert!( + cx.update(|window, cx| { view.read(cx).file_focus.is_focused(window) }) + ); + assert!(temp.path().join("keep/notes.txt").exists()); +} + +#[gpui_kit::test] +fn accessible_list_review_sibling_navigation_tracks_page( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = paginated_fixture(235); + let (view, cx) = view_over(temp.path(), cx); + focus_file_list(&view, cx); + update(&view, cx, |app, cx| app.select(Some(vec![99]), cx)); + // Tab traverses controls; n retains the shared sibling-navigation path. + press(cx, "n"); + assert_eq!(read(&view, cx, |app| app.selected.clone()), Some(vec![100])); + assert_eq!(read(&view, cx, |app| app.file_page), 1); + assert!(cx.debug_bounds("file-row-100").is_some()); + assert!(cx.debug_bounds("file-row-99").is_none()); + let marked = read(&view, cx, |app| app.path_at(&[100]).unwrap()); + press(cx, "space shift-n"); + assert_eq!(read(&view, cx, |app| app.selected.clone()), Some(vec![99])); + assert_eq!(read(&view, cx, |app| app.file_page), 0); + assert!(cx.debug_bounds("file-row-99").is_some()); + assert!(read(&view, cx, |app| { + app.marks.contains(&marked, app.path_style()) + })); + assert!(marked.exists(), "marking never removes the file"); +} + +#[gpui_kit::test] +fn accessible_list_review_previous_uses_filtered_page(cx: &mut TestAppContext) { + cx.update(init); + let temp = paginated_fixture(450); + let (view, cx) = view_over(temp.path(), cx); + focus_file_list(&view, cx); + press(cx, "down pagedown pagedown pagedown pagedown"); + assert_eq!(read(&view, cx, |app| app.file_page), 4); + press(cx, "/"); + cx.simulate_input("match"); + cx.run_until_parked(); + press(cx, "enter"); + assert_eq!(read(&view, cx, |app| app.file_entries().len()), 150); + assert!(cx.debug_bounds("file-row-100").is_some()); + click_on(cx, "file-previous"); + assert_eq!(read(&view, cx, |app| app.file_page), 0); + assert!(cx.debug_bounds("file-row-0").is_some()); + assert!(cx.debug_bounds("file-row-100").is_none()); +} + +#[gpui_kit::test] +fn accessible_list_review_previous_uses_shrunken_marks_page( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = paginated_fixture(4801); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + for index in 0..4801 { + let target = app.target_at(&[index]).expect("file"); + app.marks.toggle(target, app.path_style()); + } + app.review_page = 4; + app.open_review(cx); + }); + draw(cx); + // Removing marks leaves one row on the effective last page, so the + // real Previous button remains visible without scrolling 1,200 rows. + update(&view, cx, |app, cx| { + let keep = app.marks.items()[..1201].to_vec(); + app.marks.clear(); + for target in keep { + app.marks.toggle(target, app.path_style()); + } + cx.notify(); + }); + draw(cx); + assert_eq!(read(&view, cx, |app| app.marks.len()), 1201); + click_on(cx, "review-previous"); + assert_eq!(read(&view, cx, |app| app.review_page), 0); + assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 4801); +} + +#[gpui_kit::test] +fn accessible_list_review_noop_navigation_preserves_page( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = paginated_fixture(235); + std::fs::create_dir(temp.path().join("nested")).expect("directory"); + std::fs::write(temp.path().join("nested/child.txt"), b"x").expect("file"); + let (view, cx) = view_over(temp.path(), cx); + focus_file_list(&view, cx); + let selected = update(&view, cx, |app, cx| { + let selected = child_crumbs(app, &[], "other-000150.txt"); + assert_eq!(selected, [150]); + app.file_page = 1; + app.select(Some(selected.clone()), cx); + selected + }); + for key in ["enter", "right", "left", "backspace", "u"] { + press(cx, key); + assert_eq!(read(&view, cx, |app| app.file_page), 1, "{key}"); + assert_eq!( + read(&view, cx, |app| app.selected.clone()), + Some(selected.clone()), + "{key}" + ); + assert!(cx.debug_bounds("file-row-150").is_some(), "{key}"); + } + update(&view, cx, |app, cx| { + let nested = child_crumbs(app, &[], "nested"); + app.go_to(nested, cx); + }); + draw(cx); + assert_eq!(read(&view, cx, |app| app.file_page), 0); + assert_eq!( + read(&view, cx, Disktree::current_path), + temp.path().join("nested") + ); +} + +#[gpui_kit::test] +fn readable_progress_is_throttled_but_errors_and_completion_are_immediate( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + app.start_scan(cx); + app.progress.files = 100; + let first = app.accessibility_status(); + assert!(first.contains("100 files") && first.contains("indeterminate")); + app.progress.files = 200; + assert_eq!(app.accessibility_status(), first); + app.accessible_progress.as_mut().unwrap().0 = std::time::Instant::now() + .checked_sub(std::time::Duration::from_secs(3)) + .expect("test clock"); + assert!(app.accessibility_status().contains("200 files")); + app.scan_error = Some("contrived scan error".into()); + assert!(app.accessibility_status().contains("contrived scan error")); + app.cancel_scan(cx); + assert!(app.scan.is_none() && app.progress.cancelled); + app.scan_error = None; + assert!(app.accessibility_status().contains("Scan cancelled")); + app.progress.cancelled = false; + app.progress.finished = true; + assert!(app.accessibility_status().contains("Scan complete")); + }); +} + +#[gpui_kit::test] +fn status_review_cancelled_widening_does_not_hide_the_active_screen( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(&temp.path().join("junk"), cx); + update(&view, cx, |app, cx| { + app.widen_to(temp.path().to_path_buf(), cx); + app.cancel_scan(cx); + app.open_review(cx); + for (screen, phase) in [ + (Screen::Review, "Review marked paths"), + (Screen::Running, "Removal running"), + (Screen::Done, "Removal finished"), + ] { + app.screen = screen; + let label = app.accessibility_status(); + assert!(label.starts_with(phase), "{label}"); + assert!(label.contains("Previous scan cancelled"), "{label}"); + app.scan_error = Some("contrived widening error".into()); + let label = app.accessibility_status(); + assert!(label.starts_with(phase), "{label}"); + assert!(label.contains("contrived widening error"), "{label}"); + app.scan_error = None; + } + }); + draw(cx); + assert!(temp.path().join("junk/blob.bin").exists()); +} + +#[gpui_kit::test] +fn status_review_removal_completion_survives_its_background_rescan( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + let epoch = update(&view, cx, |app, cx| { + let keep = child_crumbs(app, &[], "keep"); + let notes = child_crumbs(app, &keep, "notes.txt"); + app.toggle_mark(¬es, cx); + app.removal_mode = RemovalMode::Permanent; + // Remove & rescan. + app.rescan_after_removal = true; + app.begin_removal(cx); + assert_eq!(app.screen, Screen::Running, "{:?}", app.notice()); + app.run_epoch + }); + let mut status = None; + for _ in 0..400 { + std::thread::sleep(std::time::Duration::from_millis(5)); + status = update(&view, cx, |app, cx| { + app.poll_removal_once(epoch, cx); + (app.screen == Screen::Done).then(|| { + assert!(app.is_indexing(), "completion starts a refresh"); + app.accessibility_status() + }) + }); + if status.is_some() { + break; + } + } + let status = status.expect("removal completes"); + assert!(status.starts_with("Removal finished"), "{status}"); + assert!(status.contains("Background scan"), "{status}"); + assert!(!status.contains("Escape cancels"), "{status}"); + finish_scan(&view, cx); + draw(cx); + assert!(!temp.path().join("keep/notes.txt").exists()); + assert!(temp.path().join("junk/blob.bin").exists()); +} + +/// Run a contrived permanent removal of `names`, each under the root, to +/// its Done screen. +fn remove_now(view: &Entity, cx: &mut Window, names: &[&str]) { + let epoch = update(view, cx, |app, cx| { + for name in names { + let crumbs = app + .crumbs_for_path(&app.root_path.join(name)) + .expect("in the tree"); + app.toggle_mark(&crumbs, cx); + } + app.removal_mode = RemovalMode::Permanent; + app.begin_removal(cx); + assert_eq!(app.screen, Screen::Running, "{:?}", app.notice()); + app.run_epoch + }); + for _ in 0..400 { + std::thread::sleep(std::time::Duration::from_millis(5)); + let done = update(view, cx, |app, cx| { + app.poll_removal_once(epoch, cx); + app.screen == Screen::Done + }); + if done { + return; + } + } + panic!("the removal did not finish"); +} + +/// The run's list is on screen from Removing's first frame, says what +/// each item is, and stays on Done, every item checked off, rather than +/// only the names of what already went. +#[gpui_kit::test] +fn the_removal_list_stays_on_screen_from_start_to_done( + cx: &mut TestAppContext, +) { + use crate::run_list::Status; + cx.update(init); + let temp = fixture(); + // This test exercises ordinary raw removal. Cache removal is covered + // separately and must go through an owner preview. + let build_output = temp.path().join("target/debug/deps"); + std::fs::create_dir_all(build_output.parent().expect("build profile")) + .expect("build output parent"); + std::fs::rename(temp.path().join(".cache"), &build_output) + .expect("ordinary removal fixture"); + let (view, cx) = view_over(temp.path(), cx); + let epoch = update(&view, cx, |app, cx| { + for name in ["target/debug/deps", "junk/deeper"] { + let crumbs = app + .crumbs_for_path(&app.root_path.join(name)) + .expect("in the tree"); + app.toggle_mark(&crumbs, cx); + } + app.removal_mode = RemovalMode::Permanent; + app.begin_removal(cx); + assert_eq!(app.screen, Screen::Running, "{:?}", app.notice()); + app.run_epoch + }); + draw(cx); + // Nothing is reported until the poll: both are listed, waiting, and + // the first is the one in hand. + assert!(cx.debug_bounds("run-list").is_some()); + assert!(cx.debug_bounds("run-row-0").is_some()); + assert!(cx.debug_bounds("run-row-1").is_some()); + assert!(cx.debug_bounds("run-summary").is_some()); + update(&view, cx, |app, _| { + let items = &app.run_list.items; + assert_eq!(items.len(), 2); + assert!(items.iter().all(|item| item.status == Status::Waiting)); + assert_eq!(app.run_list.current(), Some(0)); + let output = items + .iter() + .find(|item| item.target.path == build_output) + .expect("the build output is listed"); + assert_eq!(output.kind(), Some("build output"), "and says why"); + assert_eq!(output.target.bytes, 300_000); + }); + + let mut finished = false; + for _ in 0..400 { + std::thread::sleep(std::time::Duration::from_millis(5)); + finished = update(&view, cx, |app, cx| { + app.poll_removal_once(epoch, cx); + app.screen == Screen::Done + }); + if finished { + break; + } + } + assert!(finished, "the removal finished"); + draw(cx); + assert!( + cx.debug_bounds("run-row-0").is_some(), + "Done keeps the list" + ); + assert!(cx.debug_bounds("run-row-1").is_some()); + update(&view, cx, |app, _| { + assert!( + app.run_list + .items + .iter() + .all(|item| item.status == Status::Removed), + "every item is checked off" + ); + let totals = app.run_list.totals(); + assert_eq!((totals.removed, totals.failed), (2, 0)); + assert_eq!(totals.reported_done, 400_000); + }); + assert!(!build_output.exists()); + assert!(temp.path().join("target/debug").exists()); + assert!(temp.path().join("keep/notes.txt").exists()); +} + +/// Review draws its rows as Removing does: a deep path is shortened from +/// the middle onto one line, so its row is as tall as a short one's, and +/// the row says why the path is listed. +#[gpui_kit::test] +fn review_rows_shorten_deep_paths_and_say_why(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let deep: PathBuf = (0..30) + .map(|level| format!("nested-directory-{level:02}")) + .collect(); + let file = temp.path().join(&deep).join("leaf.bin"); + std::fs::create_dir_all(file.parent().expect("parent")).expect("mkdir"); + std::fs::write(&file, vec![b'x'; 5_000]).expect("write"); + let (view, cx) = view_over(temp.path(), cx); + mark_paths(&view, cx, &[temp.path().join(".cache"), file.clone()]); + update(&view, cx, |app, cx| { + app.screen = Screen::Review; + cx.notify(); + }); + draw(cx); + let rows: Vec<_> = (0..2) + .map(|index| { + let selector: &'static str = + Box::leak(format!("review-row-{index}").into_boxed_str()); + cx.debug_bounds(selector) + .unwrap_or_else(|| panic!("{selector} is drawn")) + }) + .collect(); + assert_eq!( + rows[0].size.height, rows[1].size.height, + "the deep path does not wrap: {rows:?}" + ); + // The cache says it is regenerable; the plain file has nothing to say. + assert!(cx.debug_bounds("review-kind-0").is_some(), "a kind chip"); + assert!(cx.debug_bounds("review-kind-1").is_none()); + // What each mark is was read once: a later frame walks no directory. + crate::marks::work::reset(); + update(&view, cx, |_, cx| cx.notify()); + draw(cx); + assert!(crate::marks::work::RENDERS.get() > 0, "it drew again"); + assert_eq!( + crate::marks::work::RESOLUTION.get(), + 0, + "and walked nothing" + ); + let folder = read(&view, cx, |app| { + crate::run_view::folder_line(app, &file, 40) + }); + assert!(folder.contains('\u{2026}'), "{folder}"); + assert!(folder.ends_with("nested-directory-29"), "{folder}"); +} + +/// A long run scrolls with the item in hand, as the live log follows its +/// newest line: scrolling it out of view pauses that and shows the pill, +/// and the pill follows again. +#[gpui_kit::test] +fn the_removal_list_follows_the_item_in_hand_like_the_live_log( + cx: &mut TestAppContext, +) { + use crate::run_list::{Item, RunList, Status}; + use crate::run_view::focus_place; + use std::cmp::Ordering; + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + let path = |index: usize| temp.path().join(format!("dir-{index:03}")); + update(&view, cx, |app, cx| { + app.run_list = RunList::new( + (0..80) + .map(|index| Item { + target: disktree_core::removal::Target { + path: path(index), + bytes: 1_000, + is_dir: true, + hidden: false, + }, + category: disktree_core::classify::Category::Other, + // Every other row has a kind chip, so rows differ in + // what they hold. + reclaim: (index % 2 == 1).then_some( + disktree_core::classify::Reclaim::BuildOutput, + ), + private: None, + status: Status::Waiting, + }) + .collect(), + ); + app.screen = Screen::Running; + cx.notify(); + }); + draw(cx); + // Every row spans the list, whatever it holds, so its size and status + // lanes line up with the rows around it. A virtualized row is only as + // wide as its content unless it says otherwise. + let list = cx.debug_bounds("run-list").expect("the list"); + for index in ["run-row-0", "run-row-1"] { + let row = cx.debug_bounds(index).expect("a row"); + assert!( + row.size.width >= list.size.width - px(4.), + "{index} is {:?} wide in a {:?} list", + row.size.width, + list.size.width + ); + } + let place = + |cx: &mut Window, view: &Entity| read(view, cx, focus_place); + assert_eq!(place(cx, &view), Some(Ordering::Equal), "row 0 shows"); + let settle = |cx: &mut Window, view: &Entity, upto| { + update(view, cx, |app, cx| { + app.update_follow(); + for index in 0..upto { + if app.run_list.settle(&path(index), &Ok(())).is_some() { + app.scroll_to_focus(); + } + } + cx.notify(); + }); + draw(cx); + draw(cx); + }; + + // Most of the way down: the list went with it. + settle(cx, &view, 60); + assert_eq!(read(&view, cx, |app| app.run_list.current()), Some(60)); + assert_eq!(place(cx, &view), Some(Ordering::Equal), "row 60 shows"); + assert!(cx.debug_bounds("run-row-60").is_some(), "and is drawn"); + // Only the rows in view are built, however long the run. + assert!(cx.debug_bounds("run-row-0").is_none(), "row 0 is not"); + assert!(cx.debug_bounds("follow-removal").is_none()); + + // Scrolled back to the top, away from it: following pauses, the pill + // shows, and the list stays where it was put. + let list = cx.debug_bounds("run-list").expect("the list"); + cx.simulate_event(gpui_kit::ScrollWheelEvent { + position: list.center(), + delta: gpui_kit::ScrollDelta::Pixels(gpui_kit::point( + px(0.), + px(100_000.), + )), + ..Default::default() + }); + draw(cx); + settle(cx, &view, 65); + assert!(!read(&view, cx, |app| app.run_list.follow), "paused"); + assert_eq!(place(cx, &view), Some(Ordering::Greater)); + assert!(cx.debug_bounds("follow-removal").is_some(), "the pill"); + + // The pill follows again. + click_on(cx, "follow-removal"); + draw(cx); + assert!(read(&view, cx, |app| app.run_list.follow)); + assert_eq!(place(cx, &view), Some(Ordering::Equal), "row 65 shows"); + assert!(cx.debug_bounds("follow-removal").is_none()); +} + +#[gpui_kit::test] +fn a_removal_leaves_what_went_in_the_tree_as_removed_and_counts_it( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + // Stand in the directory that is about to lose a child. + update(&view, cx, |app, cx| { + let junk = app + .crumbs_for_path(&temp.path().join("junk")) + .expect("junk"); + app.go_to(junk, cx); + }); + let (scan, before) = read(&view, cx, |app| { + ( + app.scan_epoch, + app.tree.as_ref().expect("a tree").root().bytes, + ) + }); + + remove_now(&view, cx, &["junk/deeper"]); + assert!(read(&view, cx, |app| app.scan.is_none()), "no rescan"); + draw(cx); + let deeper = temp.path().join("junk/deeper"); + update(&view, cx, |app, _| { + let root = app.tree.as_ref().expect("a tree").root(); + assert_eq!(root.bytes, before, "the scan's figures stay"); + assert!(app.crumbs_for_path(&deeper).is_some(), "and so does it"); + assert!(app.was_removed(&deeper)); + assert_eq!(app.current_path(), temp.path().join("junk")); + assert!( + app.prepare().tiles.iter().any(|tile| tile.removed), + "it is drawn as removed" + ); + let cohorts = app.ledger.since(app.scans_done); + assert_eq!(app.scan_epoch, scan); + assert_eq!(cohorts.len(), 1); + assert_eq!(cohorts[0].removed, 1); + assert_eq!(cohorts[0].reported, 100_000); + assert!(cohorts[0].observed().is_some(), "free space is measured"); + }); + assert!(cx.debug_bounds("removal-ledger").is_some(), "Done lists it"); + + // The inspector offers no mark for it, and says why. + update(&view, cx, |app, cx| { + app.screen = Screen::Explore; + app.selected = app.crumbs_for_path(&deeper); + cx.notify(); + }); + draw(cx); + assert!(cx.debug_bounds("inspector-mark").is_none()); + update(&view, cx, |app, cx| { + app.selected = app.crumbs_for_path(&temp.path().join("junk/blob.bin")); + cx.notify(); + }); + draw(cx); + assert!(cx.debug_bounds("inspector-mark").is_some(), "its neighbour"); + + update(&view, cx, |app, cx| { + // What went cannot be marked again. + let crumbs = app.crumbs_for_path(&deeper).expect("still drawn"); + app.toggle_mark(&crumbs, cx); + assert!(app.marks.is_empty()); + let notice = app.notice().map(|(text, _)| text); + assert!(notice.is_some_and(|text| text.contains("was removed"))); + // Its directory can, for what is left in it. + let junk = app.crumbs_for_path(&temp.path().join("junk")).unwrap(); + let listed = app.node_at(&junk).unwrap().bytes; + app.toggle_mark(&junk, cx); + assert_eq!(app.marks.items()[0].bytes, listed - 100_000); + app.toggle_mark(&junk, cx); + assert!(app.marks.is_empty()); + }); + + // A second batch, still without a scan: two rows and a total. + remove_now(&view, cx, &["keep"]); + draw(cx); + let totals = read(&view, cx, |app| { + assert!(app.was_removed(&temp.path().join("keep/notes.txt"))); + crate::ledger::Ledger::totals(app.ledger.since(app.scans_done)) + }) + .expect("totals"); + assert_eq!(totals.count, 2); + assert_eq!(totals.reported, 101_000); + assert!( + temp.path().join("junk/blob.bin").exists(), + "neighbours stay" + ); + + update(&view, cx, |app, cx| { + app.screen = Screen::Explore; + // A scan started and stopped keeps the tree, and so the account. + app.scan_epoch += 1; + cx.notify(); + }); + draw(cx); + assert!( + cx.debug_bounds("freed-since-scan").is_some(), + "the Disk section keeps the account" + ); + + // A rescan starts a new account and forgets what was removed. + update(&view, cx, Disktree::start_scan); + finish_scan(&view, cx); + draw(cx); + read(&view, cx, |app| { + assert!(app.ledger.since(app.scans_done).is_empty()); + assert!(app.removed.is_empty()); + assert!(app.crumbs_for_path(&deeper).is_none(), "the disk now"); + }); + assert!(cx.debug_bounds("freed-since-scan").is_none()); +} + +#[gpui_kit::test] +fn removing_a_directory_after_part_of_it_counts_only_the_rest( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + remove_now(&view, cx, &["junk/deeper"]); + update(&view, cx, |app, cx| { + app.screen = Screen::Explore; + cx.notify(); + }); + remove_now(&view, cx, &["junk"]); + read(&view, cx, |app| { + let cohorts = app.ledger.since(app.scans_done); + assert_eq!(cohorts.len(), 2); + let rest = cohorts[1].reported; + assert!( + cohorts[1].private.is_none_or(|private| private <= rest), + "{:?} private of {rest} reported", + cohorts[1].private + ); + let totals = crate::ledger::Ledger::totals(cohorts).unwrap(); + assert!(totals.private.is_none_or(|p| p <= totals.reported)); + }); +} + +#[gpui_kit::test] +fn an_agent_listing_says_what_was_removed_since_the_scan( + cx: &mut TestAppContext, +) { + use disktree_link::{FindRequest, Request, Response}; + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + let root = temp.path().to_path_buf(); + let ask = |request: Request, cx: &mut Window| { + update(&view, cx, |app, cx| app.answer_agent(&request, cx)) + }; + // Before any removal, nothing says removed. + let Response::Listing(before) = ask( + Request::Ls { + path: root.clone(), + limit: 10, + }, + cx, + ) else { + panic!("a listing"); + }; + assert!( + before + .children + .iter() + .all(|child| !child.removed && child.removed_bytes == 0) + ); + + remove_now(&view, cx, &["junk/deeper"]); + let Response::Listing(listing) = ask( + Request::Ls { + path: root.clone(), + limit: 10, + }, + cx, + ) else { + panic!("a listing"); + }; + let junk = listing + .children + .iter() + .find(|child| child.name == "junk") + .expect("junk is still listed"); + assert!(!junk.removed); + assert_eq!(junk.removed_bytes, 100_000, "part of it went"); + assert_eq!(listing.entry.removed_bytes, 100_000, "and so of the root"); + let keep = listing.children.iter().find(|c| c.name == "keep").unwrap(); + assert!( + !keep.removed && keep.removed_bytes == 0, + "neighbours say nothing" + ); + + let Response::Listing(inside) = ask( + Request::Ls { + path: root.join("junk"), + limit: 10, + }, + cx, + ) else { + panic!("a listing"); + }; + let deeper = inside.children.iter().find(|c| c.name == "deeper").unwrap(); + assert!(deeper.removed, "it went whole"); + assert_eq!(deeper.removed_bytes, 0); + + let Response::Found(found) = ask( + Request::Find(FindRequest { + kind: "any".into(), + name: Some("deeper".into()), + limit: 5, + ..FindRequest::default() + }), + cx, + ) else { + panic!("matches"); + }; + let hit = found + .matches + .iter() + .find(|hit| hit.path == root.join("junk/deeper")) + .expect("still found"); + assert!(hit.entry.removed); + + // An estimate over what went, or around it, would price space already + // gone: it asks for a rescan instead. + for path in [root.join("junk/deeper"), root.join("junk")] { + let answer = ask( + Request::Estimate { + paths: vec![path], + peer_scope: None, + peer_limit: 0, + }, + cx, + ); + assert!( + matches!(&answer, Response::Error { message } if message.contains("rescan")), + "{answer:?}" + ); + } + + // A rescan sees the disk as it is, and nothing is flagged. + update(&view, cx, Disktree::start_scan); + finish_scan(&view, cx); + let Response::Listing(after) = ask( + Request::Ls { + path: root.join("junk"), + limit: 10, + }, + cx, + ) else { + panic!("a listing"); + }; + assert!(after.children.iter().all(|c| c.name != "deeper")); + assert_eq!(after.entry.removed_bytes, 0); +} + +#[gpui_kit::test] +fn what_was_removed_stays_removed_across_a_metric_change( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + remove_now(&view, cx, &["junk/deeper"]); + let junk = temp.path().join("junk"); + update(&view, cx, |app, cx| { + app.screen = Screen::Explore; + let crumbs = app.crumbs_for_path(&junk).unwrap(); + app.toggle_mark(&crumbs, cx); + // Size | Files reorders the tree and re-reads every mark's size. + app.toggle_metric(cx); + app.toggle_metric(cx); + }); + read(&view, cx, |app| { + assert!(app.was_removed(&junk.join("deeper"))); + let crumbs = app.crumbs_for_path(&junk).unwrap(); + let listed = app.node_at(&crumbs).unwrap().bytes; + assert_eq!( + app.marks.items()[0].bytes, + listed - 100_000, + "a mark around it still leaves it out" + ); + }); +} + +#[gpui_kit::test] +fn status_review_widening_announces_each_in_flight_root_immediately( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let inner = temp.path().join("junk/deeper"); + let (view, cx) = view_over(&inner, cx); + update(&view, cx, |app, cx| { + for target in [temp.path().join("junk"), temp.path().to_path_buf()] { + app.widen_to(target.clone(), cx); + assert_eq!(app.root_path, inner, "the old tree stays usable"); + assert_eq!(app.scan_root, target); + let status = app.accessibility_status(); + assert!( + status.starts_with(&format!("Scanning {}.", target.display())), + "{status}" + ); + app.progress.files = 500; + assert_eq!(app.accessibility_status(), status, "counts sampled"); + } + app.cancel_scan(cx); + assert!(app.accessibility_status().starts_with("Scan cancelled")); + }); + draw(cx); + assert!(inner.join("more.bin").exists()); +} + +#[gpui_kit::test] +fn source_tab_traversal_stays_in_the_modal_and_escape_restores_origin( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + press(cx, "tab"); + let origin = cx + .update(|window, cx| window.focused(cx)) + .expect("control focus"); + let root_focus = read(&view, cx, |app| app.focus.clone()); + assert!(!cx.update(|window, _| root_focus.is_focused(window))); + for ssh in [false, true] { + update(&view, cx, |app, cx| { + app.open_volumes(cx); + app.volumes = vec![Volume { + point: temp.path().into(), + device: None, + space: None, + }]; + app.volumes_loading = false; + app.picker_ssh = ssh; + }); + draw(cx); + assert_eq!(cx.debug_bounds("source-host").is_some(), ssh); + let (host, path) = view.read_with(cx, |app, cx| { + use gpui_kit::Focusable as _; + ( + app.picker_host.as_ref().unwrap().read(cx).focus_handle(cx), + app.picker_path.as_ref().unwrap().read(cx).focus_handle(cx), + ) + }); + let roots = read(&view, cx, |app| app.source_roots_focus.clone()); + let mut saw_roots = false; + let mut saw_host = false; + let mut saw_path = false; + for key in ["tab", "shift-tab"] { + for _ in 0..24 { + press(cx, key); + saw_roots |= cx.update(|window, _| roots.is_focused(window)); + saw_host |= cx.update(|window, _| host.is_focused(window)); + saw_path |= cx.update(|window, _| path.is_focused(window)); + let modal = read(&view, cx, |app| app.confirm_focus.clone()); + assert!( + cx.update(|window, cx| modal.contains_focused(window, cx)) + ); + assert!(read(&view, cx, |app| app.marks.is_empty() + && app.scan.is_none())); + } + } + assert!(saw_roots, "the root list remains a tab stop"); + assert_eq!(saw_host, ssh, "only SSH mode shows the host field"); + assert_eq!(saw_path, !ssh, "Directory appears after a source is ready"); + press(cx, "escape"); + assert!(cx.update(|window, _| origin.is_focused(window))); + } +} + +#[gpui_kit::test] +fn help_focus_returns_to_the_originating_control(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + press(cx, "tab"); + let origin = cx + .update(|window, cx| window.focused(cx)) + .expect("control focus"); + for dismissal in ["escape", "done", "backdrop"] { + update(&view, cx, Disktree::open_help); + draw(cx); + press(cx, "tab shift-tab"); + match dismissal { + "escape" => press(cx, "escape"), + "done" => click_on(cx, "overlay-done"), + _ => { + let card = cx.debug_bounds("help-overlay").expect("card"); + let outside = card.origin - Point::new(px(8.), px(8.)); + cx.simulate_click(outside, gpui_kit::Modifiers::none()); + draw(cx); + } + } + assert!(cx.update(|window, _| origin.is_focused(window))); + assert!(read(&view, cx, |app| !app.show_help && app.marks.is_empty())); + } +} + +#[gpui_kit::test] +fn custom_menu_arrows_and_escape_leave_files_untouched( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, Disktree::toggle_app_menu); + draw(cx); + press(cx, "down down up"); + assert_eq!(read(&view, cx, |app| app.app_menu_index), 1); + press(cx, "escape"); + assert!(read(&view, cx, |app| !app.app_menu_open && app.marks.is_empty())); + assert!(temp.path().join("junk/blob.bin").exists()); +} + +#[gpui_kit::test] +fn custom_menu_enter_activates_the_named_safe_action(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + let index = crate::app_menu::menus(crate::app_menu::Platform::Other) + .into_iter() + .flat_map(|menu| menu.items) + .filter_map(|item| { + if let gpui_kit::MenuItem::Action { name, .. } = item { + Some(name) + } else { + None + } + }) + .position(|name| name == "Keyboard Shortcuts") + .expect("safe menu action"); + update(&view, cx, |app, cx| { + app.toggle_app_menu(cx); + app.app_menu_index = index; + }); + draw(cx); + press(cx, "enter"); + assert!(read(&view, cx, |app| app.show_help + && !app.app_menu_open + && app.marks.is_empty())); + press(cx, "escape"); + assert!(temp.path().join("junk/blob.bin").exists()); +} + +#[gpui_kit::test] +fn a_large_directory_keeps_zero_weight_files_reachable_in_bounded_pages( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = tempfile::tempdir().expect("tempdir"); + for index in 0..50_000 { + std::fs::write(temp.path().join(format!("entry-{index:05}.txt")), []) + .expect("empty fixture file"); + } + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + app.file_list = true; + app.selected = None; + app.file_step(1, cx); + app.file_step(isize::MAX, cx); + }); + draw(cx); + assert!(cx.debug_bounds("file-row-49999").is_some()); + assert!(cx.debug_bounds("file-row-49899").is_none()); + read(&view, cx, |app| { + assert_eq!(app.current().unwrap().children().len(), 50_000); + assert_eq!(app.selected.as_deref(), Some([49_999].as_slice())); + assert!(app.marks.is_empty()); + }); +} + +#[gpui_kit::test] +fn tab_reaches_file_navigation_without_changing_selection( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + let navigation = read(&view, cx, |app| app.file_focus.clone()); + let selected = read(&view, cx, |app| app.selected.clone()); + let mut reached = false; + // Each legend chip adds a tab stop alongside the platform's chrome + // and navigation controls. Growing the inventory must not make this + // reachability check depend on a fixed number of categories. + let tab_budget = 16 + + disktree_core::classify::Category::LEGEND.len() + + crate::palette::AGE_BUCKETS.len(); + for _ in 0..tab_budget { + press(cx, "tab"); + if cx.update(|window, _| navigation.is_focused(window)) { + reached = true; + break; + } + } + assert!(reached, "file navigation participates in the tab order"); + assert_eq!(read(&view, cx, |app| app.selected.clone()), selected); +} + +/// Keyboard activation of Cancel must never authorize the marked removal. +#[gpui_kit::test] +fn focus_review_delete_cancel_enter_preserves_the_fixture( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + app.removal_mode = RemovalMode::Permanent; + let junk = child_crumbs(app, &[], "junk"); + app.toggle_mark(&junk, cx); + app.open_review(cx); + }); + draw(cx); + let cancel_tabs = if crate::chrome::Platform::current() + == crate::chrome::Platform::Windows + { + 2 + } else { + 1 + }; + for activation in ["enter", "space"] { + press(cx, "enter"); + for _ in 0..cancel_tabs { + press(cx, "tab"); + } + let keystroke = gpui_kit::Keystroke::parse(activation).unwrap(); + cx.simulate_event(gpui_kit::KeyDownEvent { + keystroke: keystroke.clone(), + is_held: false, + prefer_character_input: false, + }); + cx.simulate_event(gpui_kit::KeyUpEvent { keystroke }); + draw(cx); + read(&view, cx, |app| { + assert!(!app.confirm_open, "Cancel {activation} closes the alert"); + assert!(app.run.is_none(), "Cancel never starts removal"); + assert_eq!(app.screen, Screen::Review); + assert_eq!(app.marks.len(), 1); + }); + assert!(temp.path().join("junk/blob.bin").exists()); + assert!(temp.path().join("keep/notes.txt").exists()); + } + press(cx, "enter"); + for _ in 0..(3 - cancel_tabs) { + press(cx, "tab"); + } + press(cx, "enter"); + assert_eq!(read(&view, cx, |app| app.screen), Screen::Running); + let epoch = read(&view, cx, |app| app.run_epoch); + let mut finished = false; + for _ in 0..400 { + std::thread::sleep(std::time::Duration::from_millis(5)); + finished = update(&view, cx, |app, cx| { + app.poll_removal_once(epoch, cx); + app.screen == Screen::Done + }); + if finished { + break; + } + } + assert!(finished, "focused Delete completes the contrived removal"); + assert!(!temp.path().join("junk").exists()); + assert!(temp.path().join("keep/notes.txt").exists()); + read(&view, cx, |app| { + assert!(app.scan.is_none(), "Delete alone does not rescan"); + let root = app.tree.as_ref().expect("a tree").root(); + assert!(root.child_named("junk").is_some(), "the tree keeps it"); + assert!(app.was_removed(&temp.path().join("junk")), "as removed"); + }); +} + +#[gpui_kit::test] +fn focus_review_source_cancel_enter_does_not_scan(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + let epoch = read(&view, cx, |app| app.scan_epoch); + // Supply only a contrived root, without starting host discovery. + update(&view, cx, |app, cx| { + app.volumes_open = true; + app.volumes_loading = false; + app.volumes = vec![Volume { + point: temp.path().into(), + device: None, + space: None, + }]; + app.focus_request = Some(crate::state::FocusTarget::Dialog); + cx.notify(); + }); + draw(cx); + let cancel_tabs = if crate::chrome::Platform::current() + == crate::chrome::Platform::Windows + { + 1 + } else { + 2 + }; + for _ in 0..cancel_tabs { + press(cx, "shift-tab"); + } + press(cx, "enter"); + read(&view, cx, |app| { + assert!(!app.volumes_open, "Cancel closes the picker"); + assert!(app.scan.is_none()); + assert_eq!(app.scan_epoch, epoch, "Cancel does not accept a root"); + assert_eq!(app.root_path, temp.path()); + }); +} + +#[gpui_kit::test] +fn focus_review_escape_cancels_removal_before_background_scan( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(&temp.path().join("junk"), cx); + update(&view, cx, |app, cx| { + app.widen_to(temp.path().into(), cx); + app.screen = Screen::Running; + // No paths are removed: this checks delivery of the cancellation + // request while a real, contrived widening scan is still active. + app.run = Some(disktree_core::removal::spawn( + disktree_core::removal::Plan::default(), + RemovalMode::Permanent, + )); + cx.notify(); + }); + draw(cx); + press(cx, "escape"); + read(&view, cx, |app| { + assert!(app.scan.is_some(), "foreground Escape preserves the scan"); + assert!( + app.notice().as_ref().is_some_and( + |(text, _)| text == "stopping after the current item" + ) + ); + }); + update(&view, cx, |app, cx| { + app.run = None; + app.cancel_scan(cx); + }); + assert!(temp.path().join("junk/blob.bin").exists()); +} + +#[gpui_kit::test] +fn focus_review_escape_leaves_review_and_done_with_refresh_intact( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(&temp.path().join("junk"), cx); + for screen in [Screen::Review, Screen::Done] { + update(&view, cx, |app, cx| { + app.widen_to(temp.path().into(), cx); + app.screen = screen; + cx.notify(); + }); + draw(cx); + press(cx, "escape"); + read(&view, cx, |app| { + assert_eq!(app.screen, Screen::Explore); + assert!( + app.scan.is_some(), + "foreground Escape preserves the refresh" + ); + }); + update(&view, cx, Disktree::cancel_scan); + } + assert!(temp.path().join("junk/blob.bin").exists()); +} + +fn cycle_back_to_focus( + cx: &mut Window, + target: &gpui_kit::FocusHandle, + key: &str, +) { + press(cx, key); + for _ in 0..60 { + if cx.update(|window, _| target.is_focused(window)) { + return; + } + press(cx, key); + } + panic!("{key} traversal did not reach the navigation control"); +} + +#[gpui_kit::test] +fn focus_review_settings_panes_are_forward_and_reverse_tab_stops( + cx: &mut TestAppContext, +) { + use crate::settings::{Pane, SettingsWindow}; + cx.update(init); + let (_view, cx) = + cx.add_window_view(|_, cx| SettingsWindow::new(Pane::About, cx)); + draw(cx); + for pane in Pane::ALL { + click_on(cx, pane.nav_id()); + let target = cx + .update(|window, cx| window.focused(cx)) + .expect("pane focus"); + cycle_back_to_focus(cx, &target, "tab"); + cycle_back_to_focus(cx, &target, "shift-tab"); + } +} + +#[gpui_kit::test] +fn focus_review_application_menu_is_a_forward_and_reverse_tab_stop( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + app.chrome_pin = window_frames() + .into_iter() + .find(|(name, _)| *name == "GNOME, controls right") + .map(|(_, frame)| frame); + cx.notify(); + }); + draw(cx); + click_on(cx, "app-menu-button"); + press(cx, "escape"); + let target = cx + .update(|window, cx| window.focused(cx)) + .expect("menu trigger focus"); + cycle_back_to_focus(cx, &target, "tab"); + cycle_back_to_focus(cx, &target, "shift-tab"); + press(cx, "enter"); + assert!(read(&view, cx, |app| app.app_menu_open)); + press(cx, "escape"); + assert!(temp.path().join("junk/blob.bin").exists()); +} + +#[gpui_kit::test] +fn routing_review_search_escape_preserves_the_widening_scan( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(&temp.path().join("junk"), cx); + for file_list in [false, true] { + update(&view, cx, |app, cx| { + app.file_list = file_list; + app.widen_to(temp.path().into(), cx); + }); + draw(cx); + let epoch = read(&view, cx, |app| app.scan_epoch); + press(cx, "/ b l o b"); + assert!(read(&view, cx, |app| app.find_open && app.find == "blob")); + press(cx, "escape"); + read(&view, cx, |app| { + assert!(!app.find_open, "Escape dismisses the foreground search"); + assert!(app.find.is_empty()); + assert!(app.scan.is_some(), "dismissing search preserves the scan"); + assert_eq!(app.scan_epoch, epoch); + assert!(!app.progress.cancelled); + assert!(app.tree().is_some()); + }); + press(cx, "escape"); + read(&view, cx, |app| { + assert!(app.scan.is_none(), "the next Escape cancels the scan"); + assert!(app.progress.cancelled); + }); + } + assert!(temp.path().join("junk/blob.bin").exists()); +} + +#[gpui_kit::test] +fn routing_review_menu_escape_preserves_the_widening_scan( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(&temp.path().join("junk"), cx); + for menu in ["crumb", "power", "application"] { + update(&view, cx, |app, cx| { + app.widen_to(temp.path().into(), cx); + match menu { + "crumb" => { + let deeper = child_crumbs(app, &[], "deeper"); + app.open_crumb_menu(&deeper, cx); + } + "power" => { + app.cpu_threads = 8; + app.toggle_power_menu(cx); + } + _ => app.toggle_app_menu(cx), + } + }); + draw(cx); + let epoch = read(&view, cx, |app| app.scan_epoch); + press(cx, "escape"); + read(&view, cx, |app| { + assert!(app.crumb_menu.is_none(), "{menu}"); + assert!(app.power_menu.is_none(), "{menu}"); + assert!(!app.app_menu_open, "{menu}"); + assert!(app.scan.is_some(), "{menu} Escape preserves the scan"); + assert_eq!(app.scan_epoch, epoch); + assert!(!app.progress.cancelled); + }); + press(cx, "escape"); + assert!(read(&view, cx, |app| app.scan.is_none())); + } +} + +#[gpui_kit::test] +fn routing_review_help_dismisses_menus_and_contains_navigation( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + let junk = read(&view, cx, |app| child_crumbs(app, &[], "junk")); + update(&view, cx, |app, cx| { + app.go_to(junk.clone(), cx); + app.power_settings_path = None; + app.cpu_threads = 8; + app.chrome_pin = window_frames() + .into_iter() + .find(|(name, _)| *name == "GNOME, controls right") + .map(|(_, frame)| frame); + cx.notify(); + }); + draw(cx); + for menu in ["crumb", "power", "application"] { + for native_action in [false, true] { + update(&view, cx, |app, cx| match menu { + "crumb" => app.open_crumb_menu(&junk, cx), + "power" => app.toggle_power_menu(cx), + _ => app.toggle_app_menu(cx), + }); + draw(cx); + if native_action { + cx.update(|window, cx| { + window.dispatch_action( + Box::new(crate::app_menu::ShowKeyboardShortcuts), + cx, + ); + }); + draw(cx); + } else { + press(cx, "?"); + } + read(&view, cx, |app| { + assert!(app.show_help, "{menu}, action={native_action}"); + assert!(app.crumb_menu.is_none(), "Help closes {menu}"); + assert!(app.power_menu.is_none(), "Help closes {menu}"); + assert!(!app.app_menu_open, "Help closes {menu}"); + }); + press(cx, "down enter"); + read(&view, cx, |app| { + assert!(app.show_help); + assert_eq!(app.crumbs, junk, "Help contains navigation"); + assert!(app.marks.is_empty()); + assert_eq!(app.screen, Screen::Explore); + }); + press(cx, "escape"); + assert!(read(&view, cx, |app| !app.show_help)); + } + } + assert!(temp.path().join("junk/blob.bin").exists()); +} + +/// A made-up updater state: `finished` checks done, the last ending in +/// `outcome`, and the download held for the default channel, if any. +fn update_state( + finished: u64, + outcome: crate::updater::Outcome, + held: Option<&str>, +) -> crate::updater::State { + use crate::update_channel::Slot; + crate::updater::State { + finished, + last: Some(( + std::time::UNIX_EPOCH + std::time::Duration::from_secs(finished), + outcome, + )), + held: held.map(|version| crate::updater::Held { + version: version.to_owned(), + file_name: format!("PwrDisk-{version}-full.nupkg"), + slot: Slot::default().key(), + switch_back: false, + }), + ..crate::updater::State::default() + } +} + +/// Asks as Check for Updates… does, against a made-up check that has not +/// finished yet, without starting a real one. +fn ask_for_updates(view: &Entity, cx: &mut Window) { + use crate::update_channel::Slot; + update(view, cx, |app, cx| { + app.update_watch.ask(0); + let state = crate::updater::State { + checking: true, + ..crate::updater::State::default() + }; + app.follow_updates(state, "0.14.0", Slot::default(), cx); + }); +} + +/// Check for Updates… shows a live card, then answers in its place: here, +/// that this copy is the latest. +#[gpui_kit::test] +fn a_check_asked_for_answers_in_a_toast(cx: &mut TestAppContext) { + use crate::update_channel::Slot; + use crate::updater::Outcome; + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + ask_for_updates(&view, cx); + draw(cx); + assert!(cx.debug_bounds("toast-update").is_some(), "checking shows"); + assert!(cx.debug_bounds("toast-track").is_some(), "with its sweep"); + assert!( + cx.debug_bounds("toast-update-timer").is_none(), + "work under way has no countdown" + ); + + let state = update_state(1, Outcome::UpToDate("0.14.0".into()), None); + update(&view, cx, |app, cx| { + app.follow_updates(state, "0.14.0", Slot::default(), cx); + }); + draw(cx); + let title = read(&view, cx, |app| { + app.toasts + .get(crate::toasts::UPDATE) + .map(|t| t.title.clone()) + }); + assert_eq!( + title.as_deref(), + Some("PwrDisk is up to date"), + "replaced in place" + ); + assert!(cx.debug_bounds("toast-release-notes").is_some()); + assert!( + cx.debug_bounds("toast-update-timer").is_some(), + "counts down" + ); + assert!(cx.debug_bounds("toast-track").is_none()); + assert!(cx.debug_bounds("toast-restart").is_none()); +} + +/// A download's percent redraws the live card, and only Check for +/// Updates… shows one: a background download raises nothing until it is +/// ready. +#[gpui_kit::test] +fn a_menu_check_shows_its_download_percent(cx: &mut TestAppContext) { + use crate::updater::Download; + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + let download = Download { + version: "0.15.0".into(), + switch_back: false, + percent: Some(42), + }; + update(&view, cx, |app, _| { + app.update_watch.follow_progress(Some(download.clone())); + }); + draw(cx); + assert!( + cx.debug_bounds("toast-stack").is_none(), + "nobody asked: a background download is silent" + ); + + ask_for_updates(&view, cx); + update(&view, cx, |app, _| { + app.update_watch.follow_progress(Some(download)); + }); + draw(cx); + let card = read(&view, cx, crate::toasts::update_card).expect("live"); + assert_eq!(card.title, "Downloading update"); + assert_eq!(card.body, "PwrDisk 0.15.0 \u{00b7} 42%"); + assert!(cx.debug_bounds("toast-track").is_some()); +} + +/// A download's percent is drawn by the toast alone: it never rebuilds +/// Settings, which collects the diagnostics again. A real change does. +#[gpui_kit::test] +fn a_progress_tick_does_not_rebuild_settings(cx: &mut TestAppContext) { + use crate::settings::REFRESHES; + use crate::updater::Change; + cx.update(init); + let temp = fixture(); + let (_view, cx) = view_over(temp.path(), cx); + let before = REFRESHES.get(); + for _ in 0..100 { + cx.update(|_, cx| crate::toasts::updater_changed(Change::Progress, cx)); + } + assert_eq!(REFRESHES.get(), before, "a hundred ticks, no rebuild"); + cx.update(|_, cx| crate::toasts::updater_changed(Change::State, cx)); + assert_eq!(REFRESHES.get(), before + 1, "a real change refreshes"); +} + +/// A ready release stays: a background check offers it, Later puts that +/// version away (the strip's chip still offers it), and a newer one comes +/// back. +#[gpui_kit::test] +fn a_ready_download_stays_until_later(cx: &mut TestAppContext) { + use crate::update_channel::Slot; + use crate::updater::Outcome; + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + let slot = Slot::default(); + + let quiet = update_state(1, Outcome::UpToDate("0.14.0".into()), None); + update(&view, cx, |app, cx| { + app.follow_updates(quiet, "0.14.0", slot, cx); + }); + draw(cx); + assert!(cx.debug_bounds("toast-stack").is_none(), "nothing new"); + assert!(cx.debug_bounds(crate::views::UPDATE_CHIP_ID).is_none()); + + let ready = + update_state(2, Outcome::Downloaded("0.15.0".into()), Some("0.15.0")); + update(&view, cx, |app, cx| { + app.follow_updates(ready, "0.14.0", slot, cx); + }); + draw(cx); + assert!(cx.debug_bounds("toast-restart").is_some()); + assert!(cx.debug_bounds(crate::views::UPDATE_CHIP_ID).is_some()); + let later = cx.debug_bounds("toast-later").expect("ready toast"); + cx.simulate_click(later.center(), gpui_kit::Modifiers::none()); + draw(cx); + assert!(cx.debug_bounds("toast-update").is_none(), "put away"); + assert!( + cx.debug_bounds(crate::views::UPDATE_CHIP_ID).is_some(), + "the chip still offers it" + ); + + // The next background check finds the same download: still down. + let again = + update_state(3, Outcome::Pending("0.15.0".into()), Some("0.15.0")); + update(&view, cx, |app, cx| { + app.follow_updates(again, "0.14.0", slot, cx); + }); + draw(cx); + assert!( + cx.debug_bounds("toast-update").is_none(), + "once per version" + ); + + let newer = + update_state(4, Outcome::Downloaded("0.15.1".into()), Some("0.15.1")); + update(&view, cx, |app, cx| { + app.follow_updates(newer, "0.14.0", slot, cx); + }); + draw(cx); + let body = read(&view, cx, crate::toasts::update_card).map(|t| t.body); + assert_eq!( + body.as_deref(), + Some( + "PwrDisk 0.15.1 is downloaded. It installs when you restart or quit." + ) + ); +} + +/// An answer takes the ready card's place while it stands, and the ready +/// card comes back once it leaves: a failed check never hides a release. +#[gpui_kit::test] +fn the_ready_card_comes_back_after_an_answer(cx: &mut TestAppContext) { + use crate::update_channel::Slot; + use crate::updater::Outcome; + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + let slot = Slot::default(); + let ready = + update_state(1, Outcome::Downloaded("0.15.0".into()), Some("0.15.0")); + update(&view, cx, |app, cx| { + app.follow_updates(ready, "0.14.0", slot, cx); + }); + ask_for_updates(&view, cx); + let mut failed = + update_state(2, Outcome::Failed("timed out".into()), Some("0.15.0")); + failed.checking = false; + update(&view, cx, |app, cx| { + app.update_watch.ask(1); + app.follow_updates(failed, "0.14.0", slot, cx); + }); + draw(cx); + assert!(cx.debug_bounds("toast-check-again").is_some(), "the answer"); + assert!(cx.debug_bounds("toast-restart").is_none(), "in its place"); + cx.executor().advance_clock(crate::toasts::ANSWER); + cx.run_until_parked(); + draw(cx); + assert!(cx.debug_bounds("toast-check-again").is_none(), "gone"); + assert!(cx.debug_bounds("toast-restart").is_some(), "offered again"); +} + +/// Restart pressed says so and cannot be pressed again; a failed restart +/// is offered again, with why. +#[gpui_kit::test] +fn restarting_waits_and_a_failure_is_offered_again(cx: &mut TestAppContext) { + use crate::update_channel::Slot; + use crate::updater::Outcome; + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + let slot = Slot::default(); + let mut state = + update_state(1, Outcome::Downloaded("0.15.0".into()), Some("0.15.0")); + state.restarting = true; + update(&view, cx, |app, cx| { + app.follow_updates(state.clone(), "0.14.0", slot, cx); + }); + draw(cx); + let card = read(&view, cx, crate::toasts::update_card).expect("ready"); + assert!(card.actions.contains(&crate::toasts::Action::Restart { + switch_back: false, + restarting: true, + })); + + state.restarting = false; + state.restart_failed = Some("the updater did not start".into()); + update(&view, cx, |app, cx| { + app.follow_updates(state, "0.14.0", slot, cx); + }); + draw(cx); + assert!(cx.debug_bounds("toast-update-problem").is_some()); + let notice = read(&view, cx, Disktree::notice); + assert!(notice.is_some_and(|(text, _)| text.contains("did not start"))); +} + +/// A failed check asked for by hand says why, with the log one click away. +#[gpui_kit::test] +fn a_failed_check_says_why(cx: &mut TestAppContext) { + use crate::update_channel::Slot; + use crate::updater::Outcome; + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + ask_for_updates(&view, cx); + let failed = update_state(1, Outcome::Failed("rate limited".into()), None); + update(&view, cx, |app, cx| { + app.follow_updates(failed, "0.14.0", Slot::default(), cx); + }); + draw(cx); + assert!(cx.debug_bounds("toast-open-logs").is_some()); + assert!(cx.debug_bounds("toast-check-again").is_some()); + assert!( + !read(&view, cx, |app| app.update_watch.is_asking()), + "answered" + ); +} + +/// An answer leaves on its own after 8 s, and under Reduce Motion too: the +/// strip only stops draining. +#[gpui_kit::test] +fn an_answer_leaves_on_its_own(cx: &mut TestAppContext) { + use crate::update_channel::Slot; + use crate::updater::Outcome; + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.update(|_, cx| cx.set_reduce_motion(true)); + ask_for_updates(&view, cx); + let up = update_state(1, Outcome::UpToDate("0.14.0".into()), None); + update(&view, cx, |app, cx| { + app.follow_updates(up, "0.14.0", Slot::default(), cx); + }); + draw(cx); + let full = cx.debug_bounds("toast-update").expect("answer").size.width; + cx.executor() + .advance_clock(std::time::Duration::from_secs(5)); + cx.run_until_parked(); + draw(cx); + assert!( + !read(&view, cx, |app| app.toasts.is_empty()), + "still reading" + ); + let strip = cx.debug_bounds("toast-update-timer").expect("strip"); + // The card's border lies outside the strip: within two pixels is full. + assert!( + strip.size.width >= full - px(2.), + "Reduce Motion: the strip holds still" + ); + cx.executor() + .advance_clock(std::time::Duration::from_secs(4)); + cx.run_until_parked(); + draw(cx); + assert!( + read(&view, cx, |app| app.toasts.is_empty()), + "gone after 8 s" + ); + assert!(cx.debug_bounds("toast-update").is_none()); + cx.update(|_, cx| cx.set_reduce_motion(false)); +} + +/// The toasts sit above each screen's footer: on Review they never cover +/// Export, Unmark all, Back or the removal button. +#[gpui_kit::test] +fn a_toast_never_covers_the_review_footer(cx: &mut TestAppContext) { + use crate::update_channel::Slot; + use crate::updater::Outcome; + cx.update(init); + let temp = fixture(); + let (view, cx, _tree) = review_with_tree(temp.path(), cx); + // Short enough that a stack anchored to the window would reach the + // footer. + cx.simulate_resize(gpui_kit::size(px(900.), px(420.))); + ask_for_updates(&view, cx); + let failed = update_state(1, Outcome::Failed("timed out".into()), None); + update(&view, cx, |app, cx| { + app.follow_updates(failed, "0.14.0", Slot::default(), cx); + }); + draw(cx); + let stack = cx.debug_bounds("toast-stack").expect("the answer"); + let footer = cx.debug_bounds("review-footer").expect("footer"); + assert!( + stack.bottom() <= footer.top(), + "the stack ends above the footer: {stack:?} over {footer:?}" + ); + for id in ["unmark-all", "back", "commit"] { + let button = cx.debug_bounds(id).expect(id); + assert!(!stack.intersects(&button), "{id} is clear"); + } +} + +/// A toast drawn over the treemap takes the pointer: the tile under it +/// shows no tooltip while the pointer is on the card, and a click or a +/// scroll on the card never reaches the mosaic. +#[gpui_kit::test] +fn a_toast_hides_the_treemap_under_it(cx: &mut TestAppContext) { + use crate::update_channel::Slot; + use crate::updater::Outcome; + use gpui_kit::{Modifiers, MouseButton, MouseDownEvent, MouseUpEvent}; + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + ask_for_updates(&view, cx); + let failed = update_state(1, Outcome::Failed("timed out".into()), None); + update(&view, cx, |app, cx| { + app.follow_updates(failed, "0.14.0", Slot::default(), cx); + }); + draw(cx); + let stack = cx.debug_bounds("toast-stack").expect("the answer"); + let treemap = cx.debug_bounds("treemap").expect("the mosaic"); + // On the card's padding, clear of its buttons, and over the mosaic. + let on_card = stack.origin + Point::new(px(6.), px(6.)); + assert!(treemap.contains(&on_card), "{stack:?} over {treemap:?}"); + + // Into the mosaic first, so there is a tooltip for the card to end. + let beside = Point::new(stack.right() + px(20.), on_card.y); + assert!(treemap.contains(&beside), "{beside:?} in {treemap:?}"); + cx.simulate_mouse_move(beside, None, Modifiers::none()); + draw(cx); + assert!(cx.debug_bounds("cursor-tooltip").is_some(), "a tile's card"); + + cx.simulate_mouse_move(on_card, None, Modifiers::none()); + draw(cx); + assert!( + cx.debug_bounds("cursor-tooltip").is_none(), + "the pointer is on the toast, not the tile under it" + ); + assert!( + read(&view, cx, |app| app.hovered.is_none()), + "nothing hovered" + ); + assert!( + read(&view, cx, |app| app.toasts.is_hovered()), + "the stack is" + ); + + let (selected, zoom) = + read(&view, cx, |app| (app.selected.clone(), app.view)); + cx.simulate_event(MouseDownEvent { + button: MouseButton::Left, + position: on_card, + modifiers: Modifiers::none(), + click_count: 1, + first_mouse: false, + }); + cx.simulate_event(MouseUpEvent { + button: MouseButton::Left, + position: on_card, + modifiers: Modifiers::none(), + click_count: 1, + }); + cx.simulate_event(gpui_kit::ScrollWheelEvent { + position: on_card, + delta: gpui_kit::ScrollDelta::Lines(Point::new(0., 3.)), + modifiers: Modifiers::none(), + touch_phase: gpui_kit::TouchPhase::Moved, + }); + draw(cx); + assert_eq!( + read(&view, cx, |app| (app.selected.clone(), app.view)), + (selected, zoom), + "a click or a scroll on the card leaves the mosaic alone" + ); +} + +/// Review's export menu opens over the marked list and takes the pointer: +/// resting on it never raises the path tooltip of the row underneath, and +/// a press on its padding reaches no row. +#[gpui_kit::test] +fn the_export_menu_hides_the_list_under_it(cx: &mut TestAppContext) { + use gpui_kit::Modifiers; + const TIP: &str = "app-tooltip-surface"; + cx.update(init); + let temp = fixture(); + let (view, cx, _tree) = review_with_tree(temp.path(), cx); + // Short enough that the menu, which opens upward from the footer, + // reaches the first row. + cx.simulate_resize(gpui_kit::size(px(900.), px(300.))); + draw(cx); + let row = cx.debug_bounds("review-row-0").expect("the marked row"); + + // The row's own tooltip, so its absence below means something. + rest_at(cx, row.center()); + assert!(cx.debug_bounds(TIP).is_some(), "the row names its path"); + let back = cx.debug_bounds("back").expect("Back"); + rest_at(cx, back.center()); + + click_on(cx, "export"); + let menu = cx.debug_bounds("export-menu").expect("the menu"); + // In the menu's top padding, above its first item, and over the row. + let on_menu = menu.origin + Point::new(px(24.), px(2.)); + assert!(row.contains(&on_menu), "{menu:?} over {row:?}"); + + rest_at(cx, on_menu); + assert!( + cx.debug_bounds(TIP).is_none(), + "the pointer is on the menu, not the row under it" + ); + + let marks = read(&view, cx, |app| app.marks.len()); + cx.simulate_click(on_menu, Modifiers::none()); + draw(cx); + assert_eq!(read(&view, cx, |app| app.marks.len()), marks, "no row hit"); + assert!( + cx.debug_bounds("export-menu").is_some(), + "a press inside the menu leaves it open" + ); +} + +/// Rest the pointer at `at` past a tooltip's delay, and draw what shows. +fn rest_at(cx: &mut Window, at: Point) { + cx.simulate_mouse_move(at, None, gpui_kit::Modifiers::none()); + // Past the tooltip's delay, so a rest shows the tooltip it would. + cx.executor().advance_clock( + crate::widgets::TOOLTIP_DELAY + std::time::Duration::from_millis(100), + ); + cx.run_until_parked(); + draw(cx); +} + +/// The first log line drawn, by its number: it moves when the list scrolls. +fn first_log_row(cx: &mut Window) -> Option { + (1..=400).find(|number| { + cx.debug_bounds(Box::leak(format!("log-row-{number}").into_boxed_str())) + .is_some() + }) +} + +fn scroll_at(cx: &mut Window, at: Point, dy: f32) { + cx.simulate_event(gpui_kit::ScrollWheelEvent { + position: at, + delta: gpui_kit::ScrollDelta::Pixels(Point::new(px(0.), px(dy))), + ..Default::default() + }); + draw(cx); +} + +/// Logs' context menu drops over the lines and takes the pointer: a scroll +/// on it moves nothing. The selection bar floats over the lines too: a +/// press on it never picks the line number beneath, though a scroll there +/// still moves the lines, as it does over the new-lines pill. +#[gpui_kit::test] +fn logs_overlays_hide_the_lines_under_them(cx: &mut TestAppContext) { + use crate::logs_window::{CONTEXT_ID, LIVE_ID, PILL_ID}; + use gpui_kit::Modifiers; + let line = |number: usize| { + format!("2026-10-31T12:00:00.000-04:00 INFO pwrdisk: line {number}\n") + }; + let text: String = (1..=200).map(line).collect(); + let (_dir, path, view, cx) = logs_over(cx, &text); + let viewport = cx.debug_bounds("logs-viewport").expect("the lines"); + + // The context menu: a search in Filter mode offers it. + let search = cx.update(|_, cx| view.read(cx).search_state()); + cx.update(|window, cx| { + search.update(cx, |search, cx| search.focus(window, cx)); + }); + cx.simulate_input("line"); + draw(cx); + click_on(cx, CONTEXT_ID); + let menu = cx.debug_bounds("logs-context-menu").expect("the menu"); + let on_menu = Point::new(menu.left() + px(24.), menu.bottom() - px(2.)); + assert!(viewport.contains(&on_menu), "{menu:?} over {viewport:?}"); + let first = first_log_row(cx); + scroll_at(cx, on_menu, -400.); + assert_eq!(first_log_row(cx), first, "the lines stay put"); + assert!(cx.debug_bounds("logs-context-menu").is_some(), "still open"); + cx.update(|window, cx| { + search.update(cx, |search, cx| search.focus(window, cx)); + }); + cx.simulate_keystrokes("escape"); + draw(cx); + + // The selection bar, at double text size in a narrow window, where it + // reaches the line numbers; tall enough that lines show beneath it. + cx.update(|window, _| window.set_rem_size(px(32.))); + cx.simulate_resize(gpui_kit::size(px(640.), px(1000.))); + draw(cx); + let first = first_log_row(cx).expect("a line"); + let picked: &'static str = + Box::leak(format!("log-number-{first}").into_boxed_str()); + click_on(cx, picked); + let selection = cx.update(|_, cx| view.read(cx).selection); + assert!(selection.is_some(), "a line is picked"); + let bar = cx.debug_bounds("logs-selection-bar").expect("the bar"); + // The line number that lies most under the bar, within the lines' + // visible frame: a row's part outside it is clipped and takes no press. + let lines = cx.debug_bounds("logs-viewport").expect("the lines"); + let clear = bar.intersect(&lines); + let under = (first..first + 60) + .filter_map(|number| { + cx.debug_bounds(Box::leak( + format!("log-number-{number}").into_boxed_str(), + )) + }) + .max_by(|a, b| { + let tall = |g: &Bounds| g.intersect(&clear).size.height; + tall(a).as_f32().total_cmp(&tall(b).as_f32()) + }) + .filter(|gutter| gutter.intersect(&clear).size.height > px(8.)) + .unwrap_or_else(|| panic!("a line number under {bar:?}")); + // In the middle of where the two overlap: the bar's label there is + // only text, so the press is the bar's. + let on_bar = under.intersect(&clear).center(); + assert!(bar.contains(&on_bar), "{bar:?} at {on_bar:?}"); + assert!(under.contains(&on_bar), "{bar:?} over {under:?}"); + cx.simulate_click(on_bar, Modifiers::none()); + draw(cx); + assert_eq!( + cx.update(|_, cx| view.read(cx).selection), + selection, + "a press on the bar picks no line" + ); + let top = first_log_row(cx); + scroll_at(cx, on_bar, -400.); + assert_ne!(first_log_row(cx), top, "a scroll there moves the lines"); + cx.simulate_keystrokes("escape"); + draw(cx); + + // The pill: paused, new lines count on it, and a scroll over it still + // reaches the lines. + cx.update(|window, _| window.set_rem_size(px(16.))); + cx.simulate_resize(gpui_kit::size(px(1120.), px(720.))); + draw(cx); + if cx.update(|_, cx| view.read(cx).live) { + click_on(cx, LIVE_ID); + } + append_log(&path, &line(201)); + poll_logs(cx); + let pill = cx.debug_bounds(PILL_ID).expect("the pill"); + let top = first_log_row(cx); + scroll_at(cx, pill.center(), 400.); + assert_ne!(first_log_row(cx), top, "a scroll over the pill moves them"); +} + +/// The note that nothing passes the legend's filter sits over the mosaic: +/// the pointer on it raises no tile's card and a press selects no tile. +#[gpui_kit::test] +fn the_empty_filter_note_hides_the_treemap_under_it(cx: &mut TestAppContext) { + use crate::legend::ChipId; + use gpui_kit::Modifiers; + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1440.), px(900.))); + draw(cx); + update(&view, cx, |app, cx| { + app.cycle_legend(ChipId::Reclaimable, cx); + app.cycle_legend(ChipId::Kind(2), cx); + }); + cx.run_until_parked(); + draw(cx); + let note = cx.debug_bounds("legend-empty").expect("the note"); + let on_note = note.origin + Point::new(px(4.), px(4.)); + cx.simulate_mouse_move(on_note, None, Modifiers::none()); + draw(cx); + assert!( + cx.debug_bounds("cursor-tooltip").is_none(), + "the pointer is on the note" + ); + let selected = read(&view, cx, |app| app.selected.clone()); + cx.simulate_click(on_note, Modifiers::none()); + draw(cx); + assert_eq!(read(&view, cx, |app| app.selected.clone()), selected); +} + +/// Removing's Follow pill floats over the list: resting on it raises no +/// row's path, though a scroll over it still scrolls the list. +#[gpui_kit::test] +fn the_follow_pill_hides_the_row_under_it(cx: &mut TestAppContext) { + use crate::run_list::{Item, RunList, Status}; + const TIP: &str = "app-tooltip-surface"; + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + let path = |index: usize| temp.path().join(format!("dir-{index:03}")); + update(&view, cx, |app, cx| { + app.run_list = RunList::new( + (0..80) + .map(|index| Item { + target: disktree_core::removal::Target { + path: path(index), + bytes: 1_000, + is_dir: true, + hidden: false, + }, + category: disktree_core::classify::Category::Other, + reclaim: None, + private: None, + status: Status::Waiting, + }) + .collect(), + ); + app.screen = Screen::Running; + cx.notify(); + }); + draw(cx); + let settle = |cx: &mut Window, view: &Entity, upto| { + update(view, cx, |app, cx| { + app.update_follow(); + for index in 0..upto { + if app.run_list.settle(&path(index), &Ok(())).is_some() { + app.scroll_to_focus(); + } + } + cx.notify(); + }); + draw(cx); + draw(cx); + }; + settle(cx, &view, 60); + let list = cx.debug_bounds("run-list").expect("the list"); + scroll_at(cx, list.center(), 100_000.); + settle(cx, &view, 65); + let pill = cx.debug_bounds("follow-removal").expect("the pill"); + + // A row's own tooltip, so its absence below means something. + rest_at(cx, Point::new(list.left() + px(40.), pill.center().y)); + assert!(cx.debug_bounds(TIP).is_some(), "the row names its path"); + rest_at(cx, list.origin - Point::new(px(4.), px(4.))); + rest_at(cx, pill.origin + Point::new(px(4.), px(4.))); + assert!( + cx.debug_bounds(TIP).is_none(), + "the pointer is on the pill, not the row under it" + ); + + update(&view, cx, |app, _| app.run_list.scrolled_by_hand = false); + scroll_at(cx, pill.center(), -200.); + assert!( + read(&view, cx, |app| app.run_list.scrolled_by_hand), + "a scroll over the pill still scrolls the list" + ); +} + +/// The strip's menu drops over the treemap and takes the pointer: a press +/// on its padding selects no tile, and a scroll there zooms nothing. +#[gpui_kit::test] +fn the_app_menu_hides_the_treemap_under_it(cx: &mut TestAppContext) { + use gpui_kit::Modifiers; + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, Disktree::toggle_app_menu); + draw(cx); + let menu = cx.debug_bounds("app-menu").expect("the menu"); + let treemap = cx.debug_bounds("treemap").expect("the mosaic"); + // On a group's heading, which is only text: just above the group's + // first row, in the first group drawn over the mosaic. + let on_menu = (1..8) + .filter_map(|group| { + let first = (0..8).find_map(|index| { + cx.debug_bounds(Box::leak( + format!("app-menu-{group}-{index}").into_boxed_str(), + )) + })?; + Some(Point::new(menu.origin.x + px(24.), first.top() - px(4.))) + }) + .find(|at| treemap.contains(at)) + .unwrap_or_else(|| panic!("a heading over {treemap:?} in {menu:?}")); + + let (selected, zoom) = + read(&view, cx, |app| (app.selected.clone(), app.view)); + cx.simulate_click(on_menu, Modifiers::none()); + cx.simulate_event(gpui_kit::ScrollWheelEvent { + position: on_menu, + delta: gpui_kit::ScrollDelta::Lines(Point::new(0., 3.)), + modifiers: Modifiers::none(), + touch_phase: gpui_kit::TouchPhase::Moved, + }); + draw(cx); + assert_eq!( + read(&view, cx, |app| (app.selected.clone(), app.view)), + (selected, zoom), + "a press or a scroll on the menu leaves the mosaic alone" + ); + assert!(read(&view, cx, |app| app.app_menu_open), "still open"); + + // The menu is taller than its cap, and still scrolls itself. + cx.simulate_event(gpui_kit::ScrollWheelEvent { + position: on_menu, + delta: gpui_kit::ScrollDelta::Lines(Point::new(0., -3.)), + modifiers: Modifiers::none(), + touch_phase: gpui_kit::TouchPhase::Moved, + }); + draw(cx); + assert!( + read(&view, cx, |app| app.menu_scroll.offset().y) < px(0.), + "the list scrolled" + ); + assert_eq!(read(&view, cx, |app| app.view), zoom, "the mosaic did not"); +} + +/// The ready card gives way while a removal runs (Restart would wait for +/// it anyway); the strip's chip still offers the release. The pointer that +/// rested on the card is forgotten with it, so the next answer still runs +/// out. +#[gpui_kit::test] +fn a_removal_keeps_the_ready_card_down(cx: &mut TestAppContext) { + use crate::update_channel::Slot; + use crate::updater::Outcome; + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + let ready = + update_state(1, Outcome::Downloaded("0.15.0".into()), Some("0.15.0")); + update(&view, cx, |app, cx| { + app.follow_updates(ready, "0.14.0", Slot::default(), cx); + }); + draw(cx); + assert!(cx.debug_bounds("toast-update").is_some()); + update(&view, cx, |app, cx| { + // The pointer is on the card when the removal starts. + let now = cx.background_executor().now(); + app.toasts.set_hovered(true, now); + app.run = Some(disktree_core::removal::spawn( + disktree_core::removal::Plan::default(), + RemovalMode::Trash, + )); + }); + draw(cx); + assert!(cx.debug_bounds("toast-update").is_none()); + assert!(cx.debug_bounds(crate::views::UPDATE_CHIP_ID).is_some()); + assert!( + !read(&view, cx, |app| app.toasts.is_hovered()), + "a stack that is not drawn holds no pointer" + ); + update(&view, cx, |app, _| app.run = None); +} + +/// A window over the fixture, on the review screen with `junk` marked, and +/// a weak handle to its tree. +fn review_with_tree<'a>( + temp: &Path, + cx: &'a mut TestAppContext, +) -> ( + Entity, + &'a mut Window, + std::sync::Weak, +) { + let (view, cx) = view_over(temp, cx); + draw(cx); + let tree = update(&view, cx, |app, cx| { + let junk = child_crumbs(app, &[], "junk"); + app.toggle_mark(&junk, cx); + std::sync::Arc::downgrade(app.tree.as_ref().expect("a scanned tree")) + }); + press(cx, "c"); + assert_eq!(read(&view, cx, |app| app.screen), Screen::Review); + (view, cx, tree) +} + +/// Quitting from the review screen drops the window and its tree. Freed on +/// the main thread, a home directory's tens of millions of nodes kept the +/// app from exiting for seconds after Quit, and macOS called it not +/// responding. On quit nothing is freed: the process exits and the system +/// takes the memory back whole. +#[gpui_kit::test] +fn quitting_from_review_leaves_the_tree_to_the_system(cx: &mut TestAppContext) { + use crate::marks::work; + + cx.update(init); + let temp = fixture(); + let (view, cx, tree) = review_with_tree(temp.path(), cx); + + work::reset(); + drop(view); + // What Quit runs on every platform: the quit hooks, then every window + // and the state it held is dropped, on this thread. + cx.cx.update(gpui_kit::App::shutdown); + + assert_eq!(work::DISCARDED.get(), 0, "no thread is started to free it"); + assert_eq!(tree.strong_count(), 1, "nothing walks the nodes on quit"); +} + +/// Closing the window while the app stays frees the tree, off the main +/// thread: nothing is leaked and nothing waits on it. +#[gpui_kit::test] +fn closing_a_window_frees_its_tree_off_the_main_thread( + cx: &mut TestAppContext, +) { + use crate::marks::work; + use std::time::{Duration, Instant}; + + cx.update(init); + let temp = fixture(); + let (view, cx, tree) = review_with_tree(temp.path(), cx); + + work::reset(); + drop(view); + cx.update(|window, _| window.remove_window()); + cx.run_until_parked(); + + assert_eq!(work::DISCARDED.get(), 1, "the tree is handed off"); + let deadline = Instant::now() + Duration::from_secs(10); + while tree.strong_count() > 0 { + assert!(Instant::now() < deadline, "the tree is never freed"); + std::thread::sleep(Duration::from_millis(5)); + } +} + +#[gpui_kit::test] +fn main_integration_help_dismisses_the_export_menu(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + let junk = child_crumbs(app, &[], "junk"); + app.toggle_mark(&junk, cx); + app.open_review(cx); + }); + draw(cx); + click_on(cx, "export"); + assert!(read(&view, cx, |app| app.export_menu_open)); + press(cx, "?"); + read(&view, cx, |app| { + assert!(app.show_help); + assert!(!app.export_menu_open); + assert_eq!(app.screen, Screen::Review); + assert_eq!(app.marks.len(), 1); + }); + press(cx, "escape"); + assert!(read(&view, cx, |app| !app.show_help && app.marks.len() == 1)); + assert!(temp.path().join("junk/blob.bin").exists()); +} + +/// Offscreen document text becomes a real row before its active semantic +/// descendant changes. Copy remains complete, independent of virtualization. +#[gpui_kit::test] +fn documents_reach_the_end_and_copy_by_keyboard(cx: &mut TestAppContext) { + use crate::doc_window::{Doc, DocWindow}; + cx.update(init); + let (view, cx) = cx.add_window_view(|window, cx| { + let view = DocWindow::new(Doc::ThirdPartyNotices, cx); + window.focus(&view.focus, cx); + view + }); + draw(cx); + press(cx, "end"); + let last = view.read_with(cx, |view, _| view.position); + assert!(last > 1_000, "a long document, beyond its first viewport"); + assert!(cx.debug_bounds("document-current").is_some()); + press(cx, "home"); + assert_eq!(view.read_with(cx, |view, _| view.position), 0); + assert!(cx.debug_bounds("document-current").is_some()); + press(cx, "ctrl-c"); + assert_eq!( + cx.read_from_clipboard() + .and_then(|item| item.text()) + .as_deref(), + Some(Doc::ThirdPartyNotices.source()) + ); +} + +/// Keyboard selection reaches virtual log rows and copying retains the full +/// Unicode line. No append is a live announcement. +#[gpui_kit::test] +fn logs_read_and_copy_offscreen_lines_by_keyboard(cx: &mut TestAppContext) { + use std::fmt::Write as _; + let mut text = String::new(); + for n in 0..300 { + writeln!(text, "2026-10-31T12:00:00.000-04:00 INFO fixture: invented line {n} 日本語") + .expect("string"); + } + let (_dir, _path, view, cx) = logs_over(cx, &text); + cx.update(|window, cx| { + view.read(cx) + .search_state() + .update(cx, |search, cx| search.focus(window, cx)); + }); + draw(cx); + press(cx, "escape"); + press(cx, "end"); + assert_eq!( + view.read_with(cx, |view, _| view.selection), + Some((300, 300)) + ); + assert!(cx.debug_bounds("log-row-300").is_some()); + press(cx, "ctrl-c"); + let copied = cx + .read_from_clipboard() + .and_then(|item| item.text()) + .unwrap_or_default(); + assert!(copied.contains("invented line 299 日本語")); + assert!(!copied.contains("invented line 298")); + press(cx, "home"); + assert_eq!(view.read_with(cx, |view, _| view.selection), Some((1, 1))); + assert!(cx.debug_bounds("log-row-1").is_some()); +} + +fn invented_log(lines: usize) -> String { + use std::fmt::Write as _; + let mut text = String::new(); + for n in 0..lines { + writeln!( + text, + "2026-10-31T12:00:00.000-04:00 INFO fixture: invented line {n}" + ) + .expect("string"); + } + text +} + +/// The level and mode segments are reachable by Tab, both ways, and Space +/// works them: focusable alone is not a tab stop in GPUI. +#[gpui_kit::test] +fn aux_review_log_toggles_are_tab_stops(cx: &mut TestAppContext) { + use crate::log_view::Level; + let (_dir, _path, view, cx) = logs_over(cx, &invented_log(30)); + draw(cx); + click_on(cx, "logs-level-info"); + assert!(!view.read_with(cx, |view, _| view.view.shows(Level::Info))); + let target = cx + .update(|window, cx| window.focused(cx)) + .expect("segment focus"); + cycle_back_to_focus(cx, &target, "tab"); + cycle_back_to_focus(cx, &target, "shift-tab"); + press(cx, "space"); + assert!(view.read_with(cx, |view, _| view.view.shows(Level::Info))); +} + +/// With nothing selected, Down starts at the first line and Up at the +/// last, rather than stepping past either. +#[gpui_kit::test] +fn aux_review_first_log_step_selects_an_end(cx: &mut TestAppContext) { + let (_dir, _path, view, cx) = logs_over(cx, &invented_log(30)); + cx.update(|window, cx| { + view.read(cx) + .search_state() + .update(cx, |search, cx| search.focus(window, cx)); + }); + draw(cx); + press(cx, "escape"); + press(cx, "down"); + assert_eq!(view.read_with(cx, |view, _| view.selection), Some((1, 1))); + press(cx, "escape"); + assert_eq!(view.read_with(cx, |view, _| view.selection), None); + press(cx, "up"); + assert_eq!(view.read_with(cx, |view, _| view.selection), Some((30, 30))); +} + +/// The release channels are one radio group with one Tab stop, on the +/// channel picked. +#[gpui_kit::test] +fn aux_review_picked_channel_is_a_tab_stop(cx: &mut TestAppContext) { + use crate::settings::{Pane, SettingsWindow}; + cx.update(init); + let saved_in = tempfile::TempDir::new().expect("tempdir"); + let (view, cx) = + cx.add_window_view(|_, cx| SettingsWindow::new(Pane::Updates, cx)); + cx.update(|_, cx| { + view.update(cx, |view, _| { + view.updates_dir = Some(saved_in.path().to_path_buf()); + }); + }); + draw(cx); + click_on(cx, "update-slot-0"); + let target = cx + .update(|window, cx| window.focused(cx)) + .expect("channel focus"); + cycle_back_to_focus(cx, &target, "tab"); + cycle_back_to_focus(cx, &target, "shift-tab"); +} + +/// Tab leaves the title strip's Copy for the reader and comes back: the +/// frame takes Tab above the strip, where the reader's own keys cannot. +#[gpui_kit::test] +fn aux_review_document_tab_leaves_the_title_strip(cx: &mut TestAppContext) { + use crate::doc_window::{COPY_ID, Doc, DocWindow}; + cx.update(init); + let (view, cx) = cx.add_window_view(|window, cx| { + let view = DocWindow::new(Doc::License, cx); + window.focus(&view.focus, cx); + view + }); + draw(cx); + let reader = view.read_with(cx, |view, _| view.focus.clone()); + cycle_back_to_focus(cx, &reader, "tab"); + click_on(cx, COPY_ID); + let copy = cx + .update(|window, cx| window.focused(cx)) + .expect("copy focus"); + assert!(copy != reader, "the strip's Copy takes focus"); + cycle_back_to_focus(cx, &reader, "tab"); + cycle_back_to_focus(cx, ©, "shift-tab"); +} + +/// Three 10 GiB worktrees sharing all but 100 MiB each, marked one by one +/// in the window: the meter and the review button project each one's own +/// 100 MiB until the last clone of the group is marked, then the shared +/// data once. Synthetic clone facts, so it runs on every system. +#[gpui_kit::test] +fn marking_a_worktree_trio_one_by_one_frees_one_copy_at_the_end( + cx: &mut TestAppContext, +) { + use disktree_core::sharing::{Allocation, CloneInfo}; + use disktree_core::tree::{Draft, Metric, NodeKind, Tree, aggregate}; + const MIB: u64 = 1024 * 1024; + + cx.update(init); + let temp = tempfile::tempdir_in(std::env::current_dir().expect("cwd")) + .expect("tempdir in the checkout"); + let root_path = std::fs::canonicalize(temp.path()).expect("root"); + let mut root = Draft::directory("fixture"); + for name in ["wt-a", "wt-b", "wt-c"] { + std::fs::create_dir(root_path.join(name)).expect("mkdir"); + let mut dir = Draft::directory(name); + let mut file = Draft::entry("objects", NodeKind::File, 10_140 * MIB); + file.allocation = Some(Box::new(Allocation { + bytes: 10_140 * MIB, + identity: None, + links: 1, + followed: false, + clone: Some(CloneInfo { + device: 1, + id: 77, + references: 3, + private_bytes: Some(0), + data_bytes: 10_140 * MIB, + }), + })); + dir.children.push(file); + dir.children + .push(Draft::entry("own", NodeKind::File, 100 * MIB)); + root.children.push(dir); + } + let mut root = Tree::from(root); + aggregate(&mut root, Metric::Bytes); + let path = root_path.clone(); + let (view, cx) = cx.add_window_view(move |_, cx| { + // Allocated sizes: the helper's apparent sizes project nothing. + Disktree::with_tree(path.clone(), root, ScanOptions::default(), 3, cx) + }); + // 30 GiB of synthetic worktrees on whatever disk runs the tests: past + // 5% of a small CI disk, which is not what this test is about. + update(&view, cx, |app, _| { + app.safety_policy.replace(Some(crate::safety::Policy { + limit: None, + ..crate::safety::Policy::default() + })); + }); + draw(cx); + let mut seen = Vec::new(); + for name in ["wt-a", "wt-b", "wt-c"] { + update(&view, cx, |app, cx| { + let crumbs = app + .crumbs_for_path(&root_path.join(name)) + .expect("in the tree"); + app.toggle_mark(&crumbs, cx); + }); + draw(cx); + seen.push(read(&view, cx, |app| { + let plan = app.plan(); + let linked = app.agent_state().estimate.expect("an estimate"); + assert_eq!(linked.lower, plan.reclaimable_bytes()); + ( + plan.reclaimable_bytes(), + plan.possible_bytes(), + plan.reclaim(), + ) + })); + } + assert_eq!( + seen, + [ + (100 * MIB, 100 * MIB, 100 * MIB), + (200 * MIB, 200 * MIB, 200 * MIB), + (10_440 * MIB, 10_440 * MIB, 10_440 * MIB), + ] + ); +} + +/// Help keeps its heading/Done on screen and scrolls its reading lane at +/// minimum dimensions; neither zoom nor keys act on the marked background. +#[gpui_kit::test] +fn help_reflows_and_scrolls_at_minimum_size_and_double_scale( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + for rem in [16., 32.] { + cx.simulate_resize(gpui_kit::size(px(900.), px(600.))); + cx.update(|window, _| window.set_rem_size(px(rem))); + update(&view, cx, Disktree::open_help); + draw(cx); + let popup = cx.debug_bounds("help-overlay").expect("Help popup"); + let close = cx.debug_bounds("overlay-done").expect("Done"); + assert!( + cx.debug_bounds("help-scroll") + .expect("reading lane") + .size + .height + >= px(rem * 3.0) + ); + assert!( + popup.left() >= px(0.) && popup.right() <= px(900.), + "{popup:?}" + ); + assert!( + popup.top() >= px(0.) && popup.bottom() <= px(600.), + "{popup:?}" + ); + assert!( + close.top() >= px(0.) && close.bottom() <= px(600.), + "{close:?}" + ); + press(cx, "end"); + assert!(read(&view, cx, |app| app.help_scroll.offset().y) < px(0.)); + press(cx, "home"); + assert!( + read(&view, cx, |app| app.help_scroll.offset().y).abs() < px(1.) + ); + press(cx, "escape"); + assert!(!read(&view, cx, |app| app.show_help)); + assert!(temp.path().join("junk/blob.bin").exists()); + } +} + +/// Controls stay reachable when the toolbar wraps; tiny tiles have the +/// same larger file-list target alternative at every zoom step. +#[gpui_kit::test] +fn double_scale_wraps_controls_and_keeps_pointer_targets( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (_view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(900.), px(600.))); + for _ in 0..5 { + press(cx, "ctrl-="); + } + assert!( + (cx.update(|window, _| window.rem_size().as_f32()) - 32.).abs() < 0.01 + ); + // At 28 rem the bar keeps only the view switch; Depth is in ⋮. + assert!(cx.debug_bounds("depth-less-target").is_none()); + click_on(cx, "more-toggle"); + for selector in ["more-toggle", "more-depth-less", "more-depth-more"] { + let bounds = cx.debug_bounds(selector).expect("depth target"); + assert!( + bounds.right() <= px(900.) && bounds.bottom() <= px(600.), + "{bounds:?}" + ); + assert!( + bounds.size.width >= px(24.) && bounds.size.height >= px(24.), + "{bounds:?}" + ); + } + press(cx, "ctrl-0"); + for _ in 0..2 { + press(cx, "ctrl--"); + } + let bounds = cx.debug_bounds("depth-more-target").expect("depth target"); + assert!(bounds.size.width >= px(24.) && bounds.size.height >= px(24.)); +} + +#[gpui_kit::test] +fn settings_panes_scroll_at_minimum_size_and_double_scale( + cx: &mut TestAppContext, +) { + use crate::settings::{Pane, SettingsWindow}; + cx.update(init); + let (view, cx) = + cx.add_window_view(|_, cx| SettingsWindow::new(Pane::About, cx)); + cx.simulate_resize(gpui_kit::size(px(640.), px(480.))); + cx.update(|window, _| window.set_rem_size(px(32.))); + draw(cx); + let scroll = cx.debug_bounds("settings-scroll").expect("pane scroll"); + assert!( + scroll.size.width > px(300.), + "navigation reflows above the pane: {scroll:?}" + ); + let nav = cx.debug_bounds("settings-nav-about").expect("About tab"); + cx.simulate_click(nav.center(), gpui_kit::Modifiers::none()); + press(cx, "end"); + assert!(view.read_with(cx, |view, _| view.pane_scroll.offset().y) < px(0.)); +} + +/// Reflow is measured in glyph widths rather than a fixed 100 characters. +/// Complete copy and end navigation remain available at the document minimum. +#[gpui_kit::test] +fn documents_reflow_at_minimum_size_and_double_scale(cx: &mut TestAppContext) { + use crate::doc_window::{Doc, DocWindow}; + cx.update(init); + let (view, cx) = cx.add_window_view(|window, cx| { + let view = DocWindow::new(Doc::ThirdPartyNotices, cx); + window.focus(&view.focus, cx); + view + }); + cx.simulate_resize(gpui_kit::size(px(640.), px(480.))); + cx.update(|window, _| window.set_rem_size(px(32.))); + draw(cx); + press(cx, "end"); + assert!(view.read_with(cx, |view, _| view.position) > 1_000); + let row = cx.debug_bounds("document-current").expect("last row"); + assert!(row.left() >= px(0.) && row.right() <= px(640.), "{row:?}"); + press(cx, "ctrl--"); + assert!( + (cx.update(|window, _| window.rem_size().as_f32()) - 28.).abs() < 0.01 + ); + press(cx, "ctrl-c"); + assert_eq!(clipboard(cx), Doc::ThirdPartyNotices.source()); +} + +/// The review's list and explanation stack in a narrow text viewport. +/// Scrolling never commits a removal. +#[gpui_kit::test] +fn review_scrolls_at_minimum_size_and_double_scale(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + let junk = child_crumbs(app, &[], "junk"); + app.toggle_mark(&junk, cx); + app.open_review(cx); + }); + cx.simulate_resize(gpui_kit::size(px(900.), px(600.))); + cx.update(|window, _| window.set_rem_size(px(32.))); + draw(cx); + press(cx, "end"); + assert!(read(&view, cx, |app| app.review_scroll.offset().y) < px(0.)); + assert_eq!(read(&view, cx, |app| app.screen), Screen::Review); + assert!(temp.path().join("junk/blob.bin").exists()); + assert!(temp.path().join("keep/notes.txt").exists()); +} + +#[gpui_kit::test] +fn logs_wrap_at_minimum_size_and_double_scale(cx: &mut TestAppContext) { + let text = format!( + "2026-10-31T12:00:00.000-04:00 INFO fixture: {}\n", + "invented 日本語 ".repeat(50) + ); + let (_dir, _path, view, cx) = logs_over(cx, &text); + cx.update(|window, _| window.set_rem_size(px(32.))); + for width in [640., 880., 1120.] { + cx.simulate_resize(gpui_kit::size(px(width), px(480.))); + draw(cx); + let search = cx + .debug_bounds(crate::logs_window::SEARCH_ID) + .expect("named search"); + assert!(search.right() <= px(width), "{search:?}"); + assert!( + search.size.width >= px(400.), + "search retains room for input and match controls: {search:?}" + ); + let row = cx.debug_bounds("log-row-1").unwrap_or_else(|| { + panic!( + "wrapped line at {width}: toolbar={:?}, viewport={:?}", + cx.debug_bounds("logs-toolbar"), + cx.debug_bounds("logs-viewport") + ) + }); + assert!(row.right() <= px(width), "{row:?}"); + } + assert!(view.read_with(cx, |view, _| view.wrap)); +} + +/// A single wrapped log line can be taller than the entire window. Paging +/// must expose its lower text instead of repeatedly selecting its start. +#[gpui_kit::test] +fn page_scrolls_inside_an_oversized_log_line(cx: &mut TestAppContext) { + let text = format!( + "2026-10-31T12:00:00.000-04:00 INFO fixture: {}\n", + "invented 日本語 ".repeat(300) + ); + let (_dir, _path, view, cx) = logs_over(cx, &text); + cx.simulate_resize(gpui_kit::size(px(640.), px(480.))); + cx.update(|window, cx| { + window.set_rem_size(px(32.)); + view.read(cx) + .search_state() + .update(cx, |search, cx| search.focus(window, cx)); + }); + draw(cx); + press(cx, "escape"); + press(cx, "home"); + let before = view.read_with(cx, |view, _| view.scroll_offset()); + press(cx, "pagedown"); + let after = view.read_with(cx, |view, _| view.scroll_offset()); + assert!( + after < before, + "paging progresses inside one log line: {before:?} -> {after:?}" + ); + assert_eq!(view.read_with(cx, |view, _| view.selection), Some((1, 1))); +} + +/// Low-vision readers need a complete file entry between the fixed heading +/// and actions, including when a long root path would otherwise wrap. +#[gpui_kit::test] +fn file_list_keeps_a_complete_entry_visible_at_double_scale( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + app.file_list = true; + app.selected = Some(vec![0]); + cx.notify(); + }); + cx.simulate_resize(gpui_kit::size(px(900.), px(600.))); + cx.update(|window, _| window.set_rem_size(px(32.))); + draw(cx); + draw(cx); + let viewport = read(&view, cx, |app| app.file_scroll.bounds()); + let row = cx.debug_bounds("file-row-0").expect("first file entry"); + // 24 px type plus 32 px vertical padding at 200%, before a border. + assert!( + row.size.height >= px(56.), + "text must fit inside its row: {row:?}" + ); + assert!( + viewport.size.height >= row.size.height, + "{viewport:?}, row {row:?}" + ); + assert!( + row.bottom() <= viewport.bottom() + px(1.), + "{viewport:?}, row {row:?}" + ); + assert!(row.size.height >= px(24.)); +} + +/// Reduced motion lands on the same real layout and preserves the ordinary +/// selection/history/mark behavior, including wheel-driven descent. +#[gpui_kit::test] +fn reduced_motion_lands_navigation_history_and_zoom(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + cx.update(|_, cx| cx.set_reduce_motion(true)); + update(&view, cx, |app, cx| { + let junk = child_crumbs(app, &[], "junk"); + let keep = child_crumbs(app, &[], "keep"); + app.toggle_mark(&keep, cx); + app.selected = Some(junk.clone()); + app.descend(cx); + assert!(app.transition.is_none(), "descent lands immediately"); + assert_eq!(app.crumbs, junk); + assert_eq!(app.selected.as_ref(), Some(&junk)); + let expected: Vec<_> = app + .layout() + .expect("layout") + .iter() + .map(|tile| tile.rect) + .collect(); + let drawn: Vec<_> = app + .prepare() + .tiles + .into_iter() + .map(|tile| tile.rect) + .collect(); + assert_eq!(drawn, expected, "no transient geometry"); + app.ascend(cx); + assert!(app.transition.is_none()); + assert!(app.crumbs.is_empty()); + app.go_back(cx); + assert_eq!(app.crumbs, junk); + assert!(app.transition.is_none()); + app.go_forward(cx); + assert!(app.crumbs.is_empty()); + assert!(app.transition.is_none()); + app.go_to(junk.clone(), cx); + app.zoom_at(100., 100., 1.2, false, cx); + assert!(app.view.scale > 1.0, "user-controlled zoom still works"); + assert!(app.transition.is_none()); + app.reset_view(cx); + let deeper = child_crumbs(app, &junk, "deeper"); + let body = app.tile_body(&deeper).expect("nested directory"); + let pivot = disktree_core::treemap::Rect::new( + body.x + body.w / 2., + body.y + body.h / 2., + 0., + 0., + ); + for _ in 0..80 { + if app.crumbs == deeper { + break; + } + let screen = app.view.project(pivot); + app.zoom_at(screen.x, screen.y, 1.15, true, cx); + } + assert_eq!(app.crumbs, deeper, "wheel zoom reaches its directory"); + assert!(app.transition.is_none()); + assert_eq!(app.marks.len(), 1); + }); + draw(cx); + assert!(temp.path().join("keep/notes.txt").exists()); +} + +/// A live policy change cancels an in-flight transition. Turning the policy +/// off restores ordinary navigation motion without changing the destination. +#[gpui_kit::test] +fn reduced_motion_cancels_active_transition_and_can_be_disabled( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + cx.update(|_, cx| cx.set_reduce_motion(false)); + update(&view, cx, |app, cx| { + let junk = child_crumbs(app, &[], "junk"); + app.selected = Some(junk); + app.descend(cx); + assert!(app.transition.is_some(), "normal motion remains available"); + }); + let destination = read(&view, cx, Disktree::current_path); + cx.update(|_, cx| cx.set_reduce_motion(true)); + draw(cx); + assert!(read(&view, cx, |app| app.transition.is_none())); + assert_eq!(read(&view, cx, Disktree::current_path), destination); + cx.update(|_, cx| cx.set_reduce_motion(false)); + update(&view, cx, |app, cx| { + app.ascend(cx); + assert!(app.transition.is_some(), "normal ascent animates again"); + }); + cx.update(|_, cx| cx.set_reduce_motion(true)); + draw(cx); + assert!(read(&view, cx, |app| app.transition.is_none())); + assert!(read(&view, cx, |app| app.crumbs.is_empty())); +} + +#[gpui_kit::test] +fn the_view_switch_and_the_view_menu_show_the_file_list( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1440.), px(900.))); + draw(cx); + // The switch is in the title bar, not a row of its own over the mosaic. + let strip = cx.debug_bounds("title-strip").expect("strip"); + let list = cx.debug_bounds("view-list").expect("switch"); + assert!(strip.contains(&list.center()), "{list:?} in {strip:?}"); + + click_on(cx, "view-list"); + assert!(read(&view, cx, |app| app.file_list)); + assert!(cx.debug_bounds("file-list").is_some()); + assert!( + cx.update(|window, cx| view.read(cx).file_focus.is_focused(window)), + "the list takes the keyboard, so a screen reader lands in it" + ); + + cx.dispatch_action(crate::app_menu::ShowTreemap); + draw(cx); + assert!(!read(&view, cx, |app| app.file_list)); + assert!(cx.update(|window, cx| view.read(cx).focus.is_focused(window))); + cx.dispatch_action(crate::app_menu::ShowFileList); + draw(cx); + assert!(read(&view, cx, |app| app.file_list)); + click_on(cx, "view-treemap"); + assert!(!read(&view, cx, |app| app.file_list)); +} + +#[gpui_kit::test] +fn the_bar_folds_into_more_as_the_window_narrows(cx: &mut TestAppContext) { + use crate::toolbar::BarFit; + + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + // Window size and interface zoom presses, then the tier it lands in. + let cases = [ + (1440., 900., 0, BarFit::Full), + (1100., 700., 0, BarFit::Folded), + (900., 600., 0, BarFit::Folded), + (900., 600., 2, BarFit::Narrow), + (900., 600., 4, BarFit::Tight), + ]; + let mut labelled_width = None; + for (width, height, zoom, fit) in cases { + press(cx, "ctrl-0"); + cx.simulate_resize(gpui_kit::size(px(width), px(height))); + for _ in 0..zoom { + press(cx, "ctrl-="); + } + draw(cx); + assert_eq!(read(&view, cx, |app| app.bar_fit), fit, "{width} {zoom}"); + let full = fit == BarFit::Full; + assert_eq!( + cx.debug_bounds("power-efficiency").is_some(), + full, + "{fit:?}" + ); + assert_eq!(cx.debug_bounds("more-toggle").is_none(), full, "{fit:?}"); + assert_eq!( + cx.debug_bounds("history-back").is_some(), + fit.shows_history_and_depth(), + "{fit:?}" + ); + assert_eq!( + cx.debug_bounds("depth-less-target").is_some(), + fit.shows_history_and_depth(), + "{fit:?}" + ); + assert_eq!(cx.debug_bounds("measure-mode").is_some(), fit.shows_mode()); + + // Whatever is left fits in one bar, beside the brand. + let strip = cx.debug_bounds("title-strip").expect("strip"); + let brand = cx.debug_bounds("strip-brand").expect("brand"); + let switch = cx.debug_bounds("view-treemap").expect("switch"); + let last = cx + .debug_bounds(if full { + "power-efficiency" + } else { + "more-toggle" + }) + .expect("last control"); + assert!(switch.left() >= brand.right(), "{fit:?}: {switch:?}"); + assert!(last.right() <= px(width), "{fit:?}: {last:?}"); + assert!(strip.contains(&last.center()), "{fit:?}: one row"); + assert!(switch.size.height >= px(24.), "{fit:?}: {switch:?}"); + + // The switch keeps its words until 64 rem. + if zoom == 0 && width >= 1100. { + labelled_width = Some(switch.size.width); + } else if zoom == 0 { + let labelled = labelled_width.expect("a labelled switch"); + assert!(switch.size.width < labelled, "glyph alone at {width}"); + } + } +} + +#[gpui_kit::test] +fn more_holds_the_folded_controls_and_takes_the_keys(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1100.), px(700.))); + update(&view, cx, |app, _| app.cpu_threads = 18); + let hidden = read(&view, cx, |app| app.options.include_hidden); + let epoch = read(&view, cx, |app| app.scan_epoch); + + click_on(cx, "more-toggle"); + assert_eq!(read(&view, cx, |app| app.more_menu), Some(0)); + assert!(cx.debug_bounds("more-menu").is_some()); + // Hidden files rescans, as its checkbox does. + press(cx, "enter"); + read(&view, cx, |app| { + assert_eq!(app.options.include_hidden, !hidden); + assert_eq!(app.scan_epoch, epoch + 1); + assert!(app.more_menu.is_none()); + }); + update(&view, cx, |app, _| { + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + }); + + // Scan workers opens the power menu in ⋮'s place; ⋮ closes it again. + click_on(cx, "more-toggle"); + press(cx, "end"); + press(cx, "enter"); + assert!(read(&view, cx, |app| app.power_menu.is_some())); + assert!(cx.debug_bounds("power-menu").is_some()); + // A real press arrives after the pointer is on ⋮. + let more = cx.debug_bounds("more-toggle").expect("more"); + cx.simulate_mouse_move(more.center(), None, gpui_kit::Modifiers::none()); + click_on(cx, "more-toggle"); + read(&view, cx, |app| { + assert!(app.power_menu.is_none()); + assert!(app.more_menu.is_none()); + }); + + // Escape closes without acting; a screen key closes and still acts. + click_on(cx, "more-toggle"); + press(cx, "escape"); + assert!(read(&view, cx, |app| app.more_menu.is_none())); + click_on(cx, "more-toggle"); + press(cx, "?"); + assert!(read(&view, cx, |app| app.more_menu.is_none() && app.show_help)); +} + +#[gpui_kit::test] +fn more_steps_depth_in_place_when_the_stepper_folds(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(900.), px(600.))); + press(cx, "ctrl-="); + press(cx, "ctrl-="); + let depth = read(&view, cx, |app| app.layout_options.max_depth); + click_on(cx, "more-toggle"); + // Nowhere to go back or forward yet, so ⋮ opens on Depth, past the + // disabled history rows; the up arrow does not land on them either. + assert_eq!(read(&view, cx, |app| app.more_menu), Some(2)); + press(cx, "up"); + assert_eq!(read(&view, cx, |app| app.more_menu), Some(2)); + // The row stays open while the arrows step it. + press(cx, "left"); + assert_eq!( + read(&view, cx, |app| app.layout_options.max_depth), + depth - 1 + ); + assert_eq!(read(&view, cx, |app| app.more_menu), Some(2)); + click_on(cx, "more-depth-more"); + assert_eq!(read(&view, cx, |app| app.layout_options.max_depth), depth); +} + +/// The names the mosaic lays out, top to bottom of the tree. +fn laid_out(view: &Entity, cx: &mut Window) -> Vec { + update(view, cx, |app, _| { + let tiles = app.layout().map(<[Tile]>::to_vec).unwrap_or_default(); + tiles + .iter() + .filter_map(|tile| app.node_at(tile.crumbs())) + .map(|node| node.name().to_string()) + .collect() + }) +} + +#[gpui_kit::test] +fn a_legend_chip_shows_only_then_hides_its_kind(cx: &mut TestAppContext) { + use crate::legend::{Chip, ChipId}; + + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1440.), px(900.))); draw(cx); - let (applied, count, open) = read(&view, cx, |app| { - ( - app.filter_applied, - app.matches.as_deref().map(|matches| matches.count), - app.find_open, - ) + assert!( + cx.debug_bounds("legend-clear").is_none(), + "nothing filtered" + ); + + // Reclaimable, once: only `.cache`, the fixture's one regenerable tree. + click_on(cx, "legend-reclaimable"); + cx.run_until_parked(); + let chip = read(&view, cx, |app| app.legend.get(ChipId::Reclaimable)); + assert_eq!(chip, Chip::Only); + let drawn = laid_out(&view, cx); + assert!(drawn.contains(&".cache".to_string()), "{drawn:?}"); + assert!( + !drawn.iter().any(|name| name == "junk" || name == "keep"), + "{drawn:?}" + ); + // The totals line says the share on screen, and Show all appears. + let shown = read(&view, cx, |app| { + app.legend_matches.as_deref().map(|matches| matches.bytes) }); - assert!(applied, "Enter was not lost to a search in flight"); - assert_eq!(count, Some(2)); - assert!(!open); + assert_eq!(shown, Some(300_000)); + assert!(cx.debug_bounds("legend-clear").is_some()); + + // Again: hidden, so everything but `.cache`. + click_on(cx, "legend-reclaimable"); + cx.run_until_parked(); + let drawn = laid_out(&view, cx); + assert!(!drawn.contains(&".cache".to_string()), "{drawn:?}"); + assert!(drawn.contains(&"junk".to_string()), "{drawn:?}"); + + // Show all gives everything back, and keys reach the mosaic again. + click_on(cx, "legend-clear"); + cx.run_until_parked(); + assert!(!read(&view, cx, |app| app.legend.is_active())); + assert!(cx.update(|window, cx| view.read(cx).focus.is_focused(window))); + let drawn = laid_out(&view, cx); + assert!( + drawn.contains(&".cache".to_string()) + && drawn.contains(&"junk".to_string()) + ); + + // A kind set to only, cleared by Escape. + update(&view, cx, |app, cx| app.cycle_legend(ChipId::Kind(7), cx)); + cx.run_until_parked(); + let drawn = laid_out(&view, cx); + assert!(drawn.contains(&".cache".to_string()), "Cache: {drawn:?}"); + assert!(!drawn.contains(&"keep".to_string()), "{drawn:?}"); + press(cx, "escape"); + cx.run_until_parked(); + assert!(!read(&view, cx, |app| app.legend.is_active())); +} + +#[gpui_kit::test] +fn the_legend_filter_follows_into_folders_and_into_a_search( + cx: &mut TestAppContext, +) { + use crate::legend::ChipId; + + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1440.), px(900.))); + draw(cx); + // Hide Cache: `.cache` goes, and a search for blobs finds only junk's. + update(&view, cx, |app, cx| { + app.cycle_legend(ChipId::Kind(7), cx); + app.cycle_legend(ChipId::Kind(7), cx); + }); + cx.run_until_parked(); + press(cx, "/"); + cx.simulate_input("blob"); + cx.run_until_parked(); + let count = read(&view, cx, |app| app.matches.as_deref().map(|m| m.count)); + assert_eq!(count, Some(1), "the cached blob is hidden"); + press(cx, "escape"); + cx.run_until_parked(); + + // Descending keeps the filter: no search runs, the root's answer holds. + let junk = read(&view, cx, |app| { + app.crumbs_for_path(&temp.path().join("junk")) + .expect("junk") + }); + update(&view, cx, |app, cx| app.go_to(junk, cx)); + draw(cx); + assert!(read(&view, cx, |app| app.legend.is_active())); + let drawn = laid_out(&view, cx); + assert!(drawn.contains(&"blob.bin".to_string()), "{drawn:?}"); +} + +#[gpui_kit::test] +fn marking_a_partly_shown_folder_says_it_takes_all_of_it( + cx: &mut TestAppContext, +) { + use crate::legend::ChipId; + + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1440.), px(900.))); + draw(cx); + update(&view, cx, |app, cx| { + app.cycle_legend(ChipId::Reclaimable, cx); + app.cycle_legend(ChipId::Reclaimable, cx); + }); + cx.run_until_parked(); + // The scanned root holds `.cache`, which the filter hides. + update(&view, cx, |app, _| app.selected = Some(Vec::new())); + draw(cx); + assert!(cx.debug_bounds("selection-partly-shown").is_some()); + // A folder that passes whole needs no such note. + let junk = read(&view, cx, |app| { + app.crumbs_for_path(&temp.path().join("junk")) + .expect("junk") + }); + update(&view, cx, |app, _| app.selected = Some(junk)); + draw(cx); + assert!(cx.debug_bounds("selection-partly-shown").is_none()); +} + +/// Every chip is a filter, so none may be clipped away or pushed onto a +/// second row: the legend is one row, at any width and text size, in both +/// colour modes, and what it has no room for is in its "+N" menu. +#[gpui_kit::test] +fn every_legend_chip_is_on_the_row_or_in_its_menu(cx: &mut TestAppContext) { + use crate::legend::ChipId; + use disktree_core::classify::Category; + + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + for age in [false, true] { + update(&view, cx, |app, cx| { + app.color_mode = if age { + crate::state::ColorMode::Age + } else { + crate::state::ColorMode::Kind + }; + cx.notify(); + }); + let chips: Vec = if age { + (0..crate::palette::AGE_BUCKETS.len()) + .map(ChipId::Age) + .collect() + } else { + (0..Category::LEGEND.len()).map(ChipId::Kind).collect() + }; + for width in [900., 1100., 1440.] { + for rem in [16., 24., 32.] { + cx.simulate_resize(gpui_kit::size(px(width), px(900.))); + cx.update(|window, _| window.set_rem_size(px(rem))); + draw(cx); + draw(cx); + let legend = cx.debug_bounds("legend").expect("legend"); + let mut missing = Vec::new(); + for id in chips.iter().copied().chain([ChipId::Reclaimable]) { + let at = format!("{id:?} at {width} rem {rem}"); + let key = Box::leak(id.key().into_boxed_str()); + let Some(chip) = cx.debug_bounds(key) else { + missing.push(id); + continue; + }; + assert!( + chip.right() <= legend.right() + px(0.5) + && chip.left() >= px(0.) + && chip.size.width > px(0.), + "{at}: {chip:?} inside the legend {legend:?}" + ); + // One row: no chip starts below the first line. + assert!( + chip.top() - legend.top() < chip.size.height, + "{at}: {chip:?} on the legend's one row {legend:?}" + ); + } + if missing.is_empty() { + assert!(cx.debug_bounds("legend-more").is_none()); + continue; + } + let more = cx.debug_bounds("legend-more").expect("+N"); + assert!(more.right() <= legend.right() + px(0.5), "{more:?}"); + click_on(cx, "legend-more"); + draw(cx); + for id in missing { + let key = format!( + "legend-menu-{}", + id.key().trim_start_matches("legend-") + ); + let at = format!("{key} at {width} rem {rem}"); + let row = cx + .debug_bounds(Box::leak(key.into_boxed_str())) + .expect(&at); + assert!( + row.right() <= px(width) + px(0.5) + && row.left() >= px(0.), + "{at}: {row:?}" + ); + } + click_on(cx, "legend-more"); + draw(cx); + assert!(cx.debug_bounds("legend-menu").is_none()); + } + } + } +} + +/// The legend belongs to the scan, not to the folder on screen: drilling +/// into a folder with none of a kind keeps that kind's chip set, on the +/// row and at its scan-wide size, and coming back up finds it unchanged. +#[gpui_kit::test] +fn a_set_chip_survives_drilling_into_a_folder_without_its_kind( + cx: &mut TestAppContext, +) { + use crate::legend::{Chip, ChipId}; + use disktree_core::classify::Category; + + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1440.), px(900.))); + draw(cx); + draw(cx); + let cache = ChipId::Kind( + Category::LEGEND + .iter() + .position(|kind| *kind == Category::Cache) + .unwrap(), + ); + let key = Box::leak(cache.key().into_boxed_str()); + let shares = read(&view, cx, |app| app.legend_shares.clone()); + for state in [Chip::Only, Chip::Hidden] { + update(&view, cx, |app, cx| { + app.clear_legend(None, cx); + while app.legend.get(cache) != state { + app.cycle_legend(cache, cx); + } + }); + // `junk` holds no cache at all. + let junk = read(&view, cx, |app| { + app.crumbs_for_path(&temp.path().join("junk")) + .expect("junk") + }); + update(&view, cx, |app, cx| app.go_to(junk, cx)); + draw(cx); + draw(cx); + assert_eq!(read(&view, cx, |app| app.legend.get(cache)), state); + assert!(cx.debug_bounds(key).is_some(), "{state:?}: on the row"); + assert_eq!( + read(&view, cx, |app| app.legend_shares.clone()), + shares, + "sizes are the scan's, not the folder's" + ); + update(&view, cx, Disktree::ascend); + draw(cx); + assert_eq!(read(&view, cx, |app| app.legend.get(cache)), state); + assert!(cx.debug_bounds(key).is_some()); + } +} + +/// Each chip says how much of the scan it keeps. Empty and tiny kinds wait +/// in "+N"; a chip set from there moves to the row, where its state shows. +#[gpui_kit::test] +fn legend_chips_carry_sizes_and_empty_kinds_wait_in_the_menu( + cx: &mut TestAppContext, +) { + use crate::legend::{Chip, ChipId}; + use disktree_core::classify::Category; + + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1440.), px(900.))); + draw(cx); + draw(cx); + let shares = read(&view, cx, |app| app.legend_shares.clone()) + .expect("shares worked out"); + let cache = Category::LEGEND + .iter() + .position(|kind| *kind == Category::Cache) + .unwrap(); + // `.cache/blob.bin` holds 300,000 bytes of the fixture's ~601,000. + assert_eq!(shares.kind(Category::Cache), 300_000); + let key = Box::leak(ChipId::Kind(cache).key().into_boxed_str()); + assert!(cx.debug_bounds(key).is_some(), "Cache has data: on the row"); + // The fixture holds no code: Code waits in the menu. + let code = Category::LEGEND + .iter() + .position(|kind| *kind == Category::Code) + .unwrap(); + assert_eq!(shares.kind(Category::Code), 0); + let code_key = Box::leak(ChipId::Kind(code).key().into_boxed_str()); + assert!(cx.debug_bounds(code_key).is_none(), "empty: not on the row"); + assert!(cx.debug_bounds("legend-more").is_some()); + + click_on(cx, "legend-more"); + draw(cx); + let menu_key = + Box::leak(format!("legend-menu-kind-{code}").into_boxed_str()); + assert!(cx.debug_bounds(menu_key).is_some(), "Code is in the menu"); + click_on(cx, menu_key); + draw(cx); + assert_eq!( + read(&view, cx, |app| app.legend.get(ChipId::Kind(code))), + Chip::Only + ); + assert!(!read(&view, cx, |app| app.legend_menu_open), "menu closed"); + assert!(cx.debug_bounds(code_key).is_some(), "set: on the row"); +} + +/// A filter that keeps nothing in the folder on screen says so, says +/// whether anything elsewhere passes, and offers Show all, in the mosaic +/// and in List view alike. +#[gpui_kit::test] +fn a_legend_filter_that_keeps_nothing_says_so(cx: &mut TestAppContext) { + use crate::legend::ChipId; + + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1440.), px(900.))); + draw(cx); + assert!(cx.debug_bounds("legend-empty").is_none()); + + // Reclaimable toolchains: the fixture's only reclaimable tree is a + // cache, so nothing anywhere passes. + update(&view, cx, |app, cx| { + app.cycle_legend(ChipId::Reclaimable, cx); + app.cycle_legend(ChipId::Kind(2), cx); + }); + cx.run_until_parked(); + draw(cx); + assert_eq!(read(&view, cx, Disktree::legend_empty_here), Some((0, 0))); + assert!(cx.debug_bounds("legend-empty").is_some(), "in the mosaic"); + update(&view, cx, |app, cx| { + app.file_list = true; + cx.notify(); + }); + draw(cx); + assert!(cx.debug_bounds("legend-empty").is_some(), "in List view"); + assert!( + cx.debug_bounds("legend-empty-status").is_some(), + "announced" + ); + // Compact List view draws no legend, so its header says what filters. + let note = read(&view, cx, Disktree::list_filter_note); + assert!(note.contains("suggested Toolchains"), "{note}"); + click_on(cx, "legend-empty-clear"); + cx.run_until_parked(); + draw(cx); + assert!(!read(&view, cx, |app| app.legend.is_active())); + assert!(cx.debug_bounds("legend-empty").is_none()); + + // Reclaimable alone, from inside `keep`: nothing here, but `.cache` + // passes elsewhere. + let keep = read(&view, cx, |app| { + app.crumbs_for_path(&temp.path().join("keep")) + .expect("keep") + }); + update(&view, cx, |app, cx| { + app.file_list = false; + app.crumbs = keep; + app.selected = None; + app.cycle_legend(ChipId::Reclaimable, cx); + }); + cx.run_until_parked(); + draw(cx); + assert_eq!( + read(&view, cx, Disktree::legend_empty_here), + Some((300_000, 1)) + ); + assert!(cx.debug_bounds("legend-empty").is_some()); +} + +/// The age chips judge by the scan's clock, as the age colours do, and +/// a partly shown folder's row in List view says what share passed. +#[gpui_kit::test] +fn the_age_filter_keeps_the_scan_clock_and_lists_partial_shares( + cx: &mut TestAppContext, +) { + use crate::legend::ChipId; + + cx.update(init); + let temp = fixture(); + // Two years old: in the Older bucket, unlike everything else. + let old = std::time::SystemTime::now() + - std::time::Duration::from_hours(800 * 24); + std::fs::File::options() + .write(true) + .open(temp.path().join("junk/deeper/more.bin")) + .and_then(|file| file.set_modified(old)) + .expect("age the file"); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + app.file_list = true; + app.scanned_at -= 3 * 86_400; + app.cycle_legend(ChipId::Age(4), cx); + }); + cx.run_until_parked(); + let (now, scanned) = read(&view, cx, |app| { + (app.legend_rule().map(|rule| rule.now), app.scanned_at) + }); + assert_eq!(now, Some(scanned), "ages measured from the scan"); + + let junk = read(&view, cx, |app| { + app.crumbs_for_path(&temp.path().join("junk")) + .expect("junk") + }); + let size = read(&view, cx, |app| { + app.entry_size(&junk, app.node_at(&junk).expect("junk")) + }); + assert!(size.contains(" of "), "partly shown: {size}"); + let keep = read(&view, cx, |app| { + app.crumbs_for_path(&temp.path().join("keep")) + .expect("keep") + }); + let listed = read(&view, cx, Disktree::file_entries); + assert!( + !listed.contains(keep.last().expect("a child")), + "{listed:?}" + ); +} + +/// Switching size and file count reorders every folder, so the legend's +/// result, keyed by position, is dropped at once and worked out again. +#[gpui_kit::test] +fn switching_the_metric_recomputes_the_legend(cx: &mut TestAppContext) { + use crate::legend::ChipId; + + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1440.), px(900.))); + draw(cx); + update(&view, cx, |app, cx| { + app.cycle_legend(ChipId::Reclaimable, cx); + }); + cx.run_until_parked(); + assert!(read(&view, cx, |app| app.legend_matches.is_some())); + update(&view, cx, |app, cx| { + app.toggle_metric(cx); + assert!(app.legend_matches.is_none(), "old positions dropped"); + }); + cx.run_until_parked(); + let drawn = laid_out(&view, cx); + assert!(drawn.contains(&".cache".to_string()), "{drawn:?}"); + assert!(!drawn.contains(&"junk".to_string()), "{drawn:?}"); +} + +#[gpui_kit::test] +fn the_marked_total_is_pinned_above_the_disk_with_the_review( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1440.), px(900.))); + draw(cx); + assert!(cx.debug_bounds("marked-total").is_none(), "nothing marked"); + + for name in ["junk", ".cache"] { + let crumbs = read(&view, cx, |app| { + app.crumbs_for_path(&temp.path().join(name)) + .expect("present") + }); + update(&view, cx, |app, cx| app.toggle_mark(&crumbs, cx)); + } + draw(cx); + let total = cx.debug_bounds("marked-total").expect("marked total drawn"); + let disk = cx.debug_bounds("disk-section").expect("disk drawn"); + let scroll = cx.debug_bounds("side-panel-scroll").expect("lists drawn"); + assert!(total.bottom() <= disk.top() + px(0.5), "{total:?} {disk:?}"); + assert!( + scroll.bottom() <= total.top() + px(0.5), + "pinned below lists" + ); + // The list leads the scroll, so on a short window it is suggestions + // that scroll out of sight, not what is marked. + let row = cx.debug_bounds("marked-row-0").expect("marked row drawn"); + let worth = cx.debug_bounds("worth-section").expect("worth drawn"); + assert!(row.bottom() <= worth.top(), "{row:?} {worth:?}"); + assert!(row.bottom() <= scroll.bottom(), "{row:?} {scroll:?}"); + // Without clones what is marked is what is freed, said once. + assert!(cx.debug_bounds("marked-frees").is_some()); + assert!(cx.debug_bounds("marked-split").is_none()); + let review = cx.debug_bounds("review").expect("review button"); + assert!( + total.contains(&review.center()), + "the review is in the block" + ); + click_on(cx, "review"); + assert_eq!(read(&view, cx, |app| app.screen), Screen::Review); +} + +/// Preparation yields to the window; confirmation leaves fresh recursive +/// inspection to the removal worker, which must still refuse new caches. +#[gpui_kit::test] +fn raw_inspection_prepares_off_thread_and_execution_rechecks( + cx: &mut TestAppContext, +) { + use disktree_link::{ConfirmedRemoval, RemovalChoice, Request, Response}; + + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + #[cfg(not(windows))] + let socket = temp.path().join("inspection.sock"); + #[cfg(windows)] + let socket = PathBuf::from(format!( + r"\\.\pipe\pwrdisk-inspection-{}", + temp.path() + .file_name() + .expect("temp name") + .to_string_lossy() + )); + let listener = disktree_link::Listener::bind_at(&socket).expect("link"); + update(&view, cx, |app, cx| { + app.attach_agent(listener, cx); + let junk = child_crumbs(app, &[], "junk"); + app.toggle_mark(&junk, cx); + }); + let mut ask = |cx: &mut Window, request: Request| { + update(&view, cx, |app, cx| app.answer_agent(&request, cx)) + }; + let request = Request::PrepareRemoval { + mode: RemovalChoice::Permanent, + decisions: None, + files: None, + }; + assert!( + matches!(ask(cx, request.clone()), Response::Error { message } + if message.contains("preparing")) + ); + // Another request and a frame can proceed while inspection is pending. + assert!(matches!(ask(cx, Request::State), Response::State(_))); + draw(cx); + let preview = await_removal_preview(&mut ask, cx, &request); + assert_eq!(preview.paths, [temp.path().join("junk")]); + + // This appears after the preview. Confirmation must not walk it on the + // UI thread, but the fresh worker check must protect it before writes. + let tag = temp.path().join("junk/deeper/CACHEDIR.TAG"); + std::fs::write(&tag, "cache").expect("fixture cache appeared"); + let response = ask( + cx, + Request::Remove(ConfirmedRemoval { + preview_id: preview.preview_id, + mode: preview.mode, + paths: preview.paths, + confirmation: preview.mode.confirmation().into(), + rescan: false, + }), + ); + assert!(matches!(response, Response::State(state) + if state.screen == "running")); + let epoch = read(&view, cx, |app| app.run_epoch); + let mut done = false; + for _ in 0..400 { + std::thread::sleep(std::time::Duration::from_millis(5)); + done = update(&view, cx, |app, cx| { + app.poll_removal_once(epoch, cx); + app.screen == Screen::Done + }); + if done { + break; + } + } + assert!(done); + read(&view, cx, |app| assert_eq!(app.run_list.totals().failed, 1)); + assert!(tag.exists()); + assert!(temp.path().join("junk/blob.bin").exists()); + assert!(temp.path().join("keep/notes.txt").exists()); +} + +/// Exporting a cache selection cannot substitute raw deletion for its owner. +#[gpui_kit::test] +fn cache_exports_keep_marks_and_refuse_raw_scripts(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let selected = temp.path().join(".cache").join("blob.bin"); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + let cache = child_crumbs(app, &[], ".cache"); + let file = child_crumbs(app, &cache, "blob.bin"); + app.toggle_mark(&file, cx); + app.open_review(cx); + let (list, count) = app.export_text(false).expect("marked list"); + assert_eq!(count, 1); + assert_eq!(list, format!("{}\n", selected.display())); + for mode in [ + RemovalMode::OwnerCleanup, + RemovalMode::Permanent, + RemovalMode::Trash, + ] { + app.removal_mode = mode; + assert!( + app.export_text(true) + .expect_err("no raw script") + .contains("owner cleanup") + ); + cx.write_to_clipboard(gpui_kit::ClipboardItem::new_string( + "keep".into(), + )); + app.copy_delete_script(cx); + app.save_delete_script(cx); + assert!( + app.notice() + .as_ref() + .expect("refusal") + .0 + .contains("owner cleanup") + ); + } + }); + assert_eq!(clipboard(cx), "keep", "refusal leaves clipboard alone"); + assert!(selected.exists()); + assert!(temp.path().join("junk/blob.bin").exists()); +} + +/// Cache classification steers review, but grants no generic deletion. +#[gpui_kit::test] +fn cache_review_requires_owner_preview_and_never_falls_back_to_raw_removal( + cx: &mut TestAppContext, +) { + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + let cache = child_crumbs(app, &[], ".cache"); + app.toggle_mark(&cache, cx); + app.open_review(cx); + assert_eq!(app.removal_mode, RemovalMode::OwnerCleanup); + // Confirm cannot execute a missing owner preview, even if reached + // directly rather than through the disabled/preview UI. + app.confirm_delete(cx); + assert!(app.run.is_none()); + assert_eq!(app.screen, Screen::Review); + assert!(app.cleanup_description().contains("Check owners")); + // Neither explicit raw mode can silently replace owner cleanup. + for mode in [RemovalMode::Permanent, RemovalMode::Trash] { + app.removal_mode = mode; + app.begin_removal(cx); + assert!(app.run.is_none()); + assert!( + app.notice() + .as_ref() + .expect("refusal") + .0 + .contains("Cache cleanup") + ); + } + app.removal_mode = RemovalMode::OwnerCleanup; + app.confirm_open = true; + app.cancel_delete(cx); + assert!(!app.confirm_open); + assert!(app.run.is_none()); + }); + draw(cx); + assert!(temp.path().join(".cache/blob.bin").exists()); + assert!(temp.path().join("junk/blob.bin").exists()); } +/// An empty Marked or Worth a look is its header alone, at any height: the +/// hint and the "none" sit where a full section shows its count or total. #[gpui_kit::test] -fn a_crumb_lists_its_siblings_and_jumps_sideways(cx: &mut TestAppContext) { - use gpui_kit::{Modifiers, MouseButton}; - - cx.update(gpui_omarchy::init); +fn empty_panel_lists_are_one_line(cx: &mut TestAppContext) { + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); - cx.simulate_resize(gpui_kit::size(px(1400.), px(900.))); + cx.simulate_resize(gpui_kit::size(px(1440.), px(900.))); draw(cx); - // Into junk, so the trail ends in a crumb that has siblings. - let junk = read(&view, cx, |app| { - app.tree() - .and_then(|tree| { - tree.children.iter().position(|c| &*c.name == "junk") - }) - .expect("junk") + draw(cx); + // The header, and the gap before the section's hidden status line. + let head = + px((crate::ui::size::SECTION_HEAD.0 + crate::ui::space::XS.0) * 16.) + + px(0.5); + let marked = cx.debug_bounds("marked-section").expect("marked"); + let worth = cx.debug_bounds("worth-section").expect("worth a look"); + assert!(marked.size.height <= head, "{marked:?}"); + assert!(worth.size.height <= head, "{worth:?}"); + + let crumbs = read(&view, cx, |app| { + app.crumbs_for_path(&temp.path().join("junk")) + .expect("present") }); - update(&view, cx, |app, cx| app.go_to(vec![junk], cx)); + update(&view, cx, |app, cx| app.toggle_mark(&crumbs, cx)); draw(cx); + let marked = cx.debug_bounds("marked-section").expect("marked"); + assert!(marked.size.height > head, "a row: {marked:?}"); + assert!(cx.debug_bounds("marked-row-0").is_some()); +} - let last = read(&view, cx, |app| app.breadcrumbs().len() - 1); - let chevron = cx - .debug_bounds(Box::leak(format!("crumb-{last}-menu").into_boxed_str())) - .expect("the current crumb has a menu"); - cx.simulate_click(chevron.center(), Modifiers::none()); +/// Under 48 rem tall the selection's four figures are one line that opens +/// the grid, and an idle agent line gives way, so with an assessment +/// selected at 1200×600 Marked still starts in sight; suggestions may +/// scroll, the cart may not. The assessment itself never folds. A tall +/// window draws the grid as before. +#[gpui_kit::test] +fn a_short_panel_folds_the_selection_figures(cx: &mut TestAppContext) { + cx.update(init); + let temp = fixture(); + let output = temp.path().join("target/debug/deps"); + std::fs::create_dir_all(&output).unwrap(); + std::fs::write(output.join("libapp.rlib"), vec![b'x'; 200_000]).unwrap(); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + let (crumbs, _) = app + .tree() + .unwrap() + .descend(Path::new("target/debug/deps")) + .unwrap(); + app.selected = Some(crumbs); + app.hovered = None; + app.pointer_active = false; + cx.notify(); + }); + cx.simulate_resize(gpui_kit::size(px(1200.), px(600.))); draw(cx); + draw(cx); + assert!(cx.debug_bounds("selection-summary").is_some(), "one line"); assert!( - cx.debug_bounds("sibling-menu").is_some(), - "the menu is drawn" + cx.debug_bounds("selection-figures").is_none(), + "grid folded" ); - let (names, highlighted) = read(&view, cx, |app| { - let menu = app.crumb_menu.clone().expect("open"); - let (rows, _) = app.siblings(&menu.parent); - let names: Vec = - rows.iter().map(|row| row.name.clone()).collect(); - let highlighted = names_at(&names, menu.highlighted); - (names, highlighted) - }); assert!( - names.contains(&".cache".to_string()) - && names.contains(&"keep".to_string()) + cx.debug_bounds("artifact-suggested").is_some(), + "never folds" + ); + assert!(cx.debug_bounds("agent-line").is_none(), "idle line gone"); + let scroll = cx.debug_bounds("side-panel-scroll").unwrap(); + let marked = cx.debug_bounds("marked-section").unwrap(); + assert!( + marked.bottom() <= scroll.bottom(), + "Marked in sight: {marked:?} {scroll:?}" ); - assert_eq!(highlighted, "junk", "it opens on where you are"); - - // Walk to .cache by name, not by rank: it and junk are close in size. - let target = names - .iter() - .position(|name| name == ".cache") - .expect("listed"); - let here = names - .iter() - .position(|name| name == "junk") - .expect("listed"); - let key = if target < here { "up" } else { "down" }; - for _ in 0..target.abs_diff(here) { - press(cx, key); - } - press(cx, "enter"); - let (crumbs, open) = read(&view, cx, |app| { - (app.crumbs.clone(), app.crumb_menu.is_some()) - }); - let cache = read(&view, cx, |app| { - app.tree() - .and_then(|tree| { - tree.children.iter().position(|c| &*c.name == ".cache") - }) - .expect(".cache") - }); - assert_eq!(crumbs, vec![cache], "went sideways into .cache"); - assert!(!open); - // A click outside closes it. - let chevron = cx - .debug_bounds(Box::leak(format!("crumb-{last}-menu").into_boxed_str())) - .expect("menu chevron"); - cx.simulate_click(chevron.center(), Modifiers::none()); + // The chevron opens the grid, and it stays open for the session. + click_on(cx, "selection-summary"); draw(cx); - assert!(read(&view, cx, |app| app.crumb_menu.is_some())); - cx.simulate_mouse_down( - gpui_kit::point(px(700.), px(600.)), - MouseButton::Left, - Modifiers::none(), - ); - cx.simulate_mouse_up( - gpui_kit::point(px(700.), px(600.)), - MouseButton::Left, - Modifiers::none(), - ); + assert!(read(&view, cx, |app| app.selection_details)); + assert!(cx.debug_bounds("selection-figures").is_some(), "opened"); + assert!(cx.debug_bounds("selection-summary").is_some(), "to close"); + click_on(cx, "selection-summary"); draw(cx); - assert!(read(&view, cx, |app| app.crumb_menu.is_none())); -} + assert!(cx.debug_bounds("selection-figures").is_none(), "closed"); -fn names_at(names: &[String], index: usize) -> String { - names.get(index).cloned().unwrap_or_default() + // Tall: the grid, no summary, and the invitation to connect an agent. + cx.simulate_resize(gpui_kit::size(px(1440.), px(900.))); + draw(cx); + assert!(cx.debug_bounds("selection-summary").is_none()); + assert!(cx.debug_bounds("selection-figures").is_some()); + assert!(cx.debug_bounds("agent-line").is_some()); } +/// A side panel list's header stays at the top of the list while its rows +/// scroll under it, and the next section pushes it up rather than covering +/// it, as PwrGit's and PwrAgnt's sidebars do. #[gpui_kit::test] -fn marking_a_directory_marks_everything_inside_it(cx: &mut TestAppContext) { - cx.update(gpui_omarchy::init); +fn panel_headers_stay_in_sight_while_their_list_scrolls( + cx: &mut TestAppContext, +) { + cx.update(init); let temp = fixture(); + // Suggestions to scroll under the headers: the selection leads the + // lists, so the fixture's own are too few to reach the top. + for name in ["a", "b", "c", "d", "e", "f"] { + let file = temp.path().join(name).join(".cache/blob.bin"); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + // Sparse: the scan measures apparent size, and a suggestion has to + // pass `insights::MIN_BYTES`. + std::fs::File::create(file) + .unwrap() + .set_len(65 << 20) + .unwrap(); + } let (view, cx) = view_over(temp.path(), cx); + // Rows for Marked's header to stay above: empty, the section is only + // its header. + for name in ["junk", ".cache"] { + let crumbs = read(&view, cx, |app| { + app.crumbs_for_path(&temp.path().join(name)) + .expect("present") + }); + update(&view, cx, |app, cx| app.toggle_mark(&crumbs, cx)); + } + // Short enough that the lists scroll. + cx.simulate_resize(gpui_kit::size(px(1100.), px(520.))); draw(cx); - let crumbs = |view: &Entity, cx: &mut Window, rel: &str| { - let path = temp.path().join(rel); - read(view, cx, |app| app.crumbs_for_path(&path)).expect(rel) + draw(cx); + let scroll_to = |cx: &mut Window, y: f32| { + update(&view, cx, |app, cx| { + app.panel_scroll.set_offset(gpui_kit::point(px(0.), px(-y))); + cx.notify(); + }); + draw(cx); }; - let junk = crumbs(&view, cx, "junk"); - let deeper = crumbs(&view, cx, "junk/deeper"); - - // Marked inside first, then the directory around it: one mark remains, - // and it covers the inner one. - update(&view, cx, |app, cx| app.toggle_mark(&deeper, cx)); - update(&view, cx, |app, cx| app.toggle_mark(&junk, cx)); - let marks = read(&view, cx, |app| { - app.marks - .items() - .iter() - .map(|item| item.path.clone()) - .collect::>() - }); - assert_eq!( - marks, - vec![temp.path().join("junk")], - "the inner mark is absorbed" + let list = cx.debug_bounds("side-panel-scroll").expect("the lists"); + // The selection leads the lists without a header of its own, so the + // offsets below count from where Marked starts. + let marked = cx.debug_bounds("marked-section").expect("marked"); + let start = f32::from(marked.top() - list.top()); + // Marked's last line just in sight: its header is pushed up by the + // section's end, with Worth a look coming up below. + let push = f32::from(marked.bottom() - list.top()) - 2.; + assert!( + read(&view, cx, |app| app.panel_scroll.max_offset().y) > px(push), + "the lists must scroll for this test" ); - - // Every tile inside it is drawn marked: the ones below the mark are - // "covered", which paints the same fill and label. - let mosaic = update(&view, cx, |app, _| app.prepare()); - let (inside, covered) = update(&view, cx, |app, _| { - let tiles = app.layout().map(<[Tile]>::to_vec).unwrap_or_default(); - let inside: Vec = tiles - .iter() - .zip(&mosaic.tiles) - .filter(|(tile, _)| { - tile.crumbs().starts_with(&junk) && tile.crumbs() != junk - }) - .map(|(_, deco)| deco.covered) - .collect(); - (inside.len(), inside.iter().all(|covered| *covered)) + assert!(cx.debug_bounds("pinned-head").is_none(), "nothing at rest"); + + // Marked's header leaves the top: its copy pins there. + scroll_to(cx, start + 10.); + let pinned = cx.debug_bounds("pinned-head").expect("pinned"); + assert_eq!(pinned.top(), list.top(), "{pinned:?} {list:?}"); + + // A wheel over the pinned header still scrolls the list it heads. + cx.simulate_event(gpui_kit::ScrollWheelEvent { + position: pinned.center(), + delta: gpui_kit::ScrollDelta::Pixels(gpui_kit::point(px(0.), px(-10.))), + ..Default::default() }); - assert!(inside >= 2, "blob.bin and deeper are drawn inside junk"); - assert!(covered, "every tile inside junk goes with it"); + draw(cx); + assert!( + read(&view, cx, |app| app.panel_scroll.offset().y) < px(-(start + 10.)), + "the wheel reached the list" + ); - // Marking something inside it is refused, and says why. - update(&view, cx, |app, cx| app.toggle_mark(&deeper, cx)); - let (count, notice) = read(&view, cx, |app| { - ( - app.marks.len(), - app.notice.as_ref().map(|(text, _)| text.clone()), - ) - }); - assert_eq!(count, 1); - assert!(notice.is_some_and(|text| text.contains("goes with the marked"))); + // Worth a look comes up under it and pushes it off, never under it. + scroll_to(cx, push); + let pinned = cx.debug_bounds("pinned-head").expect("still pinned"); + let worth = cx.debug_bounds("worth-section").expect("worth a look"); + assert!(pinned.top() < list.top(), "pushed up: {pinned:?}"); + assert!(pinned.bottom() < worth.top(), "{pinned:?} {worth:?}"); - // Unmarking the directory unmarks everything. - update(&view, cx, |app, cx| app.toggle_mark(&junk, cx)); - assert!(read(&view, cx, |app| app.marks.is_empty())); + // Back at the top, nothing is pinned. + scroll_to(cx, 0.); + assert!(cx.debug_bounds("pinned-head").is_none()); } -/// `<` and `>` retrace the directories visited, are disabled when there is -/// nowhere to go, and a fresh move ends what was ahead. +/// What just happened is a toast that runs out, not a line in the panel +/// that stays for hours. A newer notice replaces it with a fresh +/// countdown; an error stays until closed. #[gpui_kit::test] -fn back_and_forward_retrace_where_you_have_been(cx: &mut TestAppContext) { - use gpui_kit::Modifiers; +fn notices_are_toasts_that_run_out(cx: &mut TestAppContext) { + use gpui_omarchy::Status; - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); let (view, cx) = view_over(temp.path(), cx); - cx.simulate_resize(gpui_kit::size(px(1400.), px(900.))); draw(cx); - let can = |view: &Entity, cx: &Window| { - read(view, cx, |app| (app.can_go_back(), app.can_go_forward())) - }; - assert_eq!(can(&view, cx), (false, false), "nowhere to go yet"); - - let (junk, deeper, keep) = update(&view, cx, |app, cx| { - let junk = child_crumbs(app, &[], "junk"); - let deeper = child_crumbs(app, &junk, "deeper"); - let keep = child_crumbs(app, &[], "keep"); - app.select(Some(deeper.clone()), cx); - app.descend(cx); - (junk, deeper, keep) + update(&view, cx, |app, cx| { + app.say("copied a thing", Status::Success, cx); }); draw(cx); - assert_eq!(can(&view, cx), (true, false)); - - // Hovering `<` shows the card for where it goes, as hovering a tile - // does: here, the scanned root. It hangs below the button, never on it. - let back = cx - .debug_bounds("history-back") - .expect("the button is drawn"); - cx.simulate_mouse_move(back.center(), None, Modifiers::none()); - draw(cx); - let card = cx.debug_bounds("history-tip").expect("the card is shown"); - assert!(card.top() >= back.bottom(), "{card:?} covers {back:?}"); - assert_eq!( - read(&view, cx, |app| app.history_target(true)), - Some((0, Vec::new())) - ); - - let click = |cx: &mut Window, selector: &'static str| { - let bounds = cx.debug_bounds(selector).expect("the button is drawn"); - cx.simulate_click(bounds.center(), Modifiers::none()); - draw(cx); - }; - click(cx, "history-back"); - assert_eq!( - read(&view, cx, |app| app.crumbs.clone()), - Vec::::new() - ); - assert_eq!(can(&view, cx), (false, true), "back at the start"); - - click(cx, "history-forward"); - assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); - assert_eq!(can(&view, cx), (true, false)); - - // Up a level is a move of its own, and the keys retrace it too. - press(cx, "backspace"); - assert_eq!(read(&view, cx, |app| app.crumbs.clone()), junk); - press(cx, "alt-left"); - assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); - press(cx, "alt-left"); - assert_eq!( - read(&view, cx, |app| app.crumbs.clone()), - Vec::::new() - ); - press(cx, "alt-right"); - assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); + assert!(cx.debug_bounds("toast-notice").is_some(), "a toast"); + assert!(cx.debug_bounds("toast-notice-timer").is_some(), "it drains"); - // Going somewhere new from the middle of the history drops what was - // ahead of it, as in a browser. - press(cx, "alt-left"); - update(&view, cx, |app, cx| app.go_to(keep, cx)); - draw(cx); - assert_eq!(can(&view, cx), (true, false), "the forward trail is gone"); - press(cx, "alt-left"); + // Half its time later a newer one takes its place, and its full time. + let half = crate::toasts::ANSWER / 2; + cx.executor().advance_clock(half); + update(&view, cx, |app, cx| { + app.say("nothing to copy", Status::Warning, cx); + }); + cx.executor().advance_clock(half + half / 2); + cx.run_until_parked(); assert_eq!( - read(&view, cx, |app| app.crumbs.clone()), - Vec::::new() - ); -} - -/// Regression: children are ordered by the metric, so switching between -/// Size and Files reorders them. The directory on screen and the selection -/// are found again by path, rather than following their old positions into -/// a sibling. -#[gpui_kit::test] -fn switching_the_metric_keeps_the_directory_and_the_selection( - cx: &mut TestAppContext, -) { - cx.update(gpui_omarchy::init); - let temp = tempfile::TempDir::new().expect("tempdir"); - let root = temp.path(); - // Largest by size, but fewest files: the two swap places. - std::fs::create_dir_all(root.join("big")).expect("mkdir"); - std::fs::write(root.join("big/one.bin"), vec![b'x'; 500_000]) - .expect("write"); - std::fs::write(root.join("big/two.bin"), vec![b'x'; 1_000]).expect("write"); - for index in 0..5 { - let file = root.join(format!("many/{index}.txt")); - std::fs::create_dir_all(file.parent().expect("parent")).expect("mkdir"); - std::fs::write(&file, b"x").expect("write"); - } - let (view, cx) = view_over(root, cx); + read(&view, cx, Disktree::notice), + Some(("nothing to copy".to_owned(), Status::Warning)) + ); + cx.executor().advance_clock(crate::toasts::ANSWER); + cx.run_until_parked(); draw(cx); + assert_eq!(read(&view, cx, Disktree::notice), None, "gone"); + assert!(cx.debug_bounds("toast-notice").is_none()); + // An error stays, with no countdown, until × closes it. update(&view, cx, |app, cx| { - let big = child_crumbs(app, &[], "big"); - assert_eq!(big, vec![0], "largest first by size"); - app.go_to(big.clone(), cx); - let one = child_crumbs(app, &big, "one.bin"); - app.select(Some(one), cx); + app.say("could not save /x: denied", Status::Error, cx); }); + cx.executor().advance_clock(crate::toasts::ANSWER * 4); + cx.run_until_parked(); draw(cx); - - update(&view, cx, |app, cx| app.set_mode(1, cx)); + assert!(cx.debug_bounds("toast-notice").is_some(), "an error stays"); + assert!(cx.debug_bounds("toast-notice-timer").is_none()); + click_on(cx, "toast-close-notice"); draw(cx); - let (here, selected) = read(&view, cx, |app| { - ( - app.current_path(), - app.selected - .as_deref() - .and_then(|crumbs| app.path_at(crumbs)), - ) - }); - assert_eq!(here, root.join("big")); - assert_eq!(selected, Some(root.join("big/one.bin"))); + assert_eq!(read(&view, cx, Disktree::notice), None); - update(&view, cx, |app, cx| app.set_mode(0, cx)); - draw(cx); - assert_eq!(read(&view, cx, Disktree::current_path), root.join("big")); + // So does a warning that something failed on the person's behalf. + update(&view, cx, |app, cx| { + app.say_until_closed( + "Remote identity changed; previous marks were cleared.", + Status::Warning, + cx, + ); + }); + cx.executor().advance_clock(crate::toasts::ANSWER * 4); + cx.run_until_parked(); + assert!(read(&view, cx, Disktree::notice).is_some(), "it stays"); } -/// Escape stops a first scan. What the walk found so far is not shown as a -/// tree, a late result is ignored, and `r` starts over. +/// Unmark all's notice carries Undo, which puts the marks back. #[gpui_kit::test] -fn escape_cancels_the_first_scan_and_r_starts_it_again( - cx: &mut TestAppContext, -) { - cx.update(gpui_omarchy::init); +fn unmark_all_offers_undo_on_its_toast(cx: &mut TestAppContext) { + cx.update(init); let temp = fixture(); - let root = temp.path().to_path_buf(); - let (view, cx) = - cx.add_window_view(move |_, cx| Disktree::new(root, options(), 3, cx)); - let focus = view.read_with(cx, |app, _| app.focus.clone()); - cx.update(|window, cx| window.focus(&focus, cx)); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, cx| { + let junk = child_crumbs(app, &[], "junk"); + app.toggle_mark(&junk, cx); + app.clear_marks(cx); + }); draw(cx); - let epoch = read(&view, cx, |app| app.scan_epoch); + assert!(read(&view, cx, |app| app.marks.is_empty())); + click_on(cx, "toast-undo"); + draw(cx); + assert_eq!(read(&view, cx, |app| app.marks.len()), 1); +} - press(cx, "escape"); - let (scanning, cancelled) = read(&view, cx, |app| { - (app.scan.is_some(), app.progress.cancelled) +/// `junk` on a pretend 1 MB USB disk mounted inside the scan, the rest on +/// a boot disk of `boot` bytes, as Review's probe finds them. +fn two_disks(path: &Path, boot: u64) -> crate::mark_guard::Disk { + if path.components().any(|part| part.as_os_str() == "junk") { + crate::mark_guard::Disk { + key: "usb".into(), + capacity: 1_000_000, + name: "/Volumes/USB".into(), + } + } else { + crate::mark_guard::Disk { + key: "boot".into(), + capacity: boot, + name: "/".into(), + } + } +} + +/// The fixture on a pretend 1 MB disk, with `junk` (300 kB, 30% of it) +/// selected: past the default 5% limit. +fn over_limit_view<'a>( + temp: &Path, + cx: &'a mut TestAppContext, +) -> (Entity, &'a mut Window, Vec) { + let (view, cx) = view_over(temp, cx); + let junk = update(&view, cx, |app, cx| { + // Every path on one pretend 1 MB disk. + app.disk_probe = |_| { + Ok(crate::mark_guard::Disk { + key: "disk".into(), + capacity: 1_000_000, + name: "/".into(), + }) + }; + app.space = Some(SpaceInfo { + total: 1_000_000, + free: 100_000, + available: 100_000, + }); + let junk = app + .tree() + .and_then(|tree| tree.find("junk").map(|(crumbs, _)| crumbs)) + .expect("the junk directory"); + app.select(Some(junk.clone()), cx); + junk }); - assert!(!scanning, "the walk was dropped"); - assert!(cancelled, "the panel can say it stopped"); - std::thread::sleep(std::time::Duration::from_millis(50)); - let polling = update(&view, cx, |app, cx| app.poll_scan_once(epoch, cx)); - assert!(!polling, "the old poller stops"); - assert!(read(&view, cx, |app| app.tree().is_none())); draw(cx); - - press(cx, "r"); - finish_scan(&view, cx); - assert!(read(&view, cx, |app| app.tree().is_some())); + (view, cx, junk) } -/// Escape stops a widening scan and keeps the tree it started from. +/// Past the limit, Space marks nothing; only the chevron's Mark anyway +/// does, and Review then wants the phrase before anything is removed. #[gpui_kit::test] -fn escape_cancels_widening_and_keeps_the_tree_on_screen( +fn past_the_limit_marking_needs_mark_anyway_and_review_the_phrase( cx: &mut TestAppContext, ) { - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); - let inner = temp.path().join("junk"); - let (view, cx) = view_over(&inner, cx); + let (view, cx, _) = over_limit_view(temp.path(), cx); + assert!(cx.debug_bounds("mark-guard").is_some()); + assert!(cx.debug_bounds("inspector-mark-more").is_some()); + + press(cx, "space"); + read(&view, cx, |app| { + assert!(app.marks.is_empty()); + assert!(app.notice().is_some_and(|(notice, _)| { + notice.contains("30%") && notice.contains("5% limit") + })); + }); + + click_on(cx, "inspector-mark-more"); + assert!(cx.debug_bounds("mark-menu").is_some()); + click_on(cx, "mark-anyway"); + read(&view, cx, |app| { + assert_eq!(app.marks.len(), 1); + assert_eq!(app.mark_menu, None); + }); + update(&view, cx, |app, _| { - app.disk_root = Some(temp.path().to_path_buf()); + app.removal_mode = RemovalMode::Permanent; }); - let before = read(&view, cx, |app| app.tree().map(|tree| tree.files)); + press(cx, "c"); + assert_eq!(read(&view, cx, |app| app.screen), Screen::Review); + assert!(cx.debug_bounds("over-limit-gate").is_some()); + assert!(cx.debug_bounds("over-limit-matched").is_none()); - press(cx, "g"); - assert!(read(&view, cx, |app| app.scan.is_some())); - press(cx, "escape"); - let (scanning, root, scan_root, files) = read(&view, cx, |app| { - ( - app.scan.is_some(), - app.root_path.clone(), - app.scan_root.clone(), - app.tree().map(|tree| tree.files), - ) + // Enter commits nothing until the phrase is typed. + press(cx, "enter"); + read(&view, cx, |app| { + assert!(!app.confirm_open); + assert!(app.run.is_none()); + assert!(app.notice().is_some_and(|(notice, _)| { + notice.contains("delete 30% of my disk") + })); + }); + + // Close is not enough, and neither is the other mode's verb. + click_on(cx, "over-limit-phrase"); + cx.simulate_input("trash 30% of my disk"); + draw(cx); + assert!(cx.debug_bounds("over-limit-matched").is_none()); + let typed = "trash 30% of my disk".chars().count(); + cx.simulate_keystrokes(&vec!["backspace"; typed].join(" ")); + cx.simulate_input("Delete 30% of my disk"); + draw(cx); + assert!(cx.debug_bounds("over-limit-matched").is_some()); + // What the worker is held to is what was typed, not the 5% setting: + // a share that grew past 30% since is refused there. + update(&view, cx, |app, cx| { + let plan = app.plan(); + let ceilings = app.removal_limit(&plan, cx).expect("confirmed"); + assert_eq!(ceilings.of("disk").percent(), 30); + }); + + // Enter in the field commits, and the permanent dialog still asks. + cx.simulate_keystrokes("enter"); + draw(cx); + assert!(read(&view, cx, |app| app.confirm_open)); + assert!( + temp.path().join("junk").exists(), + "nothing has happened yet" + ); + press(cx, "enter"); + assert_eq!(read(&view, cx, |app| app.screen), Screen::Running); + let epoch = read(&view, cx, |app| app.run_epoch); + let mut finished = false; + for _ in 0..400 { + std::thread::sleep(std::time::Duration::from_millis(5)); + finished = update(&view, cx, |app, cx| { + app.poll_removal_once(epoch, cx); + app.screen == Screen::Done + }); + if finished { + break; + } + } + assert!(finished, "the removal finished"); + assert!(!temp.path().join("junk").exists()); + assert!(temp.path().join("keep/notes.txt").exists()); + // The phrase confirmed that removal only: the next one asks again. + read(&view, cx, |app| { + assert!(app.over_phrase.is_none()); + assert_eq!(app.over_ticked, None); }); - assert!(!scanning); - assert_eq!(root, inner); - assert_eq!(scan_root, inner, "the trail stops showing a widening"); - assert_eq!(files, before, "the tree on screen is unchanged"); } -/// The mouse's back and forward buttons retrace the same history as -/// alt-arrows and the header buttons, and only on the explore screen. +/// A mark on a disk mounted inside the scan counts against that disk, not +/// the scanned one. Review names each disk past the limit, and the worker +/// holds each to the share confirmed for it and every other to the limit: +/// 30% confirmed for one disk lets nothing past 5% on another. #[gpui_kit::test] -fn mouse_side_buttons_go_back_and_forward(cx: &mut TestAppContext) { - use gpui_kit::{Modifiers, MouseButton, NavigationDirection}; - - cx.update(gpui_omarchy::init); +fn past_the_limit_review_names_each_disk_and_holds_each_to_its_own_share( + cx: &mut TestAppContext, +) { + cx.update(init); let temp = fixture(); - let (view, cx) = view_over(temp.path(), cx); - cx.simulate_resize(gpui_kit::size(px(1400.), px(900.))); + let (view, cx, junk) = over_limit_view(temp.path(), cx); + let keep = update(&view, cx, |app, cx| { + // A boot disk large enough that nothing here nears its limit. + app.disk_probe = |path| Ok(two_disks(path, 1_000_000_000)); + app.removal_mode = RemovalMode::Permanent; + app.mark_anyway(&junk, cx); + app.open_review(cx); + app.tree() + .and_then(|tree| tree.find("keep").map(|(crumbs, _)| crumbs)) + .expect("the keep directory") + }); draw(cx); - let (junk, deeper) = update(&view, cx, |app, cx| { - let junk = child_crumbs(app, &[], "junk"); - let deeper = child_crumbs(app, &junk, "deeper"); - app.select(Some(junk.clone()), cx); - app.descend(cx); - app.select(Some(deeper.clone()), cx); - app.descend(cx); - (junk, deeper) + // Only the USB disk is past the limit, and the gate says which. + assert!(cx.debug_bounds("over-limit-disk-0").is_some()); + assert!(cx.debug_bounds("over-limit-disk-1").is_none()); + update(&view, cx, |app, _| { + let gate = app.removal_gate(&app.plan()).expect("past the limit"); + assert_eq!(gate.summary(), "30% of /Volumes/USB"); + assert_eq!(app.gate_phrase(&gate), "delete 30% of my disk"); }); + click_on(cx, "over-limit-phrase"); + cx.simulate_input("delete 30% of my disk"); draw(cx); - assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); - - // Over the mosaic, buttons 8 and 9 step the history, as alt-arrows do. - let mosaic = cx.debug_bounds("treemap").expect("the mosaic is drawn"); - let at = mosaic.center(); - let press_button = |cx: &mut Window, button: MouseButton| { - cx.simulate_mouse_move(at, None, Modifiers::none()); - cx.simulate_mouse_down(at, button, Modifiers::none()); - cx.simulate_mouse_up(at, button, Modifiers::none()); - draw(cx); - }; - press_button(cx, MouseButton::Navigate(NavigationDirection::Back)); - assert_eq!(read(&view, cx, |app| app.crumbs.clone()), junk); - press_button(cx, MouseButton::Navigate(NavigationDirection::Forward)); - assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); - - // On the review screen the same press changes nothing: the marked list - // is not somewhere the history can take you back to. - update(&view, cx, |app, cx| app.toggle_mark(&junk, cx)); - press(cx, "c"); - assert_eq!(read(&view, cx, |app| app.screen), Screen::Review); - press_button(cx, MouseButton::Navigate(NavigationDirection::Back)); - assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); - assert_eq!(read(&view, cx, |app| app.screen), Screen::Review); -} + assert!(cx.debug_bounds("over-limit-matched").is_some()); + update(&view, cx, |app, cx| { + let plan = app.plan(); + let ceilings = app.removal_limit(&plan, cx).expect("confirmed"); + assert_eq!(ceilings.of("usb").percent(), 30); + assert_eq!(ceilings.of("boot").percent(), 5, "not confirmed"); + }); -/// The restart as administrator reopens the same root and options: every -/// flag it writes is one the command line reads back. -#[test] -fn restart_arguments_parse_back_to_the_same_scan() { - use disktree_core::tree::Metric; - let temp = tempfile::TempDir::new().expect("tempdir"); - let root = temp.path().join("a folder"); - std::fs::create_dir(&root).expect("mkdir"); - let root = dunce::canonicalize(&root).expect("canonical root"); - let changed = ScanOptions { - apparent_size: true, - follow_links: true, - include_hidden: false, - one_filesystem: false, - metric: Metric::Files, - threads: disktree_core::scan_threads::ScanThreads { - max_threads: 8, - adaptive: true, - retained_throughput: 0.85, - system_cpu_limit: Some(0.70), - }, - ..ScanOptions::default() - }; - for (options, depth) in [(changed, 5), (ScanOptions::default(), 1)] { - let args = crate::state::restart_args(&options, depth, &root); - let parsed = crate::parse_args(args.into_iter()).expect("parses"); - assert_eq!(parsed.root, root); - assert_eq!(parsed.depth, depth); - let got = &parsed.options; - assert_eq!(got.threads.max_threads, options.threads.max_threads); - assert_eq!(got.threads.adaptive, options.threads.adaptive); + // `keep` takes a small boot disk past the limit too: the gate lists + // both, the phrase names both shares, and the one typed is no longer + // enough. + update(&view, cx, |app, cx| { + // A 10 kB boot disk, which `keep` (1 kB) takes past the limit. + app.disk_probe = |path| Ok(two_disks(path, 10_000)); + app.screen = Screen::Explore; + app.mark_anyway(&keep, cx); + app.open_review(cx); + }); + draw(cx); + assert!(cx.debug_bounds("over-limit-disk-0").is_some()); + assert!(cx.debug_bounds("over-limit-disk-1").is_some()); + assert!(cx.debug_bounds("over-limit-matched").is_none()); + update(&view, cx, |app, cx| { + let plan = app.plan(); + let gate = app.removal_gate(&plan).expect("past the limit"); + assert_eq!(gate.summary(), "30% of /Volumes/USB and 10% of /"); + assert_eq!(app.gate_phrase(&gate), "delete 30% and 10% of my disks"); + let refused = app.removal_limit(&plan, cx).expect_err("unconfirmed"); assert!( - (got.threads.retained_throughput - - options.threads.retained_throughput) - .abs() - < f64::EPSILON - ); - assert_eq!( - got.threads.system_cpu_limit, - options.threads.system_cpu_limit - ); - assert_eq!( - ( - got.apparent_size, - got.follow_links, - got.include_hidden, - got.one_filesystem, - got.metric, - ), - ( - options.apparent_size, - options.follow_links, - options.include_hidden, - options.one_filesystem, - options.metric, - ) + refused.contains("delete 30% and 10% of my disks"), + "{refused}" ); - } + }); + // A click lands the caret where it falls in the text; clear from the + // end so every character typed before goes. + click_on(cx, "over-limit-phrase"); + cx.simulate_keystrokes("end"); + let typed = "delete 30% of my disk".chars().count(); + cx.simulate_keystrokes(&vec!["backspace"; typed].join(" ")); + cx.simulate_input("delete 30% and 10% of my disks"); + draw(cx); + assert!(cx.debug_bounds("over-limit-matched").is_some()); + update(&view, cx, |app, cx| { + let plan = app.plan(); + let ceilings = app.removal_limit(&plan, cx).expect("confirmed"); + assert_eq!(ceilings.of("usb").percent(), 30); + assert_eq!(ceilings.of("boot").percent(), 10); + assert_eq!(ceilings.of("elsewhere").percent(), 5); + }); } +/// An agent's confirmed removal is held to the agent limit on the worker, +/// as its preview was. With the window's limit Off, the person's removal +/// would be held only to 100%; an agent's that grew past 5% since its +/// preview must still be refused, and nothing removed. +#[cfg(any(unix, windows))] #[gpui_kit::test] -fn power_efficiency_menu_saves_without_discarding_the_tree( +fn an_agent_removal_stays_at_the_agent_limit_with_the_windows_off( cx: &mut TestAppContext, ) { - use crate::power::{self, PowerEfficiency as Power}; - use gpui_kit::Modifiers; + use disktree_link::{ + ConfirmedRemoval, MarkRequest, RemovalChoice, Request, Response, + }; - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); - let config = tempfile::tempdir().expect("config"); - let path = config.path().join("power-efficiency"); + let root = temp.path().to_path_buf(); + let settings = tempfile::TempDir::new().expect("settings"); + crate::safety::save_limit(Some(settings.path()), None).expect("off"); let (view, cx) = view_over(temp.path(), cx); - cx.simulate_resize(gpui_kit::size(px(900.), px(600.))); update(&view, cx, |app, _| { - app.power_settings_path = Some(path.clone()); - // Enough CPUs that every preset is offered, whatever runs the test. - app.cpu_threads = 18; + app.removal_settings_dir = Some(settings.path().to_path_buf()); + app.safety_policy.replace(None); }); - let epoch = read(&view, cx, |app| app.scan_epoch); - for preset in Power::ALL { - draw(cx); - let button = cx.debug_bounds("power-efficiency").expect("control"); - cx.simulate_click(button.center(), Modifiers::none()); - draw(cx); - let choice = cx.debug_bounds(preset.key()).expect("preset"); - cx.simulate_click(choice.center(), Modifiers::none()); - draw(cx); - assert_eq!(power::load(&path).expect("saved"), preset); - read(&view, cx, |app| { - assert_eq!(app.power_choice, Some(preset)); - assert_eq!( - app.options.threads.max_threads, - preset.threads(app.cpu_threads) - ); - assert!(!app.options.threads.adaptive); - assert!(app.power_menu.is_none()); - assert_eq!(app.scan_epoch, epoch); - assert!(app.tree.is_some()); - }); - } - // Persistence failure must not masquerade as a saved preference. + draw(cx); + + let mut link = Some(link_agent(&view, temp.path(), cx)); + let mut ask = |cx: &mut Window, request: Request| -> Response { + ask_over(&view, &mut link, cx, request) + }; + let hello = ask( + cx, + Request::Hello { + client: "Claude Code".into(), + version: disktree_link::VERSION, + }, + ); + assert!(matches!(hello, Response::State(_)), "{hello:?}"); + ask( + cx, + Request::Mark { + root: root.clone(), + targets: vec![MarkRequest { + path: root.join("junk"), + bytes: 0, + is_dir: true, + }], + }, + ); + + // The preview is checked at the agent limit, Off or not. + let preview = await_removal_preview( + &mut ask, + cx, + &Request::PrepareRemoval { + mode: RemovalChoice::Permanent, + decisions: None, + files: None, + }, + ); + assert_eq!(preview.limit_percent, 5); + + // Since the preview, `junk` has become 30% of its disk: a pretend + // 1 MB disk stands in for growth the fixture cannot make on a real + // one. The person's removal would be allowed, the agent's is not. update(&view, cx, |app, cx| { - app.power_settings_path = Some(config.path().to_owned()); - app.set_power_efficiency(Power::Miser, cx); + app.disk_probe = |_| { + Ok(crate::mark_guard::Disk { + key: "disk".into(), + capacity: 1_000_000, + name: "/".into(), + }) + }; + let plan = app.plan(); + let person = app.removal_limit(&plan, cx).expect("Off allows it"); + assert_eq!(person.of("disk").percent(), 100); + let refused = app.agent_removal_limit(&plan).expect_err("held to 5%"); + assert!(refused.contains("5% per-operation"), "{refused}"); }); - assert!(read(&view, cx, |app| app.notice.as_ref().is_some_and( - |(message, _)| message.contains("could not be saved") - ))); - update(&view, cx, Disktree::start_scan); - assert_eq!(read(&view, cx, |app| app.scan_epoch), epoch + 1); + let removed = ask( + cx, + Request::Remove(ConfirmedRemoval { + rescan: false, + preview_id: preview.preview_id.clone(), + mode: preview.mode, + paths: preview.paths.clone(), + confirmation: preview.mode.confirmation().into(), + }), + ); + assert!( + matches!( + removed, + Response::Error { ref message } if message.contains("did not start") + ), + "{removed:?}" + ); + read(&view, cx, |app| { + assert_ne!(app.screen, Screen::Running); + assert!(app.run.is_none()); + }); + assert!(root.join("junk/blob.bin").exists(), "nothing removed"); } +/// Settings › Safety relaxes the window, never an agent: Off gives the +/// plain Mark back, Tick a box asks for a tick, and an agent is still held +/// to 5%. #[gpui_kit::test] -fn the_power_menu_offers_only_what_the_cpus_can_tell_apart( +fn safety_settings_relax_the_window_but_never_an_agent( cx: &mut TestAppContext, ) { - use crate::power::PowerEfficiency as Power; - use gpui_kit::Modifiers; + use crate::safety::{Confirm, save_confirm, save_limit}; - cx.update(gpui_omarchy::init); + cx.update(init); let temp = fixture(); - let config = tempfile::tempdir().expect("config"); - let (view, cx) = view_over(temp.path(), cx); - cx.simulate_resize(gpui_kit::size(px(900.), px(600.))); - update(&view, cx, |app, _| { - app.power_settings_path = Some(config.path().join("power")); - // Aggressive and Drain My Battery would both run four workers. - app.cpu_threads = 4; - app.power_choice = Some(Power::Balanced); + let settings = tempfile::TempDir::new().expect("settings"); + save_confirm(Some(settings.path()), Confirm::Tick).expect("tick"); + let (view, cx, junk) = over_limit_view(temp.path(), cx); + update(&view, cx, |app, cx| { + app.removal_settings_dir = Some(settings.path().to_path_buf()); + app.safety_policy.replace(None); + cx.notify(); }); draw(cx); - let toggle = cx.debug_bounds("power-efficiency").expect("control"); - cx.simulate_mouse_move(toggle.center(), None, Modifiers::none()); - cx.simulate_click(toggle.center(), Modifiers::none()); + assert!(cx.debug_bounds("inspector-mark-more").is_some()); + + // Ticked for 30% to the trash, then the mode changes: the tick was + // for the other one. + update(&view, cx, |app, cx| { + app.mark_anyway(&junk, cx); + app.removal_mode = RemovalMode::Trash; + app.open_review(cx); + }); draw(cx); - assert_eq!(read(&view, cx, |app| app.power_menu), Some(1)); + assert!(cx.debug_bounds("over-limit-phrase").is_none()); + click_on(cx, "over-limit-tick"); + let met = |view: &Entity, cx: &mut Window| { + update(view, cx, |app, cx| { + let plan = app.plan(); + let share = app.removal_gate(&plan).expect("past the limit"); + app.gate_met(&share, cx) + }) + }; + assert!(met(&view, cx)); + update(&view, cx, |app, _| { + app.removal_mode = RemovalMode::Permanent; + }); + assert!(!met(&view, cx), "a tick is for one mode"); - // The pointer takes the highlight, and the check stays on what is saved. - let miser = cx.debug_bounds(Power::Miser.key()).expect("row"); - cx.simulate_mouse_move(miser.center(), None, Modifiers::none()); + update(&view, cx, |app, _| { + app.removal_mode = RemovalMode::OwnerCleanup; + }); + assert!(!met(&view, cx), "trash approval cannot authorize cleanup"); draw(cx); - assert_eq!(read(&view, cx, |app| app.power_menu), Some(0)); - let balanced = cx.debug_bounds(Power::Balanced.key()).expect("row"); - let check = cx.debug_bounds("power-check").expect("check"); - assert!(balanced.contains(&check.center()), "check on {check:?}"); + assert!(cx.debug_bounds("over-limit-tick").is_some()); - // A disabled row ignores the click and leaves the menu to be dismissed. - let drain = cx.debug_bounds(Power::DrainMyBattery.key()).expect("row"); - cx.simulate_click(drain.center(), Modifiers::none()); + // Off: no gate in Review, the plain Mark in the inspector, and an + // agent still held to 5%. + save_limit(Some(settings.path()), None).expect("off"); + update(&view, cx, |app, cx| { + app.safety_policy.replace(None); + let plan = app.plan(); + assert_eq!(app.removal_gate(&plan), None); + app.clear_marks(cx); + app.screen = Screen::Explore; + app.select(Some(junk.clone()), cx); + }); + draw(cx); + assert!(cx.debug_bounds("inspector-mark-more").is_none()); + assert!(cx.debug_bounds("mark-guard").is_none()); + update(&view, cx, |app, _| { + let target = app.target_at(&junk).expect("junk"); + assert!( + app.agent_mark_refusal(&target) + .is_some_and(|reason| reason.contains("5% limit")) + ); + }); + press(cx, "space"); + assert_eq!(read(&view, cx, |app| app.marks.len()), 1); +} + +/// A fixture `uv` that answers the version and cache-root probes and +/// records a cleanup instead of doing one. It lives outside the scan, and +/// tests point `cleanup_path` at it so no real tool on this machine is +/// ever probed or run. +#[cfg(unix)] +fn mock_uv(cache: &std::path::Path) -> tempfile::TempDir { + use std::os::unix::fs::PermissionsExt as _; + let bin = tempfile::TempDir::new().expect("fixture bin"); + let uv = bin.path().join("uv"); + std::fs::write( + &uv, + "#!/bin/sh\nhere=${0%/*}\ncase \"$1 $2\" in\n '--version ') printf '%s\\n' 'uv 0.11.0';;\n 'cache dir') /bin/cat \"$here/cache-root\";;\n 'cache clean') printf '%s\\n' \"$@\" > \"$here/invocation\";;\n *) exit 97;;\nesac\n", + ) + .expect("mock uv"); + std::fs::set_permissions(&uv, std::fs::Permissions::from_mode(0o755)) + .expect("executable"); + std::fs::write( + bin.path().join("cache-root"), + format!("{}\n", cache.display()), + ) + .expect("cache root"); + bin +} + +/// Cleanup's in-use check sees any running `uv`, the other test's mock +/// included, so the tests that run one take turns. +#[cfg(unix)] +static MOCK_OWNER: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// Mark three paths and open Review over them, cache cleanup chosen. +#[cfg(unix)] +fn cache_cleanup_view<'a>( + temp: &tempfile::TempDir, + cx: &'a mut TestAppContext, +) -> ( + Entity, + &'a mut Window, + [PathBuf; 3], + tempfile::TempDir, +) { + for name in [".cache/uvdata/payload", ".cache/stale/payload"] { + let file = temp.path().join(name); + std::fs::create_dir_all(file.parent().expect("parent")).expect("dir"); + std::fs::write(file, vec![b'x'; 50_000]).expect("payload"); + } + let (view, cx) = view_over(temp.path(), cx); + let root = read(&view, cx, |app| app.root_path.clone()); + let paths = [ + root.join(".cache/uvdata"), + root.join(".cache/stale"), + root.join("junk"), + ]; + let bin = mock_uv(&paths[0]); + update(&view, cx, |app, cx| { + app.cleanup_path = Some(bin.path().display().to_string()); + let cache = child_crumbs(app, &[], ".cache"); + for name in ["uvdata", "stale"] { + let crumbs = child_crumbs(app, &cache, name); + app.toggle_mark(&crumbs, cx); + } + let junk = child_crumbs(app, &[], "junk"); + app.toggle_mark(&junk, cx); + app.open_review(cx); + assert_eq!(app.removal_mode, RemovalMode::OwnerCleanup); + }); + (view, cx, paths, bin) +} + +#[cfg(unix)] +fn await_owners(view: &Entity, cx: &Window) { + for _ in 0..400 { + cx.run_until_parked(); + if read(view, cx, |app| app.cleanup_ready().is_ok()) { + return; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("owners were not checked"); +} + +#[cfg(unix)] +fn await_done(view: &Entity, cx: &mut Window) { + let epoch = read(view, cx, |app| app.run_epoch); + for _ in 0..800 { + std::thread::sleep(std::time::Duration::from_millis(5)); + let done = update(view, cx, |app, cx| { + app.poll_removal_once(epoch, cx); + app.screen == Screen::Done + }); + if done { + return; + } + } + panic!("cleanup did not finish"); +} + +/// Each marked path is decided on its own; nothing is chosen for the +/// person; deleting files needs its own tick; and every path gets a result. +#[cfg(unix)] +#[gpui_kit::test] +fn cache_cleanup_decides_each_path_and_deleting_files_needs_its_own_tick( + cx: &mut TestAppContext, +) { + use disktree_core::cleanup::{Action, Decision, Outcome, Problem}; + let _turn = MOCK_OWNER + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + + cx.update(init); + let temp = fixture(); + let (view, cx, [uvdata, stale, junk], bin) = cache_cleanup_view(&temp, cx); + draw(cx); + assert!(cx.debug_bounds("check-owners").is_some()); + // Commit first checks owners; it never runs anything. + update(&view, cx, |app, cx| app.commit(false, cx)); + await_owners(&view, cx); draw(cx); + let index = |path: &PathBuf| { + read(&view, cx, |app| { + app.marks + .items() + .iter() + .position(|item| item.path == *path) + .expect("marked") + }) + }; + let (owner, files, skip) = (index(&uvdata), index(&stale), index(&junk)); + for proposal in [owner, files, skip] { + assert!( + cx.debug_bounds(Box::leak( + format!("cleanup-proposal-{proposal}").into_boxed_str() + )) + .is_some() + ); + } read(&view, cx, |app| { - assert_eq!(app.power_choice, Some(Power::Balanced)); - assert!(app.notice.is_none()); + let prepared = app.cleanup_ready().expect("checked"); + let ready = &prepared.proposals[owner]; + assert_eq!(ready.operations.len(), 1); + let operation = &prepared.operations[ready.operations[0]]; + assert_eq!(operation.scope, uvdata); + assert_eq!(operation.version, "uv 0.11.0"); + assert!( + operation + .command + .executable + .starts_with(std::fs::canonicalize(bin.path()).expect("bin")) + ); + assert_eq!( + prepared.proposals[files].issue.as_ref().map(|i| i.problem), + Some(Problem::UnknownOwner) + ); + for index in 0..3 { + assert_eq!(app.cleanup_decision(index), Decision::Skip); + } }); - // The arrows step over what is not offered, and Enter chooses. update(&view, cx, |app, cx| { - app.power_menu = None; - app.toggle_power_menu(cx); + // Nothing chosen: nothing to confirm. + app.commit(false, cx); + assert!(!app.confirm_open); + assert!(app.notice().expect("why").0.contains("Nothing chosen")); + // An owner command is never offered for an unknown cache. + app.decide_cleanup(files, Decision::Owner, cx); + assert_eq!(app.cleanup_decision(files), Decision::Skip); + app.decide_cleanup(owner, Decision::Owner, cx); + app.decide_cleanup(files, Decision::DeleteFiles, cx); + app.set_cleanup_files(Action::Permanent, cx); + app.commit(false, cx); + assert!(app.confirm_open, "both intents to confirm"); }); - press(cx, "down"); - assert_eq!(read(&view, cx, |app| app.power_menu), Some(1)); - press(cx, "up"); - assert_eq!(read(&view, cx, |app| app.power_menu), Some(0)); - press(cx, "enter"); + draw(cx); + assert!(cx.debug_bounds("cleanup-files-tick").is_some()); + assert!( + cx.debug_bounds(Box::leak( + format!("cleanup-delete-{files}").into_boxed_str() + )) + .is_some() + ); + update(&view, cx, |app, cx| { + // Confirming the commands is not consent to delete files. + app.confirm_delete(cx); + assert!(app.run.is_none()); + assert!(app.notice().expect("why").0.contains("Tick")); + app.commit(false, cx); + app.tick_cleanup_files(cx); + app.confirm_delete(cx); + assert_eq!(app.screen, Screen::Running); + }); + await_done(&view, cx); read(&view, cx, |app| { - assert_eq!(app.power_choice, Some(Power::Miser)); - assert_eq!(app.options.threads.max_threads, 2); - assert!(app.power_menu.is_none()); + let results: Vec<_> = app + .cleanup_results + .iter() + .map(|report| (report.path.clone(), report.action, report.outcome)) + .collect(); + assert!(results.contains(&( + junk.clone(), + Action::Skip, + Outcome::Skipped + ))); + assert!(results.contains(&( + uvdata.clone(), + Action::Owner, + Outcome::Succeeded + ))); + assert!(results.contains(&( + stale.clone(), + Action::Permanent, + Outcome::Succeeded + ))); + assert!(app.cleanup_review.is_none(), "decisions are consumed"); }); + assert!(bin.path().join("invocation").exists(), "the owner ran"); + assert!( + uvdata.join("payload").exists(), + "the mock owner deletes nothing" + ); + assert!(!stale.exists(), "deleted as chosen"); + assert!(junk.join("blob.bin").exists(), "skipped means untouched"); + assert!(temp.path().join("keep/notes.txt").exists()); +} - // The button closes what it opened, rather than the press outside the - // menu closing it only for the click to open it again. +/// Review's cache decisions against a model of them. After any command a +/// person can give (an action for one path, Trash or permanent, the +/// consent tick) the window shows the model's decisions, its kept +/// approval equals a fresh one, a change to what is deleted clears the +/// tick, and the export still lists exactly the marked paths. +/// +/// Cases come from a seed, named when one breaks the rule; set +/// `PWRDISK_SEED` to replay it. +#[cfg(unix)] +#[gpui_kit::test] +fn cache_cleanup_decisions_follow_a_model_of_them(cx: &mut TestAppContext) { + use disktree_core::cleanup::{Action, Decision}; + + /// `SplitMix64`, as disktree-core's tests use, picking commands. + fn next(state: &mut u64) -> u64 { + *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = *state; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + let _turn = MOCK_OWNER + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + cx.update(init); + let temp = fixture(); + let (view, cx, _, _bin) = cache_cleanup_view(&temp, cx); + update(&view, cx, |app, cx| app.commit(false, cx)); + await_owners(&view, cx); + let (marked, exported, trash) = read(&view, cx, |app| { + ( + app.marks.len(), + app.export_text(false).expect("marked list").0, + app.trash_backend.is_available(), + ) + }); + assert_eq!(exported.lines().count(), marked); + let initial = read(&view, cx, Disktree::cleanup_files); + let first = std::env::var("PWRDISK_SEED") + .ok() + .and_then(|seed| seed.parse().ok()) + .unwrap_or_else(|| { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default(); + now.as_secs().wrapping_mul(1_000_003) + ^ u64::from(now.subsec_nanos()) + }); + for seed in (0..8).map(|run| first.wrapping_add(run)) { + // Each seed starts from the same state, so it replays alone. + update(&view, cx, |app, cx| { + for index in 0..marked { + app.decide_cleanup(index, Decision::Skip, cx); + } + app.set_cleanup_files(initial, cx); + }); + let mut decisions = vec![Decision::Skip; marked]; + let mut files = initial; + let mut ticked = false; + let mut state = seed; + let mut history = vec![]; + for _ in 0..30 { + let command = next(&mut state) % 3; + let index = usize::try_from(next(&mut state) % marked as u64) + .expect("index"); + let decision = + [Decision::Skip, Decision::Owner, Decision::DeleteFiles] + [usize::try_from(next(&mut state) % 3).expect("index")]; + let action = if next(&mut state).is_multiple_of(2) { + Action::Trash + } else { + Action::Permanent + }; + update(&view, cx, |app, cx| match command { + 0 => { + history.push(format!("decide {index} {decision:?}")); + let offered = + app.cleanup_ready().expect("checked").proposals[index] + .allows(decision); + if offered { + decisions[index] = decision; + ticked = false; + } + app.decide_cleanup(index, decision, cx); + } + 1 => { + history.push(format!("files {action:?}")); + if action != Action::Trash || trash { + files = action; + ticked = false; + } + app.set_cleanup_files(action, cx); + } + _ => { + history.push("tick".into()); + ticked = !ticked; + app.tick_cleanup_files(cx); + } + }); + let case = format!("seed {seed}: after {history:?}"); + read(&view, cx, |app| { + let shown: Vec<_> = (0..marked) + .map(|index| app.cleanup_decision(index)) + .collect(); + assert_eq!(shown, decisions, "{case}"); + assert_eq!(app.cleanup_files(), files, "{case}"); + assert_eq!(app.cleanup_files_ticked(), ticked, "{case}"); + let fresh = app + .cleanup_ready() + .expect("checked") + .approve(&decisions, files); + match (app.cleanup_approved(), fresh) { + (Ok(kept), Ok(fresh)) => { + assert_eq!(kept.steps, fresh.steps, "{case}"); + assert_eq!(kept.decisions, fresh.decisions, "{case}"); + assert_eq!(kept.files, fresh.files, "{case}"); + assert_eq!( + kept.confirmation(), + fresh.confirmation(), + "{case}" + ); + } + (Err(kept), Err(fresh)) => { + assert_eq!(kept, fresh, "{case}"); + } + (kept, fresh) => panic!( + "{case}: kept {:?}, fresh {:?}", + kept.map(|approved| &approved.steps), + fresh.map(|approved| approved.steps) + ), + } + assert_eq!( + app.export_text(false).expect("marked list").0, + exported, + "{case}: decisions changed the export" + ); + }); + } + } +} + +/// An agent relays the same proposals and the person's choices. Without +/// decisions nothing can be confirmed; deleting files is named in the +/// confirmation; and the window's own choices are never used for it. +#[cfg(unix)] +#[gpui_kit::test] +fn an_agent_confirms_cache_decisions_by_path_with_both_intents_named( + cx: &mut TestAppContext, +) { + use disktree_core::cleanup::{Decision, RUN_AND_DELETE}; + use disktree_link::{ + ConfirmedRemoval, PathDecision, RemovalChoice, Request, Response, + }; + let _turn = MOCK_OWNER + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + + cx.update(init); + let temp = fixture(); + let (view, cx, [uvdata, stale, junk], bin) = cache_cleanup_view(&temp, cx); + let socket = temp.path().join("cleanup.sock"); + let listener = disktree_link::Listener::bind_at(&socket).expect("link"); + update(&view, cx, |app, cx| app.attach_agent(listener, cx)); + let mut ask = |cx: &mut Window, request: Request| { + update(&view, cx, |app, cx| app.answer_agent(&request, cx)) + }; + let proposals = Request::PrepareRemoval { + mode: RemovalChoice::OwnerCleanup, + decisions: None, + files: None, + }; + let listed = await_removal_preview(&mut ask, cx, &proposals); + assert_eq!(listed.proposals.len(), 3); + assert!(listed.confirmation.is_empty(), "nothing to confirm yet"); + assert!(listed.paths.is_empty()); + assert!(listed.consent.contains("Owner command (choose owner)")); + assert!(matches!( + ask( + cx, + Request::Remove(ConfirmedRemoval { + preview_id: listed.preview_id, + mode: RemovalChoice::OwnerCleanup, + paths: vec![], + confirmation: "RUN OWNER CLEANUP".into(), + rescan: false, + }) + ), + Response::Error { .. } + )); + + let decide = |files: Option| Request::PrepareRemoval { + mode: RemovalChoice::OwnerCleanup, + decisions: Some(vec![ + PathDecision { + path: uvdata.clone(), + action: Decision::Owner, + }, + PathDecision { + path: stale.clone(), + action: Decision::DeleteFiles, + }, + PathDecision { + path: junk.clone(), + action: Decision::Skip, + }, + ]), + files, + }; + assert!(matches!( + ask(cx, decide(None)), + Response::Error { message } if message.contains("Trash or permanent") + )); + let Response::RemovalPreview(preview) = + ask(cx, decide(Some(RemovalChoice::Permanent))) + else { + panic!("decided preview"); + }; + assert_eq!(preview.confirmation, RUN_AND_DELETE); + assert_eq!(preview.paths.len(), 2); + assert!(!preview.paths.contains(&junk), "skip is not executed"); + assert!(preview.consent.contains("Delete files directly")); + let confirmed = |preview: &disktree_link::RemovalPreview, text: &str| { + Request::Remove(ConfirmedRemoval { + preview_id: preview.preview_id.clone(), + mode: RemovalChoice::OwnerCleanup, + paths: preview.paths.clone(), + confirmation: text.into(), + rescan: false, + }) + }; + // Owner approval alone is not approval to delete files. + assert!(matches!( + ask(cx, confirmed(&preview, "RUN OWNER CLEANUP")), + Response::Error { .. } + )); + assert!(stale.exists()); + let Response::RemovalPreview(preview) = + ask(cx, decide(Some(RemovalChoice::Permanent))) + else { + panic!("new preview after a refused confirmation"); + }; + read(&view, cx, |app| { + for index in 0..3 { + assert_eq!(app.cleanup_decision(index), Decision::Skip); + } + }); + let started = ask(cx, confirmed(&preview, RUN_AND_DELETE)); + assert!( + matches!(&started, Response::State(state) if state.screen == "running"), + "{started:?}" + ); + await_done(&view, cx); + let results = read(&view, cx, |app| app.cleanup_results.clone()); + assert!(bin.path().join("invocation").exists(), "{results:#?}"); + assert!(uvdata.join("payload").exists()); + assert!(!stale.exists()); + assert!(junk.join("blob.bin").exists()); +} + +/// Once a set filters, hovering another chip of it offers "only": one +/// click from Code to just Cache, where the chip itself would add Cache. +/// The chip's tooltip waits, then starts below the pointer rather than +/// under it, so it never covers the pill or the next chip. +#[gpui_kit::test] +fn the_only_pill_switches_kinds_and_the_tooltip_stays_clear( + cx: &mut TestAppContext, +) { + use crate::legend::{Chip, ChipId}; + use disktree_core::classify::Category; + + cx.update(init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1440.), px(900.))); draw(cx); - let toggle = cx.debug_bounds("power-efficiency").expect("control"); - cx.simulate_mouse_move(toggle.center(), None, Modifiers::none()); - cx.simulate_click(toggle.center(), Modifiers::none()); draw(cx); - assert!(read(&view, cx, |app| app.power_menu.is_some())); - cx.simulate_click(toggle.center(), Modifiers::none()); + let kind = |wanted: Category| { + ChipId::Kind( + Category::LEGEND + .iter() + .position(|kind| *kind == wanted) + .unwrap(), + ) + }; + let (code, cache) = (kind(Category::Code), kind(Category::Cache)); + let key = Box::leak(cache.key().into_boxed_str()); + let pill = Box::leak(format!("{key}-only").into_boxed_str()); + + // Nothing set: a click already means only, so there is no pill. + let chip = cx.debug_bounds(key).expect("Cache is on the row"); + let at = chip.center(); + cx.simulate_mouse_move(at, None, gpui_kit::Modifiers::default()); draw(cx); - assert!(read(&view, cx, |app| app.power_menu.is_none())); + assert!(cx.debug_bounds(pill).is_none(), "no pill with nothing set"); + + // Code is empty in the fixture, so setting it brings it from "+N" + // to the row, and Cache moves along. + cx.simulate_mouse_move( + gpui_kit::point(px(700.), px(600.)), + None, + gpui_kit::Modifiers::default(), + ); + update(&view, cx, |app, cx| app.cycle_legend(code, cx)); + draw(cx); + let chip = cx.debug_bounds(key).expect("Cache is on the row"); + let at = chip.center(); + cx.simulate_mouse_move(at, None, gpui_kit::Modifiers::default()); + draw(cx); + let only = cx.debug_bounds(pill).expect("the pill, once Code is set"); + assert!(chip.contains(&only.center()), "laid over the chip"); + + // The tooltip waits for the pointer to rest, then starts below it. + assert!(cx.debug_bounds("app-tooltip").is_none(), "not at once"); + cx.executor().advance_clock( + crate::widgets::TOOLTIP_DELAY + std::time::Duration::from_millis(100), + ); + draw(cx); + let tip = cx.debug_bounds("app-tooltip-surface").expect("a tooltip"); + assert!( + tip.top() >= at.y + crate::ui::size::TOOLTIP_CLEARANCE, + "the tooltip clears the cursor: {tip:?} vs {at:?}" + ); + assert!(!tip.contains(&only.center()), "and the pill"); + + click_on(cx, pill); + cx.run_until_parked(); + assert_eq!(read(&view, cx, |app| app.legend.get(cache)), Chip::Only); + assert_eq!(read(&view, cx, |app| app.legend.get(code)), Chip::Shown); } diff --git a/crates/disktree-app/src/toasts.rs b/crates/disktree-app/src/toasts.rs new file mode 100644 index 00000000..783375b6 --- /dev/null +++ b/crates/disktree-app/src/toasts.rs @@ -0,0 +1,1423 @@ +//! Toasts in the main window: short notices that answer something the +//! person asked for, or offer the one thing worth acting on. Design: +//! "Update Notices" in the PwrDisk Claude Design project, after PwrSnap's +//! update banner and PwrRoute's toast, and "Notices, Sticky Headers and +//! Agents (MCP)" for the window's own notices. +//! +//! Three kinds of news, kept apart as PwrSnap and PwrAgnt do: +//! +//! - **What just happened**: a list saved, marks taken away, a key that +//! had nothing to act on ([`notice`]). These used to sit in a box above +//! the disk until something else replaced them, which could be hours. +//! Now they share one slot, [`NOTICE`]: a newer one takes the older's +//! place with a fresh countdown of [`ANSWER`]. An error stays until it +//! is closed, as PwrAgnt's do, since it may need reading twice, and so +//! does a warning that something failed or was undone on the person's +//! behalf ([`Disktree::say_until_closed`]). A copy +//! button answers on itself ("Copied"), never here; only a copy with no +//! button in sight, such as Help › Copy Diagnostics Info, says so here. +//! - **The answer to Help › Check for Updates….** Only that menu item +//! asks; the startup, timer and Settings checks never raise a toast +//! (Settings answers its own button inline). While the check runs the +//! card is live ("Checking for updates", then "Downloading update" with +//! its percent) and has no countdown. Once it settles, an answer with +//! nothing to install counts down [`ANSWER`] and goes, with a strip +//! along its top that drains. +//! - **A release ready to install**, from any check: held for the slot in +//! force (`updater::ready`). It is not pushed once: it is drawn from the +//! held download whenever no live card or answer is in its place, so it +//! comes back after an answer leaves. Later puts away that version only; +//! a newer one, or asking again, brings it back. The title strip's chip +//! offers it too, Later or not (`views::update_chip`). +//! +//! The timed answers sit in [`Toasts`], a short list with its own clock +//! that pauses while the pointer is over the stack, which is when someone +//! is reading a card or reaching for its button. The live and ready cards +//! come from [`UpdateWatch`], which keeps the updater's state as of its +//! last change, so a frame never asks the updater or the disk. +//! +//! The stack sits in the lower left of each screen's content, above its +//! footer, so it never covers the footer's buttons; dialogs draw over it. + +use std::time::{Duration, Instant}; + +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::{ + Animation, AnimationExt as _, AnyElement, App, Context, Div, ElementId, + FontWeight, Hsla, InteractiveElement as _, IntoElement, ParentElement as _, + StatefulInteractiveElement as _, Styled as _, Window, div, relative, +}; +use gpui_omarchy::{ActiveTheme as _, ButtonVariant, Status, button}; + +use crate::semantics::AccessibleButton as _; +use crate::state::Disktree; +use crate::ui::{size, space, text}; +use crate::update_channel::Slot; +use crate::updater::{self, Change, Held, Outcome, State}; + +/// The element id of the stack, for tests. +pub const STACK_ID: &str = "toast-stack"; +/// The one key the updater's cards share, so a second check replaces the +/// first card rather than stacking another. +pub const UPDATE: &str = "update"; +/// The one key the window's notices share: a newer one replaces the older. +pub const NOTICE: &str = "notice"; +/// The most toasts on screen; an older one gives way to a newer one. +const MAX: usize = 3; +/// How long an answer stays: PwrSnap's and PwrRoute's 8 s. +pub const ANSWER: Duration = Duration::from_secs(8); + +/// What colour a toast's title and edge take. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Tone { + /// An answer, an offer, or something under way. + Accent, + /// Something went wrong. + Danger, + /// A notice: done as asked. + Success, + /// A notice: nothing was done, and why. + Warning, + /// A notice that is neither. + Neutral, +} + +impl Tone { + /// The status a notice of this tone was raised with. + pub const fn status(self) -> Status { + match self { + Self::Danger => Status::Error, + Self::Success => Status::Success, + Self::Warning => Status::Warning, + Self::Accent | Self::Neutral => Status::Neutral, + } + } + + const fn color(self, theme: &gpui_omarchy::Theme) -> Hsla { + match self { + Self::Accent => theme.accent, + Self::Danger => theme.danger, + Self::Success => theme.success, + Self::Warning => theme.warning, + Self::Neutral => theme.secondary, + } + } +} + +impl From for Tone { + fn from(status: Status) -> Self { + match status { + Status::Neutral => Self::Neutral, + Status::Success => Self::Success, + Status::Warning => Self::Warning, + Status::Error => Self::Danger, + } + } +} + +/// What runs under a live card's sentence. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Track { + /// Work of unknown length: a sweep. + Sweep, + /// 0-100. + Percent(u8), +} + +/// A toast's buttons. Later is always the last one, so a click aimed at it +/// cannot land on Restart if the card changes under the pointer (PwrAgnt's +/// rule). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Action { + /// The release's page on GitHub. + ReleaseNotes(String), + /// Where to download PwrDisk, for a copy that cannot update itself. + DownloadPage, + OpenLogs, + CheckAgain, + /// Install the held download and start again; `switch_back` for an + /// older release. `restarting` once pressed. + Restart { + switch_back: bool, + restarting: bool, + }, + /// Put away the ready release until a newer one, or until asked. + Later, + /// Put back the marks Unmark all took. + Undo, +} + +/// One notice. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Toast { + pub key: &'static str, + pub tone: Tone, + pub title: String, + pub body: String, + /// A quieter line under the body. + pub detail: Option, + /// A line in the danger tone: what went wrong with the last try. + pub problem: Option, + pub actions: Vec, + /// How long it stays once shown; `None` stays until put away. + pub timeout: Option, + /// Work under way: no countdown, no close. + pub track: Option, +} + +impl Toast { + fn new(tone: Tone, title: impl Into, body: String) -> Self { + Self { + key: UPDATE, + tone, + title: title.into(), + body, + detail: None, + problem: None, + actions: Vec::new(), + timeout: None, + track: None, + } + } +} + +#[derive(Clone, Debug)] +struct Entry { + toast: Toast, + remaining: Option, +} + +/// The timed toasts on screen, oldest first, and the clock their timeouts +/// run on. +#[derive(Clone, Debug, Default)] +pub struct Toasts { + entries: Vec, + /// The pointer is over the stack: no timeout runs. + hovered: bool, + /// When the timeouts were last brought up to date. + tick: Option, +} + +impl Toasts { + /// Shows `toast`, in place of one with the same key. + pub fn push(&mut self, toast: Toast, now: Instant) { + self.settle(now); + self.entries.retain(|entry| entry.toast.key != toast.key); + let remaining = toast.timeout; + self.entries.push(Entry { toast, remaining }); + let over = self.entries.len().saturating_sub(MAX); + self.entries.drain(..over); + } + + /// Takes away the toast with `key`; whether there was one. + pub fn dismiss(&mut self, key: &str) -> bool { + let before = self.entries.len(); + self.entries.retain(|entry| entry.toast.key != key); + self.entries.len() != before + } + + /// Runs the timeouts up to `now` and drops what has run out; whether + /// anything went. + pub fn settle(&mut self, now: Instant) -> bool { + let elapsed = self.elapsed(now); + self.tick = Some(now); + if self.hovered { + return false; + } + let before = self.entries.len(); + self.entries.retain_mut(|entry| { + entry.remaining = entry + .remaining + .map(|remaining| remaining.saturating_sub(elapsed)); + entry.remaining.is_none_or(|remaining| !remaining.is_zero()) + }); + self.entries.len() != before + } + + fn elapsed(&self, now: Instant) -> Duration { + self.tick + .map_or(Duration::ZERO, |tick| now.saturating_duration_since(tick)) + } + + /// Pauses the timeouts while the pointer is over the stack. + pub fn set_hovered(&mut self, hovered: bool, now: Instant) { + self.settle(now); + self.hovered = hovered; + } + + /// A stack that is not drawn never hears the pointer leave: a click on + /// × takes the card from under it, and a ready card can step aside for + /// a removal or another channel. Left set, every later answer would + /// wait for a hover that never ends, so [`stack`] calls this whenever + /// it draws nothing. + pub const fn forget_hover(&mut self) { + self.hovered = false; + } + + pub const fn is_hovered(&self) -> bool { + self.hovered + } + + /// How long until the next toast runs out, if one will. + pub fn next_deadline(&self) -> Option { + if self.hovered { + return None; + } + self.entries + .iter() + .filter_map(|entry| entry.remaining) + .min() + } + + /// How much of `key`'s time is left at `now`, 0 to 1, for its + /// countdown strip; `None` for a toast that does not run out. + pub fn left(&self, key: &str, now: Instant) -> Option { + let entry = self.entries.iter().find(|entry| entry.toast.key == key)?; + let total = entry.toast.timeout?; + let mut remaining = entry.remaining?; + if !self.hovered { + remaining = remaining.saturating_sub(self.elapsed(now)); + } + Some((remaining.as_secs_f32() / total.as_secs_f32()).clamp(0.0, 1.0)) + } + + pub fn get(&self, key: &str) -> Option<&Toast> { + self.entries + .iter() + .find(|entry| entry.toast.key == key) + .map(|entry| &entry.toast) + } + + pub const fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + pub fn iter(&self) -> impl Iterator { + self.entries.iter().map(|entry| &entry.toast) + } +} + +// ── what the updater has said ─────────────────────────────────────────── + +/// The live card while Check for Updates… runs. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Live { + /// Asking GitHub. + Checking, + /// A release found and on its way. + Downloading { + version: String, + switch_back: bool, + percent: Option, + }, +} + +/// What the main window remembers about the updater between its changes. +#[derive(Clone, Debug, Default)] +pub struct UpdateWatch { + /// Check for Updates… is waiting for the check after this many have + /// finished (`State::finished`): the one it started, or the one that + /// was already running. + asked: Option, + /// Later on this version: its card stays down. The chip still offers + /// it. + dismissed: Option, + /// The updater as of its last change, and the release ready then: + /// what the window draws from. + seen: State, + ready: Option, + /// `PWRDISK_UPDATE_FIXTURE` drew a set state: the updater is ignored. + fixture: bool, +} + +impl UpdateWatch { + /// Check for Updates… was chosen while `finished` checks had ended. + pub fn ask(&mut self, finished: u64) { + self.asked = Some(finished); + // Asking again is asking to see the answer again, so a release put + // away earlier comes back rather than the check looking dead. + self.dismissed = None; + } + + /// Takes in the updater's state after a change, with `ready` the + /// release Restart would install. Returns the outcome of the check + /// Check for Updates… was waiting for, once it has finished. + pub fn follow( + &mut self, + state: State, + ready: Option, + ) -> Option { + let settled = self.asked.and_then(|after| { + if state.checking || state.finished <= after { + return None; + } + self.asked = None; + state.last.as_ref().map(|(_, outcome)| outcome.clone()) + }); + self.seen = state; + self.ready = ready; + settled + } + + /// A download's percent moved; nothing else did. + pub fn follow_progress(&mut self, download: Option) { + self.seen.download = download; + } + + /// The live card, while Check for Updates… waits. + pub fn live(&self) -> Option { + self.asked?; + Some(match &self.seen.download { + Some(download) => Live::Downloading { + version: download.version.clone(), + switch_back: download.switch_back, + percent: download.percent, + }, + None => Live::Checking, + }) + } + + pub const fn is_asking(&self) -> bool { + self.asked.is_some() + } + + /// The release Restart to update installs, Later or not: the chip. + pub const fn ready(&self) -> Option<&Held> { + self.ready.as_ref() + } + + /// The release the Ready card offers: ready and not put away. + pub fn offer(&self) -> Option<&Held> { + self.ready + .as_ref() + .filter(|ready| self.dismissed.as_deref() != Some(&ready.version)) + } + + /// Later: put away the release ready now. + pub fn later(&mut self) { + self.dismissed = self.ready.as_ref().map(|ready| ready.version.clone()); + } + + /// The updater as of its last change. + pub const fn seen(&self) -> &State { + &self.seen + } + + pub const fn is_fixture(&self) -> bool { + self.fixture + } +} + +// ── the updater's words ───────────────────────────────────────────────── + +/// The live card's words. +pub fn live(live: &Live) -> Toast { + match live { + Live::Checking => Toast { + track: Some(Track::Sweep), + ..Toast::new( + Tone::Accent, + "Checking for updates", + "Asking GitHub for the latest release\u{2026}".into(), + ) + }, + Live::Downloading { + version, + switch_back, + percent, + } => Toast { + track: Some(percent.map_or(Track::Sweep, Track::Percent)), + ..Toast::new( + Tone::Accent, + if *switch_back { + "Downloading switch" + } else { + "Downloading update" + }, + match percent { + Some(percent) => { + format!("PwrDisk {version} \u{00b7} {percent}%") + } + None => format!("PwrDisk {version}"), + }, + ) + }, + } +} + +/// A download that Restart to update installs now. `marks` is how many +/// paths are marked, which a restart forgets; `restarting` once pressed, +/// `problem` why the last press did not restart. +pub fn ready( + held: &Held, + marks: usize, + restarting: bool, + problem: Option<&str>, +) -> Toast { + let title = if held.switch_back { + "Switch ready" + } else { + "Update ready" + }; + let mut actions: Vec = release_notes(&held.version).collect(); + actions.push(Action::Restart { + switch_back: held.switch_back, + restarting, + }); + actions.push(Action::Later); + Toast { + detail: (marks > 0).then(|| { + let noun = if marks == 1 { "mark" } else { "marks" }; + format!("Restarting clears your {marks} {noun}.") + }), + problem: problem.map(|why| format!("Couldn't restart: {why}.")), + actions, + ..Toast::new( + Tone::Accent, + title, + format!( + "PwrDisk {} is downloaded. It installs when you restart or \ + quit.", + held.version + ), + ) + } +} + +/// The answer to Check for Updates…, or `None` when the ready release is +/// the answer (its own card says it) or nothing settled. +pub fn answer( + outcome: &Outcome, + ready_now: Option<&Held>, + slot: Slot, +) -> Option { + let timed = |tone, title: &str, body: String, actions: Vec| { + Some(Toast { + actions, + timeout: Some(ANSWER), + ..Toast::new(tone, title, body) + }) + }; + match outcome { + Outcome::Downloaded(_) + | Outcome::Pending(_) + | Outcome::SwitchReady(_) + if ready_now.is_some() => + { + None + } + // Held for another slot than the one in force now. + Outcome::Downloaded(version) | Outcome::Pending(version) => timed( + Tone::Accent, + "Update downloaded", + format!("{version} installs when PwrDisk quits."), + release_notes(version).collect(), + ), + Outcome::SwitchReady(version) => timed( + Tone::Accent, + "Switch downloaded", + format!("{version} installs from Settings \u{203a} Updates."), + release_notes(version).collect(), + ), + Outcome::UpToDate(version) => timed( + Tone::Accent, + "PwrDisk is up to date", + format!("{version} is the newest release on {slot}."), + release_notes(version).collect(), + ), + Outcome::NothingPublished(slot) => timed( + Tone::Accent, + "Nothing to install", + format!("Nothing is published on {slot} yet."), + Vec::new(), + ), + Outcome::NotInstalled(_) => timed( + Tone::Accent, + "Updates unavailable", + not_updatable().into(), + vec![Action::DownloadPage], + ), + Outcome::Failed(why) => timed( + Tone::Danger, + "Update check failed", + sentence(why), + vec![Action::OpenLogs, Action::CheckAgain], + ), + // Never settles a check: the running one does. + Outcome::AlreadyChecking => None, + } +} + +/// Why this copy cannot update itself. +const fn not_updatable() -> &'static str { + if cfg!(debug_assertions) { + "A development build: updates are off here." + } else { + "This copy wasn't installed from the DMG, Setup.exe or the MSI, so \ + it doesn't update itself." + } +} + +/// Release notes for `version`, when it is one this repository could have +/// tagged: a dev stamp gets no link onto a page that is not there. +fn release_notes(version: &str) -> impl Iterator { + crate::update_channel::parse(version) + .map(|_| Action::ReleaseNotes(version.to_owned())) + .into_iter() +} + +/// `text` as a sentence: a capital first and a full stop last. +fn sentence(text: &str) -> String { + let text = text.trim().trim_end_matches('.'); + let mut chars = text.chars(); + let mut out: String = chars.next().map_or_else(String::new, |first| { + first.to_uppercase().chain(chars).collect() + }); + out.push('.'); + out +} + +// ── the window's own notices ──────────────────────────────────────────── + +/// A notice: one line, in the [`NOTICE`] slot. It runs out after +/// [`ANSWER`] unless it is an error, which stays until closed. +pub fn notice(message: impl Into, status: Status) -> Toast { + Toast { + key: NOTICE, + timeout: (status != Status::Error).then_some(ANSWER), + ..Toast::new(status.into(), String::new(), message.into()) + } +} + +/// A notice that stays until it is closed, whatever its status. +pub fn lasting_notice(message: impl Into, status: Status) -> Toast { + Toast { + timeout: None, + ..notice(message, status) + } +} + +// ── the main window's side ────────────────────────────────────────────── + +/// Follows the updater (`updater::install`): the main window on every +/// change, Settings only when more than a download's percent moved, since +/// redrawing it collects the diagnostics again. +pub fn updater_changed(change: Change, cx: &mut App) { + let windows: Vec<_> = cx + .windows() + .into_iter() + .filter_map(|window| window.downcast::()) + .collect(); + for window in windows { + let _ = window.update(cx, |this, _, cx| { + this.updates_changed(change, cx); + }); + } + if change == Change::State { + crate::settings::refresh(cx); + } +} + +impl Disktree { + /// Help › Check for Updates…: the toast answers it. A check already + /// running (the startup one, say) gives the answer. + pub fn check_for_updates(&mut self, cx: &mut Context<'_, Self>) { + let state = updater::state(); + self.update_watch.ask(state.finished); + // The live card takes the last answer's place. + self.dismiss_toast(UPDATE, cx); + if !state.checking { + updater::check_in_background(updater::Trigger::Manual); + } + cx.notify(); + } + + /// The updater's state moved. A progress tick only redraws a live + /// card, and only while there is one; anything else is followed in + /// full. + pub fn updates_changed( + &mut self, + change: Change, + cx: &mut Context<'_, Self>, + ) { + if self.update_watch.is_fixture() { + return; + } + if change == Change::Progress { + self.update_watch.follow_progress(updater::download()); + if self.update_watch.is_asking() { + cx.notify(); + } + return; + } + let installed = updater::installed_version(); + let slot = updater::selection().resolve(&installed); + self.follow_updates(updater::state(), &installed, slot, cx); + } + + /// [`Self::updates_changed`] for a given state, so tests can hand it + /// one. + pub fn follow_updates( + &mut self, + state: State, + installed: &str, + slot: Slot, + cx: &mut Context<'_, Self>, + ) { + let failed_before = self.update_watch.seen().restart_failed.clone(); + let ready = updater::ready(&state, installed, slot); + let failed_now = state.restart_failed.clone(); + if let Some(outcome) = self.update_watch.follow(state, ready.clone()) + && let Some(toast) = answer(&outcome, ready.as_ref(), slot) + { + self.show_toast(toast, cx); + } + // A failed restart also says so as a notice, for a release whose + // card was put away: the chip said nothing. + if let Some(why) = failed_now.filter(|_| failed_before.is_none()) { + self.say_until_closed( + format!("Cannot update: {why}"), + Status::Warning, + cx, + ); + } + cx.notify(); + } + + /// Says what just happened, in the notice slot. + pub fn say( + &mut self, + message: impl Into, + status: Status, + cx: &mut Context<'_, Self>, + ) { + self.show_toast(notice(message, status), cx); + } + + /// Says something that went wrong, or was undone on the person's + /// behalf, where it stays until closed: it may be read after the fact. + pub fn say_until_closed( + &mut self, + message: impl Into, + status: Status, + cx: &mut Context<'_, Self>, + ) { + self.show_toast(lasting_notice(message, status), cx); + } + + /// Takes the notice down: what it said no longer holds. + pub fn clear_notice(&mut self, cx: &mut Context<'_, Self>) { + self.dismiss_toast(NOTICE, cx); + } + + /// The notice on screen, and the status it was raised with. + pub fn notice(&self) -> Option<(String, Status)> { + self.toasts + .get(NOTICE) + .map(|toast| (toast.body.clone(), toast.tone.status())) + } + + pub fn show_toast(&mut self, toast: Toast, cx: &mut Context<'_, Self>) { + let now = cx.background_executor().now(); + self.toasts.push(toast, now); + self.schedule_toasts(cx); + cx.notify(); + } + + pub fn dismiss_toast(&mut self, key: &str, cx: &mut Context<'_, Self>) { + if self.toasts.dismiss(key) { + self.schedule_toasts(cx); + cx.notify(); + } + } + + /// Later, or × on the Ready card. + pub fn later(&mut self, cx: &mut Context<'_, Self>) { + self.update_watch.later(); + cx.notify(); + } + + fn set_toasts_hovered( + &mut self, + hovered: bool, + cx: &mut Context<'_, Self>, + ) { + let now = cx.background_executor().now(); + self.toasts.set_hovered(hovered, now); + self.schedule_toasts(cx); + cx.notify(); + } + + /// Wakes when the next toast runs out, rather than ticking. + fn schedule_toasts(&mut self, cx: &mut Context<'_, Self>) { + let now = cx.background_executor().now(); + if self.toasts.settle(now) { + cx.notify(); + } + self.toast_timer = self.toasts.next_deadline().map(|after| { + cx.spawn(async move |this, cx| { + cx.background_executor().timer(after).await; + let _ = this.update(cx, Self::schedule_toasts); + }) + }); + } + + fn run_toast_action( + &mut self, + action: &Action, + cx: &mut Context<'_, Self>, + ) { + match action { + Action::ReleaseNotes(version) => { + cx.open_url(&format!( + "{}/releases/tag/v{version}", + crate::help::REPOSITORY + )); + } + Action::DownloadPage => { + cx.open_url(&format!("{}/releases", crate::help::REPOSITORY)); + } + Action::OpenLogs => cx.defer(crate::logs_window::open), + Action::CheckAgain => self.check_for_updates(cx), + Action::Restart { .. } => self.restart_to_update(cx), + Action::Later => self.later(cx), + Action::Undo => self.undo_unmark(cx), + } + } + + /// `PWRDISK_UPDATE_FIXTURE`: draws one update state without the + /// network, for screenshots and manual checks, and then ignores the + /// updater. `checking`, `downloading`, `up-to-date`, `failed`, `ready` + /// or `restarting`. An answer holds still, its strip part drained, + /// until the pointer passes over it. Release builds keep it, as + /// PwrRoute's `PWRROUTE_UPDATE_FIXTURE`, since screenshots are taken of + /// one; it changes only what the window says, never what installs. + pub fn apply_update_fixture(&mut self, cx: &mut Context<'_, Self>) { + let Ok(kind) = std::env::var("PWRDISK_UPDATE_FIXTURE") else { + return; + }; + let held = Held { + version: "0.15.0".into(), + file_name: "PwrDisk-0.15.0-full.nupkg".into(), + slot: Slot::default().key(), + switch_back: false, + }; + let mut watch = UpdateWatch { + fixture: true, + ..UpdateWatch::default() + }; + let mut answer_to = None; + match kind.as_str() { + "checking" => { + watch.asked = Some(0); + watch.seen.checking = true; + } + "downloading" => { + watch.asked = Some(0); + watch.seen.checking = true; + watch.seen.download = Some(updater::Download { + version: held.version, + switch_back: false, + percent: Some(42), + }); + } + "up-to-date" => { + answer_to = Some(Outcome::UpToDate("0.14.0".into())); + } + "failed" => { + answer_to = Some(Outcome::Failed( + "could not reach GitHub Releases (timed out)".into(), + )); + } + "ready" => watch.ready = Some(held), + "restarting" => { + watch.ready = Some(held); + watch.seen.restarting = true; + } + _ => return, + } + self.update_watch = watch; + if let Some(toast) = answer_to + .and_then(|outcome| answer(&outcome, None, Slot::default())) + { + // Pushed 3 s ago and held: the strip shows part drained. + let now = cx.background_executor().now(); + let then = now.checked_sub(Duration::from_secs(3)).unwrap_or(now); + self.toasts.push(toast, then); + self.toasts.set_hovered(true, now); + } + cx.notify(); + } +} + +/// The element id of a toast's button, for tests. +pub const fn action_id(action: &Action) -> &'static str { + match action { + Action::ReleaseNotes(_) => "toast-release-notes", + Action::DownloadPage => "toast-download", + Action::OpenLogs => "toast-open-logs", + Action::CheckAgain => "toast-check-again", + Action::Restart { .. } => "toast-restart", + Action::Later => "toast-later", + Action::Undo => "toast-undo", + } +} + +/// The update card [`UpdateWatch`] draws now, if any: the live card while +/// Check for Updates… waits, else the ready release unless an answer is in +/// its place or it was put away. A running removal keeps the ready card +/// down: Restart would wait for it anyway, and the chip still offers it. +pub fn update_card(app: &Disktree) -> Option { + let watch = &app.update_watch; + if let Some(state) = watch.live() { + return Some(live(&state)); + } + if app.toasts.get(UPDATE).is_some() || !app.can_restart_to_update() { + return None; + } + let held = watch.offer()?; + let seen = watch.seen(); + Some(ready( + held, + app.marks.len(), + seen.restarting, + seen.restart_failed.as_deref(), + )) +} + +/// The stack, lower left of the screen's content (the caller anchors it +/// there, above the footer); `None` when there is nothing to show. +pub fn stack( + app: &mut Disktree, + window: &Window, + cx: &mut Context<'_, Disktree>, +) -> Option { + let derived = update_card(app); + if app.toasts.is_empty() && derived.is_none() { + app.toasts.forget_hover(); + return None; + } + let app = &*app; + let now = cx.background_executor().now(); + let moving = app + .toasts + .iter() + .any(|toast| toast.timeout.is_some() && !app.toasts.is_hovered()) + || derived + .as_ref() + .is_some_and(|toast| toast.track == Some(Track::Sweep)); + // Asked only while something moves: the answer is a platform call. + let still = moving && crate::state::prefers_reduced_motion(cx); + let mut column = div() + .id(STACK_ID) + .debug_selector(|| STACK_ID.into()) + .absolute() + .left(space::LG) + .bottom(space::LG) + .w(size::TOAST) + .flex() + .flex_col() + .gap(space::SM) + // The stack floats over the treemap and the lists. Without this the + // hit test reaches through it: the tile under a card kept its + // tooltip over the card, and a click or a scroll on the card + // selected or zoomed what lay beneath. Scroll too, since nothing + // here scrolls and a zoom behind the card is never what was meant. + .occlude() + .on_hover(cx.listener(|this, hovered: &bool, _, cx| { + this.set_toasts_hovered(*hovered, cx); + })); + let mut draining = false; + for toast in app.toasts.iter() { + let left = app.toasts.left(toast.key, now); + draining |= left.is_some() && !app.toasts.is_hovered() && !still; + column = column.child(card(app, toast, left, still, false, cx)); + } + if let Some(toast) = &derived { + column = column.child(card(app, toast, None, still, true, cx)); + } + // The countdown strip drains frame by frame; it holds while the pointer + // is over the stack, as the timeout does. + if draining { + window.request_animation_frame(); + } + Some(column.into_any_element()) +} + +fn card( + app: &Disktree, + toast: &Toast, + left: Option, + still: bool, + // Drawn from the updater's state rather than held in the list: × + // is Later. + derived: bool, + cx: &Context<'_, Disktree>, +) -> gpui_kit::Stateful
{ + let theme = cx.omarchy(); + let edge: Hsla = toast.tone.color(theme); + let key = toast.key; + // A live card reports work still running: it has nothing to close. + let close = toast.track.is_none().then(|| { + gpui_omarchy::icon_button( + ElementId::Name(format!("toast-close-{key}").into()), + gpui_omarchy::IconName::Close, + "Close", + ButtonVariant::Secondary, + cx, + ) + .debug_selector(move || format!("toast-close-{key}")) + .on_click(cx.listener(move |this, _, _, cx| { + if derived { + this.later(cx); + } else { + this.dismiss_toast(key, cx); + } + })) + }); + let mut actions = div().flex().flex_row().items_center().gap(space::XS); + let mut primary_seen = false; + for action in &toast.actions { + // Links lead, then a spacer, then the commands, so Restart and + // Later sit together at the right. + let link = + matches!(action, Action::ReleaseNotes(_) | Action::DownloadPage); + if !link && !primary_seen { + primary_seen = true; + actions = actions.child(div().flex_1()); + } + actions = actions.child(action_button(app, action, cx)); + } + // A live status, as the window's other notices are, so a screen reader + // speaks the answer as well as showing it. A live card's percent is + // left out of it: "42%... 44%..." would bury the phase changes. + let spoken = match toast.track { + Some(Track::Percent(_)) => toast.title.clone(), + _ if toast.title.is_empty() => toast.body.clone(), + _ => format!("{}: {}", toast.title, toast.body), + }; + let shell = crate::semantics::status(key, spoken) + .debug_selector(move || format!("toast-{key}")) + .relative() + .overflow_hidden() + .flex() + .flex_col() + .gap(space::XS) + .p(space::MD) + .border_1() + .border_color(edge) + .bg(theme.surface) + .shadow_lg() + .when_some(left, |card, left| { + card.child(countdown(key, if still { 1.0 } else { left }, edge)) + }); + // A notice is one line: a dot in its tone, what happened, its button + // if it has one, and ×. No title: the sentence is the whole of it. + if toast.title.is_empty() { + return shell.child( + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .child(div().text_color(edge).child("\u{25cf}")) + .child( + div() + .debug_selector(move || format!("toast-{key}-body")) + .flex_1() + .min_w_0() + .text_color(theme.bright) + .child(toast.body.clone()), + ) + .children( + toast + .actions + .iter() + .map(|action| action_button(app, action, cx)), + ) + .children(close), + ); + } + shell + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .child( + div() + .flex_1() + .font_family(theme.mono_font.clone()) + .text_size(text::CAPTION) + .font_weight(FontWeight::BOLD) + .text_color(edge) + .child(toast.title.to_uppercase()), + ) + .children(close), + ) + .child( + div() + .debug_selector(move || format!("toast-{key}-body")) + .text_color(theme.bright) + .child(toast.body.clone()), + ) + .when_some(toast.detail.clone(), |card, detail| { + card.child( + div() + .text_size(text::CAPTION) + .text_color(theme.foreground) + .child(detail), + ) + }) + .when_some(toast.problem.clone(), |card, problem| { + card.child( + div() + .debug_selector(move || format!("toast-{key}-problem")) + .text_size(text::CAPTION) + .text_color(theme.danger) + .child(problem), + ) + }) + .when_some(toast.track, |card, track| { + card.child(progress(track, still, theme.accent, theme.divider())) + }) + .when(!toast.actions.is_empty(), |card| card.child(actions)) +} + +/// The family's `.app-update-banner__track`: the accent over a groove. A +/// percent fills from the left; a sweep runs across, or under Reduce +/// Motion stands still at half strength. +fn progress(track: Track, still: bool, accent: Hsla, groove: Hsla) -> Div { + let bar = || div().absolute().top_0().bottom_0().bg(accent); + let groove = div() + .debug_selector(|| "toast-track".into()) + .relative() + .overflow_hidden() + .h(size::TOAST_TRACK) + .w_full() + .bg(groove); + match track { + Track::Percent(percent) => groove.child( + bar() + .left_0() + .w(relative(f32::from(percent.min(100)) / 100.0)), + ), + Track::Sweep if still => { + groove.child(bar().left_0().right_0().opacity(0.5)) + } + Track::Sweep => groove.child(bar().w(relative(SWEEP)).with_animation( + "toast-sweep", + Animation::new(Duration::from_millis(1100)).repeat(), + // From just off the left edge to just off the right. + |bar, t| bar.left(relative((1.0 + SWEEP).mul_add(t, -SWEEP))), + )), + } +} + +/// How much of the track the sweep covers. +const SWEEP: f32 = 0.35; + +/// The family's `.app-update-banner__timer`: along the top edge, as much +/// of it as there is time left. +fn countdown(key: &'static str, left: f32, color: Hsla) -> Div { + div() + .debug_selector(move || format!("toast-{key}-timer")) + .absolute() + .top_0() + .left_0() + .h(size::TOAST_TIMER) + .w(relative(left)) + .bg(color) +} + +fn action_button( + app: &Disktree, + action: &Action, + cx: &Context<'_, Disktree>, +) -> AnyElement { + let id = action_id(action); + let waiting = !app.can_restart_to_update(); + let (label, variant) = match action { + Action::ReleaseNotes(_) => ("Release notes", ButtonVariant::Secondary), + Action::DownloadPage => ("Download page", ButtonVariant::Secondary), + Action::OpenLogs => ("Open Logs", ButtonVariant::Outline), + Action::CheckAgain => ("Try again", ButtonVariant::Outline), + Action::Restart { + restarting: true, .. + } => ("Restarting\u{2026}", ButtonVariant::Primary), + Action::Restart { .. } if waiting => { + ("Restart after the removal", ButtonVariant::Primary) + } + Action::Restart { + switch_back: true, .. + } => ("Restart to switch", ButtonVariant::Primary), + Action::Restart { .. } => ("Restart to update", ButtonVariant::Primary), + Action::Later => ("Later", ButtonVariant::Outline), + Action::Undo => ("Undo", ButtonVariant::Outline), + }; + let disabled = matches!( + action, + Action::Restart { + restarting: true, + .. + } + ) || (matches!(action, Action::Restart { .. }) && waiting); + let action = action.clone(); + button(id, label, variant, cx) + .debug_selector(move || id.into()) + .semantic_disabled(disabled) + .on_click(cx.listener(move |this, _, _, cx| { + if !disabled { + this.run_toast_action(&action, cx); + } + })) + .into_any_element() +} + +#[cfg(test)] +mod tests { + use std::time::SystemTime; + + use super::*; + use crate::updater::Download; + + fn note(key: &'static str, timeout: Option) -> Toast { + Toast { + key, + timeout: timeout.map(Duration::from_secs), + ..Toast::new(Tone::Accent, key, String::new()) + } + } + + fn held(version: &str) -> Held { + Held { + version: version.to_owned(), + file_name: format!("PwrDisk-{version}-full.nupkg"), + slot: Slot::default().key(), + switch_back: false, + } + } + + fn finished(state: &mut State, outcome: Outcome) { + state.checking = false; + state.download = None; + state.finished += 1; + state.last = Some((SystemTime::now(), outcome)); + } + + #[test] + fn a_toast_runs_out_unless_the_pointer_rests_on_it() { + let start = Instant::now(); + let mut toasts = Toasts::default(); + toasts.push(note("a", Some(8)), start); + toasts.push(note("sticky", None), start); + assert_eq!(toasts.next_deadline(), Some(Duration::from_secs(8))); + + toasts.set_hovered(true, start + Duration::from_secs(3)); + assert_eq!(toasts.next_deadline(), None, "paused while hovered"); + // Ten seconds of reading take nothing off, the strip included. + let left = toasts.left("a", start + Duration::from_secs(13)); + assert_eq!(left, Some(5.0 / 8.0)); + toasts.set_hovered(false, start + Duration::from_secs(13)); + assert_eq!(toasts.next_deadline(), Some(Duration::from_secs(5))); + let left = toasts.left("a", start + Duration::from_secs(17)); + assert_eq!(left, Some(1.0 / 8.0), "drains once the pointer leaves"); + assert_eq!(toasts.left("sticky", start), None, "no strip"); + + assert!(toasts.settle(start + Duration::from_secs(18))); + assert!(toasts.get("a").is_none()); + assert!(toasts.get("sticky").is_some(), "no timeout, stays"); + } + + #[test] + fn a_key_replaces_its_toast_and_the_oldest_gives_way() { + let now = Instant::now(); + let mut toasts = Toasts::default(); + toasts.push(note(UPDATE, None), now); + let mut answer = note(UPDATE, Some(8)); + answer.title = "answer".into(); + toasts.push(answer, now); + assert_eq!(toasts.iter().count(), 1); + assert_eq!( + toasts.get(UPDATE).map(|t| t.title.as_str()), + Some("answer") + ); + + for key in ["b", "c", "d"] { + toasts.push(note(key, None), now); + } + let keys: Vec<_> = toasts.iter().map(|toast| toast.key).collect(); + assert_eq!(keys, ["b", "c", "d"]); + assert!(toasts.dismiss("c")); + assert!(!toasts.dismiss("c")); + } + + #[test] + fn only_a_menu_check_raises_a_card_until_a_release_is_ready() { + let mut watch = UpdateWatch::default(); + // The startup check runs and finds nothing: no card. + let mut state = State { + checking: true, + ..State::default() + }; + assert_eq!(watch.follow(state.clone(), None), None); + assert_eq!(watch.live(), None); + finished(&mut state, Outcome::UpToDate("0.14.0".into())); + assert_eq!(watch.follow(state.clone(), None), None); + assert_eq!(watch.offer(), None); + // A background download that lands is offered. + state.held = Some(held("0.15.0")); + watch.follow(state, Some(held("0.15.0"))); + assert_eq!(watch.offer(), Some(&held("0.15.0"))); + } + + #[test] + fn a_menu_check_follows_its_progress_then_settles() { + let mut watch = UpdateWatch::default(); + let slot = Slot::default(); + let mut state = State::default(); + watch.ask(state.finished); + state.checking = true; + assert_eq!(watch.follow(state.clone(), None), None); + assert_eq!(watch.live(), Some(Live::Checking)); + let download = Download { + version: "0.15.0".into(), + switch_back: false, + percent: Some(42), + }; + watch.follow_progress(Some(download)); + assert_eq!( + watch.live(), + Some(Live::Downloading { + version: "0.15.0".into(), + switch_back: false, + percent: Some(42), + }) + ); + let card = live(&watch.live().unwrap()); + assert_eq!(card.body, "PwrDisk 0.15.0 \u{00b7} 42%"); + assert_eq!(card.track, Some(Track::Percent(42))); + assert_eq!(card.timeout, None, "work under way has no countdown"); + + finished(&mut state, Outcome::Failed("timed out".into())); + let outcome = watch.follow(state, None).expect("settles"); + assert_eq!(watch.live(), None); + let failed = answer(&outcome, None, slot).expect("an answer"); + assert_eq!(failed.tone, Tone::Danger); + assert_eq!(failed.body, "Timed out."); + assert_eq!(failed.timeout, Some(ANSWER)); + } + + #[test] + fn a_menu_check_waits_for_the_check_already_running() { + let mut watch = UpdateWatch::default(); + let mut state = State { + checking: true, + finished: 3, + ..State::default() + }; + watch.ask(state.finished); + // The running check has not ended: still waiting. + assert_eq!(watch.follow(state.clone(), None), None); + assert!(watch.is_asking()); + finished(&mut state, Outcome::UpToDate("0.14.0".into())); + assert!(watch.follow(state, None).is_some()); + assert!(!watch.is_asking()); + } + + #[test] + fn later_puts_away_one_release_and_asking_brings_it_back() { + let mut watch = UpdateWatch::default(); + let slot = Slot::default(); + let mut state = State::default(); + watch.ask(state.finished); + finished(&mut state, Outcome::Downloaded("0.15.0".into())); + let ready = held("0.15.0"); + let outcome = watch + .follow(state.clone(), Some(ready.clone())) + .expect("settles"); + assert_eq!( + answer(&outcome, Some(&ready), slot), + None, + "the ready card is the answer" + ); + assert_eq!(watch.offer(), Some(&ready)); + + watch.later(); + assert_eq!(watch.offer(), None, "put away"); + assert_eq!(watch.ready(), Some(&ready), "the chip still offers it"); + // The next background check finds the same download: still down. + finished(&mut state, Outcome::Pending("0.15.0".into())); + watch.follow(state.clone(), Some(ready)); + assert_eq!(watch.offer(), None); + // A newer release comes back up. + finished(&mut state, Outcome::Downloaded("0.15.1".into())); + watch.follow(state.clone(), Some(held("0.15.1"))); + assert_eq!(watch.offer(), Some(&held("0.15.1"))); + // And asking again brings back one put away. + watch.later(); + watch.ask(state.finished); + assert_eq!(watch.offer(), Some(&held("0.15.1"))); + } + + #[test] + fn the_ready_card_says_restarting_and_why_a_restart_failed() { + let ready = held("0.15.0"); + let card = super::ready(&ready, 3, false, None); + assert_eq!(card.title, "Update ready"); + assert_eq!(card.timeout, None, "stays until acted on"); + assert_eq!( + card.detail.as_deref(), + Some("Restarting clears your 3 marks.") + ); + assert_eq!(card.actions.last(), Some(&Action::Later), "Later is last"); + assert_eq!( + card.actions.first(), + Some(&Action::ReleaseNotes("0.15.0".into())) + ); + let pressed = super::ready(&ready, 0, true, None); + assert!(pressed.actions.contains(&Action::Restart { + switch_back: false, + restarting: true + })); + assert_eq!(pressed.detail, None, "nothing marked, nothing to lose"); + let failed = super::ready(&ready, 0, false, Some("no updater")); + assert_eq!( + failed.problem.as_deref(), + Some("Couldn't restart: no updater.") + ); + } + + #[test] + fn answers_say_what_a_check_found() { + let slot = Slot::default(); + let up = + answer(&Outcome::UpToDate("0.14.0".into()), None, slot).unwrap(); + assert_eq!(up.title, "PwrDisk is up to date"); + assert!(up.body.starts_with("0.14.0 is the newest release on ")); + assert_eq!(up.actions, [Action::ReleaseNotes("0.14.0".into())]); + assert_eq!(up.timeout, Some(ANSWER)); + + let dev = + answer(&Outcome::NotInstalled("no manifest".into()), None, slot) + .unwrap(); + assert_eq!(dev.title, "Updates unavailable"); + assert_eq!(dev.actions, [Action::DownloadPage]); + + let none = + answer(&Outcome::NothingPublished("Beta".into()), None, slot) + .unwrap(); + assert_eq!(none.title, "Nothing to install"); + assert!(answer(&Outcome::AlreadyChecking, None, slot).is_none()); + // Downloaded with no ready release (held for another slot) still + // says something. + let other = + answer(&Outcome::Downloaded("0.15.0".into()), None, slot).unwrap(); + assert_eq!(other.title, "Update downloaded"); + // A dev stamp gets no release notes link. + let stamp = + answer(&Outcome::UpToDate("dev".into()), None, slot).unwrap(); + assert!(stamp.actions.is_empty()); + } +} diff --git a/crates/disktree-app/src/toolbar.rs b/crates/disktree-app/src/toolbar.rs new file mode 100644 index 00000000..d54073c7 --- /dev/null +++ b/crates/disktree-app/src/toolbar.rs @@ -0,0 +1,269 @@ +//! How much of the explore bar fits, and the ⋮ menu that holds the rest. +//! +//! The bar folds by what is changed least: the scan options first (they +//! apply on the next scan), then history and depth (which have keys), then +//! Size | Files | Age. The Treemap | List switch never folds. + +use gpui_kit::Context; + +use crate::state::Disktree; + +/// Widest first. Measured in rems, not pixels, so interface zoom walks +/// through the tiers exactly as a narrower window does. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum BarFit { + /// Every control in the bar; no ⋮. + #[default] + Full, + /// Hidden files, Apparent size and the scan workers go in ⋮. + Folded, + /// History and Depth join them. + Narrow, + /// Size | Files | Age too: only the view switch and ⋮ are left. + Tight, +} + +/// At and above this many rems across, the whole bar fits beside a +/// readable trail: the settings take about 51 rem, the stoplights, mark +/// and wordmark about 12, and the trail keeps at least 13. +const FULL_REMS: f32 = 76.0; +/// Below this the side panel gives way too (`PANEL_SHOWN_REMS`); it is +/// where the settings used to wrap onto a second row. +const NARROW_REMS: f32 = 52.0; +/// Below this Size | Files | Age (11 rem) would leave the trail no room. +const TIGHT_REMS: f32 = 40.0; +/// The switch keeps its words down to here; under it, glyphs alone. +const LABELLED_SWITCH_REMS: f32 = 64.0; + +impl BarFit { + pub fn for_width(rems: f32) -> Self { + if rems >= FULL_REMS { + Self::Full + } else if rems >= NARROW_REMS { + Self::Folded + } else if rems >= TIGHT_REMS { + Self::Narrow + } else { + Self::Tight + } + } + + pub fn labelled_switch(rems: f32) -> bool { + rems >= LABELLED_SWITCH_REMS + } + + pub fn shows_scan_options(self) -> bool { + self == Self::Full + } + + pub fn shows_history_and_depth(self) -> bool { + self <= Self::Folded + } + + pub fn shows_mode(self) -> bool { + self <= Self::Narrow + } + + /// The ⋮ menu's rows, top to bottom. The most-used come first, as they + /// would read left to right in a wider bar. + pub fn more_items(self) -> Vec { + let mut items = Vec::new(); + if !self.shows_mode() { + items.extend([MoreItem::Mode(0), MoreItem::Mode(1)]); + items.push(MoreItem::Mode(2)); + } + if !self.shows_history_and_depth() { + items.extend([MoreItem::Back, MoreItem::Forward, MoreItem::Depth]); + } + if !self.shows_scan_options() { + items.extend([ + MoreItem::Hidden, + MoreItem::Apparent, + MoreItem::Workers, + ]); + } + items + } +} + +/// One row of the ⋮ menu. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MoreItem { + /// Size, Files or Age, by its index in the segmented control. + Mode(usize), + Back, + Forward, + /// Depth, adjusted in place with ← → or the row's − and +. + Depth, + Hidden, + Apparent, + /// Opens the Power Efficiency menu in its place. + Workers, +} + +impl MoreItem { + /// The section a row belongs to; a caption opens each. + pub const fn section(self) -> &'static str { + match self { + Self::Mode(_) => "Measure by", + Self::Back | Self::Forward | Self::Depth => "View", + Self::Hidden | Self::Apparent | Self::Workers => "Scan", + } + } +} + +impl Disktree { + /// Treemap or file list. The list takes the keyboard when it appears, so + /// a screen reader lands in it; the treemap gives it back to the root. + pub fn show_file_list(&mut self, on: bool, cx: &mut Context<'_, Self>) { + self.more_menu = None; + if self.file_list != on { + self.file_list = on; + self.pointer_active = false; + } + cx.notify(); + } + + /// Open ⋮ on its first row, or close it. + pub fn toggle_more_menu(&mut self, cx: &mut Context<'_, Self>) { + self.crumb_menu = None; + // The worker presets open in ⋮'s place; ⋮ then closes them. + let was_open = self.more_menu.is_some() || self.power_menu.is_some(); + self.power_menu = None; + self.more_menu = if was_open { + None + } else { + self.next_enabled_more(&self.bar_fit.more_items(), None, true) + }; + cx.notify(); + } + + /// The next row after `from` (or the first, from `None`) that can act, + /// so the highlight never rests on a disabled Back or Forward. + fn next_enabled_more( + &self, + items: &[MoreItem], + from: Option, + forward: bool, + ) -> Option { + let enabled = |&index: &usize| self.more_item_enabled(items[index]); + match (from, forward) { + (None, _) => (0..items.len()).find(enabled), + (Some(at), true) => (at + 1..items.len()).find(enabled), + (Some(at), false) => (0..at).rev().find(enabled), + } + } + + /// Whether a ⋮ row can act now. History rows wait for somewhere to go. + pub fn more_item_enabled(&self, item: MoreItem) -> bool { + match item { + MoreItem::Back => self.can_go_back(), + MoreItem::Forward => self.can_go_forward(), + _ => true, + } + } + + /// Do what a ⋮ row says. Every row but Depth closes the menu. + pub fn activate_more( + &mut self, + item: MoreItem, + cx: &mut Context<'_, Self>, + ) { + if !self.more_item_enabled(item) { + return; + } + if item != MoreItem::Depth { + self.more_menu = None; + } + match item { + MoreItem::Mode(index) => self.set_mode(index, cx), + MoreItem::Back => self.go_back(cx), + MoreItem::Forward => self.go_forward(cx), + MoreItem::Depth => {} + MoreItem::Hidden => self.toggle_hidden(cx), + MoreItem::Apparent => self.toggle_apparent(cx), + MoreItem::Workers => self.toggle_power_menu(cx), + } + cx.notify(); + } + + /// Keys while ⋮ is open, as the sibling and power menus take them. Any + /// other key closes it and goes on to the screen. + pub fn on_more_key( + &mut self, + key: &str, + cx: &mut Context<'_, Self>, + ) -> bool { + let Some(highlighted) = self.more_menu else { + return false; + }; + let items = self.bar_fit.more_items(); + let Some(&item) = items.get(highlighted) else { + self.more_menu = None; + return false; + }; + let step = |forward: bool| { + self.next_enabled_more(&items, Some(highlighted), forward) + .unwrap_or(highlighted) + }; + match key { + "down" | "j" => self.more_menu = Some(step(true)), + "up" | "k" => self.more_menu = Some(step(false)), + "home" => { + self.more_menu = self.next_enabled_more(&items, None, true); + } + "end" => { + self.more_menu = (0..items.len()) + .rev() + .find(|&index| self.more_item_enabled(items[index])); + } + "left" | "h" | "-" if item == MoreItem::Depth => { + self.adjust_depth(-1, cx); + } + "right" | "l" | "+" | "=" if item == MoreItem::Depth => { + self.adjust_depth(1, cx); + } + "enter" | "space" => self.activate_more(item, cx), + "escape" => self.more_menu = None, + _ => { + self.more_menu = None; + cx.notify(); + return false; + } + } + cx.notify(); + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_bar_folds_least_used_first() { + assert_eq!(BarFit::for_width(90.0), BarFit::Full); + assert_eq!(BarFit::for_width(76.0), BarFit::Full); + // 1100 px and the 900 px minimum window, at 100%. + assert_eq!(BarFit::for_width(68.75), BarFit::Folded); + assert_eq!(BarFit::for_width(56.25), BarFit::Folded); + assert_eq!(BarFit::for_width(45.0), BarFit::Narrow); + // The minimum window at 175%. + assert_eq!(BarFit::for_width(32.0), BarFit::Tight); + + assert!(BarFit::Full.more_items().is_empty()); + assert_eq!( + BarFit::Folded.more_items(), + [MoreItem::Hidden, MoreItem::Apparent, MoreItem::Workers] + ); + assert_eq!(BarFit::Narrow.more_items().len(), 6); + assert_eq!(BarFit::Tight.more_items()[0], MoreItem::Mode(0)); + assert_eq!(BarFit::Tight.more_items().len(), 9); + } + + #[test] + fn the_switch_keeps_its_words_down_to_64_rem() { + assert!(BarFit::labelled_switch(68.75)); + assert!(!BarFit::labelled_switch(56.25)); + } +} diff --git a/crates/disktree-app/src/treemap_view.rs b/crates/disktree-app/src/treemap_view.rs index 68410e9e..1f309b10 100644 --- a/crates/disktree-app/src/treemap_view.rs +++ b/crates/disktree-app/src/treemap_view.rs @@ -12,12 +12,13 @@ use std::rc::Rc; use disktree_core::treemap::Rect; +use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::{ App, Bounds, ContentMask, Context, Corners, Edges, Font, FontWeight, Hsla, InteractiveElement as _, IntoElement, MouseDownEvent, MouseMoveEvent, ParentElement as _, Pixels, Point, ScrollWheelEvent, SharedString, Size, - StatefulInteractiveElement as _, Styled, TextAlign, TextRun, Window, - canvas, div, pattern_slash, px, quad, + StatefulInteractiveElement as _, StrikethroughStyle, Styled, TextAlign, + TextRun, Window, canvas, div, pattern_slash, px, quad, underline_y_offset, }; use gpui_omarchy::{ActiveTheme, Theme}; @@ -47,6 +48,8 @@ pub struct TileDeco { pub marked: bool, /// Inside another marked directory, so it goes with its parent. pub covered: bool, + /// Removed since the scan: kept in place, drawn as gone. + pub removed: bool, pub hovered: bool, pub selected: bool, } @@ -76,19 +79,26 @@ pub fn preview( window: &Window, cx: &Context<'_, Disktree>, ) -> impl IntoElement { - use disktree_core::tree::{Node, NodeKind}; + use disktree_core::tree::{Facts, NodeKind, Tree}; use disktree_core::treemap::{LayoutOptions, layout}; - let mut root = Node::directory("preview"); // These are display buckets, never exposed through state.tree/path_at. - for entry in &preview.entries { - let mut node = - Node::entry(entry.name.as_str(), NodeKind::File, entry.bytes); - node.files = entry.files; - root.children.push(node); - } + let root = Tree::build(|builder| { + let buckets = preview + .entries + .iter() + .map(|entry| { + let facts = Facts { + files: entry.files, + ..Facts::entry(NodeKind::File, entry.bytes) + }; + builder.leaf(entry.name.as_str(), facts, None) + }) + .collect(); + builder.directory("preview", Facts::directory(), None, buckets) + }); let area = app.treemap_size.get(); let tiles = layout( - &root, + root.root(), &[], Rect::new(0., 0., area.width.as_f32(), area.height.as_f32()), app.options.metric, @@ -100,19 +110,10 @@ pub fn preview( ); let mut mosaic = Mosaic::default(); for tile in tiles { - let Some(node) = root.resolve(tile.crumbs()) else { + let Some(node) = root.root().resolve(tile.crumbs()) else { continue; }; - mosaic.labels.push(Label { - text: node.name.to_string(), - rect: tile.rect, - header: None, - depth: 0, - dim: false, - marked: false, - size_text: crate::widgets::short_value(node, app.options.metric), - }); - mosaic.tiles.push(TileDeco { + let decoration = TileDeco { rect: tile.rect, depth: 0, category: Category::Other, @@ -122,9 +123,22 @@ pub fn preview( unreadable: false, marked: false, covered: false, + removed: false, hovered: false, selected: false, + }; + mosaic.labels.push(Label { + text: node.name().to_string(), + found: None, + rect: tile.rect, + header: None, + depth: 0, + dim: false, + marked: false, + size_text: crate::widgets::short_value(node, app.options.metric), + decoration: decoration.clone(), }); + mosaic.tiles.push(decoration); } mosaic_inner(mosaic, app, window, cx, false) } @@ -153,6 +167,8 @@ fn mosaic_inner( } = mosaic; let canvas_origin = Rc::clone(&origin); let canvas_measured = Rc::clone(&measured); + // A hand over a tile a click would open: the selection, clicked again. + let opens = interactive && app.click_opens_hovered(); div() .id("disktree-treemap") @@ -163,6 +179,7 @@ fn mosaic_inner( .min_w_0() .overflow_hidden() .bg(theme.inset) + .when(opens, Styled::cursor_pointer) .on_hover(cx.listener(move |this, hovered: &bool, _, cx| { if interactive && !hovered { this.on_mouse_leave(cx); @@ -226,6 +243,7 @@ struct Colors { /// Fills per age bucket, then per depth. age: Vec<[Hsla; DEPTHS]>, marked_fill: Hsla, + removed_fill: Hsla, /// The surface a filtered-out fill steps back toward. inset: Hsla, } @@ -234,7 +252,7 @@ struct Colors { const DEPTHS: usize = 5; /// Every category, in the order [`category_index`] numbers them. -const CATEGORIES: [Category; 9] = [ +const CATEGORIES: [Category; 12] = [ Category::Code, Category::AgentScratch, Category::Toolchain, @@ -243,6 +261,9 @@ const CATEGORIES: [Category; 9] = [ Category::Media, Category::Documents, Category::Cache, + Category::FilesystemEvents, + Category::Spotlight, + Category::VirtualMachine, Category::Other, ]; @@ -263,7 +284,7 @@ impl Colors { palette::label_color(theme, 0), palette::label_color(theme, 1), ], - label_dim: palette::label_color(theme, 1).opacity(0.5), + label_dim: theme.secondary, hover_border: theme.bright.opacity(0.55), selected_border: palette::highlight(theme), marked_border: theme.danger, @@ -288,11 +309,17 @@ impl Colors { }) .collect(), marked_fill: palette::mix(theme.inset, theme.danger, 0.16), + // Almost the surface itself: the space is still drawn where + // the scan found it, but nothing is left there to act on. + removed_fill: palette::mix(theme.inset, theme.secondary, 0.12), inset: theme.inset, } } fn fill(&self, tile: &TileDeco) -> Hsla { + if tile.removed { + return self.removed_fill; + } // Marked, or inside something marked: it all goes together. if tile.marked || tile.covered { return self.marked_fill; @@ -311,6 +338,27 @@ impl Colors { } } + fn label_inks( + &self, + tile: &TileDeco, + dim: bool, + marked: bool, + ) -> (Hsla, Hsla, Hsla) { + let fill = self.fill(tile); + let preferred = if marked { + self.marked_label + } else if dim { + self.label_dim + } else { + self.label(tile.depth) + }; + ( + fill, + palette::ink_on(preferred, fill, 4.5), + palette::ink_on(self.label_dim, fill, 4.5), + ) + } + const fn label(&self, depth: u32) -> Hsla { self.label[if depth == 0 { 0 } else { 1 }] } @@ -331,6 +379,7 @@ fn paint_tiles( // slivers of it showing in the gaps between them. let mut outlines: Vec<(u8, Bounds, f32, Hsla)> = Vec::new(); for tile in tiles { + let fill = colors.fill(tile); let rect = view.project(tile.rect); if rect.w <= 0.5 || rect.h <= 0.5 { continue; @@ -342,7 +391,7 @@ fn paint_tiles( window.paint_quad(quad( quad_bounds, Corners::default(), - colors.fill(tile), + fill, none, colors.hover_border, solid, @@ -355,6 +404,7 @@ fn paint_tiles( if tile.reclaimable && !tile.marked && !tile.covered + && !tile.removed && tile.filtered == Filtered::Shown { window.paint_quad(quad( @@ -372,6 +422,7 @@ fn paint_tiles( if tile.depth == 0 && tile.age_bucket.is_none() && tile.filtered != Filtered::Out + && !tile.removed { let strip = Bounds::new( quad_bounds.origin, @@ -399,26 +450,30 @@ fn paint_tiles( ), Size::new(px(4.), px(4.)), ); + let warning = palette::boundary_on(colors.warning, fill, 3.0); window.paint_quad(quad( mark, Corners::default(), - colors.warning, + warning, none, - colors.warning, + warning, solid, )); } // Ranked so the most important ring is painted last, on top. let outline = if tile.selected { - Some((3, 2.0, colors.selected_border)) + Some((3, 3.0, colors.selected_border)) } else if tile.hovered { Some((2, 1.0, colors.hover_border)) } else if tile.marked { Some((1, 2.0, colors.marked_border)) } else { None - }; + } + .map(|(rank, width, preferred)| { + (rank, width, palette::boundary_on(preferred, fill, 3.0)) + }); if let Some((rank, width, color)) = outline { outlines.push((rank, quad_bounds, width, color)); } @@ -480,6 +535,9 @@ fn paint_labels( let text_inset = name_size * 0.25; let min_width = name_size * 3.3; let size_gap = name_size * 0.67; + // Strike and underline are read as state, so they stay visible at the + // smallest interface zoom rather than thinning to a hairline. + let decoration = (name_size * 0.08).max(px(1.)); for label in labels { // A subdivided directory's name lives in the band it reserved; a leaf's @@ -495,13 +553,8 @@ fn paint_labels( mask.origin.x + text_padding, mask.origin.y + text_inset, ); - let color = if label.marked { - colors.marked_label - } else if label.dim { - colors.label_dim - } else { - colors.label(label.depth) - }; + let (fill, color, value_color) = + colors.label_inks(&label.decoration, label.dim, label.marked); // The first level is set in bold in its band: it names a region. let weight = if label.depth == 0 && label.header.is_some() { FontWeight::BOLD @@ -516,6 +569,14 @@ fn paint_labels( ..font.clone() }, color, + // Glyph backgrounds keep hatch out of both names and values. + background_color: Some(fill), + // Marked, or going with a mark: struck through, the usual sign + // for something on its way out, and one that costs no width. + strikethrough: label.marked.then_some(StrikethroughStyle { + thickness: decoration, + color: Some(color), + }), ..TextRun::default() }; let line = text_system.shape_line( @@ -536,6 +597,36 @@ fn paint_labels( window, cx, ); + // The part of a name the find text matched is underlined, so + // a match reads as one without its colour. Painted here, not + // as a text run's underline: GPUI sets that below the + // baseline, which the slim band of a deeper directory clips + // away. This one rises to stay inside the label's region. + if let Some(found) = label + .found + .clone() + .filter(|found| found.end <= label.text.len()) + { + let left = origin.x + line.x_for_index(found.start); + let right = origin.x + line.x_for_index(found.end); + let top = underline_top( + origin.y + + underline_y_offset( + name_line_height, + line.ascent, + line.descent, + ), + mask.origin.y + mask.size.height, + decoration, + ); + window.paint_quad(gpui_kit::fill( + Bounds::new( + Point::new(left, top), + Size::new(right - left, decoration), + ), + color, + )); + } if label.size_text.is_empty() { return; @@ -544,7 +635,8 @@ fn paint_labels( let size_run = TextRun { len: label.size_text.len(), font: font.clone(), - color: colors.label_dim, + color: value_color, + background_color: Some(fill), ..TextRun::default() }; let size_line = text_system.shape_line( @@ -608,6 +700,12 @@ fn paint_labels( } } +/// The top of a find match's underline: where GPUI would put it, raised +/// as far as needed to stay inside the region the label may draw in. +fn underline_top(natural: Pixels, bottom: Pixels, thickness: Pixels) -> Pixels { + natural.min(bottom - thickness) +} + fn to_window(rect: &Rect, bounds: Bounds) -> Bounds { Bounds::new( Point::new(bounds.origin.x + px(rect.x), bounds.origin.y + px(rect.y)), @@ -618,3 +716,113 @@ fn to_window(rect: &Rect, bounds: Bounds) -> Bounds { fn rem_px(rems: f32, rem_size: Pixels) -> Pixels { px(rems * rem_size.as_f32()) } + +#[cfg(test)] +mod tests { + use super::*; + + /// Exercise the production fill/ink path, including the deeper age ramp, + /// filtered and marked combinations the upstream diagnostic omitted. + #[test] + fn actual_tile_states_keep_text_and_boundaries_readable() { + let mut custom = Theme::flexoki_light(); + custom.bright = gpui_kit::rgb(0x0088_8888).into(); + custom.foreground = custom.bright; + custom.secondary = custom.bright; + custom.warning = custom.bright; + custom.danger = custom.bright; + for theme in [Theme::tokyo_night(), Theme::flexoki_light(), custom] { + let colors = Colors::new(&theme); + for category in CATEGORIES { + for age_bucket in std::iter::once(None).chain((0..5).map(Some)) + { + for depth in 0..=4 { + for filtered in + [Filtered::Shown, Filtered::Holds, Filtered::Out] + { + for (marked, covered, removed) in [ + (false, false, false), + (true, false, false), + (false, true, false), + (false, false, true), + ] { + let tile = TileDeco { + rect: Rect::new(0., 0., 300., 200.), + depth, + category, + age_bucket, + reclaimable: true, + filtered, + unreadable: true, + marked, + covered, + removed, + hovered: true, + selected: true, + }; + let (fill, name, value) = colors.label_inks( + &tile, + filtered == Filtered::Out || removed, + marked || covered, + ); + for ink in [name, value] { + assert!( + palette::contrast(ink, fill) >= 4.5, + "{category:?} age {age_bucket:?} \ + depth {depth} {filtered:?} marked \ + {marked} covered {covered} removed \ + {removed}" + ); + assert!( + (ink.a - 1.0).abs() < f32::EPSILON, + "text never relies on dim alpha" + ); + } + for preferred in [ + colors.selected_border, + colors.hover_border, + colors.marked_border, + colors.warning, + ] { + assert!( + palette::contrast( + palette::boundary_on( + preferred, fill, 3.0 + ), + fill + ) >= 3.0 + ); + } + } + } + } + } + } + let fill = palette::highlight(&theme); + assert!( + palette::contrast(palette::on_highlight(&theme), fill) >= 4.5 + ); + assert!( + palette::contrast( + palette::ink_on(theme.secondary, theme.background, 4.5), + theme.background + ) >= 4.5 + ); + } + } + + /// A slim band would clip GPUI's own underline position, so the + /// underline rises to stay inside; where there is room it is unmoved. + #[test] + fn a_find_underline_stays_inside_its_label() { + assert_eq!(underline_top(px(17.), px(16.), px(1.)), px(15.)); + assert_eq!(underline_top(px(17.), px(22.), px(1.)), px(17.)); + } + + #[test] + fn named_categories_use_their_own_paint_colors() { + for category in Category::LEGEND { + assert_eq!(CATEGORIES[category_index(category)], category); + } + } +} diff --git a/crates/disktree-app/src/ui.rs b/crates/disktree-app/src/ui.rs index c21d0268..35a6af24 100644 --- a/crates/disktree-app/src/ui.rs +++ b/crates/disktree-app/src/ui.rs @@ -66,6 +66,18 @@ pub mod icon { /// Region and lane widths. Each is the comfortable default for its content at /// the default rem; they scale with zoom like everything else. pub mod size { + /// Minimum physical pointer target, also at the smallest UI zoom. + pub const POINTER_TARGET: gpui_kit::Pixels = gpui_kit::px(24.0); + /// How far below the pointer's tip a tooltip starts: past the arrow + /// cursor (about 21 logical pixels on macOS, GNOME and Windows), so it + /// never sits under the pointer or over the row being pointed at. + /// Pixels, not rems: the cursor does not zoom with the UI. + pub const TOOLTIP_CLEARANCE: gpui_kit::Pixels = gpui_kit::px(26.0); + /// Below this height budget, reserve a reading lane instead of repeating + /// the color legend and long action captions in the semantic file list. + pub const FILE_LIST_FULL_DETAILS: Rems = Rems(32.0); + /// One text line plus padding; still 24 logical pixels at 75% zoom. + pub const FILE_ENTRY: Rems = Rems(2.0); use super::Rems; /// A crumb's sibling menu. @@ -75,27 +87,53 @@ pub mod size { /// names are four known words, but wide enough for Drain My Battery /// beside the check, bar and count. pub const POWER_MENU: Rems = Rems(22.0); + /// The Treemap | List glyphs: a little shorter than wide, like a text + /// line's x-height plus ascender, so they sit on the label's centre line. + pub const VIEW_GLYPH_HEIGHT: Rems = Rems(0.625); + /// The treemap glyph's tall tile: just over half its width, as the + /// largest tile in a squarified layout tends to be. + pub const VIEW_GLYPH_TILE: Rems = Rems(0.375); + /// ⋮, the bar's overflow: its longest row is Depth with its stepper. + pub const MORE_MENU: Rems = Rems(16.0); /// One bar of the Power Efficiency gauge. pub const SIGNAL_BAR: Rems = Rems(0.1875); /// A list row's share bar. pub const ROW_BAR: Rems = Rems(5.5); /// A legend or identity swatch. pub const SWATCH: Rems = Rems(0.625); + /// The legend's "+N" menu: room for the longest kind and its size. + pub const LEGEND_MENU: Rems = Rems(13.0); /// A thin meter: share of the scan, the disk. pub const METER: Rems = Rems(0.3125); /// Fixed progress rows keep paths and changing counters from reflowing. pub const PROGRESS_ROW: Rems = Rems(1.375); + /// The scan heading's box and its one line, in `text::FIGURE` type. + /// It clips, so the line must hold the mono font's whole ascent and + /// descent: `JetBrains Mono`, the usual Linux fallback, needs 1.32 em. + pub const SCAN_STATUS: Rems = Rems(2.25); pub const PROGRESS_VALUE: Rems = Rems(9.0); + /// A side panel section's header: its caption eyebrow and total on one + /// line. Fixed, since a pinned header is pushed up by exactly this. + pub const SECTION_HEAD: Rems = Rems(1.25); + + // Checked at build time: the headless tests cannot see a clipped glyph. + const _: () = assert!(SCAN_STATUS.0 >= super::text::FIGURE.0 * 1.32); /// The Size | Files | Age choice in the settings row. pub const RANKING_CHOICE: Rems = Rems(11.0); /// The review screen's summary column. pub const REVIEW_SUMMARY: Rems = Rems(22.5); + /// Exact owner command previews need more room than a short delete alert. + pub const CLEANUP_PREVIEW_WIDTH: Rems = Rems(44.0); + pub const CLEANUP_PREVIEW_HEIGHT_FRACTION: f32 = 0.6; /// The review list's share-bar lane. pub const SHARE_LANE: Rems = Rems(6.0); /// The review list's size lane: right-aligned, so sizes compare. pub const SIZE_LANE: Rems = Rems(5.0); /// The cursor tooltip. pub const TOOLTIP: Rems = Rems(16.75); + /// A figure column of the removal ledger: "-1023.9 GB" in caption + /// type, with room to spare. + pub const LEDGER_FIGURE: Rems = Rems(5.5); /// Source/root chooser, with room for host, path and mount labels. pub const SOURCE_PICKER: Rems = Rems(40.0); pub const SOURCE_LIST_HEIGHT: Rems = Rems(18.0); @@ -103,12 +141,172 @@ pub mod size { pub const SOURCE_VIEWPORT_FRACTION: f32 = 0.92; /// The keyboard overlay. pub const HELP: Rems = Rems(32.5); + /// A toast: PwrDisk's 330 px, a little under the family's 380 to 460, + /// since it sits over the treemap. + pub const TOAST: Rems = Rems(20.625); + /// The answer's countdown strip along a toast's top edge: the family's + /// 2 px. + pub const TOAST_TIMER: Rems = Rems(0.125); + /// A toast's progress track: the family's 4 px. + pub const TOAST_TRACK: Rems = Rems(0.25); /// The key column of the keyboard overlay. pub const KEY_LANE: Rems = Rems(7.0); + /// A document's measure (the changelog): about 90 characters. + pub const DOCUMENT: Rems = Rems(47.5); + /// A changelog bullet's square. + pub const BULLET: Rems = Rems(0.25); + /// Settings: the nav, the panes' measure and a field's label lane. + pub const SETTINGS_NAV: Rems = Rems(12.25); + pub const SETTINGS_PANE: Rems = Rems(47.5); + pub const SETTINGS_LABEL: Rems = Rems(10.0); + /// A pane's lede: the family's 56 characters or so. + pub const SETTINGS_LEDE: Rems = Rems(36.0); + /// A Settings nav row: the family's 28 to 30 px. + pub const SETTINGS_NAV_ROW: Rems = Rems(1.75); + /// The app icon in About's header: the family's 44 px, two lines of + /// the name and build line beside it. + pub const ABOUT_ICON: Rems = Rems(2.75); + /// Logs: the search field's least width, so a query still reads + /// beside its match count and chevrons. + pub const LOG_FILTER: Rems = Rems(16.25); + /// Logs: the line-number gutter, room for five digits. + pub const LOG_GUTTER: Rems = Rems(3.5); + /// Logs: one row of a line, body mono text at 1.67. + pub const LOG_ROW: Rems = Rems(1.25); + /// Logs: a gap row and the mark's row, a little taller than a line so + /// they read as breaks rather than lines. + pub const LOG_GAP: Rems = Rems(1.375); + pub const LOG_MARK: Rems = Rems(1.75); + /// Logs: the Context menu. + pub const LOG_CONTEXT_MENU: Rems = Rems(10.0); + /// Logs: the new-lines pill sits above the selection bar. + pub const LOG_PILL_ABOVE_BAR: Rems = Rems(3.75); + /// The strip's menu button off macOS: as tall as a window button. + pub const MENU_BUTTON: Rems = Rems(1.625); + /// Its dropdown: wide enough for a row and its shortcut. + pub const APP_MENU: Rems = Rems(18.0); + /// The review footer's Export menu: its longest row and its key. + pub const EXPORT_MENU: Rems = Rems(14.0); + pub const APP_MENU_HEIGHT: Rems = Rems(36.0); +} + +/// The title strip across the top of the window. +/// +/// Pixels, not rems: these line up with what the system draws or measures — +/// the macOS stoplights, Windows' caption buttons, a compositor's resize +/// grip — and none of those follow interface zoom. The strip's own contents +/// (the trail, the settings) stay in rems and scale as they always have. +pub mod chrome { + use gpui_kit::{Pixels, px}; + + /// The band's height. Even, so a 14 pt stoplight centres on a whole + /// point; the divider below it is drawn under the band, not inside it. + pub const STRIP: Pixels = px(40.); + /// Where macOS puts the close button, from the window's top-left: + /// 16 in, and `(40 - 14) / 2` down, so the stoplights centre on y=20. + pub const STOPLIGHTS: (f32, f32) = (16., 13.); + /// Room left for the stoplights: they end at x=76, and the brand keeps + /// 20 clear of them. + pub const STOPLIGHT_ZONE: Pixels = px(96.); + /// A Windows caption button: the system's own 46 wide, the strip tall. + pub const CAPTION_BUTTON: Pixels = px(46.); + /// A painted Linux window button, square like the rest of the app. + pub const WINDOW_BUTTON: Pixels = px(24.); + /// The glyph inside either kind of button. + pub const GLYPH: Pixels = px(10.); + /// Each of the two windows in the restore glyph. + pub const GLYPH_BEHIND: Pixels = px(8.); + /// The close cross, a little larger: its strokes are diagonal, so at + /// the same box it reads smaller than the square beside it. + pub const CLOSE_GLYPH: Pixels = px(12.); + /// The app icon beside the wordmark. + pub const MARK: Pixels = px(20.); + /// The wordmark, bold, and as tall as its line so it centres by cap + /// height rather than by the font's ascent. + pub const WORDMARK: Pixels = px(17.); + /// The mark and the wordmark. + pub const LOCKUP_GAP: Pixels = px(8.); + /// The ring a client-side window keeps for its shadow and resize grip. + pub const RESIZE_RING: Pixels = px(10.); } /// Interface zoom steps, as a factor of the 16 px default rem. -pub const ZOOM_STEPS: [f32; 7] = [0.75, 0.875, 1.0, 1.125, 1.25, 1.5, 1.75]; +pub const ZOOM_STEPS: [f32; 8] = + [0.75, 0.875, 1.0, 1.125, 1.25, 1.5, 1.75, 2.0]; /// The default rem, in pixels. pub const BASE_REM: f32 = 16.0; + +/// Below this many rems across (a narrow window, or 200% zoom of a normal +/// one) an auxiliary window drops its wordmark and Settings stacks its panes +/// above the content: a side column and the content no longer both fit. +pub const COMPACT_WINDOW_REMS: f32 = 50.0; + +/// A session-wide scale: existing and newly opened auxiliary windows agree. +/// It is not persisted and never changes an operating-system preference. +struct InterfaceScale(f32); +impl gpui_kit::Global for InterfaceScale {} + +pub fn sync_scale(window: &mut gpui_kit::Window, cx: &gpui_kit::App) -> bool { + let Some(scale) = cx.try_global::() else { + return false; + }; + let rem = BASE_REM * scale.0; + if (window.rem_size().as_f32() - rem).abs() < 0.01 { + return false; + } + window.set_rem_size(gpui_kit::px(rem)); + true +} + +pub fn zoom_interface( + event: &gpui_kit::KeyDownEvent, + window: &mut gpui_kit::Window, + cx: &mut gpui_kit::App, +) -> bool { + let key = &event.keystroke; + if !(key.modifiers.control || key.modifiers.platform) { + return false; + } + let current = window.rem_size().as_f32() / BASE_REM; + let index = ZOOM_STEPS + .iter() + .position(|step| (step - current).abs() < 0.01) + .unwrap_or(2); + let next = match key.key.as_str() { + "=" | "+" => (index + 1).min(ZOOM_STEPS.len() - 1), + "-" => index.saturating_sub(1), + "0" => 2, + _ => return false, + }; + cx.set_global(InterfaceScale(ZOOM_STEPS[next])); + sync_scale(window, cx); + cx.refresh_windows(); + true +} + +/// Keyboard scrolling is explicit, so a virtual/overflow region needs no +/// pointer wheel. Offsets are clamped to the measured content's bounds. +pub fn scroll_key( + key: &str, + scroll: &gpui_kit::ScrollHandle, + rem: gpui_kit::Pixels, +) -> bool { + let mut offset = scroll.offset(); + let page = scroll.bounds().size.height * 0.8; + offset.y = match key { + "up" => offset.y + rem * 2.0, + "down" => offset.y - rem * 2.0, + "pageup" => offset.y + page, + "pagedown" => offset.y - page, + "home" => gpui_kit::px(0.0), + "end" => -scroll.max_offset().y, + _ => return false, + } + .clamp( + -scroll.max_offset().y.max(gpui_kit::px(0.0)), + gpui_kit::px(0.0), + ); + scroll.set_offset(offset); + true +} diff --git a/crates/disktree-app/src/update_channel.rs b/crates/disktree-app/src/update_channel.rs new file mode 100644 index 00000000..46194bca --- /dev/null +++ b/crates/disktree-app/src/update_channel.rs @@ -0,0 +1,513 @@ +//! Which release a copy updates to: the Pwr family's release channel, +//! ported from `PwrRoute` so every app in the family reads tags alike. +//! +//! Two trains, two tracks, four slots: +//! +//! | Slot | Example tag | What it is | +//! | ------------------- | ------------------------- | ----------------------------------- | +//! | Stable · Latest | `v0.1.0` (promoted) | Smoke-checked; the default | +//! | Stable · Prerelease | `v0.1.1` staged, `-rc.1` | Candidates for the stable line | +//! | Beta · Latest | `v0.2.0-beta.3` | Beta builds off main | +//! | Beta · Prerelease | `v0.2.0-alpha.7` | Newest alpha off main; may not work | +//! +//! Every CI release is born a GitHub Pre-release and promoted to Latest by +//! hand (`gh release edit vX.Y.Z --latest --prerelease=false`). Until it is +//! promoted, a suffix-free tag is offered to the Prerelease slots only, so +//! Stable · Latest keeps the previous promoted release. +//! +//! The slot follows the installed build ([`infer`]) until the user picks one +//! in Settings › Updates ([`UpdateSettings::resolve`]). [`select`] picks each +//! slot's release from the published list, by `SemVer` precedence, never by +//! publish date. Nothing here touches the network. + +use std::fmt; + +use semver::Version; +use serde::{Deserialize, Serialize}; + +/// The version line: the smoke-checked releases, or builds off main. +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, +)] +#[serde(rename_all = "camelCase")] +pub enum Train { + #[default] + Stable, + Beta, +} + +/// Within a train: the smoke-checked build, or the newest one. +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, +)] +#[serde(rename_all = "camelCase")] +pub enum Track { + #[default] + Latest, + Prerelease, +} + +/// One of the four choices. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct Slot { + pub train: Train, + pub track: Track, +} + +impl Slot { + pub const STABLE_LATEST: Self = Self::new(Train::Stable, Track::Latest); + pub const STABLE_PRERELEASE: Self = + Self::new(Train::Stable, Track::Prerelease); + pub const BETA_LATEST: Self = Self::new(Train::Beta, Track::Latest); + pub const BETA_PRERELEASE: Self = Self::new(Train::Beta, Track::Prerelease); + /// In the order Settings lays them out: by train, then by track. + pub const ALL: [Self; 4] = [ + Self::STABLE_LATEST, + Self::STABLE_PRERELEASE, + Self::BETA_LATEST, + Self::BETA_PRERELEASE, + ]; + + /// Where this slot sits in [`Slot::ALL`]: its row in the Updates panel. + pub fn index(self) -> usize { + Self::ALL + .iter() + .position(|&slot| slot == self) + .unwrap_or_default() + } + + pub const fn new(train: Train, track: Track) -> Self { + Self { train, track } + } + + /// "stable:latest": what a download is recorded against. + pub fn key(self) -> String { + format!( + "{}:{}", + match self.train { + Train::Stable => "stable", + Train::Beta => "beta", + }, + match self.track { + Track::Latest => "latest", + Track::Prerelease => "prerelease", + } + ) + } + + /// The inverse of [`Slot::key`]. + pub fn from_key(key: &str) -> Option { + Self::ALL.into_iter().find(|slot| slot.key() == key) + } +} + +/// "Stable · Latest". +impl fmt::Display for Slot { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let train = match self.train { + Train::Stable => "Stable", + Train::Beta => "Beta", + }; + let track = match self.track { + Track::Latest => "Latest", + Track::Prerelease => "Prerelease", + }; + write!(f, "{train} \u{00b7} {track}") + } +} + +/// Whether the slot was picked in Settings or follows the installed build. +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, +)] +#[serde(rename_all = "camelCase")] +pub enum SelectionSource { + /// Re-derived from the running build every time it is read, so + /// installing an alpha over a stable build moves the feed with it. + #[default] + Inferred, + /// Picked in Settings › Updates; kept until another pick. + User, +} + +/// `settings.json`'s `updates`: the slot the user picked, if any. +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, +)] +#[serde(rename_all = "camelCase", default)] +pub struct UpdateSettings { + #[serde(skip_serializing_if = "Option::is_none")] + pub train: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub channel: Option, + pub selection_source: SelectionSource, +} + +impl UpdateSettings { + /// A pick in Settings: both axes, kept. + pub const fn picked(slot: Slot) -> Self { + Self { + train: Some(slot.train), + channel: Some(slot.track), + selection_source: SelectionSource::User, + } + } + + /// The slot in force for a copy at `installed`: the user's pick, each + /// axis falling back to its default on its own, or the one the build + /// implies. + pub fn resolve(self, installed: &str) -> Slot { + match self.selection_source { + SelectionSource::User => Slot::new( + self.train.unwrap_or_default(), + self.channel.unwrap_or_default(), + ), + SelectionSource::Inferred => infer(installed), + } + } + + /// The slot follows the build, rather than a pick. + pub const fn is_inferred(self) -> bool { + matches!(self.selection_source, SelectionSource::Inferred) + } +} + +/// The slot a build at `version` belongs to, by its prerelease suffix: +/// none is Stable · Latest, `-alpha` Beta · Prerelease, `-beta` Beta · +/// Latest, and anything else (`-rc`, `-prerelease`) Stable · Prerelease. A +/// version that does not parse is Stable · Latest. +pub fn infer(version: &str) -> Slot { + let Some(version) = parse(version) else { + return Slot::STABLE_LATEST; + }; + match pre0(&version).as_deref() { + None => Slot::STABLE_LATEST, + Some("alpha") => Slot::BETA_PRERELEASE, + Some("beta") => Slot::BETA_LATEST, + Some(_) => Slot::STABLE_PRERELEASE, + } +} + +/// A published release, as far as choosing one goes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Release { + /// "v0.1.0". + pub tag: String, + /// GitHub's Pre-release flag: not promoted yet. + pub prerelease: bool, +} + +impl Release { + pub fn new(tag: impl Into, prerelease: bool) -> Self { + Self { + tag: tag.into(), + prerelease, + } + } + + /// The tag as `SemVer`, without its `v`. + pub fn version(&self) -> Option { + parse(&self.tag) + } +} + +/// `version`, with or without a leading `v`, as `SemVer`. +pub fn parse(version: &str) -> Option { + Version::parse(version.trim().trim_start_matches('v')).ok() +} + +/// The first prerelease identifier, lowercased: "alpha" for `-alpha.7`. +fn pre0(version: &Version) -> Option { + let pre = version.pre.as_str(); + (!pre.is_empty()).then(|| { + pre.split('.') + .next() + .unwrap_or_default() + .to_ascii_lowercase() + }) +} + +const fn core(version: &Version) -> (u64, u64, u64) { + (version.major, version.minor, version.patch) +} + +/// The release each slot resolves to, from `releases` (drafts and releases +/// without this platform's update feed already left out). A slot with no +/// release is `None`. +pub fn select(releases: &[Release], slot: Slot) -> Option { + let parsed: Vec<(Version, &Release)> = releases + .iter() + .filter_map(|release| Some((release.version()?, release))) + .collect(); + let highest = |keep: &dyn Fn(&Version, &Release) -> bool| { + parsed + .iter() + .filter(|(version, release)| keep(version, release)) + .max_by(|a, b| a.0.cmp(&b.0)) + .map(|(version, release)| (version.clone(), *release)) + }; + // The promoted release. A suffix-free tag first, so a suffixed tag + // promoted by mistake cannot take the slot while a real one exists. + let stable_latest = highest(&|v, r| !r.prerelease && v.pre.is_empty()) + .or_else(|| highest(&|_, r| !r.prerelease)); + let stable_core = stable_latest.as_ref().map(|(v, _)| core(v)); + let stable_final = stable_latest + .as_ref() + .filter(|(v, _)| v.pre.is_empty()) + .cloned(); + let is_beta_train = |v: &Version, r: &Release| { + let pre = pre0(v); + r.prerelease + && matches!(pre.as_deref(), Some("alpha" | "beta")) + && match stable_core { + // Ahead of the promoted line, or it is that line's past. + Some(stable) => core(v) > stable, + None => { + pre.as_deref() == Some("alpha") + || parsed.iter().any(|(other, other_release)| { + other_release.prerelease + && core(other) == core(v) + && pre0(other).as_deref() == Some("alpha") + }) + } + } + }; + let is_beta_latest = |v: &Version, r: &Release| { + pre0(v).as_deref() == Some("beta") && is_beta_train(v, r) + }; + let ahead_of_stable = + |v: &Version| stable_latest.as_ref().is_none_or(|(s, _)| v > s); + let is_stable_candidate_ahead = |v: &Version, r: &Release| { + r.prerelease + && ahead_of_stable(v) + && matches!(pre0(v).as_deref(), None | Some("prerelease" | "rc")) + }; + let chosen = match (slot.train, slot.track) { + (Train::Stable, Track::Latest) => stable_latest, + // Staged finals, -rc, -prerelease and the like; never an alpha or a + // beta-train build, and never below the promoted release. + (Train::Stable, Track::Prerelease) => at_least( + highest(&|v, r| { + r.prerelease + && pre0(v).as_deref() != Some("alpha") + && !is_beta_latest(v, r) + }), + stable_latest, + ), + (Train::Beta, Track::Latest) => { + highest(&is_beta_latest).or(stable_final) + } + (Train::Beta, Track::Prerelease) => at_least( + highest(&|v, r| { + is_beta_train(v, r) || is_stable_candidate_ahead(v, r) + }), + stable_final, + ), + }; + chosen.map(|(_, release)| release.clone()) +} + +/// The higher of the two, by precedence. +fn at_least<'a>( + candidate: Option<(Version, &'a Release)>, + floor: Option<(Version, &'a Release)>, +) -> Option<(Version, &'a Release)> { + match (candidate, floor) { + (Some(c), Some(f)) => Some(if c.0 >= f.0 { c } else { f }), + (c, f) => c.or(f), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn promoted(tag: &str) -> Release { + Release::new(tag, false) + } + + fn pre(tag: &str) -> Release { + Release::new(tag, true) + } + + fn tags(releases: &[Release]) -> [Option; 4] { + Slot::ALL.map(|slot| select(releases, slot).map(|r| r.tag)) + } + + #[allow( + clippy::unnecessary_wraps, + reason = "reads as the `Some` each slot is compared against" + )] + fn some(tag: &str) -> Option { + Some(tag.to_owned()) + } + + #[test] + fn the_build_implies_its_slot() { + assert_eq!(infer("0.1.0"), Slot::STABLE_LATEST); + assert_eq!(infer("v1.2.3"), Slot::STABLE_LATEST); + assert_eq!(infer("0.1.0-rc.3"), Slot::STABLE_PRERELEASE); + assert_eq!(infer("0.1.1-prerelease.1"), Slot::STABLE_PRERELEASE); + assert_eq!(infer("0.2.0-beta.3"), Slot::BETA_LATEST); + assert_eq!(infer("0.2.0-alpha.7"), Slot::BETA_PRERELEASE); + assert_eq!(infer("0.0.1-Alpha.0"), Slot::BETA_PRERELEASE); + assert_eq!(infer("0.2.0-nightly.1"), Slot::STABLE_PRERELEASE); + assert_eq!(infer("not a version"), Slot::STABLE_LATEST); + } + + #[test] + fn a_pick_is_kept_and_an_inferred_slot_follows_the_build() { + let inferred = UpdateSettings::default(); + assert!(inferred.is_inferred()); + assert_eq!(inferred.resolve("0.1.0-rc.3"), Slot::STABLE_PRERELEASE); + assert_eq!(inferred.resolve("0.1.0"), Slot::STABLE_LATEST); + let picked = UpdateSettings::picked(Slot::BETA_PRERELEASE); + assert!(!picked.is_inferred()); + assert_eq!(picked.resolve("0.1.0"), Slot::BETA_PRERELEASE); + // A half pick falls back per axis. + let half = UpdateSettings { + train: Some(Train::Beta), + channel: None, + selection_source: SelectionSource::User, + }; + assert_eq!(half.resolve("0.1.0-alpha.1"), Slot::BETA_LATEST); + } + + #[test] + fn the_settings_read_and_write_back_as_the_siblings_store_them() { + let picked = UpdateSettings::picked(Slot::STABLE_PRERELEASE); + let json = serde_json::to_value(picked).unwrap(); + assert_eq!( + json, + serde_json::json!({ + "train": "stable", + "channel": "prerelease", + "selectionSource": "user" + }) + ); + assert_eq!( + serde_json::from_value::(serde_json::json!({})) + .unwrap(), + UpdateSettings::default() + ); + for slot in Slot::ALL { + assert_eq!(Slot::from_key(&slot.key()), Some(slot)); + } + assert_eq!(Slot::BETA_LATEST.to_string(), "Beta \u{00b7} Latest"); + } + + #[test] + fn a_staged_final_waits_for_promotion_on_stable_latest() { + // v0.1.0 is published (born a Pre-release) over the rc line, and + // nothing has been promoted yet. + let releases = [pre("v0.1.0"), pre("v0.1.0-rc.3"), pre("v0.1.0-rc.2")]; + assert_eq!( + tags(&releases), + [None, some("v0.1.0"), None, some("v0.1.0")] + ); + // Promoted: every slot but the beta ones' own builds has it. + let releases = [promoted("v0.1.0"), pre("v0.1.0-rc.3")]; + assert_eq!( + tags(&releases), + [ + some("v0.1.0"), + some("v0.1.0"), + some("v0.1.0"), + some("v0.1.0") + ] + ); + // The next final staged: Stable · Latest keeps the promoted one. + let releases = [pre("v0.1.1"), promoted("v0.1.0")]; + assert_eq!( + tags(&releases), + [ + some("v0.1.0"), + some("v0.1.1"), + some("v0.1.0"), + some("v0.1.1") + ] + ); + } + + #[test] + fn each_train_takes_its_own_builds() { + // The next line's alphas, this line's betas. + let releases = [ + pre("v0.3.0-alpha.7"), + pre("v0.2.0-beta.3"), + pre("v0.1.1-rc.1"), + promoted("v0.1.0"), + pre("v0.1.0-rc.3"), + ]; + assert_eq!( + tags(&releases), + [ + some("v0.1.0"), + some("v0.1.1-rc.1"), + some("v0.2.0-beta.3"), + some("v0.3.0-alpha.7"), + ] + ); + // Within one line a beta comes after its alphas. + let releases = [ + pre("v0.2.0-alpha.7"), + pre("v0.2.0-beta.3"), + promoted("v0.1.0"), + ]; + assert_eq!(tags(&releases)[3], some("v0.2.0-beta.3")); + // Precedence, not publish order: a newer alpha listed last wins. + let releases = [ + pre("v0.2.0-alpha.2"), + promoted("v0.1.0"), + pre("v0.2.0-alpha.10"), + ]; + assert_eq!(tags(&releases)[3], some("v0.2.0-alpha.10")); + } + + #[test] + fn a_promoted_line_retires_its_betas() { + // v0.2.0 promoted: the leftover v0.2.0 betas and alphas are its + // past, and Beta falls back to the release. + let releases = [ + promoted("v0.2.0"), + pre("v0.2.0-beta.3"), + pre("v0.2.0-alpha.7"), + promoted("v0.1.0"), + ]; + assert_eq!( + tags(&releases), + [ + some("v0.2.0"), + some("v0.2.0"), + some("v0.2.0"), + some("v0.2.0") + ] + ); + } + + #[test] + fn a_mis_promoted_suffix_does_not_take_stable_latest() { + let releases = [promoted("v0.2.0-alpha.1"), promoted("v0.1.0")]; + assert_eq!(tags(&releases)[0], some("v0.1.0")); + // With no suffix-free release promoted at all, it is all there is. + assert_eq!( + select(&[promoted("v0.2.0-alpha.1")], Slot::STABLE_LATEST) + .map(|r| r.tag), + some("v0.2.0-alpha.1") + ); + } + + #[test] + fn nothing_published_leaves_a_slot_empty_and_bad_tags_are_skipped() { + assert_eq!(tags(&[]), [None, None, None, None]); + // A release candidate is offered to both Prerelease slots. + let releases = [pre("nightly"), pre("v0.1.0-rc.1")]; + assert_eq!( + tags(&releases), + [None, some("v0.1.0-rc.1"), None, some("v0.1.0-rc.1")] + ); + // Before any stable release, an alpha line is the beta train. + let releases = [pre("v0.0.1-alpha.3")]; + assert_eq!(tags(&releases), [None, None, None, some("v0.0.1-alpha.3")]); + } +} diff --git a/crates/disktree-app/src/updater.rs b/crates/disktree-app/src/updater.rs new file mode 100644 index 00000000..5b77a6dd --- /dev/null +++ b/crates/disktree-app/src/updater.rs @@ -0,0 +1,1223 @@ +//! Installs and updates through Velopack, ported from `PwrRoute`. +//! +//! [`run_startup_hooks`] is Velopack's startup logic, which every Velopack +//! app runs before anything else. [`check_in_background`] asks GitHub +//! Releases for a newer version, at startup, every [`CHECK_EVERY`] and from +//! the Updates panel, and downloads it into Velopack's package cache. +//! +//! A downloaded package is never applied at launch: Velopack's startup +//! apply would install whatever it downloaded last, including a package +//! held for a channel the user has since left. The package is applied when +//! PwrDisk quits, by any route ([`install`] hooks the app's quit), or when +//! the user asks for it (the panel's Restart to update, +//! [`restart_to_update`]). +//! +//! Only a copy Velopack installed can update. `cargo run`, `make install` +//! and the Linux tarball have no Velopack manifest, so their check says so +//! and stops. +//! +//! Which release: the slot of the release channel in force +//! ([`crate::update_channel`]), the Pwr family's Stable or Beta × Latest or +//! Prerelease. A check reads the published list +//! ([`crate::github_releases`]), picks the slot's release, and points +//! Velopack at that one release's files. A release older than this copy is +//! a switch back: only Check now downloads one, and it installs only from +//! Restart to switch, never on quit. A download is recorded with its slot +//! ([`Held`], `update-download.json` beside the other settings); after +//! another slot is picked it is neither shown nor installed. +//! +//! What a check found is kept in [`state`] for the Updates panel and the +//! main window's notices (`toasts.rs`), which [`install`] tells when it +//! changes. A download's percent is a [`Change::Progress`]: only what draws +//! progress follows it, so Settings is not rebuilt a hundred times a +//! download. Apart from the channel and the held download nothing is +//! persisted, so a fresh launch starts at "not checked yet". + +use std::{ + cmp::Ordering as Precedence, + fmt, fs, + path::{Path, PathBuf}, + sync::{ + Mutex, OnceLock, PoisonError, + atomic::{AtomicBool, Ordering}, + }, + thread, + time::{Duration, SystemTime}, +}; + +use gpui_kit::App; +use serde::{Deserialize, Serialize}; + +use velopack::{ + UpdateCheck, UpdateManager, UpdateOptions, VelopackApp, VelopackAsset, + locator::{self, LocationContext, VelopackLocator}, + sources::{HttpSource, NoneSource}, +}; + +use crate::github_releases; +use crate::update_channel::{self, Release, Slot, UpdateSettings}; + +/// The held download's record, beside the other settings. +const HELD_FILE: &str = "update-download.json"; +/// The release channel the user picked, beside the other settings. +const CHANNEL_FILE: &str = "update-channel.json"; + +/// How often a running copy checks again after the startup check: the +/// family's "at startup and every 6 hours while running". A Velopack +/// install only; a dev build has nothing to check. +pub const CHECK_EVERY: Duration = Duration::from_hours(6); + +/// One check at a time: a second "Check for Updates…" while the startup +/// check is still downloading would only contend for Velopack's lock. +static CHECKING: AtomicBool = AtomicBool::new(false); + +/// A restart to update is under way: a second press waits for it. +static RESTARTING: AtomicBool = AtomicBool::new(false); + +/// A check asked for while one was running, to run when it ends. +static AGAIN: Mutex> = Mutex::new(None); + +/// What [`run_startup_hooks`] tells Velopack, apart from the hooks. Kept +/// as data so a test can hold the policy without a Velopack install. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct StartupPolicy { + /// Apply a downloaded package at launch, swapping it in and restarting + /// the process. Velopack's default is `true`; PwrDisk's is `false`, so + /// the held download's channel decides what installs (see the module + /// docs). + pub auto_apply: bool, +} + +/// The policy PwrDisk runs with. +pub const STARTUP: StartupPolicy = StartupPolicy { auto_apply: false }; + +/// Velopack's startup logic. Call it first in `main`, before the window. +/// +/// Setup, updates and the uninstaller start `pwrdisk.exe` with a hook +/// argument; this runs that hook and exits the process. Otherwise it +/// returns at once, also for builds Velopack did not install, and also +/// when an update was downloaded on a previous run: that waits for Quit or +/// Restart to update ([`STARTUP`]). +pub fn run_startup_hooks() { + startup_hooks(STARTUP).run(); +} + +/// The builder behind [`run_startup_hooks`]: `policy`, and no hooks of +/// PwrDisk's own: it registers nothing with the system on install, so there +/// is nothing to undo on uninstall. +fn startup_hooks(policy: StartupPolicy) -> VelopackApp<'static> { + VelopackApp::build().set_auto_apply_on_startup(policy.auto_apply) +} + +/// What quitting did about a downloaded update. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum QuitApply { + /// Nothing downloaded, or not a Velopack install: a plain quit. + Nothing, + /// Velopack's updater is waiting for this process to exit, and then + /// swaps `version` in without starting PwrDisk again. + Applying(String), + /// A package was downloaded but the updater could not be started; it + /// stays downloaded for the next quit or Restart to update. + Failed(String), +} + +/// Applies a downloaded update once this process has exited. [`install`] +/// runs it as the app quits, by any route: the menu, `q`, closing the +/// window. The updater waits for the exit on its own, so this returns at +/// once and the quit goes on; PwrDisk is not started again, and the next +/// launch is the new version. +fn apply_pending_on_quit() { + if !first_hand_off(&HANDED_OFF) { + return; + } + match apply_pending() { + QuitApply::Nothing => {} + QuitApply::Applying(version) => { + log::info!("updates: installing {version} after this quit"); + } + QuitApply::Failed(why) => { + log::warn!( + "updates: could not install the downloaded update: {why}" + ); + } + } +} + +/// Whether this process has handed a downloaded update to Velopack. +static HANDED_OFF: AtomicBool = AtomicBool::new(false); + +/// True the first time only. Two updaters waiting on the same exit each +/// replace the installed app, racing for Velopack's lock on the packages +/// directory; one is all a quit needs. +fn first_hand_off(handed_off: &AtomicBool) -> bool { + !handed_off.swap(true, Ordering::SeqCst) +} + +fn apply_pending() -> QuitApply { + // The manager locates the manifest itself and refuses a copy Velopack + // did not install; no feed is read here. + let Ok(locator) = + locator::auto_locate_app_manifest(LocationContext::FromCurrentExe) + else { + return QuitApply::Nothing; + }; + let Ok(manager) = UpdateManager::new(NoneSource {}, None, None) else { + return QuitApply::Nothing; + }; + let installed = locator.get_manifest_version().to_string(); + let slot = selection().resolve(&installed); + let held = load_held().filter(|held| package_exists(&locator, held)); + let pending = match &held { + Some(held) => quit_package(&installed, slot, held).map(Held::asset), + // Nothing recorded: a package an earlier build downloaded, which + // only ever fetched its own channel's newer releases. + None => manager.get_update_pending_restart(), + }; + on_quit(pending, |pending| { + manager + // Silent: no progress window over a quit, and no restart. + .wait_exit_then_apply_updates(pending, true, false, Vec::::new()) + .map_err(|e| e.to_string()) + }) +} + +/// The quit path's branch: `apply` runs only for a downloaded package. +fn on_quit( + pending: Option, + apply: impl FnOnce(&VelopackAsset) -> Result<(), String>, +) -> QuitApply { + let Some(pending) = pending else { + return QuitApply::Nothing; + }; + match apply(&pending) { + Ok(()) => QuitApply::Applying(pending.Version), + Err(why) => QuitApply::Failed(why), + } +} + +/// What asked for the check, for the log line. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Trigger { + Startup, + /// Every [`CHECK_EVERY`] while running. + Timer, + /// Check now, from the Updates panel or "Check for Updates…". + Manual, + /// Another slot was picked in the Updates panel. + Selection, +} + +impl Trigger { + /// Check now: the one check that may switch back to an older release. + pub const fn is_manual(self) -> bool { + matches!(self, Self::Manual) + } +} + +/// What the updater has said so far this launch. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct State { + /// A check is running now. + pub checking: bool, + /// The last check that finished, and when. + pub last: Option<(SystemTime, Outcome)>, + /// The published releases the last check read, or why it could not. + pub releases: Option, String>>, + /// The package downloaded and not installed yet, and its slot. + pub held: Option, + /// The download running now, if the check found one to fetch. + pub download: Option, + /// How many checks have finished this launch: Check for Updates… + /// waits for the next one (`toasts.rs`). + pub finished: u64, + /// Restart to update was pressed and has not failed: the process is + /// about to be replaced ([`restart_in_background`]). + pub restarting: bool, + /// Why the last restart to update did not happen, until the next try. + pub restart_failed: Option, +} + +/// A download in progress. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Download { + /// Velopack's version: "0.1.1". + pub version: String, + /// Older than this copy: Restart to switch installs it. + pub switch_back: bool, + /// 0-100, once Velopack has said. + pub percent: Option, +} + +/// What moved in [`state`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Change { + /// A check started or finished, a download landed, a restart began or + /// failed, or the channel changed: everything that reads the state + /// redraws. + State, + /// Only [`State::download`]: a download began or its percent moved. + /// Only what draws progress follows it. + Progress, +} + +static STATE: Mutex = Mutex::new(State { + checking: false, + last: None, + releases: None, + held: None, + download: None, + finished: 0, + restarting: false, + restart_failed: None, +}); + +/// The release channel as `update-channel.json` has it; [`set_selection`] +/// keeps it current. `None` until the file is read: the defaults. +static SELECTION: Mutex> = Mutex::new(None); + +/// The release channel in force: picked, or following the build. +pub fn selection() -> UpdateSettings { + SELECTION + .lock() + .unwrap_or_else(PoisonError::into_inner) + .unwrap_or_default() +} + +/// Follows `settings` from now on, and saves them in `dir` (normally +/// [`settings_dir`]). When the slot in force changes, the new slot is +/// checked at once, forward only, and the window redrawn: a download held +/// for the old slot is neither shown nor installed now. Says why when the +/// pick could not be saved; it holds for this session either way. +pub fn set_selection( + settings: UpdateSettings, + dir: Option<&Path>, +) -> Result<(), String> { + let installed = installed_version(); + let before = selection().resolve(&installed); + *SELECTION.lock().unwrap_or_else(PoisonError::into_inner) = Some(settings); + if settings.resolve(&installed) != before { + check_in_background(Trigger::Selection); + } + set_state(|_| {}); + let path = dir + .ok_or("there is no settings folder to save it in")? + .join(CHANNEL_FILE); + write_json(&path, &settings).map_err(|error| error.to_string()) +} + +fn load_selection() -> Option { + let text = fs::read_to_string(settings_dir()?.join(CHANNEL_FILE)).ok()?; + serde_json::from_str(&text).ok() +} + +/// The version this copy reports: Velopack's manifest, else the crate's. +pub fn installed_version() -> String { + match installation() { + Installation::Velopack { version } => version, + Installation::NotInstalled { .. } => { + env!("CARGO_PKG_VERSION").to_owned() + } + } +} + +/// Wakes [`install`]'s task after every change to [`state`]. +static CHANGED: OnceLock> = OnceLock::new(); + +/// Where the channel and the held download are kept: PwrDisk's settings +/// folder, beside the Power Efficiency preset. +pub fn settings_dir() -> Option { + crate::power::settings_path()? + .parent() + .map(Path::to_path_buf) +} + +/// The download running now: what a progress tick changed, without +/// cloning the rest of the state. +pub fn download() -> Option { + STATE + .lock() + .unwrap_or_else(PoisonError::into_inner) + .download + .clone() +} + +/// The updater's state as it stands. +pub fn state() -> State { + STATE.lock().unwrap_or_else(PoisonError::into_inner).clone() +} + +fn set_state(edit: impl FnOnce(&mut State)) { + changed(Change::State, edit); +} + +/// [`set_state`] for the download's percent: wakes only what draws it. +fn set_progress(edit: impl FnOnce(&mut Option)) { + changed(Change::Progress, |state| edit(&mut state.download)); +} + +fn changed(change: Change, edit: impl FnOnce(&mut State)) { + edit(&mut STATE.lock().unwrap_or_else(PoisonError::into_inner)); + if let Some(changed) = CHANGED.get() { + let _ = changed.try_send(change); + } +} + +/// Reads the saved channel, runs `changed` (which redraws the window) +/// whenever the state moves, saying how, checks again every +/// [`CHECK_EVERY`] on a Velopack install, and applies a downloaded update +/// when the app quits. Call once, after the window is open. +pub fn install(cx: &App, changed: impl Fn(Change, &mut App) + 'static) { + let (tx, rx) = async_channel::unbounded::(); + if CHANGED.set(tx).is_err() { + return; + } + if let Some(settings) = load_selection() { + *SELECTION.lock().unwrap_or_else(PoisonError::into_inner) = + Some(settings); + } + if let Some(held) = load_held() { + set_state(|state| state.held = Some(held)); + } + cx.on_app_quit(|_| { + apply_pending_on_quit(); + async {} + }) + .detach(); + cx.spawn(async move |cx| { + while let Ok(change) = rx.recv().await { + cx.update(|cx| changed(change, cx)); + } + }) + .detach(); + if let Some(every) = check_every(&installation()) { + cx.spawn(async move |cx| { + loop { + cx.background_executor().timer(every).await; + check_in_background(Trigger::Timer); + } + }) + .detach(); + } +} + +/// How often `installation` checks again on its own: [`CHECK_EVERY`] for +/// a Velopack install, never for a copy that cannot update itself. +pub const fn check_every(installation: &Installation) -> Option { + match installation { + Installation::Velopack { .. } => Some(CHECK_EVERY), + Installation::NotInstalled { .. } => None, + } +} + +/// Where this copy came from, as far as Velopack can tell without the +/// network: its manifest version, or why there is none. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Installation { + /// Velopack installed this copy at `version`; it can update itself. + Velopack { version: String }, + /// No Velopack manifest: `cargo run`, `make install` or the tarball. + NotInstalled { why: String }, +} + +/// Reads the manifest beside the executable. Local files only. +/// Read once: an update replaces this process rather than changing its +/// manifest under it, and the Updates panel asks on every frame it draws. +pub fn installation() -> Installation { + static INSTALLATION: OnceLock = OnceLock::new(); + INSTALLATION + .get_or_init(|| { + match locator::auto_locate_app_manifest( + LocationContext::FromCurrentExe, + ) { + Ok(locator) => Installation::Velopack { + version: locator.get_manifest_version().to_string(), + }, + Err(error) => Installation::NotInstalled { + why: error.to_string(), + }, + } + }) + .clone() +} + +/// Check for an update, and download it, on a thread of its own: Velopack's +/// client blocks, and a download can take a while. +pub fn check_in_background(trigger: Trigger) { + if CHECKING.swap(true, Ordering::AcqRel) { + // A new channel picked mid-check, or Check now: the running check + // read the slot before this, so check once more when it ends. + if matches!(trigger, Trigger::Selection | Trigger::Manual) { + *AGAIN.lock().unwrap_or_else(PoisonError::into_inner) = + Some(trigger); + } + log(trigger, &Outcome::AlreadyChecking); + return; + } + set_state(|state| state.checking = true); + let spawned = thread::Builder::new() + .name("pwrdisk-updater".to_owned()) + .spawn(move || { + let outcome = check_and_download(trigger); + CHECKING.store(false, Ordering::Release); + log(trigger, &outcome); + set_state(|state| finish(state, outcome)); + let again = + AGAIN.lock().unwrap_or_else(PoisonError::into_inner).take(); + if let Some(again) = again { + check_in_background(again); + } + }); + if let Err(error) = spawned { + CHECKING.store(false, Ordering::Release); + let outcome = Outcome::Failed(error.to_string()); + log(trigger, &outcome); + set_state(|state| finish(state, outcome)); + } +} + +/// A check ended with `outcome`. +fn finish(state: &mut State, outcome: Outcome) { + state.checking = false; + state.download = None; + state.finished += 1; + state.last = Some((SystemTime::now(), outcome)); +} + +/// Installs the downloaded release and starts PwrDisk again: the Updates +/// panel's Restart to update (or Restart to switch, for an older release). +/// Velopack swaps the package and relaunches, so this returns only when +/// there is nothing to apply or it could not start. +fn restart_to_update() -> Result<(), String> { + let locator = + locator::auto_locate_app_manifest(LocationContext::FromCurrentExe) + .map_err(|e| e.to_string())?; + // The manager refuses a copy Velopack did not install; no feed is read. + let manager = UpdateManager::new(NoneSource {}, None, None) + .map_err(|e| e.to_string())?; + let installed = locator.get_manifest_version().to_string(); + let slot = selection().resolve(&installed); + let pending = + match load_held().filter(|held| package_exists(&locator, held)) { + Some(held) => restart_package(&installed, slot, &held) + .map(Held::asset) + .ok_or_else(|| { + "the downloaded update is not for the selected channel" + .to_owned() + })?, + None => manager + .get_update_pending_restart() + .ok_or_else(|| "no downloaded update to install".to_owned())?, + }; + // The quit hook hands the same package off too. This runs off the GPUI + // thread, so a Quit can land before Velopack exits the process: claim + // the hand-off, or two updaters race for Velopack's lock. + if !first_hand_off(&HANDED_OFF) { + return Err("PwrDisk is already quitting to install it".to_owned()); + } + manager.apply_updates_and_restart(&pending).map_err(|e| { + // Nothing was handed off: the next quit or restart may try. + HANDED_OFF.store(false, Ordering::SeqCst); + e.to_string() + }) +} + +/// [`restart_to_update`] on a thread of its own: Velopack exits this +/// process once the updater is waiting, so nothing waits on it, and the +/// window keeps drawing meanwhile. The toast, the strip's chip and +/// Settings all restart through this. One restart at a time +/// ([`State::restarting`]); a failed one clears it and says why, so they +/// offer Restart again. +pub fn restart_in_background() { + if !begin(&RESTARTING) { + return; + } + set_state(|state| { + state.restarting = true; + state.restart_failed = None; + }); + let failed = |why: String| { + log::warn!("updates: could not restart to update: {why}"); + RESTARTING.store(false, Ordering::Release); + set_state(|state| restart_ended(state, why)); + }; + let spawned = thread::Builder::new() + .name("pwrdisk-restart".to_owned()) + .spawn(move || { + if let Err(why) = restart_to_update() { + failed(why); + } + }); + if let Err(error) = spawned { + failed(error.to_string()); + } +} + +/// True for the first caller until `guard` is cleared: a double-clicked +/// Restart starts Velopack's apply once. +fn begin(guard: &AtomicBool) -> bool { + !guard.swap(true, Ordering::AcqRel) +} + +/// A restart that did not happen: offered again, with why. +fn restart_ended(state: &mut State, why: String) { + state.restarting = false; + state.restart_failed = Some(why); +} + +/// A downloaded package and the slot it was downloaded for. Velopack keeps +/// one package at a time (a download deletes the others), so one record. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Held { + /// Velopack's version: "0.1.1". + pub version: String, + /// The full package's file in Velopack's packages directory. + pub file_name: String, + /// The slot's key ([`Slot::key`]): "stable:latest". + pub slot: String, + /// Older than the copy that downloaded it: installed only from Restart + /// to switch. + #[serde(default)] + pub switch_back: bool, +} + +impl Held { + /// Held for `slot`. + pub fn is_for(&self, slot: Slot) -> bool { + Slot::from_key(&self.slot) == Some(slot) + } + + /// The package, as Velopack's apply takes it: by its file name. + fn asset(&self) -> VelopackAsset { + VelopackAsset { + Version: self.version.clone(), + FileName: self.file_name.clone(), + Type: "Full".to_owned(), + ..VelopackAsset::default() + } + } +} + +/// The download Restart to update installs now, for the Updates panel: +/// held for `slot` and not this very version. +pub fn ready(state: &State, installed: &str, slot: Slot) -> Option { + state + .held + .as_ref() + .and_then(|held| restart_package(installed, slot, held)) + .cloned() +} + +/// What quitting installs: the held package when it is for `slot`, newer +/// than `installed` and not a switch back. +fn quit_package<'a>( + installed: &str, + slot: Slot, + held: &'a Held, +) -> Option<&'a Held> { + let newer = + matches!(compare(&held.version, installed), Some(Precedence::Greater)); + (held.is_for(slot) && newer && !held.switch_back).then_some(held) +} + +/// What Restart to update installs: the held package when it is for +/// `slot` and not this very version. +fn restart_package<'a>( + installed: &str, + slot: Slot, + held: &'a Held, +) -> Option<&'a Held> { + let other = + !matches!(compare(&held.version, installed), Some(Precedence::Equal)); + (held.is_for(slot) && other).then_some(held) +} + +/// `a` against `b` by `SemVer` precedence; `None` when either does not parse. +fn compare(a: &str, b: &str) -> Option { + Some(update_channel::parse(a)?.cmp(&update_channel::parse(b)?)) +} + +/// What a check does once it knows the slot's release. +#[derive(Clone, Debug, PartialEq, Eq)] +enum Plan { + /// Nothing to do: `Outcome` says why. + Done(Outcome), + /// Download `tag`; `switch_back` for an older release. + Download { tag: String, switch_back: bool }, +} + +/// The check's decision, apart from Velopack and the network: `target` is +/// the slot's release, `held` what is downloaded already. +fn plan( + installed: &str, + slot: Slot, + target: Option<&Release>, + held: Option<&Held>, + trigger: Trigger, +) -> Plan { + let Some(target) = target else { + return Plan::Done(Outcome::NothingPublished(slot.to_string())); + }; + let version = target.tag.trim_start_matches('v').to_owned(); + let held = held.filter(|held| held.is_for(slot)); + // A switch back already downloaded stays until Restart to switch; only + // Check now looks past it. + if let Some(held) = + held.filter(|held| held.switch_back && !trigger.is_manual()) + { + return Plan::Done(Outcome::SwitchReady(held.version.clone())); + } + match compare(&version, installed) { + // A tag that does not parse is never taken for an older release. + None | Some(Precedence::Equal) => { + Plan::Done(Outcome::UpToDate(installed.to_owned())) + } + Some(Precedence::Less) if !trigger.is_manual() => { + Plan::Done(Outcome::UpToDate(installed.to_owned())) + } + Some(Precedence::Less) => match held { + Some(held) if held.switch_back && held.version == version => { + Plan::Done(Outcome::SwitchReady(held.version.clone())) + } + _ => Plan::Download { + tag: target.tag.clone(), + switch_back: true, + }, + }, + Some(Precedence::Greater) => match held { + // As new or newer is downloaded already for this slot. + Some(held) + if !held.switch_back + && matches!( + compare(&held.version, &version), + Some(Precedence::Greater | Precedence::Equal) + ) => + { + Plan::Done(Outcome::Pending(held.version.clone())) + } + _ => Plan::Download { + tag: target.tag.clone(), + switch_back: false, + }, + }, + } +} + +fn check_and_download(trigger: Trigger) -> Outcome { + // The installed version (Velopack's sq.version), not the one compiled + // in: packages are stamped separately from Cargo.toml. + let locator = match locator::auto_locate_app_manifest( + LocationContext::FromCurrentExe, + ) { + Ok(locator) => locator, + Err(error) => return Outcome::NotInstalled(error.to_string()), + }; + let installed = locator.get_manifest_version().to_string(); + let slot = selection().resolve(&installed); + let releases = github_releases::fetch(&locator.get_manifest_channel()); + set_state(|state| state.releases = Some(releases.clone())); + let releases = match releases { + Ok(releases) => releases, + Err(error) => return Outcome::Failed(error), + }; + let target = update_channel::select(&releases, slot); + let held = load_held().filter(|held| package_exists(&locator, held)); + // A package Velopack no longer has is not ready to install. + set_state(|state| state.held.clone_from(&held)); + let (tag, switch_back) = + match plan(&installed, slot, target.as_ref(), held.as_ref(), trigger) { + Plan::Done(outcome) => return outcome, + Plan::Download { tag, switch_back } => (tag, switch_back), + }; + let options = UpdateOptions { + AllowVersionDowngrade: switch_back, + ..UpdateOptions::default() + }; + let source = HttpSource::new(github_releases::download_base(&tag)); + let manager = match UpdateManager::new(source, Some(options), None) { + Ok(manager) => manager, + Err(error) => return Outcome::NotInstalled(error.to_string()), + }; + match manager.check_for_updates() { + Ok(UpdateCheck::UpdateAvailable(update)) => { + let target = &update.TargetFullRelease; + if let Err(error) = fetch(&manager, &update, switch_back) { + return Outcome::Failed(error.to_string()); + } + let held = Held { + version: target.Version.clone(), + file_name: target.FileName.clone(), + slot: slot.key(), + switch_back, + }; + save_held(&held); + set_state(|state| state.held = Some(held.clone())); + if switch_back { + Outcome::SwitchReady(held.version) + } else { + Outcome::Downloaded(held.version) + } + } + Ok(UpdateCheck::NoUpdateAvailable | UpdateCheck::RemoteIsEmpty) => { + Outcome::UpToDate(installed) + } + Err(error) => Outcome::Failed(error.to_string()), + } +} + +/// Downloads `update`, keeping [`State::download`]'s percent current. Each +/// whole percent is one [`Change::Progress`], so Velopack's finer reports +/// cost nothing on the GPUI thread. +fn fetch( + manager: &UpdateManager, + update: &velopack::UpdateInfo, + switch_back: bool, +) -> Result<(), velopack::Error> { + let version = update.TargetFullRelease.Version.clone(); + set_progress(|download| { + *download = Some(Download { + version, + switch_back, + percent: None, + }); + }); + let (progress, percents) = std::sync::mpsc::channel::(); + // Ends when Velopack drops the sender, at the end of the download. + let follow = thread::Builder::new() + .name("pwrdisk-download".to_owned()) + .spawn(move || { + let mut last = None; + for raw in percents { + if let Some(percent) = next_percent(last, raw) { + last = Some(percent); + set_progress(|download| { + if let Some(download) = download { + download.percent = Some(percent); + } + }); + } + } + }); + manager.download_updates(update, follow.is_ok().then_some(progress)) +} + +/// The percent to show after Velopack says `raw`, when it moved from +/// `last`; `None` when it did not. +fn next_percent(last: Option, raw: i16) -> Option { + let percent = u8::try_from(raw.clamp(0, 100)).unwrap_or(0); + (last != Some(percent)).then_some(percent) +} + +/// Whether `held`'s package is still in Velopack's packages directory. +fn package_exists(locator: &VelopackLocator, held: &Held) -> bool { + locator.get_packages_dir().join(&held.file_name).is_file() +} + +fn held_path() -> Option { + settings_dir().map(|dir| dir.join(HELD_FILE)) +} + +/// The file's shape: room for more than the held download later. +#[derive(Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +struct HeldFile { + held: Option, +} + +fn load_held() -> Option { + read_held(&held_path()?) +} + +fn read_held(path: &Path) -> Option { + let text = fs::read_to_string(path).ok()?; + serde_json::from_str::(&text).ok()?.held +} + +fn save_held(held: &Held) { + let Some(path) = held_path() else { + return; + }; + if let Err(error) = write_held(&path, held) { + log::warn!("updates: could not record the download: {error}"); + } +} + +fn write_held(path: &Path, held: &Held) -> std::io::Result<()> { + write_json( + path, + &HeldFile { + held: Some(held.clone()), + }, + ) +} + +fn write_json(path: &Path, value: &impl Serialize) -> std::io::Result<()> { + if let Some(dir) = path.parent() { + fs::create_dir_all(dir)?; + } + let mut text = + serde_json::to_string_pretty(value).map_err(std::io::Error::other)?; + text.push('\n'); + fs::write(path, text) +} + +/// How a check went. The version strings are Velopack's. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Outcome { + AlreadyChecking, + NotInstalled(String), + UpToDate(String), + /// The slot (by name) has no release published yet. + NothingPublished(String), + Downloaded(String), + Pending(String), + /// An older release is downloaded; Restart to switch installs it. + SwitchReady(String), + Failed(String), +} + +impl fmt::Display for Outcome { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::AlreadyChecking => write!(f, "a check is already running"), + Self::NotInstalled(why) => { + write!(f, "not a Velopack install, so no updates here ({why})") + } + Self::UpToDate(version) => write!(f, "{version} is the latest"), + Self::Downloaded(version) => { + write!( + f, + "downloaded {version}; it installs when PwrDisk quits or restarts" + ) + } + Self::Pending(version) => { + write!( + f, + "{version} is downloaded and installs when PwrDisk quits or restarts" + ) + } + Self::NothingPublished(slot) => { + write!(f, "nothing is published on {slot} yet") + } + Self::SwitchReady(version) => { + write!( + f, + "{version} is downloaded; Restart to switch installs it" + ) + } + Self::Failed(why) => write!(f, "check failed: {why}"), + } + } +} + +fn log(trigger: Trigger, outcome: &Outcome) { + let trigger = match trigger { + Trigger::Startup => "startup", + Trigger::Timer => "timer", + Trigger::Manual => "check now", + Trigger::Selection => "channel", + }; + log::info!("updates ({trigger}): {outcome}"); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_dev_build_has_no_installation_and_nothing_to_restart_into() { + assert!(matches!(installation(), Installation::NotInstalled { .. })); + assert!(restart_to_update().is_err()); + } + + #[test] + fn startup_never_applies_a_downloaded_update() { + // The held download's channel decides what installs: the package + // waits for Quit or Restart to update. The builder takes the policy + // as given; a + // Velopack install is needed to see it act, so the policy is what + // the test can hold. + assert_eq!(STARTUP, StartupPolicy { auto_apply: false }); + // The builder is made, hooks and all, without a Velopack install. + let _off = startup_hooks(STARTUP); + let _on = startup_hooks(StartupPolicy { auto_apply: true }); + } + + #[test] + fn quitting_with_nothing_downloaded_applies_nothing() { + let mut applied = 0; + let outcome = on_quit(None, |_| { + applied += 1; + Ok(()) + }); + assert_eq!(outcome, QuitApply::Nothing); + assert_eq!(applied, 0); + // A test binary is not a Velopack install: the real path says the + // same, without starting an updater. + assert_eq!(apply_pending(), QuitApply::Nothing); + } + + #[test] + fn quitting_with_a_download_hands_it_to_the_updater() { + let asset = || VelopackAsset { + Version: "0.2.1".to_owned(), + ..VelopackAsset::default() + }; + assert_eq!( + on_quit(Some(asset()), |pending| { + assert_eq!(pending.Version, "0.2.1"); + Ok(()) + }), + QuitApply::Applying("0.2.1".to_owned()) + ); + assert_eq!( + on_quit(Some(asset()), |_| Err("no updater".to_owned())), + QuitApply::Failed("no updater".to_owned()) + ); + } + + #[test] + fn a_quit_hands_the_update_off_once() { + let handed_off = AtomicBool::new(false); + assert!(first_hand_off(&handed_off)); + assert!(!first_hand_off(&handed_off), "a second updater"); + } + + #[test] + fn a_restart_runs_once_until_it_fails() { + let guard = AtomicBool::new(false); + assert!(begin(&guard)); + assert!(!begin(&guard), "a second press waits"); + // A failure clears the guard and says why, so Restart is offered + // again. + let mut state = State { + restarting: true, + ..State::default() + }; + guard.store(false, Ordering::Release); + restart_ended(&mut state, "no updater".to_owned()); + assert!(!state.restarting); + assert_eq!(state.restart_failed.as_deref(), Some("no updater")); + assert!(begin(&guard), "offered again"); + } + + #[test] + fn progress_moves_once_per_whole_percent() { + assert_eq!(next_percent(None, 0), Some(0)); + assert_eq!(next_percent(Some(0), 0), None, "the same percent"); + assert_eq!(next_percent(Some(0), 42), Some(42)); + assert_eq!(next_percent(Some(42), 250), Some(100), "clamped"); + assert_eq!(next_percent(None, -3), Some(0), "clamped"); + } + + #[test] + fn a_finished_check_clears_its_download_and_counts() { + let mut state = State { + checking: true, + download: Some(Download { + version: "0.15.0".into(), + switch_back: false, + percent: Some(99), + }), + ..State::default() + }; + finish(&mut state, Outcome::Downloaded("0.15.0".into())); + assert!(!state.checking); + assert_eq!(state.download, None); + assert_eq!(state.finished, 1); + } + + #[test] + fn only_a_velopack_install_checks_on_a_timer() { + assert_eq!( + check_every(&Installation::Velopack { + version: "0.2.0".to_owned() + }), + Some(CHECK_EVERY) + ); + assert_eq!( + check_every(&Installation::NotInstalled { + why: "no manifest".to_owned() + }), + None + ); + assert_eq!(CHECK_EVERY, Duration::from_hours(6)); + } + + #[test] + fn a_dev_build_reports_it_is_not_installed() { + // The test binary is not in a Velopack layout, so the manager cannot + // load and nothing reaches the network. + assert!(matches!( + check_and_download(Trigger::Manual), + Outcome::NotInstalled(_) + )); + } + + fn held(version: &str, slot: Slot, switch_back: bool) -> Held { + Held { + version: version.to_owned(), + file_name: format!("PwrDisk-{version}-osx-full.nupkg"), + slot: slot.key(), + switch_back, + } + } + + fn download(tag: &str, switch_back: bool) -> Plan { + Plan::Download { + tag: tag.to_owned(), + switch_back, + } + } + + #[test] + fn a_check_downloads_a_newer_release_for_the_slot() { + let target = Release::new("v0.1.1", true); + let slot = Slot::STABLE_PRERELEASE; + assert_eq!( + plan("0.1.0", slot, Some(&target), None, Trigger::Timer), + download("v0.1.1", false) + ); + // Already downloaded for this slot: kept, not fetched again. + let same = held("0.1.1", slot, false); + assert_eq!( + plan("0.1.0", slot, Some(&target), Some(&same), Trigger::Startup), + Plan::Done(Outcome::Pending("0.1.1".into())) + ); + // A newer release replaces an older download. + let older = held("0.1.0-rc.9", slot, false); + assert_eq!( + plan( + "0.1.0-rc.3", + slot, + Some(&target), + Some(&older), + Trigger::Timer + ), + download("v0.1.1", false) + ); + // A download for another slot does not count. + let other = held("0.1.1", Slot::BETA_LATEST, false); + assert_eq!( + plan("0.1.0", slot, Some(&target), Some(&other), Trigger::Timer), + download("v0.1.1", false) + ); + } + + #[test] + fn only_check_now_switches_back_to_an_older_release() { + let target = Release::new("v0.1.0", false); + let slot = Slot::STABLE_LATEST; + for trigger in [Trigger::Startup, Trigger::Timer, Trigger::Selection] { + assert_eq!( + plan("0.2.0-alpha.1", slot, Some(&target), None, trigger), + Plan::Done(Outcome::UpToDate("0.2.0-alpha.1".into())), + "{trigger:?}" + ); + } + assert_eq!( + plan("0.2.0-alpha.1", slot, Some(&target), None, Trigger::Manual), + download("v0.1.0", true) + ); + // Downloaded already: ready to switch, and a background check + // leaves it alone. + let back = held("0.1.0", slot, true); + assert_eq!( + plan( + "0.2.0-alpha.1", + slot, + Some(&target), + Some(&back), + Trigger::Manual + ), + Plan::Done(Outcome::SwitchReady("0.1.0".into())) + ); + let newer = Release::new("v0.2.0", false); + assert_eq!( + plan( + "0.2.0-alpha.1", + slot, + Some(&newer), + Some(&back), + Trigger::Timer + ), + Plan::Done(Outcome::SwitchReady("0.1.0".into())) + ); + } + + #[test] + fn the_same_version_or_an_empty_slot_downloads_nothing() { + let slot = Slot::STABLE_LATEST; + assert_eq!( + plan( + "0.1.0", + slot, + Some(&Release::new("v0.1.0", false)), + None, + Trigger::Manual + ), + Plan::Done(Outcome::UpToDate("0.1.0".into())) + ); + assert_eq!( + plan("0.1.0", slot, None, None, Trigger::Manual), + Plan::Done(Outcome::NothingPublished( + "Stable \u{00b7} Latest".into() + )) + ); + // A tag that does not parse is never taken for an older release. + assert_eq!( + plan( + "0.1.0", + slot, + Some(&Release::new("nightly", false)), + None, + Trigger::Manual + ), + Plan::Done(Outcome::UpToDate("0.1.0".into())) + ); + } + + #[test] + fn quit_installs_only_a_newer_download_for_the_slot_in_force() { + let slot = Slot::STABLE_LATEST; + let newer = held("0.1.1", slot, false); + assert_eq!(quit_package("0.1.0", slot, &newer), Some(&newer)); + assert_eq!(quit_package("0.1.0", Slot::BETA_LATEST, &newer), None); + assert_eq!(quit_package("0.1.1", slot, &newer), None); + let back = held("0.0.9", slot, true); + assert_eq!(quit_package("0.1.0", slot, &back), None); + // Restart to switch installs it; Restart never reinstalls this copy. + assert_eq!(restart_package("0.1.0", slot, &back), Some(&back)); + assert_eq!(restart_package("0.1.0", Slot::BETA_LATEST, &back), None); + assert_eq!(restart_package("0.1.1", slot, &newer), None); + } + + #[test] + fn the_held_download_is_recorded_beside_the_settings() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(HELD_FILE); + assert_eq!(read_held(&path), None); + let back = held("0.0.9", Slot::BETA_PRERELEASE, true); + write_held(&path, &back).unwrap(); + assert_eq!(read_held(&path), Some(back.clone())); + let text = fs::read_to_string(&path).unwrap(); + assert!(text.contains("\"slot\": \"beta:prerelease\""), "{text}"); + assert!(text.contains("\"switchBack\": true"), "{text}"); + assert_eq!(back.asset().FileName, "PwrDisk-0.0.9-osx-full.nupkg"); + fs::write(&path, "{").unwrap(); + assert_eq!(read_held(&path), None, "a bad file is no download"); + } + + #[test] + fn outcomes_read_as_log_lines() { + assert_eq!( + Outcome::AlreadyChecking.to_string(), + "a check is already running" + ); + assert_eq!( + Outcome::Downloaded("0.0.2".to_owned()).to_string(), + "downloaded 0.0.2; it installs when PwrDisk quits or restarts" + ); + } +} diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs index 32aedf5f..14317eab 100644 --- a/crates/disktree-app/src/views.rs +++ b/crates/disktree-app/src/views.rs @@ -4,28 +4,42 @@ //! always exactly what the state says — there is no second copy of anything to //! keep in sync. +use crate::semantics::AccessibleButton as _; + +use std::path::Path; + use disktree_core::classify::Category; +use disktree_core::filter::Keep; use disktree_core::insights::{Candidate, Finding, STALE_DAYS}; +use disktree_core::path_style::PathStyle; use disktree_core::removal::{Plan, RemovalMode, Target}; use disktree_core::size::human_bytes; use disktree_core::tree::Metric; use gpui_kit::base::CheckboxState; use gpui_kit::{ - App, AppContext as _, ClickEvent, Context, Div, DragMoveEvent, ElementId, - Focusable as _, FontWeight, InteractiveElement as _, IntoElement, - KeyDownEvent, MouseDownEvent, ParentElement, Rems, SharedString, Stateful, - StatefulInteractiveElement as _, Styled, Window, anchored, deferred, div, - pattern_slash, px, relative, + AnyElement, App, AppContext as _, ClickEvent, Context, Div, DragMoveEvent, + ElementId, Focusable as _, FontWeight, InteractiveElement as _, + IntoElement, KeyDownEvent, MouseDownEvent, ParentElement, Rems, + SharedString, Stateful, StatefulInteractiveElement as _, Styled, Window, + anchored, deferred, div, pattern_slash, px, relative, }; use gpui_omarchy::{ ActiveTheme, ButtonVariant, ChoiceItem, Theme, alert_dialog, button, button_group, checkbox, dialog_button, dialog_description, dialog_popup, - dialog_title, separator, with_tooltip, + dialog_title, }; +use crate::widgets::with_tooltip; + use gpui_kit::prelude::FluentBuilder as _; +use rustc_hash::{FxHashMap, FxHashSet}; +use crate::chrome::{self, Frame}; +use crate::git_store::{Probe, Shown}; +use crate::ledger::Cohort; +use crate::mark_guard::{Gate, MarkCheck, Over, Share}; use crate::palette; +use crate::safety::Confirm; use crate::state::{ ColorMode, Crumb, Disktree, PANEL_REMS, Screen, panel_width, }; @@ -33,32 +47,123 @@ use crate::treemap_view::{self, Mosaic}; use crate::ui::{icon, size, space, text}; use crate::widgets; -/// How many marks the review screen lists. Everything above the cap is still -/// removed; the list only stops being exhaustive, which it says out loud. +/// Marks per review page: every mark stays reachable while bounding layout +/// and semantic work independently of the full marked list. const LIST_LIMIT: usize = 1200; +/// Row decoration borrows this render's freshly evaluated plan. It must +/// not cache removal authorization, and each displayed row needs constant +/// expected hash lookups rather than scans of all blocked/covered targets. +#[derive(Debug)] +struct ReviewStatus<'a> { + covered: FxHashSet<&'a Path>, + blocked: FxHashMap<&'a Path, &'a str>, +} + +impl<'a> ReviewStatus<'a> { + fn new(plan: &'a Plan) -> Self { + let mut status = Self { + covered: FxHashSet::default(), + blocked: FxHashMap::default(), + }; + for target in &plan.covered { + #[cfg(test)] + crate::marks::work::REVIEW + .set(crate::marks::work::REVIEW.get() + 1); + status.covered.insert(target.path.as_path()); + } + for target in &plan.blocked { + #[cfg(test)] + crate::marks::work::REVIEW + .set(crate::marks::work::REVIEW.get() + 1); + // A raw queue may repeat a path. Keep the first explanation, + // matching the original linear find's behavior. + status + .blocked + .entry(target.path.as_path()) + .or_insert(target.reason.as_str()); + } + status + } + + fn covered(&self, path: &Path) -> bool { + #[cfg(test)] + crate::marks::work::REVIEW.set(crate::marks::work::REVIEW.get() + 1); + self.covered.contains(path) + } + + fn blocked(&self, path: &Path) -> Option<&str> { + #[cfg(test)] + crate::marks::work::REVIEW.set(crate::marks::work::REVIEW.get() + 1); + self.blocked.get(path).copied() + } +} + +/// Below the list-plus-explanation width budget, review becomes one column. +pub const REVIEW_COLUMNS_REMS: f32 = 65.0; + /// The whole window. pub fn root( app: &mut Disktree, + frame: &Frame, window: &mut Window, cx: &mut Context<'_, Disktree>, ) -> Stateful
{ if app.volumes_open { app.prepare_picker_inputs(window, cx); } + if app.screen == Screen::Review { + app.prepare_over_phrase(window, cx); + } app.apply_focus(window, cx); + let fit = crate::toolbar::BarFit::for_width( + window.viewport_size().width.as_f32() / app.rem, + ); + // What ⋮ held at the old width is not what it holds at the new one. + if fit != app.bar_fit { + app.more_menu = None; + // ⋮ may vanish under the pointer, which then never reports leaving. + app.more_hover = false; + } + app.bar_fit = fit; + // A dialog owns the keys; a menu left open behind it would take them + // first (see `dispatch_key`). + if app.has_modal() { + app.more_menu = None; + app.power_menu = None; + } let theme = cx.omarchy().clone(); + let readable_status = app.accessibility_status(); + let strip = title_strip(app, frame, window, cx); + // Each screen anchors the toasts in its content, above its footer, so + // they never cover the footer's buttons. Dialogs draw over them. + let toasts = crate::toasts::stack(app, window, cx); let body = match app.screen { - Screen::Explore => explore(app, window, cx), - Screen::Review => review(app, window, cx), - Screen::Running => running(app, cx), - Screen::Done => done(app, cx), + Screen::Explore => explore(app, toasts, window, cx), + Screen::Review => review(app, toasts, window, cx), + Screen::Running => crate::run_view::running(app, toasts, window, cx), + Screen::Done => crate::run_view::done(app, toasts, window, cx), }; + let modal = app.has_modal() || app.app_menu_open; + let background = div().id("application-content") + .role(gpui_kit::Role::Group).aria_label("Application content") + .a11y_synthetic_children(move |b| { if modal { b.parent_node().set_hidden(); } }) + .flex().flex_col().flex_1().min_h_0().w_full() + .child(strip) + .child(body) + .children(app.is_indexing().then(|| div().id("scan-progress") + .role(gpui_kit::Role::ProgressIndicator) + .aria_label(if app.screen == Screen::Explore { "Scan in progress; indeterminate; overview is incomplete; Escape cancels" } else { "Background scan in progress; indeterminate; overview is incomplete" }) + .a11y_synthetic_children(|b| b.parent_node().set_busy()))) + .child(crate::semantics::status("current-status", readable_status)); let mut root = div() .id("disktree-root") + .role(gpui_kit::Role::Group) + .aria_label("Disk usage explorer") .debug_selector(|| "disktree-root".into()) .track_focus(&app.focus) + .tab_group().tab_stop(false) .key_context("Disktree") .on_action(cx.listener(|this, _: &crate::app_menu::Rescan, _, cx| { // Where `r` would: not behind the confirmation, and not under @@ -76,24 +181,86 @@ pub fn root( )) .on_action(cx.listener( |this, _: &crate::app_menu::ShowInFinder, _, cx| { - this.reveal_target(cx); + if !this.has_modal() { this.reveal_target(cx); } }, )) // Only where the history buttons are: the review screen has none. .on_action(cx.listener(|this, _: &crate::app_menu::GoBack, _, cx| { - if this.screen == Screen::Explore { + if this.screen == Screen::Explore && !this.has_modal() { this.go_back(cx); } })) .on_action(cx.listener( |this, _: &crate::app_menu::GoForward, _, cx| { - if this.screen == Screen::Explore { + if this.screen == Screen::Explore && !this.has_modal() { this.go_forward(cx); } }, )) + .on_action(cx.listener( + |this, _: &crate::app_menu::ChooseSource, _, cx| { + this.open_volumes(cx); + }, + )) + .on_action(cx.listener(|this, _: &crate::app_menu::Undo, _, cx| { + this.undo_unmark(cx); + })) + .on_action(cx.listener( + |this, _: &crate::app_menu::ShowExplore, _, cx| { + if this.screen == Screen::Review && !this.has_modal() { + this.screen = Screen::Explore; + cx.notify(); + } + }, + )) + .on_action(cx.listener( + |this, _: &crate::app_menu::ShowReview, _, cx| { + if this.screen == Screen::Explore && !this.has_modal() { + this.open_review(cx); + } + }, + )) + .on_action(cx.listener( + |this, _: &crate::app_menu::ShowTreemap, window, cx| { + choose_view(this, false, window, cx); + }, + )) + .on_action(cx.listener( + |this, _: &crate::app_menu::ShowFileList, window, cx| { + choose_view(this, true, window, cx); + }, + )) + .on_action(cx.listener( + |this, _: &crate::app_menu::ShowKeyboardShortcuts, _, cx| { + this.open_help(cx); + }, + )) + .on_action(cx.listener( + |this, _: &crate::app_menu::ToggleAppMenu, _, cx| { + if frame_has_app_menu(this.chrome_pin.as_ref()) { + this.toggle_app_menu(cx); + } + }, + )) + .on_action(cx.listener( + |_, _: &crate::app_menu::ConnectAgent, _, cx| { + open_agents_settings(cx); + }, + )) .on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| { - if this.zoom_interface(event, window) { + if this.zoom_interface(event, window, cx) { + cx.notify(); + return; + } + // An open menu owns the arrows before the page behind it scrolls. + if this.app_menu_open && app_menu_key(this, event, window, cx) { return; } + if !this.has_modal() && this.screen == Screen::Review && !this.editing_phrase(window, cx) && crate::ui::scroll_key(&event.keystroke.key, &this.review_scroll, window.rem_size()) { cx.stop_propagation(); cx.notify(); return; } + if this.show_help && crate::ui::scroll_key(&event.keystroke.key, &this.help_scroll, window.rem_size()) { cx.stop_propagation(); cx.notify(); return; } + if event.keystroke.key == "tab" && !event.keystroke.modifiers.control && !event.keystroke.modifiers.platform { + if !this.has_modal() { this.find_open = false; } + let scope = (this.has_modal() || this.app_menu_open).then(|| this.confirm_focus.clone()); + crate::semantics::advance_focus(window, cx, event.keystroke.modifiers.shift, scope.as_ref()); + cx.stop_propagation(); cx.notify(); return; } @@ -102,6 +269,18 @@ pub fn root( .flatten().any(|input| input.read(cx).focus_handle(cx).is_focused(window)); if editing && event.keystroke.key != "escape" { return; } } + if event.keystroke.key == "?" && !this.has_modal() && !this.find_open && !this.editing_phrase(window, cx) { + this.open_help(cx); this.apply_focus(window, cx); return; + } + if event.keystroke.key == "escape" && this.screen == Screen::Explore && !this.has_modal() && this.is_indexing() { + // Search and menus own Escape before scan cancellation, + // including when a toolbar control currently has focus. + this.on_key_down(event, cx); this.apply_focus(window, cx); return; + } + if !this.has_modal() && !this.app_menu_open && this.screen != Screen::Running && !this.focus.is_focused(window) && !this.file_focus.is_focused(window) { + if event.keystroke.key == "escape" { window.focus(&this.focus, cx); cx.notify(); } + return; + } this.on_key_down(event, cx); this.apply_focus(window, cx); })) @@ -113,84 +292,149 @@ pub fn root( .text_color(theme.foreground) .font_family(theme.font) .text_size(text::BODY) - .child(body); - if let Some(tip) = cursor_tooltip(app, window, cx) { + .child(background); + // A modal hides the mosaic's hover card: the pointer last seen on the + // treemap is stale while the backdrop takes the mouse, so the card would + // otherwise sit, or drift, behind the dialog. + if !modal && let Some(tip) = cursor_tooltip(app, window, cx) { root = root.child(tip); } if app.show_help { root = root.child(help_overlay(app, cx)); } + if app.app_menu_open { + root = root.child(app_menu_dropdown(app, cx)); + } if app.volumes_open { root = root.child(volumes_dialog(app, window, cx)); } if app.confirm_open { - root = root.child(delete_dialog(app, cx)); + root = root.child(delete_dialog(app, window, cx)); } root } +/// Enter resolves to the dialog's Confirm action before button key events. +/// Consume it at the focused button so Cancel and every peer keep their +/// own click behavior instead of falling through to the dialog default. +fn modal_action( + button: gpui_omarchy::Button, + action: fn(&mut Disktree, &mut Window, &mut Context<'_, Disktree>), + cx: &Context<'_, Disktree>, +) -> gpui_omarchy::Button { + button + .on_click(cx.listener(move |this, _, window, cx| { + action(this, window, cx); + })) + .on_action(cx.listener( + move |this, _: &gpui_kit::base::actions::Confirm, window, cx| { + action(this, window, cx); + cx.stop_propagation(); + }, + )) +} + /// Discovery is lightweight; a separate, explicit action starts the walk. fn volumes_dialog( app: &Disktree, - window: &Window, + window: &mut Window, cx: &mut Context<'_, Disktree>, ) -> impl IntoElement { let theme = cx.omarchy().clone(); let cancel = cx.entity().downgrade(); + let source_error = app.picker_error.as_ref().or(app.volumes_error.as_ref()); + let host_invalid = app.volumes_error.is_some(); + let path_invalid = app.picker_error.is_some(); let source_ready = app.picker_source_matches(cx); - let source = app.volumes_source.as_ref().map_or_else( - || "This computer".to_owned(), - |host| format!("{host} · SSH · read-only"), - ); + let listable = source_ready + && !app.volumes_loading + && app.volumes_error.is_none() + && !(app.picker_ssh && app.volumes_source.is_none()); let mut rows = div() .id("volume-rows") + .role(gpui_kit::Role::ListBox) + .track_focus(&app.source_roots_focus).tab_index(0).tab_stop(true) + .border_2().border_color(theme.background.opacity(0.)) + .focus_visible(|style| style.border_color(theme.accent)) + .aria_description("Up and Down select a root. Enter explicitly accepts the selected root and starts its scan.") + .aria_label( + "Available roots in the selected machine; listing is not a scan", + ) .debug_selector(|| "volume-rows".into()) .flex() .flex_col() - .gap(space::XS) .max_h(size::SOURCE_LIST_HEIGHT) - .overflow_y_scroll(); - if app.volumes_loading { - rows = rows.child(dialog_description( - "Listing mounts, not scanning files…", - cx, + .overflow_y_scroll() + .border_1() + .border_color(theme.border) + .bg(theme.inset); + let quiet = |line: String| { + div() + .px(space::MD) + .py(space::SM) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(line) + }; + if app.picker_ssh && app.volumes_source.is_none() && !app.volumes_loading { + rows = rows.child(quiet( + "Enter an SSH alias or user@host, then Connect.".into(), )); + } else if app.volumes_loading { + rows = rows.child(quiet("Listing mounts, not scanning files…".into())); } else if let Some(error) = &app.volumes_error { - rows = rows.child(div().text_color(theme.danger).child(error.clone())); - } else if app.volumes.is_empty() { - rows = rows.child(dialog_description( - "No mounts listed. Enter a directory below.", - cx, - )); + rows = rows.child( + div() + .id("discovery-error") + .role(gpui_kit::Role::Alert) + .aria_label(error.clone()) + .px(space::MD) + .py(space::SM) + .text_color(theme.danger) + .child(error.clone()), + ); } - for (index, volume) in app.volumes.iter().enumerate() { + let row = |id: ElementId, index: usize, label: String| { let highlighted = index == app.volume_highlight; + div() + .id(id) + .role(gpui_kit::Role::ListBoxOption) + .aria_label(label) + .aria_selected(highlighted) + .when( + highlighted, + gpui_kit::StatefulInteractiveElement::aria_active_descendant, + ) + .debug_selector(move || format!("volume-{index}")) + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .px(space::MD) + .py(space::SM) + .text_size(text::BODY) + .text_color(if highlighted { + theme.bright + } else { + theme.foreground + }) + .when(highlighted, |row| row.bg(theme.accent.opacity(0.18))) + .hover(|row| row.bg(theme.accent.opacity(0.1))) + }; + for (index, volume) in app.volumes.iter().enumerate() { let label = format!( "{} · {}", volume.point.display(), volume.device.as_deref().unwrap_or("Mounted volume") ); - rows = rows.child( - div() - .id(ElementId::Name(format!("volume-{index}").into())) - .debug_selector(move || format!("volume-{index}")) - .px(space::MD) - .py(space::SM) - .text_size(text::BODY) - .text_color(if highlighted { - theme.bright - } else { - theme.foreground - }) - .when(highlighted, |row| row.bg(theme.accent.opacity(0.18))) - .hover(|row| row.bg(theme.accent.opacity(0.1))) - .child(label) - .on_click(cx.listener(move |this, _, window, cx| { - this.volume_highlight = index; - window.focus(&this.confirm_focus, cx); - cx.notify(); - })), - ); + let id = ElementId::Name(crate::file_list::path_id(&volume.point)); + rows = rows.child(row(id, index, label.clone()).child(label).on_click( + cx.listener(move |this, _, window, cx| { + this.volume_highlight = index; + window.focus(&this.confirm_focus, cx); + cx.notify(); + }), + )); } let host = app .picker_host @@ -200,41 +444,207 @@ fn volumes_dialog( .picker_path .as_ref() .expect("picker prepared before rendering"); - let popup = dialog_popup(cx).w_full() + // The typed path is the list's last row, so one Scan acts on whichever + // row is highlighted and Enter never depends on which field has focus. + let directory = app.volumes.len(); + if listable { + rows = rows.child( + row( + "source-directory".into(), + directory, + "Directory to scan".into(), + ) + .child("Directory") + .child( + gpui_omarchy::input("source-path", path, window, cx) + .aria_label("Root directory to scan") + .aria_value(path.read(cx).value()) + .a11y_synthetic_children(move |b| { + if path_invalid { + b.parent_node().set_invalid( + gpui_kit::accesskit::Invalid::True, + ); + } + }) + .aria_description(format!( + "Absolute path in the selected machine. Scan starts \ + only after explicit acceptance. {}", + source_error.map_or("", String::as_str) + )) + .debug_selector(|| "source-path".into()) + .flex_1(), + ) + .when(app.volumes_source.is_none(), |row| { + row.child( + button( + "source-browse", + "Choose\u{2026}", + ButtonVariant::Secondary, + cx, + ) + .debug_selector(|| "source-browse".into()) + .map(|button| { + modal_action( + button, + |this, _, cx| { + this.browse_picker_path(cx); + }, + cx, + ) + }), + ) + }) + .on_click(cx.listener(move |this, _, _, cx| { + this.volume_highlight = directory; + cx.notify(); + })), + ); + } + let entity = cx.entity().downgrade(); + let switch = button_group( + "source-switch", + vec![ + ChoiceItem::new("local", "This computer"), + ChoiceItem::new("ssh", "SSH host"), + ], + Some(usize::from(app.picker_ssh)), + move |index, window, cx| { + let _ = entity.update(cx, |this, cx| { + if index == 0 { + this.choose_local_source(window, cx); + } else { + this.choose_ssh_source(window, cx); + } + }); + }, + window, + cx, + ); + let scan_ready = listable + && (app.volume_highlight < app.volumes.len() + || !path.read(cx).value().trim().is_empty()); + let cancel_button = + dialog_button("source-cancel", "Cancel", ButtonVariant::Secondary, cx) + .debug_selector(|| "source-cancel".into()) + .map(|button| { + modal_action( + button, + |this, window, cx| { + this.close_volumes(cx); + this.apply_focus(window, cx); + }, + cx, + ) + }); + let scan_button = + dialog_button("source-scan", "Scan", ButtonVariant::Primary, cx) + .debug_selector(|| "source-scan".into()) + .semantic_disabled(!scan_ready) + .map(|button| { + modal_action( + button, + |this, window, cx| { + this.choose_volume(cx); + this.apply_focus(window, cx); + }, + cx, + ) + }); + let popup = dialog_popup(cx) + .w_full() + .child(crate::semantics::text( + "source-cautions", + "Choose this computer or an SSH host, then select a mount or \ + directory. No scan starts until Scan is accepted. Nested mounts \ + and symlinks are not traversed; remote sources are read-only. \ + Space is measured only after selection.", + )) .child(dialog_title("Choose what to scan", cx)) - .child(dialog_description( - "Connect, then select a mount or directory. No new scan starts until you choose Scan.", - cx)) - .child(div().flex().flex_row().gap(space::SM) - .child(button("source-local", "This computer", ButtonVariant::Secondary, cx) - .on_click(cx.listener(|this, _, window, cx| this.choose_local_source(window, cx)))) - .child(gpui_omarchy::input("source-host", host, window, cx) - .debug_selector(|| "source-host".into()).flex_1()) - .child(button("source-connect", "Connect SSH", ButtonVariant::Secondary, cx) - .on_click(cx.listener(|this, _, _, cx| this.connect_picker(cx))))) - .child(div().text_color(theme.bright).child(source)) + .child( + div() + .debug_selector(|| "source-switch".into()) + .child(switch), + ) + .when(app.picker_ssh, |popup| { + popup.child( + div() + .flex() + .flex_row() + .gap(space::SM) + .child( + gpui_omarchy::input("source-host", host, window, cx) + .aria_label("SSH destination") + .aria_value(host.read(cx).value()) + .a11y_synthetic_children(move |b| { + if host_invalid { + b.parent_node().set_invalid( + gpui_kit::accesskit::Invalid::True, + ); + } + }) + .aria_description(format!( + "SSH alias or user@host. {}", + source_error.map_or("", String::as_str) + )) + .debug_selector(|| "source-host".into()) + .flex_1(), + ) + .child( + button( + "source-connect", + "Connect", + ButtonVariant::Secondary, + cx, + ) + .debug_selector(|| "source-connect".into()) + .map(|button| { + modal_action( + button, + |this, _, cx| { + this.connect_picker(cx); + }, + cx, + ) + }), + ), + ) + }) + .children(app.volumes_source.as_ref().map(|host| { + let source = format!("{host} \u{b7} SSH \u{b7} read-only"); + crate::semantics::text("selected-source", source.clone()) + .text_color(theme.bright) + .child(source) + })) .child(rows) .child(dialog_description( - "Nested mounts and symlinks are not traversed. Space is measured only after selection.", cx)) - .child(div().flex().flex_row().gap(space::SM) - .child(gpui_omarchy::input("source-path", path, window, cx) - .debug_selector(|| "source-path".into()).flex_1()) - .child(button("source-scan-path", "Scan directory", ButtonVariant::Secondary, cx) - .disabled(!source_ready || app.volumes_loading || app.volumes_error.is_some()) - .on_click(cx.listener(|this, _, _, cx| this.choose_picker_path(cx))))) - .children(app.picker_error.as_ref().map(|error| div().text_color(theme.danger).child(error.clone()))) - .child(div().flex().flex_row().justify_end().gap(space::SM) - .child(dialog_button("source-cancel", "Cancel", ButtonVariant::Secondary, cx) - .on_click(cx.listener(|this, _, window, cx| { - this.close_volumes(cx); this.apply_focus(window, cx); - }))) - .child(dialog_button("source-scan", "Scan selected root", ButtonVariant::Primary, cx) - .disabled(!source_ready || app.volumes_loading || app.volumes_error.is_some() || app.volumes.is_empty()) - .on_click(cx.listener(|this, _, window, cx| { - this.choose_volume(cx); this.apply_focus(window, cx); - })))); + if app.picker_ssh { + "Read-only over SSH. Nested mounts and symlinks are not \ + followed. Nothing is read until you press Scan." + } else { + "Nested mounts and symlinks are not followed. Nothing is \ + read until you press Scan." + }, + cx, + )) + .children(app.picker_error.as_ref().map(|error| { + div() + .id("source-error") + .role(gpui_kit::Role::Alert) + .aria_label(error.clone()) + .text_color(theme.danger) + .child(error.clone()) + })) + .child(dialog_footer( + [], + Some(cancel_button.into_any_element()), + Some(scan_button.into_any_element()), + )); let popup = div() .id("source-picker-scroll") + .role(gpui_kit::Role::Dialog) + .aria_label("Choose what to scan") + .a11y_synthetic_children(|b| b.parent_node().set_modal()) + .tab_group() .debug_selector(|| "source-picker".into()) .w(size::SOURCE_PICKER) .max_w(Rems( @@ -247,15 +657,7 @@ fn volumes_dialog( )) .overflow_y_scroll() .child(popup); - let centred = centred_popup(popup, { - let close = cancel.clone(); - move |_, window, cx| { - let _ = close.update(cx, |this, cx| { - this.close_volumes(cx); - this.apply_focus(window, cx); - }); - } - }); + let centred = centred_popup(popup); let accept = cx.entity().downgrade(); alert_dialog(&app.confirm_focus, cx) .open(true) @@ -274,7 +676,9 @@ fn volumes_dialog( this.connect_picker(cx); } else if path_focused { this.choose_picker_path(cx); - } else { + } else if this.confirm_focus.is_focused(window) + || this.source_roots_focus.is_focused(window) + { this.choose_volume(cx); } } @@ -292,19 +696,16 @@ fn volumes_dialog( .popup(centred) } -/// Put a dialog's popup in the middle of the window, and close it when a -/// click lands outside it. +/// Put a dialog's popup in the middle of the window, where a click outside +/// it does nothing. /// /// The base dialog hosts its popup as an ordinary child of a full-window box, -/// so a popup lands in the top-left corner unless something centres it. That -/// something ends up in front of the backdrop, which is what used to receive -/// the click that dismisses a dialog, so the click is taken here instead. The -/// card stops a mouse-down from reaching this wrapper, so a click on the -/// dialog itself stays the dialog's own. -fn centred_popup( - card: impl IntoElement, - on_outside: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static, -) -> Stateful
{ +/// so a popup lands in the top-left corner unless something centres it. A +/// dialog asks something or holds typing, so a stray click must not answer +/// or discard it, as macOS sheets and Windows dialogs ignore one: Cancel and +/// Escape close it. Overlays, which only show, close on one instead (see +/// `overlay_backdrop`). +fn centred_popup(card: impl IntoElement) -> Stateful
{ div() .id("dialog-outside") .absolute() @@ -312,11 +713,9 @@ fn centred_popup( .flex() .items_center() .justify_center() - // Any button, as the backdrop took them: a right-click outside closes - // the dialog too. - .on_any_mouse_down(move |event, window, cx| { + // Taken here, so nothing behind the dialog sees it either. + .on_any_mouse_down(|_: &MouseDownEvent, _: &mut Window, cx| { cx.stop_propagation(); - on_outside(event, window, cx); }) .child( div() @@ -330,101 +729,331 @@ fn centred_popup( ) } -/// The one question disktree asks: a permanent deletion cannot be undone, so -/// it is an alert dialog that names what goes and what comes back. The trash is -/// reversible and needs no dialog. -fn delete_dialog( - app: &Disktree, - cx: &mut Context<'_, Disktree>, -) -> impl IntoElement { - let plan = app.plan(); - let title = match plan.targets.as_slice() { - [only] => format!( - "Delete \u{201c}{}\u{201d} permanently?", - short_name(&only.path) - ), - targets => format!("Delete {} items permanently?", targets.len()), - }; - let body = format!( - "This frees {}. Deleted files can\u{2019}t be recovered; move them to the trash if you might need them again.", - human_bytes(plan.bytes()) - ); - let confirm = cx.entity().downgrade(); - let cancel = confirm.clone(); - let actions = div() +/// The footer every dialog and screen ends with. What does not end it sits +/// on the left; what does sits on the right, in the order the system +/// expects: Cancel then the default on macOS, GNOME and Omarchy, so the +/// default is in the corner; the default then Cancel on Windows. +pub fn dialog_footer( + left: impl IntoIterator, + cancel: Option, + primary: Option, +) -> Div { + let (first, second) = + if chrome::Platform::current() == chrome::Platform::Windows { + (primary, cancel) + } else { + (cancel, primary) + }; + div() .flex() .flex_row() - .justify_end() + .flex_wrap() + .items_center() .gap(space::SM) - .child( - dialog_button( - "delete-cancel", - "Cancel", - ButtonVariant::Secondary, - cx, - ) - .on_click(cx.listener(|this, _, window, cx| { - this.cancel_delete(cx); - this.apply_focus(window, cx); - })), - ) - .child( - dialog_button( - "delete-confirm", - "Delete", - ButtonVariant::Danger, - cx, - ) - .on_click(cx.listener(|this, _, window, cx| { - this.confirm_delete(cx); - this.apply_focus(window, cx); - })), - ); - let popup = dialog_popup(cx) - .child(dialog_title(title, cx)) - .child(dialog_description(body, cx)) - .child(actions); - // Built before the chain below, which moves `cancel` into its own - // handler for Escape. - let centred = centred_popup(popup, { - let close = cancel.clone(); - move |_, window, cx| { - let _ = close.update(cx, |this, cx| { - this.cancel_delete(cx); - this.apply_focus(window, cx); - }); - } - }); - alert_dialog(&app.confirm_focus, cx) - .open(true) - .on_ok(move |_, window, cx| { - let _ = confirm.update(cx, |this, cx| { - this.confirm_delete(cx); - this.apply_focus(window, cx); - }); - false - }) - .on_cancel(move |_, window, cx| { - let _ = cancel.update(cx, |this, cx| { - this.cancel_delete(cx); - this.apply_focus(window, cx); - }); - false - }) - .popup(centred) + .children(left) + .child(div().flex_1()) + .children(first) + .children(second) } -// ── explore ───────────────────────────────────────────────────────────── +/// Clears an overlay's flag; one value serves its Done and its backdrop. +type CloseOverlay = fn(&mut Disktree); -fn explore( - app: &mut Disktree, - window: &mut Window, +/// The backdrop of an overlay that only shows something: it dims the +/// window, takes every mouse event so nothing behind it hovers or clicks, +/// and closes the overlay on a click outside the card. The card is never +/// taller than the window: give it `min_h_0` and let its middle scroll. +fn overlay_backdrop( + id: &'static str, + card: impl IntoElement, + close: CloseOverlay, + cx: &Context<'_, Disktree>, +) -> Stateful
{ + let theme = cx.omarchy(); + div() + .id(id) + .absolute() + .inset_0() + .occlude() + .flex() + .items_center() + .justify_center() + .bg(theme.background.opacity(0.86)) + // Room on every side, so a card taller than a short window still + // reads as a dialog instead of a page. + .p(space::LG) + .on_any_mouse_down(cx.listener(move |this, _, window, cx| { + // The click only dismisses; nothing behind or above sees it. + cx.stop_propagation(); + close(this); + this.focus_request = Some(crate::state::FocusTarget::Root); + this.apply_focus(window, cx); + cx.notify(); + })) + .child( + div() + .id("overlay-card") + .occlude() + .flex() + .flex_col() + .max_w_full() + .max_h_full() + .on_any_mouse_down( + |_: &MouseDownEvent, _: &mut Window, cx: &mut App| { + cx.stop_propagation(); + }, + ) + .child(card), + ) +} + +/// An overlay's footer: what it says on the left, Done where a dialog's +/// default button sits, on the right. +fn overlay_footer( + note: impl IntoElement, + close: CloseOverlay, + cx: &Context<'_, Disktree>, +) -> Div { + let theme = cx.omarchy(); + let done = div().debug_selector(|| "overlay-done".into()).child( + dialog_button("overlay-done", "Done", ButtonVariant::Primary, cx) + .on_click(cx.listener(move |this, _, window, cx| { + close(this); + this.focus_request = Some(crate::state::FocusTarget::Root); + this.apply_focus(window, cx); + cx.notify(); + })), + ); + dialog_footer( + [div() + .flex_1() + .min_w_0() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(note) + .into_any_element()], + None, + Some(done.into_any_element()), + ) +} + +/// The one question disktree asks: a permanent deletion cannot be undone, so +/// it is an alert dialog that names what goes and what comes back. The trash is +/// reversible and needs no dialog. +/// Names both intents and their counts, so the button says what it does. +/// Review's subtitle once every marked path has a decision. +fn cleanup_header( + app: &Disktree, + approved: &disktree_core::cleanup::Approved, + plan: &Plan, +) -> String { + let commands = match approved.owner_steps() { + 1 => "1 command".to_string(), + count => format!("{count} commands"), + }; + format!( + "{} marked \u{b7} {commands} \u{b7} {} to delete \u{b7} {} skipped \u{b7} {} scope allocation; savings unmeasured", + app.marks.len(), + approved.file_steps(), + approved.skipped.len(), + human_bytes(plan.bytes()) + ) +} + +fn cleanup_commit_label(commands: usize, files: usize) -> String { + let plural = |count: usize, one: &str, many: &str| { + format!("{count} {}", if count == 1 { one } else { many }) + }; + match (commands, files) { + (0, files) => format!("Delete {}", plural(files, "path", "paths")), + (commands, 0) => { + format!("Run {}", plural(commands, "command", "commands")) + } + (commands, files) => format!( + "Run {} \u{b7} delete {files}", + plural(commands, "command", "commands") + ), + } +} + +fn delete_dialog( + app: &Disktree, + window: &Window, cx: &mut Context<'_, Disktree>, +) -> impl IntoElement { + let plan = app.plan(); + let approved = (app.removal_mode == RemovalMode::OwnerCleanup) + .then(|| app.cleanup_approved().ok()) + .flatten(); + let title = if let Some(approved) = &approved { + format!("Clean up {} items?", approved.steps.len()) + } else if app.removal_mode == RemovalMode::OwnerCleanup { + "Check owners and choose actions first".to_string() + } else { + match plan.targets.as_slice() { + [only] => format!( + "Delete \u{201c}{}\u{201d} permanently?", + short_name(&only.path, app.path_style()) + ), + targets => format!("Delete {} items permanently?", targets.len()), + } + }; + let body = if let Some(approved) = &approved { + approved.description() + } else if app.removal_mode == RemovalMode::OwnerCleanup { + app.cleanup_description() + } else { + format!( + "Estimated to free ≈ {}. Shared blocks and snapshots may retain space. Deleted files can\u{2019}t be recovered; move them to the trash if you might need them again.", + savings(plan.reclaimable_bytes(), plan.possible_bytes()) + ) + }; + let body = if app.rescan_after_removal { + format!("{body} PwrDisk rescans afterwards.") + } else { + body + }; + let confirm = cx.entity().downgrade(); + let cancel = confirm.clone(); + let cancel_button = + dialog_button("delete-cancel", "Cancel", ButtonVariant::Secondary, cx) + .debug_selector(|| "delete-cancel".into()) + .map(|button| { + modal_action( + button, + |this, window, cx| { + this.cancel_delete(cx); + this.apply_focus(window, cx); + }, + cx, + ) + }); + // Deleting files directly is its own consent: its tick is required + // even when the owner commands alone would be confirmable. + let files = + approved.map_or(0, disktree_core::cleanup::Approved::file_steps); + let ticked = app.cleanup_files_ticked(); + let delete_label = if let Some(approved) = &approved { + cleanup_commit_label(approved.owner_steps(), files) + } else if app.rescan_after_removal { + "Delete & rescan".to_string() + } else { + "Delete".to_string() + }; + let delete_button = dialog_button( + "delete-confirm", + delete_label, + ButtonVariant::Danger, + cx, + ) + .debug_selector(|| "delete-confirm".into()) + .semantic_disabled( + app.removal_mode == RemovalMode::OwnerCleanup + && (approved.is_none() || (files > 0 && !ticked)), + ) + .map(|button| { + modal_action( + button, + |this, window, cx| { + this.confirm_delete(cx); + this.apply_focus(window, cx); + }, + cx, + ) + }); + let owner_cleanup = app.removal_mode == RemovalMode::OwnerCleanup; + let description = div() + .id("cleanup-confirmation-scroll") + .min_w_0() + .max_h(Rems( + window.viewport_size().height.as_f32() / app.rem + * size::CLEANUP_PREVIEW_HEIGHT_FRACTION, + )) + .overflow_scroll() + .child(dialog_description(body.clone(), cx)); + let tick = (files > 0).then(|| { + let entity = cx.entity().downgrade(); + checkbox( + "cleanup-files-tick", + "Delete these files myself, without their owner\u{2019}s command", + if ticked { + CheckboxState::Checked + } else { + CheckboxState::Unchecked + }, + cx, + ) + .debug_selector(|| "cleanup-files-tick".into()) + .tab_stop(true) + .on_change(move |_, _, _, cx| { + let _ = entity.update(cx, Disktree::tick_cleanup_files); + }) + }); + let popup = dialog_popup(cx) + .when(owner_cleanup, |popup| popup.w(size::CLEANUP_PREVIEW_WIDTH)) + .child(dialog_title(title.clone(), cx)) + .child(description) + .children(tick) + .child(dialog_footer( + [], + Some(cancel_button.into_any_element()), + Some(delete_button.into_any_element()), + )); + let centred = centred_popup(popup) + .role(gpui_kit::Role::AlertDialog) + .aria_label(title) + .aria_description(body) + .a11y_synthetic_children(|b| b.parent_node().set_modal()); + alert_dialog(&app.confirm_focus, cx) + .open(true) + .on_ok(move |_, window, cx| { + let _ = confirm.update(cx, |this, cx| { + if this.confirm_open && this.confirm_focus.is_focused(window) { + this.confirm_delete(cx); + this.apply_focus(window, cx); + } + }); + false + }) + .on_cancel(move |_, window, cx| { + let _ = cancel.update(cx, |this, cx| { + this.cancel_delete(cx); + this.apply_focus(window, cx); + }); + false + }) + .popup(centred) +} + +// ── explore ───────────────────────────────────────────────────────────── + +/// The volume's space, for the row that stands in for the hidden panel. +fn compact_space(app: &Disktree) -> String { + app.space.map_or_else( + || "Volume space unavailable".to_owned(), + |space| { + format!( + "{} available of {}; {} marked", + human_bytes(space.available), + human_bytes(space.total), + app.marks.len() + ) + }, + ) +} + +fn explore( + app: &mut Disktree, + toasts: Option, + window: &Window, + cx: &Context<'_, Disktree>, ) -> Div { let theme = cx.omarchy().clone(); if app.awaiting_root { return div() .debug_selector(|| "choose-root-idle".into()) + .relative() + .children(toasts) .flex() .flex_col() .flex_1() @@ -461,8 +1090,32 @@ fn explore( // only gives way when the mosaic would be too narrow to read. let panel = (app.show_selection || app.is_indexing()) && width_rems >= PANEL_SHOWN_REMS; - if panel && let Some(path) = selection_checkout(app) { - app.ensure_git(&path, cx); + let compact = + window.viewport_size().height.as_f32() / app.rem < COMPACT_PANEL_REMS; + // The legend's row is the mosaic's column, less its padding. + let edges = &app.content_edges; + let legend_room = window.viewport_size().width + - edges.left + - edges.right + - if panel { + px(app.panel_rems * app.rem) + } else { + px(0.) + } + - px(space::LG.0 * 2. * app.rem); + let legend_fit = legend_fit(app, legend_room, window, &theme); + let legend_drawn = + !app.file_list || !crate::file_list::compact(window, app.rem); + // A menu with nothing to hang from is closed, not kept for later: it + // would swallow the next Escape and reopen by itself when the row + // overflows again. Its button's hover goes with it, since the button + // may have left from under a resting pointer. + if !legend_drawn || legend_fit.more.is_empty() { + app.legend_menu_open = false; + app.legend_more_hover = false; + } + if panel && let Some(path) = panel_checkout(app) { + app.want_git(&path, window.is_window_active(), cx); } let viewport = if app.tree().is_none() { @@ -476,7 +1129,25 @@ fn explore( scanning_panel(app, &theme, cx).into_any_element() } } else { - treemap_view::mosaic(mosaic, app, window, cx).into_any_element() + let view = if app.file_list { + crate::file_list::list(app, window, cx).into_any_element() + } else { + treemap_view::mosaic(mosaic, app, window, cx).into_any_element() + }; + // A filter that keeps nothing here says so over the empty view, + // rather than leave a blank mosaic or list to puzzle over. + match app.legend_empty_here() { + Some(kept) => div() + .relative() + .flex() + .flex_1() + .min_w_0() + .min_h_0() + .child(view) + .child(legend_empty(app, kept, &theme, cx)) + .into_any_element(), + None => view, + } }; div() @@ -484,7 +1155,6 @@ fn explore( .flex_col() .flex_1() .min_h_0() - .child(top_bar(app, &theme, window, cx)) .child( div() .id("explore-body") @@ -496,9 +1166,16 @@ fn explore( // pointer from here, wherever it goes in the window. .on_drag_move(cx.listener( |this, event: &DragMoveEvent, window, cx| { + // The pointer is in window coordinates; the + // panel's right edge is the content's, inset by a + // client-side frame. + let inset = &this.content_edges; this.panel_rems = panel_width( - event.event.position.x.as_f32(), - window.viewport_size().width.as_f32(), + (event.event.position.x - inset.left).as_f32(), + (window.viewport_size().width + - inset.left + - inset.right) + .as_f32(), this.rem, ); cx.notify(); @@ -506,23 +1183,34 @@ fn explore( )) .child( div() + .relative() .flex() .flex_col() .flex_1() .min_w_0() .min_h_0() - .child(trail_and_legend(app, &theme, cx)) + .when(legend_drawn, |view| view.child(trail_and_legend(app, &legend_fit, &theme, cx))) .child( div() + .id("file-navigation") + .when(app.tree().is_some() && !app.file_list, |view| view + .role(gpui_kit::Role::Group).aria_label("Treemap navigation; arrows move, Space marks, n selects the next sibling; choose List in the View switch for file details") + .track_focus(&app.file_focus).tab_index(0).tab_stop(true) + .focus_visible(|style| style.border_2().border_color(theme.accent))) .flex() .flex_1() .min_h_0() .px(space::LG) .pb(space::SM) .child(viewport), - ), + ) + // Over the mosaic's lower left, clear of the side + // panel and the bands below. + .children(toasts), ) - .children(panel.then(|| side_panel(app, &theme, cx))), + .children( + panel.then(|| side_panel(app, compact, &theme, cx)), + ), ) .children((app.is_indexing() && !panel).then(|| { div() @@ -530,25 +1218,45 @@ fn explore( .py(space::SM) .child(indexing_compact(app, &theme, cx)) })) + .children((!panel).then(|| div().flex().flex_row().flex_wrap().items_center().gap(space::SM).px(space::LG).py(space::XS) + .child({ let space = compact_space(app); crate::semantics::text("compact-space", space.clone()).child(space) }) + .child(button("compact-source", "Source…", ButtonVariant::Secondary, cx).on_click(cx.listener(|this, _, window, cx| { this.open_volumes(cx); this.apply_focus(window, cx); }))))) .child(key_bar(app, &theme, cx)) } -/// The selection, when it is a checkout git can say something about. -fn selection_checkout(app: &Disktree) -> Option { +/// The selected tile, when it is a checkout git can say something about; +/// `selection_section` reads the answer back with `known_checkout`. +/// +/// Only a selected tile: with nothing selected the panel describes the +/// directory on screen, often the scan root, and `git status` there can +/// walk a whole home directory tracked as a dotfiles checkout. +fn panel_checkout(app: &mut Disktree) -> Option { if app.remote.is_some() { return None; } - let target = app.action_target()?; + let target = git_target(app)?; let node = app.node_at(&target)?; if !node.is_dir() { return None; } let path = app.path_at(&target)?; - crate::git::is_checkout(&path).then_some(path) + app.checkout_at(&path).then_some(path) +} + +/// The tile git may be asked about: a selected one, never the scan root. +fn git_target(app: &Disktree) -> Option> { + app.action_target().filter(|target| !target.is_empty()) } /// Width, in rem, below which the side panel gives the mosaic its room. const PANEL_SHOWN_REMS: f32 = 52.0; +/// Height, in rem, below which the side panel is compact: the selection's +/// figures fold into one line and an idle agent line goes, so Marked and +/// Worth a look start in sight. A 1200×600 window with an assessment +/// selected otherwise opens on the selection alone; 48 rem is 768 px at +/// the default size, and in rems interface zoom walks through it as a +/// shorter window does, as the bar's tiers do across. +const COMPACT_PANEL_REMS: f32 = 48.0; /// What the panel handle drags. The width itself lives in the app state. #[derive(Clone, Copy, Debug)] @@ -567,37 +1275,64 @@ impl gpui_kit::Render for NoGhost { } } -// ── top bar ───────────────────────────────────────────────────────────── +// ── title strip ───────────────────────────────────────────────────────── + +/// Width, in rem, below which the wordmark gives the trail its room: the +/// settings do not shrink, and at the minimum window the stoplights' zone +/// would otherwise squeeze the trail to nothing. The mark stays. +const WORDMARK_SHOWN_REMS: f32 = 70.0; -/// The app, what the whole scan found, and the controls that decide what -/// is measured, on the edge they own. -fn top_bar( +/// The window's title strip. On explore it carries what the whole window +/// is about — where you are and how it is measured — after the brand; the +/// other screens have a heading of their own, so it is only the brand there. +fn title_strip( app: &Disktree, - theme: &Theme, + frame: &Frame, window: &mut Window, cx: &mut Context<'_, Disktree>, -) -> Div { - div() - .flex() - .flex_row() - .items_center() - .gap(space::LG) - .px(space::LG) - .py(space::MD) - .border_b_1() - .border_color(theme.divider()) - .child(with_tooltip( - logo(theme).id("choose-source").cursor_pointer() - .on_click(cx.listener(|this, _, window, cx| { - this.open_volumes(cx); - this.apply_focus(window, cx); - })), - "Choose local or SSH source · v", - )) - // Where you are is navigation, and it belongs to the whole window. - .child(trail(app, theme, cx)) - .child(div().flex_1()) - .child(view_settings(app, window, cx)) +) -> Stateful
{ + let theme = cx.omarchy().clone(); + let explore = app.screen == Screen::Explore; + let width_rems = window.viewport_size().width.as_f32() / app.rem; + let wordmark = !explore || width_rems >= WORDMARK_SHOWN_REMS; + let menu = + frame_has_app_menu(Some(frame)).then(|| app_menu_button(app, cx)); + let content = if explore { + div() + .flex() + .flex_row() + .items_center() + .flex_1() + .min_w_0() + .children(menu) + // Where you are is navigation, and it belongs to the whole window. + .child(trail(app, &theme, cx)) + // The space between the trail and the settings is all title + // bar: a gap there would look like it and not move the window. + .child( + chrome::drag_area(frame, "strip-drag", cx) + .flex_1() + .min_w(space::XXL) + .self_stretch(), + ) + .children(agent_pill(app, &theme)) + .children(update_chip(app, &theme, cx)) + .child(view_settings(app, window, cx)) + } else { + div() + .flex() + .flex_1() + .items_center() + .self_stretch() + .children(menu) + .child( + chrome::drag_area(frame, "strip-drag", cx) + .flex_1() + .self_stretch(), + ) + .children(update_chip(app, &theme, cx)) + }; + chrome::strip(frame, wordmark, content, window, cx) } /// The trail, from `/`. Above the scanned root, a crumb widens the scan; @@ -625,18 +1360,19 @@ fn trail(app: &Disktree, theme: &Theme, cx: &Context<'_, Disktree>) -> Div { for (index, (label, step)) in steps.into_iter().enumerate() { if hidden.contains(&index) { if index == hidden.start { - row = row.child(separator_glyph(theme)).child( - div() - .px(space::XS) - .text_color(theme.secondary.opacity(0.6)) - .child("…"), - ); + row = + row.child(separator_glyph(theme, app.path_style())).child( + div() + .px(space::XS) + .text_color(theme.secondary.opacity(0.6)) + .child("…"), + ); } continue; } // The root is its own separator: "/" then "home", not "/ / home". if index > 1 { - row = row.child(separator_glyph(theme)); + row = row.child(separator_glyph(theme, app.path_style())); } let id = ElementId::Name(SharedString::from(format!("crumb-{index}"))); let crumb = match step { @@ -668,13 +1404,13 @@ fn trail(app: &Disktree, theme: &Theme, cx: &Context<'_, Disktree>) -> Div { /// Steps a trail shows before it folds its middle into an ellipsis. const TRAIL_STEPS: usize = 7; -/// The platform's path separator, so the trail reads like the paths shown -/// elsewhere: `/` here, `\` on Windows. -fn separator_glyph(theme: &Theme) -> Div { +/// The scanned machine's path separator, so the trail reads like the paths +/// shown elsewhere: `/` here and on SSH hosts, `\` on Windows. +fn separator_glyph(theme: &Theme, style: PathStyle) -> Div { div() .text_color(theme.secondary.opacity(0.5)) .text_size(text::BODY) - .child(std::path::MAIN_SEPARATOR_STR) + .child(style.separator().to_string()) } /// A crumb in the tree. Its label goes there (the current one opens the @@ -697,6 +1433,10 @@ fn tree_crumb( .into_any_element(); }; let parent = parent.to_vec(); + // Inside a mark, the trail says so the way the tiles do: struck through. + // Every tile below it is struck too, but the trail is what still shows + // the mark itself once you have gone into it. + let struck = app.goes_with_a_mark(&path); let open = app .crumb_menu .as_ref() @@ -708,15 +1448,17 @@ fn tree_crumb( .flex_row() .items_center() .when(current || open, |this| this.bg(theme.hover_fill())) - .child(widgets::crumb(id.clone(), label, current, cx).on_click( - cx.listener(move |this, _, _, cx| { - if current { - this.open_crumb_menu(&label_path, cx); - } else { - this.go_to(label_path.clone(), cx); - } - }), - )) + .child( + widgets::crumb(id.clone(), label, current, cx) + .when(struck, Styled::line_through) + .on_click(cx.listener(move |this, _, _, cx| { + if current { + this.open_crumb_menu(&label_path, cx); + } else { + this.go_to(label_path.clone(), cx); + } + })), + ) .child( div() .id(ElementId::Name(format!("{id}-menu").into())) @@ -772,9 +1514,9 @@ fn sibling_menu( let largest = rows.first().map_or(1, |row| row.value.max(1)); let parent_name = app.node_at(parent).map_or_else(String::new, |node| { if parent.is_empty() { - crate::marks::display_path(&app.root_path, app.home.as_deref()) + app.display_path(&app.root_path) } else { - node.name.to_string() + node.name().to_string() } }); let metric = app.options.metric; @@ -877,44 +1619,6 @@ fn sibling_menu( panel } -/// Four tiles in category colours, and the name. -fn logo(theme: &Theme) -> Div { - let tile = |category| { - div() - .size(space::SM) - .bg(palette::category_accent(theme, category)) - }; - let column = |top, bottom| { - div() - .flex() - .flex_col() - .gap(space::XXS) - .child(tile(top)) - .child(tile(bottom)) - }; - div() - .flex() - .flex_row() - .items_center() - .gap(space::SM) - .flex_shrink_0() - .child( - div() - .flex() - .flex_row() - .gap(space::XXS) - .child(column(Category::Code, Category::Synced)) - .child(column(Category::AgentScratch, Category::Toolchain)), - ) - .child( - div() - .text_size(text::HEADING) - .font_weight(FontWeight::BOLD) - .text_color(theme.bright) - .child("disktree"), - ) -} - /// How the mosaic is measured and drawn, as real controls with visible state. /// /// Every control hands the keyboard straight back to the treemap: arrows, @@ -928,7 +1632,10 @@ fn view_settings( let focus = app.focus.clone(); let entity = cx.entity().downgrade(); - let mode = { + // What does not fit goes in ⋮, least used first; the view switch + // never does. See `toolbar::BarFit`. Folded controls are not built. + let fit = app.bar_fit; + let mode = fit.shows_mode().then(|| { let entity = entity.clone(); let focus = focus.clone(); button_group( @@ -946,11 +1653,12 @@ fn view_settings( window, cx, ) + .debug_selector(|| "measure-mode".into()) .w(size::RANKING_CHOICE) // Tighter than a standalone group, so the segmented control shares // the checkboxes' height and centre line. .p(space::XXS) - }; + }); let check = |on: bool| { if on { @@ -959,7 +1667,7 @@ fn view_settings( CheckboxState::Unchecked } }; - let hidden = { + let hidden = fit.shows_scan_options().then(|| { let entity = entity.clone(); let focus = focus.clone(); checkbox( @@ -968,31 +1676,32 @@ fn view_settings( check(app.options.include_hidden), cx, ) - .tab_stop(false) + // gpui-omarchy's checkbox is `self_start`, made to hug its label in + // a column; in the strip that pins it to the top edge instead of + // the centre line the other controls share. + .self_center() + .tab_stop(true) .on_change(move |_, _, window, cx| { - let _ = entity.update(cx, |this, cx| { - this.options.include_hidden = !this.options.include_hidden; - this.start_scan(cx); - }); + let _ = entity.update(cx, Disktree::toggle_hidden); window.focus(&focus, cx); }) - }; - let apparent = { + }); + let apparent = fit.shows_scan_options().then(|| { + let entity = entity.clone(); + let focus = focus.clone(); checkbox( "apparent", "Apparent size", check(app.options.apparent_size), cx, ) - .tab_stop(false) + .self_center() + .tab_stop(true) .on_change(move |_, _, window, cx| { - let _ = entity.update(cx, |this, cx| { - this.options.apparent_size = !this.options.apparent_size; - this.start_scan(cx); - }); + let _ = entity.update(cx, Disktree::toggle_apparent); window.focus(&focus, cx); }) - }; + }); let theme = cx.omarchy().clone(); // Back and forward through the directories visited, beside the choices @@ -1020,8 +1729,9 @@ fn view_settings( })) .child( button(id, label, ButtonVariant::Secondary, cx) - .tab_stop(false) - .disabled(!enabled) + .accessibility_label(if back { "Go back in navigation history" } else { "Go forward in navigation history" }) + .tab_stop(true) + .semantic_disabled(!enabled) // Borderless: glyphs on the bar, not controls in a // frame. Hover keeps the fill but not the outline it // would add. @@ -1052,26 +1762,28 @@ fn view_settings( ) }) }; - let history = div() - .flex() - .flex_row() - .items_center() - .child(travel( - "history-back", - "<", - app.can_go_back(), - true, - Disktree::go_back, - cx, - )) - .child(travel( - "history-forward", - ">", - app.can_go_forward(), - false, - Disktree::go_forward, - cx, - )); + let history = fit.shows_history_and_depth().then(|| { + div() + .flex() + .flex_row() + .items_center() + .child(travel( + "history-back", + "<", + app.can_go_back(), + true, + Disktree::go_back, + cx, + )) + .child(travel( + "history-forward", + ">", + app.can_go_forward(), + false, + Disktree::go_forward, + cx, + )) + }); let depth = app.layout_options.max_depth; let stepper = |id: &'static str, @@ -1079,45 +1791,445 @@ fn view_settings( step: i32, cx: &mut Context<'_, Disktree>| { button(id, label, ButtonVariant::Secondary, cx) - .tab_stop(false) - .disabled(if step < 0 { depth <= 1 } else { depth >= 6 }) + .debug_selector(move || format!("{id}-target")) + .min_w(size::POINTER_TARGET) + .min_h(size::POINTER_TARGET) + .accessibility_label(if step < 0 { + "Decrease treemap depth" + } else { + "Increase treemap depth" + }) + .tab_stop(true) + .semantic_disabled(if step < 0 { depth <= 1 } else { depth >= 6 }) .on_click(cx.listener(move |this, _, window, cx| { this.adjust_depth(step, cx); window.focus(&this.focus, cx); })) }; - let depth_control = with_tooltip( - div() - .id("depth") + let depth_control = fit.shows_history_and_depth().then(|| { + with_tooltip( + div() + .id("depth") + .flex() + .flex_row() + .items_center() + .border_1() + .border_color(theme.control_border()) + .child( + div() + .px(space::SM) + .text_size(text::BODY) + .text_color(theme.foreground) + .child(format!("Depth {depth}")), + ) + .child(stepper("depth-less", "\u{2212}", -1, cx)) + .child(stepper("depth-more", "+", 1, cx)), + "Levels drawn at once \u{00b7} [ and ]", + ) + }); + + let rems = window.viewport_size().width.as_f32() / app.rem; + let switch = + view_switch(app, crate::toolbar::BarFit::labelled_switch(rems), cx); + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .flex_shrink_0() + .children(history) + .child(switch) + .children(mode) + .children(hidden) + .children(apparent) + .children(depth_control) + .map(|row| { + if fit.shows_scan_options() { + row.child(power_efficiency(app, cx)) + } else { + row.child(more_menu(app, cx)) + } + }) +} + +/// Treemap or file list, from the menu bar or the view switch. A drawn +/// list takes the keyboard, so a screen reader lands in it; until a scan +/// finishes there is no list yet, and the root keeps it. +fn choose_view( + app: &mut Disktree, + on: bool, + window: &mut Window, + cx: &mut Context<'_, Disktree>, +) { + if app.screen != Screen::Explore || app.has_modal() { + return; + } + app.show_file_list(on, cx); + let list = on && app.tree().is_some(); + window.focus(if list { &app.file_focus } else { &app.focus }, cx); +} + +/// Treemap | List: how the directory on screen is drawn. It is a radio +/// group like Size | Files | Age, with a drawn glyph on each option and +/// its word when the bar has room. Its spoken name says what the list is +/// for, which the word on screen does not need to. +fn view_switch( + app: &Disktree, + labelled: bool, + cx: &Context<'_, Disktree>, +) -> impl IntoElement { + use gpui_kit::base::{Radio, RadioGroup}; + + let theme = cx.omarchy().clone(); + let entity = cx.entity().downgrade(); + let shortcut = if cfg!(target_os = "macos") { + "\u{2318}" + } else { + "ctrl-" + }; + let option = |list: bool| { + let checked = app.file_list == list; + let (id, word, spoken, about) = if list { + ( + "view-list", + "List", + "File list, for screen readers", + "Every entry in this folder as a row, with its size and \ + share. Works with screen readers.", + ) + } else { + ( + "view-treemap", + "Treemap", + "Treemap", + "Each entry's share of this folder, drawn as nested tiles.", + ) + }; + let ink = if checked { + theme.bright + } else { + theme.foreground + }; + let glyph = if list { + widgets::list_glyph(ink) + } else { + widgets::treemap_glyph(ink) + }; + let entity = entity.clone(); + let keys = entity.clone(); + let radio = Radio::new(id) + .debug_selector(move || id.into()) + .checked(checked) + .accessibility_label(spoken) + .set_position(usize::from(list) + 1, 2) + // One stop for the group: the option that is on, as a radio + // group's roving focus goes. + .tab_stop(checked) .flex() .flex_row() .items_center() + .justify_center() + .gap(space::SM) + .min_w(size::POINTER_TARGET) + .min_h(size::POINTER_TARGET) + .px(space::SM) .border_1() - .border_color(theme.control_border()) - .child( + .border_color(theme.foreground.opacity(0.)) + .text_size(text::BODY) + .text_color(ink) + .when(checked, |this| this.bg(theme.selected_fill())) + .when(!checked, |this| { + this.hover(|style| style.bg(theme.hover_fill())) + }) + .focus_visible(|style| style.border_color(theme.focus_border())) + .child(glyph) + .when(labelled, |this| this.child(word)) + .on_change(move |_, _, window, cx| { + let _ = entity.update(cx, |this, cx| { + choose_view(this, list, window, cx); + }); + }) + // The arrows choose, as in any radio group. Focus moves into + // the view chosen, as a click does, so the list is read out. + .on_key_down(move |event: &KeyDownEvent, window, cx| { + let to = match event.keystroke.key.as_str() { + "left" | "up" => false, + "right" | "down" => true, + _ => return, + }; + cx.stop_propagation(); + let _ = keys.update(cx, |this, cx| { + choose_view(this, to, window, cx); + }); + }); + with_tooltip( + radio, + format!( + "{} \u{00b7} {shortcut}{}\n{about}", + if list { "File list" } else { "Treemap" }, + if list { 2 } else { 1 } + ), + ) + }; + RadioGroup::new("view-switch") + .axis(gpui_kit::Axis::Horizontal) + .aria_label("View") + .flex() + .flex_row() + .flex_shrink_0() + .gap(space::XXS) + // Framed and padded as Size | Files | Age is, so both groups share + // a height and a centre line. + .p(space::XXS) + .border_1() + .border_color(theme.divider()) + .child(option(false)) + .child(option(true)) +} + +/// ⋮: the bar's controls that did not fit, in the sibling and power menus' +/// grammar. When the scan workers are among them, their menu opens here. +fn more_menu(app: &Disktree, cx: &Context<'_, Disktree>) -> Div { + use crate::toolbar::MoreItem; + + let theme = cx.omarchy().clone(); + let open = app.more_menu.is_some(); + let trigger = div() + .id("more-hover") + .on_hover(cx.listener(|this, hovered: &bool, _, cx| { + this.more_hover = *hovered; + cx.notify(); + })) + .child( + button("more-toggle", "", ButtonVariant::Secondary, cx) + .debug_selector(|| "more-toggle".into()) + .accessibility_label("More view options") + .selected(open) + .tab_stop(true) + .min_w(size::POINTER_TARGET) + .min_h(size::POINTER_TARGET) + .border_1() + .border_color(theme.control_border()) + .child( + gpui_omarchy::icon( + gpui_omarchy::IconName::EllipsisVertical, + ) + .size(icon::SM) + .text_color(theme.bright), + ) + .on_click(cx.listener(|this, _, window, cx| { + this.toggle_more_menu(cx); + // The menu's keys reach it through the root, as the + // power menu's do. + window.focus(&this.focus, cx); + })), + ); + let trigger = if open { + trigger + } else { + with_tooltip(trigger, "More view options") + }; + let mut control = div().relative().flex_shrink_0().child(trigger); + if app.power_menu.is_some() { + if let Some(popup) = power_popup(app, cx) { + control = control.child(popup); + } + return control; + } + let Some(highlighted) = app.more_menu else { + return control; + }; + + let items = app.bar_fit.more_items(); + let mut menu = div() + .id("more-menu") + .debug_selector(|| "more-menu".into()) + .occlude() + .flex() + .flex_col() + .w(size::MORE_MENU) + .p(space::XS) + .bg(theme.surface) + .border_1() + .border_color(theme.control_border()) + .shadow_lg() + .on_mouse_down_out(cx.listener(|this, _, _, cx| { + if !this.more_hover { + this.more_menu = None; + cx.notify(); + } + })); + let mut section = ""; + for (index, item) in items.into_iter().enumerate() { + if item.section() != section { + if !section.is_empty() { + menu = menu + .child(div().h(px(1.)).my(space::XS).bg(theme.divider())); + } + section = item.section(); + menu = menu.child( div() .px(space::SM) + .py(space::XS) + .text_size(text::CAPTION) + .text_color(theme.secondary.opacity(0.8)) + .child(section), + ); + } + let enabled = app.more_item_enabled(item); + let check = |on: bool| { + div().flex_shrink_0().w(icon::SM).when(on, |this| { + this.child( + gpui_omarchy::icon(gpui_omarchy::IconName::Check) + .size(icon::SM) + .text_color(theme.accent), + ) + }) + }; + let (lead, name, trail): (Div, String, Option) = match item + { + MoreItem::Mode(mode) => ( + check(app.mode_index() == mode), + ["Size", "Files", "Age"][mode].to_owned(), + None, + ), + MoreItem::Back => (check(false), "Back".into(), None), + MoreItem::Forward => (check(false), "Forward".into(), None), + MoreItem::Depth => { + let depth = app.layout_options.max_depth; + let step = |id: &'static str, label: &'static str, by: i32| { + button(id, label, ButtonVariant::Secondary, cx) + .debug_selector(move || id.into()) + .accessibility_label(if by < 0 { + "Decrease treemap depth" + } else { + "Increase treemap depth" + }) + .min_w(size::POINTER_TARGET) + .min_h(size::POINTER_TARGET) + .semantic_disabled(if by < 0 { + depth <= 1 + } else { + depth >= 6 + }) + .on_click(cx.listener(move |this, _, window, cx| { + this.adjust_depth(by, cx); + window.focus(&this.focus, cx); + })) + }; + ( + check(false), + format!("Depth {depth}"), + Some( + div() + .flex() + .flex_row() + .border_1() + .border_color(theme.control_border()) + .child(step("more-depth-less", "\u{2212}", -1)) + .child(step("more-depth-more", "+", 1)) + .into_any_element(), + ), + ) + } + MoreItem::Hidden => ( + check(app.options.include_hidden), + "Hidden files".into(), + None, + ), + MoreItem::Apparent => ( + check(app.options.apparent_size), + "Apparent size".into(), + None, + ), + MoreItem::Workers => ( + check(false), + "Scan workers".into(), + Some( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(format!( + "{} \u{203a}", + app.power_choice.map_or( + "Custom", + crate::power::PowerEfficiency::name + ) + )) + .into_any_element(), + ), + ), + }; + let key = match item { + MoreItem::Back => Some(if cfg!(target_os = "macos") { + "\u{2318}[" + } else { + "Alt+\u{2190}" + }), + MoreItem::Forward => Some(if cfg!(target_os = "macos") { + "\u{2318}]" + } else { + "Alt+\u{2192}" + }), + _ => None, + }; + let row = div() + .id(ElementId::Name(format!("more-item-{index}").into())) + .debug_selector(move || format!("more-item-{index}")) + .flex() + .flex_row() + .items_center() + .gap(space::MD) + .min_h(size::POINTER_TARGET) + .px(space::SM) + .when(index == highlighted && enabled, |this| { + this.bg(theme.hover_fill()) + }) + .when(!enabled, |this| this.opacity(0.45)) + .child(lead) + .child( + div() + .flex_1() + .min_w_0() .text_size(text::BODY) - .text_color(theme.foreground) - .child(format!("Depth {depth}")), + .text_color(theme.bright) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(name), ) - .child(stepper("depth-less", "\u{2212}", -1, cx)) - .child(stepper("depth-more", "+", 1, cx)), - "Levels drawn at once \u{00b7} [ and ]", - ); - - div() - .flex() - .flex_row() - .items_center() - .gap(space::SM) - .flex_shrink_0() - .child(history) - .child(mode) - .child(hidden) - .child(apparent) - .child(depth_control) - .child(power_efficiency(app, cx)) + .children(key.map(|key| { + div() + .flex_shrink_0() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(key) + })) + .children(trail) + .on_hover(cx.listener(move |this, hovered: &bool, _, cx| { + if *hovered && this.more_menu.is_some() { + this.more_menu = Some(index); + cx.notify(); + } + })) + .on_click(cx.listener(move |this, _, window, cx| { + this.activate_more(item, cx); + window.focus(&this.focus, cx); + })); + menu = menu.child(row); + } + control.child( + div().absolute().top_full().right_0().child( + deferred( + anchored() + .anchor(gpui_kit::Anchor::TopRight) + .snap_to_window_with_margin(px(8.)) + .offset(gpui_kit::point(px(0.), px(4.))) + .child(menu), + ) + .with_priority(2), + ), + ) } /// What the tooltip says the choice will do, where the gauge alone cannot. @@ -1162,7 +2274,7 @@ fn power_efficiency(app: &Disktree, cx: &Context<'_, Disktree>) -> Div { button("power-toggle", "", ButtonVariant::Secondary, cx) .accessibility_label(format!("Power Efficiency: {name}")) .selected(open) - .tab_stop(false) + .tab_stop(true) .child(widgets::signal( PowerEfficiency::signal(threads, cpus), cx, @@ -1191,10 +2303,23 @@ fn power_efficiency(app: &Disktree, cx: &Context<'_, Disktree>) -> Div { ), ) }; - let mut control = div().relative().child(trigger); - let Some(highlighted) = app.power_menu else { - return control; - }; + div() + .relative() + .child(trigger) + .children(power_popup(app, cx)) +} + +/// The Power Efficiency menu, hung from the right edge of whichever control +/// opened it: the gauge, or ⋮ once the gauge has folded into it. +fn power_popup( + app: &Disktree, + cx: &Context<'_, Disktree>, +) -> Option { + use crate::power::{self, PowerEfficiency}; + + let theme = cx.omarchy().clone(); + let cpus = app.cpu_threads; + let highlighted = app.power_menu?; let mut menu = div() .id("power-menu") @@ -1209,7 +2334,8 @@ fn power_efficiency(app: &Disktree, cx: &Context<'_, Disktree>) -> Div { .border_color(theme.control_border()) .shadow_lg() .on_mouse_down_out(cx.listener(|this, _, _, cx| { - if !this.power_hover { + // A press on its button (the gauge, or ⋮) is the button's. + if !this.power_hover && !this.more_hover { this.power_menu = None; cx.notify(); } @@ -1302,11 +2428,11 @@ fn power_efficiency(app: &Disktree, cx: &Context<'_, Disktree>) -> Div { }; menu = menu.child(row); } - control = control.child( + Some( div().absolute().top_full().right_0().child( deferred( - // Hung from the gauge's right edge: the bar's last control, - // so the menu opens inward rather than off the window. + // Hung from the right edge: the bar's last control, so the + // menu opens inward rather than off the window. anchored() .anchor(gpui_kit::Anchor::TopRight) .snap_to_window_with_margin(px(8.)) @@ -1315,16 +2441,16 @@ fn power_efficiency(app: &Disktree, cx: &Context<'_, Disktree>) -> Div { ) .with_priority(2), ), - ); - control + ) } // ── trail and legend ──────────────────────────────────────────────────── -/// Where you are, as a clickable trail, and what the colours mean, on one -/// row over the mosaic. +/// What the scan holds and the search, on one row over the mosaic, and +/// what the colours mean on the row under it. fn trail_and_legend( app: &Disktree, + fit: &LegendFit, theme: &Theme, cx: &Context<'_, Disktree>, ) -> Div { @@ -1333,13 +2459,21 @@ fn trail_and_legend( .flex_row() .items_center() .gap(space::LG) - .px(space::LG) - .py(space::SM) .child(scan_totals(app, theme)); if app.find_open || !app.find.is_empty() { row = row.child(find_field(app, theme)); } - row.child(div().flex_1()).child(legend(app, theme, cx)) + // The legend has a row of its own: its chips are filters, so each + // must stay reachable, and sharing the row with the search clipped + // the last of them whenever the window was not wide. + div() + .flex() + .flex_col() + .gap(space::XS) + .px(space::LG) + .py(space::SM) + .child(row) + .child(legend(app, fit, theme, cx)) } /// What the whole scan found, as one quiet line; unreadable paths are @@ -1356,7 +2490,31 @@ fn scan_totals(app: &Disktree, theme: &Theme) -> Div { let files = tree.map_or(app.progress.files, |node| node.files); let dirs = tree.map_or(app.progress.dirs, |node| u64::from(node.dirs)); let errors = app.progress.errors; + // Filtered, the line says what share of the scan is on screen, in the + // bright colour, so a filtered mosaic is never taken for the whole. + if tree.is_some() && app.legend.is_active() { + let shown = match app.legend_matches.as_deref() { + Some(matches) if !app.legend_pending => format!( + "Showing {} of {}", + human_bytes(matches.bytes), + human_bytes(bytes) + ), + _ => "Filtering\u{2026}".to_owned(), + }; + return div() + .debug_selector(|| "scan-totals".into()) + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .flex_shrink_0() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(div().text_color(theme.bright).child(shown)) + .child(format!("\u{00b7} {}", app.legend.summary())); + } div() + .debug_selector(|| "scan-totals".into()) .flex() .flex_row() .items_center() @@ -1370,6 +2528,19 @@ fn scan_totals(app: &Disktree, theme: &Theme) -> Div { widgets::human_count(files), widgets::human_count(dirs) )) + .when(tree.is_some_and(|node| node.sharing().files > 0), |this| { + let sharing = tree.expect("checked above").sharing(); + this.child(format!( + "· APFS clones: {} · ≈ {} counted again{}", + human_bytes(sharing.bytes), + human_bytes(sharing.duplicate_bytes), + if sharing.groups_truncated { + " (partial)" + } else { + "" + } + )) + }) .when(errors > 0, |this| { this.child(div().text_color(theme.warning).child(format!( "· {} unreadable", @@ -1378,57 +2549,655 @@ fn scan_totals(app: &Disktree, theme: &Theme) -> Div { }) } -/// The key to the colours: the categories, or the age ramp in age mode. -/// Clipped from the trailing end when the row runs out of room. -fn legend(app: &Disktree, theme: &Theme, cx: &App) -> Div { - let item = |swatch: Div, label: &'static str| { - div() - .flex() - .flex_row() +/// Which legend chips go on the row and which in its "+N" menu. +pub struct LegendFit { + /// On the row, in the legend's order. + pub shown: Vec, + /// In the menu, in the legend's order. + pub more: Vec, +} + +/// What a chip keeps of the whole scan, once that is worked out. +fn chip_share(app: &Disktree, id: crate::legend::ChipId) -> Option { + use crate::legend::ChipId; + let shares = app.legend_shares.as_deref()?; + Some(match id { + ChipId::Reclaimable => shares.suggested, + ChipId::Kind(index) => shares.kind(Category::LEGEND[index]), + ChipId::Age(index) => shares.ages.get(index).copied().unwrap_or(0), + }) +} + +/// A chip's size beside its name: the bytes it keeps, in the units the +/// tiles use. Nothing until the shares are worked out. +fn chip_size(app: &Disktree, id: crate::legend::ChipId) -> Option { + chip_share(app, id).map(disktree_core::size::human_bytes_short) +} + +/// Under this share of the scan a chip is too small to see on the mosaic +/// (a tile of 1/1000 of it is a few pixels at most), so it goes in the menu +/// even when the row has room. Empty chips always do. +const LITTLE_SHARE: u64 = 1_000; + +/// Lay the legend out on one row of `room`: chips that are set always +/// stay, as do the ones with data; empty and tiny ones go in the "+N" +/// menu, and when the rest still do not fit, the smallest follow them. +/// Widths are measured from the shaped labels, so the row never wraps +/// and never clips a chip. +fn legend_fit( + app: &Disktree, + room: gpui_kit::Pixels, + window: &Window, + theme: &Theme, +) -> LegendFit { + use crate::legend::{Chip, ChipId}; + let mut ids = vec![ChipId::Reclaimable]; + if app.color_mode == ColorMode::Age { + ids.extend((0..palette::AGE_BUCKETS.len()).map(ChipId::Age)); + } else { + ids.extend((0..Category::LEGEND.len()).map(ChipId::Kind)); + } + let total = app.tree().map_or(0, |tree| tree.bytes); + let set = |id: ChipId| app.legend.get(id) != Chip::Shown; + let little = |id: ChipId| { + chip_share(app, id).is_some_and(|bytes| { + bytes == 0 || bytes.saturating_mul(LITTLE_SHARE) < total + }) + }; + let (mut shown, mut more): (Vec<_>, Vec<_>) = + ids.iter().partition(|id| set(**id) || !little(**id)); + + let rem = app.rem; + let font_size = px(text::CAPTION.0 * rem); + let font = gpui_kit::font(theme.font.clone()); + let measure = |text: String| { + let run = gpui_kit::TextRun { + len: text.len(), + font: font.clone(), + color: theme.foreground, + ..gpui_kit::TextRun::default() + }; + window + .text_system() + .shape_line(text.into(), font_size, &[run], None) + .width + }; + let rems = |value: f32| px(value * rem); + // The chip's own box: padding, border, swatch and the gaps between its + // swatch, name and size (see `legend_chip`). + // Shaped once per chip, not once per pass of the loop below. + let widths: Vec<_> = ids + .iter() + .map(|id| { + let size = chip_size(app, *id) + .map_or(px(0.), |size| measure(size) + rems(space::XS.0)); + rems(space::XS.0.mul_add(3., size::SWATCH.0)) + + px(2.) + + measure(id.label().to_owned()) + + size + }) + .collect(); + let chip = |id: ChipId| { + ids.iter() + .position(|other| *other == id) + .map_or(px(0.), |index| widths[index]) + }; + let gap = rems(space::XS.0); + let button = + |label: String| measure(label) + rems(space::SM.0 * 2.) + px(2.); + let mut fixed = px(0.); + if app.legend.is_active() { + fixed += button("Show all \u{00d7}".to_owned()) + gap; + } + let off_screen = if app.color_mode == ColorMode::Age { + app.legend.kinds_summary() + } else { + app.legend.ages_summary() + }; + if let Some(summary) = off_screen { + fixed += button(summary) + gap; + } + let more_button = |count: usize| { + button(format!("+{count}")) + rems(space::XS.0 + icon::SM.0) + gap + }; + // A margin: the row is measured from the window, not laid out. + let room = room - rems(space::SM.0); + loop { + let row = shown.iter().fold(px(0.), |sum, id| sum + chip(*id) + gap); + let extra = if more.is_empty() { + px(0.) + } else { + more_button(more.len() + 1) + }; + if fixed + row + extra <= room { + break; + } + // The smallest chip that is not set goes next; before the shares + // are known, the last one. + let Some(position) = shown + .iter() + .enumerate() + .filter(|(_, id)| !set(**id)) + .min_by_key(|(position, id)| { + (chip_share(app, **id).unwrap_or(0), usize::MAX - position) + }) + .map(|(position, _)| position) + else { + break; + }; + more.push(shown.remove(position)); + } + more.sort_by_key(|id| ids.iter().position(|other| other == id)); + LegendFit { shown, more } +} + +/// The key to the colours, and the filter: the categories, or the age +/// ramp in age mode, each a chip that cycles shown → only → hidden (see +/// `legend.rs`) with what it keeps of the scan beside it. One row: what +/// does not fit (see [`legend_fit`]) is in the "+N" menu at its end. +fn legend( + app: &Disktree, + fit: &LegendFit, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Div { + use crate::legend::ChipId; + let chips: Vec<_> = fit + .shown + .iter() + .map(|id| legend_chip(app, theme, *id, false, cx)) + .collect(); + // The set of chips that is not on screen still filters, so it shows as + // one pill that clears it. + let (off_screen, pill) = if app.color_mode == ColorMode::Age { + (ChipId::Kind(0), app.legend.kinds_summary()) + } else { + (ChipId::Age(0), app.legend.ages_summary()) + }; + let pill = pill.map(|summary| { + legend_button( + "legend-other", + summary, + true, + "Click to clear this filter", + theme, + cx, + move |this, cx| this.clear_legend(Some(off_screen), cx), + ) + }); + let clear = app + .legend + .is_active() + .then(|| show_all_button("legend-clear", theme, cx)); + // Show all and the pill lead, so they are never what gives way; the + // menu sits at the row's right end, where an overflow is looked for. + let more = legend_more(app, fit, theme, cx); + div() + .debug_selector(|| "legend".into()) + .flex() + .flex_row() + // Only set chips are kept on the row whatever its width, so enough + // of them on a narrow window still wrap rather than clip. + .flex_wrap() + .items_center() + .gap(space::XS) + .min_w_0() + .children(clear) + .children(pill) + .children(chips) + .when(more.is_some(), |row| row.child(div().flex_1())) + .children(more) +} + +/// The "+N" button at the end of the legend's row, and its menu: the chips +/// with no room on the row, each still a filter, with what it keeps. +fn legend_more( + app: &Disktree, + fit: &LegendFit, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Option
{ + if fit.more.is_empty() { + return None; + } + let open = app.legend_menu_open; + let count = fit.more.len(); + let hover = theme.foreground.opacity(0.1); + let button = with_tooltip( + div() + .id("legend-more") + .debug_selector(|| "legend-more".into()) + .role(gpui_kit::Role::Button) + .aria_label(format!( + "{count} more legend {}", + if count == 1 { "chip" } else { "chips" } + )) + .aria_expanded(open) + .focusable() + .tab_stop(true) + .flex() + .flex_row() .items_center() .gap(space::XS) .flex_shrink_0() - .child(swatch) + .min_h(size::POINTER_TARGET) + .px(space::SM) + .border_1() + .border_color(if open { + theme.foreground.opacity(0.35) + } else { + gpui_kit::transparent_black() + }) + .when(open, |button| button.bg(theme.foreground.opacity(0.14))) + .hover(move |style| style.bg(hover)) + .cursor_pointer() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .on_hover(cx.listener(|this, hovered: &bool, _, _| { + this.legend_more_hover = *hovered; + })) + .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| { + if matches!(event.keystroke.key.as_str(), "enter" | "space") { + this.legend_menu_open = !this.legend_menu_open; + cx.notify(); + cx.stop_propagation(); + } + })) + .on_click(cx.listener(|this, _, _, cx| { + this.legend_menu_open = !this.legend_menu_open; + cx.notify(); + })) + .child(format!("+{count}")) .child( - div() - .text_size(text::CAPTION) - .text_color(theme.secondary) - .child(label), + gpui_omarchy::icon(gpui_omarchy::IconName::ChevronDown) + .size(icon::SM), + ), + "Kinds with little or no data, and those the row has no room for", + ); + let menu = open.then(|| { + let rows = fit + .more + .iter() + .map(|id| legend_chip(app, theme, *id, true, cx)); + div().absolute().top_full().right_0().child( + deferred( + // Hung from the right edge, the row's end, so it opens + // inward rather than off the window. + anchored() + .anchor(gpui_kit::Anchor::TopRight) + .snap_to_window_with_margin(px(8.)) + .offset(gpui_kit::point(px(0.), px(4.))) + .child( + div() + .id("legend-menu") + .debug_selector(|| "legend-menu".into()) + .occlude() + .flex() + .flex_col() + .min_w(size::LEGEND_MENU) + .p(space::XS) + .bg(theme.surface) + .border_1() + .border_color(theme.control_border()) + .shadow_lg() + .on_mouse_down_out(cx.listener(|this, _, _, cx| { + // A press on "+N" is the button's. + if !this.legend_more_hover { + this.legend_menu_open = false; + cx.notify(); + } + })) + .children(rows), + ), ) + .with_priority(2), + ) + }); + Some( + div() + .relative() + .flex_shrink_0() + .child(button) + .children(menu), + ) +} + +/// Over a mosaic or list the legend has emptied: that nothing here +/// passes, whether anything elsewhere in the scan does, and Show all. +fn legend_empty( + app: &Disktree, + (bytes, files): (u64, u64), + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Div { + let headline = + format!("Nothing here passes the filter: {}", app.legend.summary()); + // The scanned root sums everything that passed, so it is only empty + // when nothing did; anywhere else, what passed is in other folders. + let elsewhere = if files == 0 { + "Nothing in the scan passes it.".to_owned() + } else { + format!( + "{} in {} {} elsewhere in the scan passes it; \u{232b} goes up.", + human_bytes(bytes), + widgets::human_count(files), + if files == 1 { "file" } else { "files" } + ) }; - let mut lane = div() + div() + .absolute() + .inset_0() .flex() - .flex_row() .items_center() - .gap(space::MD) - .min_w_0() - .overflow_hidden(); - if app.color_mode == ColorMode::Age { - for (bucket, (_, label)) in palette::AGE_BUCKETS.iter().enumerate() { - lane = lane.child(item( - widgets::swatch(palette::age_accent(theme, bucket)), - label, - )); - } + .justify_center() + .child( + div() + .debug_selector(|| "legend-empty".into()) + // It sits over the mosaic; without this a press on it + // selected the tile beneath. + .occlude() + .flex() + .flex_col() + .items_center() + .gap(space::SM) + .p(space::LG) + .bg(theme.surface) + .border_1() + .border_color(theme.divider()) + // Announced as it appears: the mosaic emptying says + // nothing to someone who cannot see it. + .child( + crate::semantics::status( + "legend-empty-status", + format!("{headline}. {elsewhere}"), + ) + .debug_selector(|| "legend-empty-status".into()), + ) + .child( + div() + .text_size(text::BODY) + .text_color(theme.bright) + .child(headline), + ) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(elsewhere), + ) + .child(show_all_button("legend-empty-clear", theme, cx)), + ) +} + +/// Show all: clears every chip of the legend. +fn show_all_button( + id: &'static str, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Stateful
{ + legend_button( + id, + "Show all \u{00d7}".into(), + false, + "Show everything again · esc", + theme, + cx, + |this, cx| this.clear_legend(None, cx), + ) +} + +/// A chip's square: filled while it shows, hollow once hidden. +fn legend_swatch(state: crate::legend::Chip, color: gpui_kit::Hsla) -> Div { + if state == crate::legend::Chip::Hidden { + div() + .flex_shrink_0() + .size(size::SWATCH) + .border_1() + .border_color(color) } else { - for category in Category::LEGEND { - lane = lane.child(item( - widgets::swatch(palette::category_accent(theme, category)), - category.label(), - )); - } + widgets::swatch(color) } - let ground = palette::category_fill(theme, Category::Other, 0); - let hatch = cx.omarchy().bright.opacity(0.5); +} + +/// One legend chip. Filled while set to only, faded while another chip +/// of its set is, and struck through while hidden. +fn legend_chip( + app: &Disktree, + theme: &Theme, + id: crate::legend::ChipId, + in_menu: bool, + cx: &Context<'_, Disktree>, +) -> Stateful
{ + use crate::legend::{Chip, ChipId}; + let state = app.legend.get(id); + let swatch = match id { + ChipId::Reclaimable => widgets::hatch_swatch( + cx.omarchy().bright.opacity(0.5), + palette::category_fill(theme, Category::Other, 0), + ), + ChipId::Kind(index) => legend_swatch( + state, + palette::category_accent(theme, Category::LEGEND[index]), + ), + ChipId::Age(index) => { + legend_swatch(state, palette::age_accent(theme, index)) + } + }; + let size = chip_size(app, id); + let only = state == Chip::Only; + let faded = state == Chip::Shown && app.legend.narrowed(id); + let hover = theme.foreground.opacity(0.06); + // In the menu a chip is a row of its own, under its own name, so a + // test or a screen reader never finds two of one chip. + let key = if in_menu { + format!("legend-menu-{}", id.key().trim_start_matches("legend-")) + } else { + id.key() + }; + // The size is the whole scan's, wherever the view is, as the filter + // is: said so, since the mosaic beside it may show a single folder. + let spoken = size.as_ref().map_or_else( + || id.label().to_owned(), + |size| format!("{}, {size} in the scan", id.label()), + ); + let hint = size.as_ref().map_or_else( + || app.legend.hint(id), + |size| { + format!("{} \u{00b7} {size} in the whole scan", app.legend.hint(id)) + }, + ); + let pill = (app.legend_hover == Some(id) && app.legend.offers_only(id)) + .then(|| legend_only_pill(id, &key, in_menu, theme, cx)); + with_tooltip( + div() + .id(ElementId::Name(key.clone().into())) + .debug_selector(move || key) + .role(gpui_kit::Role::Button) + .aria_label(spoken) + .relative() + .aria_value(state.spoken()) + .focusable() + .tab_stop(true) + .flex() + .flex_row() + .items_center() + .gap(space::XS) + .flex_shrink_0() + .min_h(size::POINTER_TARGET) + .px(space::XS) + .border_1() + .border_color(if only { + theme.foreground.opacity(0.35) + } else { + gpui_kit::transparent_black() + }) + .when(only, |chip| chip.bg(theme.foreground.opacity(0.14))) + .when(!only, |chip| chip.hover(move |style| style.bg(hover))) + .when(faded, |chip| chip.opacity(0.42)) + .when(state == Chip::Hidden, |chip| chip.opacity(0.6)) + .cursor_pointer() + .on_hover(cx.listener(move |this, hovered: &bool, _, cx| { + if *hovered { + this.legend_hover = Some(id); + } else if this.legend_hover == Some(id) { + this.legend_hover = None; + } + cx.notify(); + })) + .on_key_down(cx.listener( + move |this, event: &KeyDownEvent, _, cx| { + match event.keystroke.key.as_str() { + "enter" | "space" => this.cycle_legend(id, cx), + // The pill, for the keyboard. + "o" if this.legend.offers_only(id) => { + this.solo_legend(id, cx); + } + _ => return, + } + cx.stop_propagation(); + }, + )) + .on_click(cx.listener(move |this, _, window, cx| { + this.cycle_legend(id, cx); + // A chip set from the menu moves to the row, where its + // state shows; the menu has done its job. + if in_menu { + this.legend_menu_open = false; + } + window.focus(&this.focus, cx); + })) + .when(in_menu, |row| row.w_full().px(space::SM)) + .child(swatch) + .child( + div() + .text_size(text::CAPTION) + .text_color(if only { + theme.bright + } else { + theme.secondary + }) + .when(state == Chip::Hidden, Styled::line_through) + .when(in_menu, Styled::flex_1) + .child(id.label()), + ) + .children(size.map(|size| { + div() + .text_size(text::CAPTION) + .text_color(theme.secondary.opacity(0.75)) + .child(size) + })) + .children(pill), + hint, + ) +} + +/// The "only" pill a chip shows on hover once its set filters: one click +/// from Code to just Cache, or from Code, Cache and Media to one of them, +/// where the chip itself would add or cycle. Laid over the chip's right +/// end, over its size, rather than beside it, so showing it never moves +/// the chips after it out from under the pointer. +fn legend_only_pill( + id: crate::legend::ChipId, + key: &str, + in_menu: bool, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Stateful
{ + let key = format!("{key}-only"); + let (fill, ink) = (theme.accent, theme.on_accent); div() + .id(ElementId::Name(key.clone().into())) + .debug_selector(move || key) + .role(gpui_kit::Role::Button) + .aria_label(format!("Show only {}", id.label())) + .absolute() + .right(px(2.)) + .top_0() + .bottom_0() .flex() - .flex_row() .items_center() - .gap(space::MD) - .min_w_0() - .overflow_hidden() - .child(item(widgets::hatch_swatch(hatch, ground), "Reclaimable")) - .child(lane) + .child( + div() + .id("only") + .px(space::XS) + .border_1() + .border_color(fill.opacity(0.55)) + .bg(theme.surface) + .text_size(text::CAPTION) + .text_color(fill) + .hover(move |style| style.bg(fill).text_color(ink)) + .cursor_pointer() + .child("only"), + ) + // The press is the pill's, not the chip's under it, which would + // cycle as well. + .on_mouse_down(gpui_kit::MouseButton::Left, |_, _, cx| { + cx.stop_propagation(); + }) + .on_click(cx.listener(move |this, _, window, cx| { + cx.stop_propagation(); + this.solo_legend(id, cx); + if in_menu { + this.legend_menu_open = false; + } + window.focus(&this.focus, cx); + })) +} + +/// Show all, or the pill that stands for the chips not on screen. A tab +/// stop that Space and Enter press, like the chips beside it. +fn legend_button( + id: &'static str, + label: String, + filled: bool, + hint: &'static str, + theme: &Theme, + cx: &Context<'_, Disktree>, + press: impl Fn(&mut Disktree, &mut Context<'_, Disktree>) + Clone + 'static, +) -> Stateful
{ + let hover = theme.foreground.opacity(0.1); + let on_key = press.clone(); + with_tooltip( + div() + .id(id) + .debug_selector(move || id.into()) + .role(gpui_kit::Role::Button) + .aria_label(label.clone()) + .focusable() + .tab_stop(true) + .on_key_down(cx.listener( + move |this, event: &KeyDownEvent, window, cx| { + if matches!(event.keystroke.key.as_str(), "enter" | "space") + { + on_key(this, cx); + window.focus(&this.focus, cx); + cx.stop_propagation(); + } + }, + )) + .on_click(cx.listener(move |this, _, window, cx| { + press(this, cx); + window.focus(&this.focus, cx); + })) + .flex() + .flex_row() + .items_center() + .flex_shrink_0() + .min_h(size::POINTER_TARGET) + .px(space::SM) + .text_size(text::CAPTION) + .text_color(theme.bright) + .when(filled, |pill| pill.bg(theme.foreground.opacity(0.14))) + .when(!filled, |button| { + button + .border_1() + .border_color(theme.foreground.opacity(0.4)) + }) + .hover(move |style| style.bg(hover)) + .cursor_pointer() + .child(label), + hint, + ) } // ── side panel ────────────────────────────────────────────────────────── @@ -1437,10 +3206,13 @@ fn legend(app: &Disktree, theme: &Theme, cx: &App) -> Div { /// needs, next to the mosaic rather than under it. fn side_panel( app: &Disktree, + compact: bool, theme: &Theme, cx: &Context<'_, Disktree>, ) -> Div { - let rule = || div().h(px(1.)).bg(theme.divider()); + // Once per frame: the marked list, the marked total and the disk all + // read it, and building it reads the mount table. + let plan = app.plan(); // A hairline to look at, a wider strip to grab; double-click resets. let handle = div() .id("panel-handle") @@ -1473,29 +3245,228 @@ fn side_panel( .border_color(theme.divider()) .bg(theme.surface) .child(handle) - .child(if app.is_indexing() { + // Selection guidance and progress can exceed a short, zoomed window, + // so both scroll with the lists while free space stays visible below. + .child(panel_lists(app, &plan, compact, theme, cx)) + .children(scan_error_line(app, theme)) + .children(privacy_line(app, theme, cx)) + .children(administrator_line(app, theme, cx)) + .children(marked_total(app, &plan, theme, cx)) + .child(disk_section(app, &plan, theme, cx).flex_shrink_0()) + .children(agent_line(app, compact, theme)) +} + +/// The panel's scrolling lists, each under a header that stays in sight +/// while its list scrolls ([`pinned_head`]). +fn panel_lists( + app: &Disktree, + plan: &Plan, + compact: bool, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Div { + let rule = || div().h(px(1.)).bg(theme.divider()).into_any_element(); + // Each child of the scroll, with the header it starts with, if any: the + // index is what the scroll handle measures by. + let mut lists: Vec<(AnyElement, Option
)> = Vec::new(); + // The selection leads, without a header to pin: an artifact's guidance + // must stay reachable above the Mark it qualifies on a short window. + if !app.is_indexing() { + lists.push(( + selection_section(app, compact, theme, cx) + .flex_shrink_0() + .into_any_element(), + None, + )); + lists.push((rule(), None)); + } + if app.is_indexing() { + lists.push(( indexing_progress(app, theme, cx) - } else { selection_section(app, theme, cx) }) - .child(rule()) - // The lists scroll; the selection above and the disk below stay put, - // so the two numbers that matter never leave the screen. - .child( + .flex_shrink_0() + .into_any_element(), + Some(section_head(widgets::eyebrow("Indexing", cx))), + )); + lists.push((rule(), None)); + } + // The marked list leads: the pinned total below takes room from this + // scroll, and on a short window what comes last scrolls out of sight. + // Suggestions can; the cart cannot. + lists.push(( + marked_section(app, plan, theme, cx).into_any_element(), + Some(marked_head(app, theme, cx)), + )); + lists.push((rule(), None)); + lists.push(( + worth_section(app, theme, cx).into_any_element(), + Some(worth_head(app, theme, cx)), + )); + if let Some(services) = macos_services_section(app, theme, cx) { + lists.push((rule(), None)); + lists.push(( + services.into_any_element(), + Some(section_head(widgets::eyebrow("macOS service stores", cx))), + )); + } + let pinned = pinned_head( + &app.panel_scroll, + lists.iter().map(|(_, head)| head.is_some()), + px(size::SECTION_HEAD.0 * app.rem), + ); + // `pinned_head` measures the last layout. When the lists change without + // a scroll (a mark, the insights, the end of indexing) that layout is + // a frame old, so draw again once it settles; an unchanged layout asks + // for nothing, so this never loops. + let scroll_handle = app.panel_scroll.clone(); + let seen = app.panel_layout.clone(); + let mut scroll = div() + .on_children_prepainted(move |_, window, _| { + let now: Vec<_> = (0..) + .map_while(|index| scroll_handle.bounds_for_item(index)) + .collect(); + if *seen.borrow() != now { + *seen.borrow_mut() = now; + window.refresh(); + } + }) + .id("panel-lists") + .debug_selector(|| "side-panel-scroll".into()) + .track_scroll(&app.panel_scroll) + .flex() + .flex_col() + .gap(if compact { space::MD } else { space::LG }) + .flex_1() + .min_h_0() + .overflow_y_scroll(); + let mut heads = Vec::new(); + for (list, head) in lists { + scroll = scroll.child(list); + heads.push(head); + } + div() + .relative() + .flex() + .flex_col() + .flex_1() + .min_h_0() + .child(scroll) + .children(pinned.and_then(|(index, top)| { + let head = heads.get_mut(index)?.take()?; + Some( + div() + .id("pinned-head") + .debug_selector(|| "pinned-head".into()) + .absolute() + .left_0() + .right_0() + .top(top) + // Opaque, with a hairline and never a shadow, as + // PwrGit's and PwrAgnt's pinned headers are; the rows + // slide under it, and a click must not reach them + // through it, though a wheel over it still scrolls + // the list it heads. + .bg(theme.surface) + .border_b_1() + .border_color(theme.divider()) + .block_mouse_except_scroll() + // A copy of the header in the list: read once. + .a11y_synthetic_children(|b| b.parent_node().set_hidden()) + .child(head), + ) + })) +} + +/// Which header to pin over the panel's lists, and how far up the next +/// section has pushed it: the section whose top has scrolled past the top +/// of the list while some of it is still in sight. `heads` says which of +/// the scroll's children start with a header of height `head`. Measured +/// from the last layout, which only a change of content moves, against the +/// current offset, which every wheel tick moves and redraws. +fn pinned_head( + scroll: &gpui_kit::ScrollHandle, + heads: impl Iterator, + head: gpui_kit::Pixels, +) -> Option<(usize, gpui_kit::Pixels)> { + let viewport = scroll.bounds(); + let offset = scroll.offset().y; + heads + .enumerate() + .filter(|(_, has_head)| *has_head) + .find_map(|(index, _)| { + let bounds = scroll.bounds_for_item(index)?; + let top = bounds.top() - viewport.top() + offset; + let bottom = bounds.bottom() - viewport.top() + offset; + // Pinned once its own header starts to leave; gone once the + // section has. Before then the next one pushes it up: the + // pinned header never overlaps the section after it. + (top < px(0.) && bottom > px(0.)) + .then(|| (index, (bottom - head).min(px(0.)))) + }) +} + +/// A section's header row, at the one height [`pinned_head`] pushes by. +fn section_head(content: Div) -> Div { + div() + .flex() + .flex_row() + .items_center() + .justify_between() + .flex_shrink_0() + .h(size::SECTION_HEAD) + .child(content) +} + +fn marked_head( + app: &Disktree, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Div { + let count = app.marks.len(); + if count == 0 { + // Empty, the section is this one line: a row under it that only + // says how to fill it is never worth its height. + return section_head(widgets::eyebrow("Marked", cx)) + .child(head_note("Space to mark", theme)); + } + section_head(widgets::eyebrow(format!("Marked · {count}"), cx)) +} + +/// The quiet words in an empty section's header, where a full one shows +/// its count or total. +fn head_note(note: &'static str, theme: &Theme) -> Div { + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(note) +} + +fn worth_head( + app: &Disktree, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Div { + let total: u64 = app.insights.iter().map(|candidate| candidate.bytes).sum(); + let head = section_head(widgets::eyebrow("Worth a look", cx)); + if app.insights.is_empty() { + // Listed rows are suggestions for review, so an empty list says + // there are none, never that nothing is disposable. + return head.child(head_note( + if app.tree().is_some() { + "none" + } else { + "after the scan" + }, + theme, + )); + } + head.when(total > 0, |head| { + head.child( div() - .id("panel-lists") - .flex() - .flex_col() - .gap(space::LG) - .flex_1() - .min_h_0() - .overflow_y_scroll() - .child(worth_section(app, theme, cx)) - .child(rule()) - .child(marked_section(app, theme, cx)), + .text_size(text::CAPTION) + .text_color(palette::highlight(theme)) + .child(human_bytes(total)), ) - .children(notice_line(app, theme, cx)) - .children(privacy_line(app, theme, cx)) - .children(administrator_line(app, theme, cx)) - .child(disk_section(app, theme, cx)) + }) } /// What the keys act on: its name and place, its size set large with its @@ -1503,75 +3474,103 @@ fn side_panel( /// things to do with it. fn selection_section( app: &Disktree, + compact: bool, theme: &Theme, cx: &Context<'_, Disktree>, ) -> Div { let section = div() .flex() .flex_col() - .gap(space::MD) - .child(widgets::eyebrow("Selection", cx)); + // Compact, tighter, so the lists below start in sight. + .gap(if compact { space::SM } else { space::MD }); let target = app.action_target().unwrap_or_else(|| app.crumbs.clone()); let Some(node) = app.node_at(&target) else { - return section.child( + return section.child(widgets::eyebrow("Selection", cx)).child( div() .text_color(theme.secondary) .child("Point at a tile or select one with the arrows"), ); }; + // The bold name heads the section; compact, its label is the one line + // that says nothing the name does not. + let section = section.when(!compact, |section| { + section.child(widgets::eyebrow("Selection", cx)) + }); let path = app.path_at(&target); + let artifact = path.as_deref().and_then(|path| { + disktree_core::artifact::assess(path, app.path_style(), node) + }); let root_value = app.tree().map_or(0, |tree| tree.bytes); - let marked = path.as_deref().is_some_and(|path| app.marks.contains(path)); + let marked = path + .as_deref() + .is_some_and(|path| app.marks.contains(path, app.path_style())); let covered_by = marks_ancestor(app, path.as_deref()); let is_current_root = target == app.crumbs; let highlight = palette::highlight(theme); - let identity = div() - .flex() - .flex_col() - .gap(space::XS) - .min_w_0() - .child( - div() - .flex() - .flex_row() - .items_center() - .gap(space::SM) - .min_w_0() - .child( - div() - .flex_shrink_0() - .w(space::XS) - .h(text::HEADING) - .bg(palette::category_accent(theme, node.category)), - ) - .child( - div() - .text_size(text::HEADING) - .font_weight(FontWeight::BOLD) - .text_color(theme.bright) - .whitespace_nowrap() - .overflow_hidden() - .text_ellipsis() - .child(node.name.to_string()), - ), - ) - .child( - div() - .text_size(text::CAPTION) - .text_color(theme.secondary) - .whitespace_nowrap() - .overflow_hidden() - .text_ellipsis() - .child(path.as_deref().map_or_else(String::new, |path| { - crate::marks::display_path(path, app.home.as_deref()) - })), - ); + let identity = + div() + .flex() + .flex_col() + .gap(space::XS) + .min_w_0() + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .min_w_0() + .child( + div() + .flex_shrink_0() + .w(space::XS) + .h(text::HEADING) + .bg(palette::category_accent(theme, node.category)), + ) + .child( + div() + .text_size(text::HEADING) + .font_weight(FontWeight::BOLD) + .text_color(theme.bright) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(node.name().to_string()), + ), + ) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(path.as_deref().map_or_else(String::new, |path| { + app.display_path(path) + })), + ); - let (number, unit) = match app.options.metric { + let (mut number, mut unit) = match app.options.metric { Metric::Bytes => widgets::split_size(&human_bytes(node.bytes)), Metric::Files => (widgets::human_count(node.files), "files".into()), }; + if disktree_core::macos_services::is_service_name(node.name()) + && let (Some(tree), Some(path)) = (app.tree(), path.as_deref()) + { + use disktree_core::macos_services::{Usage, usage}; + match usage(&app.root_path, tree, &app.options, path) { + Usage::Unavailable | Usage::OutsideScan => { + number = "Unavailable".into(); + unit.clear(); + } + Usage::Incomplete(_) => { + number = format!("≥ {number}"); + unit.push_str(" measured"); + } + Usage::Measured(_) => {} + } + } let share = node.bytes as f32 / root_value.max(1) as f32; let measure = div() .flex() @@ -1584,25 +3583,82 @@ fn selection_section( text::TITLE, cx, )) - .child(widgets::bar(share, highlight, cx)); + .child(widgets::bar(share, highlight, cx)) + .when_some(clone_split(node), |this, split| { + this.child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(split), + ) + }) + .when(node.sharing().estimate.is_some(), |this| { + // Said as this entry's own estimate, so it is never read as + // what the marks free together (that is the Marked block's). + this.child( + div() + .debug_selector(|| "selection-frees".into()) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(format!( + "Removed on its own, frees ≈ {}", + savings( + node.sharing().reclaimable(node.bytes), + node.sharing().possible(node.bytes) + ) + )), + ) + .when(node.sharing().unknown_files > 0, |this| { + this.child("Some clone private sizes are unavailable") + }) + }); + + // A filter changes what is shown, never what a mark takes: say so + // before Space marks a folder that holds more than is on screen. + let partly_shown = app + .legend_matches + .as_deref() + .filter(|_| !app.legend_pending) + .and_then(|matches| match matches.keep_at(&target, node) { + Some(Keep::Partial { bytes, .. }) => Some(bytes), + _ => None, + }); + let measure = measure.when_some(partly_shown, |this, shown| { + this.child( + div() + .debug_selector(|| "selection-partly-shown".into()) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(format!( + "{} passes the filter. Marking takes all {}, including \ + what is filtered out.", + human_bytes(shown), + human_bytes(node.bytes) + )), + ) + }); let fourth = if app.remote.is_none() && node.is_dir() && let Some(path) = &path - && crate::git::is_checkout(path) + // What `panel_checkout` asked about: a selected tile, never the + // directory on screen. + && git_target(app).is_some() + && app.known_checkout(path) { - let value = match app.git.get(path) { - Some(Some(state)) => state.summary(), - Some(None) => "not readable".to_string(), - None => "asking\u{2026}".to_string(), + let shown = app.git.shown(path); + let value = match shown { + Shown::Answer(probe) => probe.summary(), + Shown::Asking => "asking\u{2026}".to_string(), }; - let clean = - matches!(app.git.get(path), Some(Some(state)) if state.is_clean()); - widgets::figure( + let clean = matches!( + shown, + Shown::Answer(Probe::Known(state)) if state.is_clean() + ); + ( "Git", value, if clean { theme.success } else { theme.bright }, - cx, ) } else { let kind = node.reclaim.map_or_else( @@ -1611,9 +3667,35 @@ fn selection_section( format!("{} \u{00b7} {}", node.category.label(), reason.label()) }, ); - widgets::figure("Kind", kind, theme.bright, cx) + ("Kind", kind, theme.bright) }; + let of_scan = widgets::percent(node.bytes, root_value); + let written = widgets::ago(crate::state::now_seconds(), node.modified); + // Compact, the four figures are one line the person can open: the + // decision rests on the name, the size and the assessment, which stay. + let summary = compact.then(|| { + selection_summary( + &[ + format!("{of_scan} of scan"), + match node.files { + 1 => "1 file".to_string(), + files => format!("{} files", widgets::human_count(files)), + }, + if written == "unknown" { + "age unknown".to_string() + } else { + written.clone() + }, + fourth.1.clone(), + ], + app.selection_details, + theme, + cx, + ) + }); + let fourth = widgets::figure(fourth.0, fourth.1, fourth.2, cx); let grid = div() + .debug_selector(|| "selection-figures".into()) .flex() .flex_col() .gap(space::MD) @@ -1623,7 +3705,7 @@ fn selection_section( .flex_row() .child(div().flex_1().min_w_0().child(widgets::figure( "Of scan", - widgets::percent(node.bytes, root_value), + of_scan, theme.bright, cx, ))) @@ -1640,7 +3722,7 @@ fn selection_section( .flex_row() .child(div().flex_1().min_w_0().child(widgets::figure( "Last write", - widgets::ago(crate::state::now_seconds(), node.modified), + written, theme.bright, cx, ))) @@ -1649,6 +3731,15 @@ fn selection_section( // Only states that change the decision earn a badge. let mut chips = Vec::new(); + // Gone from the disk, still in the scan: nothing to mark until a rescan. + let removed = path.as_deref().is_some_and(|path| app.was_removed(path)); + if removed { + chips.push(widgets::chip( + "Removed since the scan", + theme.secondary, + cx, + )); + } if marked { chips.push(widgets::chip("Marked", theme.danger, cx)); } @@ -1674,20 +3765,50 @@ fn selection_section( // Open is secondary: Enter already does it. Marking is the action this // tool exists for, so it takes the highlight. let mut actions = div().flex().flex_row().gap(space::SM); - if !is_current_root { - if node.is_dir() { - let crumbs = target.clone(); - actions = actions.child( - button("open", "Open", ButtonVariant::Outline, cx) - .tab_stop(false) - .flex_1() - .justify_center() - .on_click(cx.listener(move |this, _, window, cx| { - this.go_to(crumbs.clone(), cx); - window.focus(&this.focus, cx); - })), - ); - } + if !is_current_root && node.is_dir() { + let crumbs = target.clone(); + actions = actions.child( + button("open", "Open", ButtonVariant::Outline, cx) + .tab_stop(true) + .flex_1() + .justify_center() + .on_click(cx.listener(move |this, _, window, cx| { + this.go_to(crumbs.clone(), cx); + window.focus(&this.focus, cx); + })), + ); + } + // A new mark is judged before it is offered: what the guards refuse is + // never offered at all, and past the limit only through Mark anyway. + let check = if is_current_root || removed || marked || covered_by.is_some() + { + MarkCheck::Allowed + } else { + app.target_at(&target) + .map_or(MarkCheck::Allowed, |candidate| app.mark_check(&candidate)) + }; + let guard = mark_guard_note(app, &check, node.is_dir(), theme, cx); + let mut menu = None; + if let MarkCheck::Protected(_) = &check { + actions = actions.child( + button("mark", "Can\u{2019}t remove", ButtonVariant::Outline, cx) + .debug_selector(|| "inspector-mark".into()) + .tab_stop(true) + .flex_1() + .justify_center() + .semantic_disabled(true), + ); + } else if let (MarkCheck::OverLimit(share), Some(path)) = (&check, &path) { + let open = app.mark_menu.as_deref() == Some(path.as_path()); + actions = actions.child(over_limit_mark( + share, + path.clone(), + open, + theme, + cx, + )); + menu = open.then(|| mark_menu(share, target.clone(), theme, cx)); + } else if !is_current_root && !removed { // Inside a marked directory there is nothing to mark on its own: it // goes with that directory, so the button offers to keep it by // unmarking the directory instead. @@ -1696,13 +3817,14 @@ fn selection_section( let crumbs = target; let label = match &ancestor { Some(ancestor) if !marked => { - format!("Unmark {}", short_name(ancestor)) + format!("Unmark {}", short_name(ancestor, app.path_style())) } _ if marked => "Unmark".to_string(), _ => "Mark for removal".to_string(), }; let mark = button("mark", label, ButtonVariant::Primary, cx) - .tab_stop(false) + .debug_selector(|| "inspector-mark".into()) + .tab_stop(true) .flex_1() .justify_center() .on_click(cx.listener(move |this, _, window, cx| { @@ -1714,15 +3836,26 @@ fn selection_section( } window.focus(&this.focus, cx); })); - let filled = !marked && covered_by.is_none(); + // A detection that is not a suggestion advises another route, such + // as the VM's own app, so Mark stays available but is not the lead. + let detected_only = artifact.is_some_and(|detection| { + detection.disposition + == disktree_core::artifact::Disposition::Detected + }); + let filled = !marked && covered_by.is_none() && !detected_only; actions = actions.child(if filled { let on = palette::on_highlight(theme); + let hover_fill = palette::mix(theme.background, highlight, 0.85); + let hover_ink = palette::ink_on(on, hover_fill, 4.5); mark.bg(highlight) .border_color(highlight) .text_color(on) .font_weight(FontWeight::SEMIBOLD) .hover(move |style| { - style.bg(highlight.opacity(0.85)).border_color(highlight) + style + .bg(hover_fill) + .text_color(hover_ink) + .border_color(highlight) }) } else { mark @@ -1732,49 +3865,508 @@ fn selection_section( section .child(identity) .child(measure) - .child(grid) + .children(summary) + .when(!compact || app.selection_details, |section| { + section.child(grid) + }) .children(badges) + .children(artifact.map(|detection| { + artifact_assessment(detection, node.category, theme, cx) + })) + .children(guard) .child(actions) + .children(menu) + .children(match node.category { + Category::FilesystemEvents => Some(service_guidance( + disktree_core::macos_services::Service::Fsevents, + theme, + cx, + )), + Category::Spotlight => Some(service_guidance( + disktree_core::macos_services::Service::Spotlight, + theme, + cx, + )), + _ => None, + }) } -/// The biggest things that could plausibly go, with their total. -fn worth_section( - app: &Disktree, +/// The compact panel's one line of figures: share of the scan, files, last +/// write and kind (or git), with a chevron that opens the grid beneath it. +fn selection_summary( + parts: &[String; 4], + open: bool, theme: &Theme, cx: &Context<'_, Disktree>, -) -> Div { - let total: u64 = app.insights.iter().map(|candidate| candidate.bytes).sum(); - let largest = app.insights.first().map_or(1, |candidate| candidate.bytes); - let highlight = palette::highlight(theme); - let mut section = div().flex().flex_col().gap(space::XS).child( - div() - .flex() - .flex_row() - .items_center() - .justify_between() - .pb(space::XS) - .child(widgets::eyebrow("Worth a look", cx)) - .when(total > 0, |this| { - this.child( - div() - .text_size(text::CAPTION) - .text_color(highlight) - .child(human_bytes(total)), - ) - }), - ); - if app.insights.is_empty() { - return section.child( +) -> Stateful
{ + let line = parts.join(" \u{00b7} "); + div() + .id("selection-summary") + .debug_selector(|| "selection-summary".into()) + .role(gpui_kit::Role::Button) + .aria_label(format!("Details: {line}")) + .aria_expanded(open) + .focusable() + .tab_stop(true) + .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| { + if matches!(event.keystroke.key.as_str(), "enter" | "space") { + this.selection_details = !this.selection_details; + cx.notify(); + cx.stop_propagation(); + } + })) + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .py(space::XS) + .border_t_1() + .border_b_1() + .border_color(theme.divider()) + .text_size(text::CAPTION) + .cursor_pointer() + .hover(|style| style.bg(theme.hover_fill())) + .on_click(cx.listener(|this, _, window, cx| { + this.selection_details = !this.selection_details; + window.focus(&this.focus, cx); + cx.notify(); + })) + .child( div() - .text_size(text::CAPTION) - .text_color(theme.secondary) - .child(if app.tree().is_some() { - "Nothing obviously disposable" - } else { - "Waiting for the scan" - }), + .flex_1() + .min_w_0() + .text_color(theme.foreground) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(line), + ) + .child( + gpui_omarchy::icon(if open { + gpui_omarchy::IconName::ChevronDown + } else { + gpui_omarchy::IconName::ChevronRight + }) + .size(icon::SM) + .text_color(theme.secondary) + .flex_shrink_0(), + ) +} + +/// What a recognized artifact is, how it was told, and what to do first. +/// It sits just above the actions so the guidance is read before Mark. +fn artifact_assessment( + detection: disktree_core::artifact::Detection, + category: Category, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Stateful
{ + use disktree_core::artifact::{Disposition, Evidence}; + let (selector, status) = match detection.disposition { + // A fact, not a warning: the guidance carries any caution. + Disposition::Detected => ("artifact-detected", theme.accent), + // The colour Worth a look gives suggestions, never a go-ahead: the + // guidance still says what to check first. + Disposition::Suggested => { + ("artifact-suggested", palette::highlight(theme)) + } + }; + // Said as a sentence: neither is a confidence that removal is safe. + let evidence = match detection.evidence { + Evidence::Name => "Identified by its name", + Evidence::Layout => "Identified by its tool layout", + }; + div() + .id(selector) + .debug_selector(move || selector.into()) + .flex() + .flex_col() + .gap(space::XS) + .pl(space::SM) + .border_l_2() + .border_color(palette::category_accent(theme, category)) + .child( + div() + .flex() + .flex_row() + .flex_wrap() + .items_center() + .gap(space::SM) + .child( + widgets::chip(detection.status(), status, cx) + .flex_shrink_0() + .debug_selector(move || format!("{selector}-status")), + ) + .child( + div() + .text_color(theme.bright) + .font_weight(FontWeight::SEMIBOLD) + .child(detection.kind.label()), + ), + ) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(evidence), + ) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.foreground) + .child(detection.guidance()), + ) +} + +/// Why Mark is not the plain button: a rule in the warning colour, a chip +/// and a line, above the actions so it is read before them. +fn mark_guard_note( + app: &Disktree, + check: &MarkCheck, + is_dir: bool, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Option
{ + let (chip, title, body, hint) = match check { + MarkCheck::Allowed => return None, + MarkCheck::Protected(reason) => { + // A home folder holds what is worth removing; the system trees + // and mount points do not, so only there is Open the way on. + let home = ["home folder", "user profile", "home directory"] + .iter() + .any(|word| reason.contains(word)); + ( + "Protected", + "PwrDisk never removes this".to_string(), + sentence(reason), + (home && is_dir) + .then_some("Open it to mark what is inside.".to_string()), + ) + } + MarkCheck::OverLimit(share) => { + let space = app.space.map_or(0, |space| space.total); + let allowed = u64::try_from( + u128::from(space) * u128::from(share.limit) / 100, + ) + .unwrap_or(u64::MAX); + ( + "Over limit", + format!("{}% of this disk", share.percent), + format!( + "One removal may take up to {}% of a disk ({} of {}). \ + Mark something smaller, or use \u{25be} to mark it \ + anyway.", + share.limit, + human_bytes(allowed), + human_bytes(space) + ), + Some("Change the limit in Settings \u{203a} Safety".into()), + ) + } + }; + Some( + div() + .debug_selector(|| "mark-guard".into()) + .flex() + .flex_row() + .gap(space::SM) + .child(div().flex_shrink_0().w(space::XXS).bg(theme.warning)) + .child( + div() + .flex() + .flex_col() + .gap(space::XS) + .min_w_0() + .py(space::XS) + .child( + div() + .flex() + .flex_row() + .flex_wrap() + .items_center() + .gap(space::SM) + .child(widgets::chip(chip, theme.warning, cx)) + .child( + div() + .text_color(theme.bright) + .font_weight(FontWeight::SEMIBOLD) + .child(title), + ), + ) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.foreground) + .child(body), + ) + .children(hint.map(|hint| { + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(hint) + })), + ), + ) +} + +/// A guard's reason as a sentence: capital first, full stop last. +fn sentence(reason: &str) -> String { + let mut chars = reason.chars(); + chars.next().map_or_else(String::new, |first| { + let mut text: String = first.to_uppercase().chain(chars).collect(); + if !text.ends_with('.') { + text.push('.'); + } + text + }) +} + +/// Mark past the limit: the main part says why it does nothing, and the +/// chevron beside it, the one live part, opens the menu with Mark anyway. +fn over_limit_mark( + share: &Share, + path: std::path::PathBuf, + open: bool, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Div { + div() + .flex() + .flex_row() + .flex_1() + .child( + button( + "mark", + format!("Over {}% limit", share.limit), + ButtonVariant::Outline, + cx, + ) + .debug_selector(|| "inspector-mark".into()) + .flex_1() + .justify_center() + .semantic_disabled(true), + ) + .child( + button("mark-more", "\u{25be}", ButtonVariant::Outline, cx) + .debug_selector(|| "inspector-mark-more".into()) + .aria_label("More ways to mark") + .tab_stop(true) + // At body size the glyph reads as a dot beside the label. + .text_size(text::HEADING) + .border_color(theme.warning) + .text_color(theme.warning) + .when(open, |button| button.bg(theme.warning.opacity(0.16))) + .on_click(cx.listener(move |this, _, window, cx| { + this.mark_menu = (!open).then(|| path.clone()); + window.focus(&this.focus, cx); + cx.notify(); + })), + ) +} + +/// What the chevron holds: Mark anyway, which names its cost, and the +/// way to the setting. Drawn in the panel's flow, below the actions, so +/// the panel's scroll never clips it; its rows are buttons, so Tab and a +/// screen reader reach them as they reach Mark. +fn mark_menu( + share: &Share, + crumbs: Vec, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Stateful
{ + let cost = format!( + "{}% of this disk \u{00b7} Review will ask you to confirm", + share.percent + ); + div() + .id("mark-menu") + .debug_selector(|| "mark-menu".into()) + .occlude() + .flex() + .flex_col() + .gap(space::SM) + .p(space::SM) + .border_1() + .border_color(theme.border) + .bg(theme.surface) + .shadow_lg() + .on_mouse_down_out(cx.listener(|this, _, _, cx| { + this.mark_menu = None; + cx.notify(); + })) + .child( + button("mark-anyway", "Mark anyway", ButtonVariant::Outline, cx) + .debug_selector(|| "mark-anyway".into()) + .aria_description(cost.clone()) + .tab_stop(true) + .justify_center() + .border_color(theme.warning) + .on_click(cx.listener(move |this, _, window, cx| { + this.mark_anyway(&crumbs, cx); + window.focus(&this.focus, cx); + })), + ) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(cost), + ) + .child( + button( + "mark-safety", + "Safety settings\u{2026}", + ButtonVariant::Outline, + cx, + ) + .debug_selector(|| "mark-safety".into()) + .tab_stop(true) + .justify_center() + .on_click(cx.listener(|this, _, window, cx| { + this.mark_menu = None; + crate::settings::open(crate::settings::Pane::Safety, cx); + window.focus(&this.focus, cx); + })), + ) +} + +fn service_guidance( + service: disktree_core::macos_services::Service, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Div { + div() + .flex() + .flex_col() + .gap(space::SM) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(service.guidance()) + .child( + button( + ElementId::Name( + format!("service-docs-{}", service.name()).into(), + ), + "Apple's guidance", + ButtonVariant::Outline, + cx, + ) + .tab_stop(true) + .on_click(cx.listener(move |this, _, window, cx| { + cx.open_url(service.documentation()); + window.focus(&this.focus, cx); + })), + ) +} + +/// Offer service figures only when this local scan measured a store. +fn macos_services_section( + app: &Disktree, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Option { + use disktree_core::macos_services::{Service, Usage, stores_volume, usage}; + if !cfg!(target_os = "macos") || app.remote.is_some() { + return None; + } + let volume = stores_volume(&app.root_path)?; + let tree = app.tree()?; + let stores = Service::ALL.map(|service| { + let path = volume.join(service.name()); + let state = usage(&app.root_path, tree, &app.options, &path); + (service, path, state) + }); + if !stores.iter().any(|(_, _, state)| { + matches!(state, Usage::Measured(_) | Usage::Incomplete(_)) + }) { + return None; + } + let mut section = div() + .id("macos-services") + .debug_selector(|| "macos-services".into()) + .flex() + .flex_col() + .gap(space::SM) + .child(section_head(widgets::eyebrow("macOS service stores", cx))); + let mut incomplete = false; + for (service, path, state) in stores { + let measured = match state { + Usage::Measured(bytes) => human_bytes(bytes), + Usage::Incomplete(bytes) => { + incomplete = true; + format!("{} measured · incomplete", human_bytes(bytes)) + } + Usage::Unavailable => { + incomplete = true; + "Unavailable".into() + } + Usage::OutsideScan => { + incomplete = true; + "Outside scan".into() + } + }; + section = section.child( + div() + .flex() + .flex_col() + .gap(space::XS) + .child(widgets::figure( + service.label(), + measured, + theme.bright, + cx, + )) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(path.display().to_string()), + ), + ); + } + if incomplete { + section = section.child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child( + "Unknown contents are not zero. Figures marked incomplete \ + include only the files this scan could measure.", + ), ); } + Some( + section.child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(if app.options.apparent_size { + "Apparent file sizes, already included in the scan. Switch \ + to disk usage for allocated bytes." + } else { + "Allocated file bytes, already included in the scan. APFS \ + shared blocks and snapshots can change actual space freed." + }), + ), + ) +} + +/// The biggest things that could plausibly go, with their total. +fn worth_section( + app: &Disktree, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Div { + let largest = app.insights.first().map_or(1, |candidate| candidate.bytes); + let mut section = div() + .debug_selector(|| "worth-section".into()) + .flex() + .flex_col() + .gap(space::XS) + .child(worth_head(app, theme, cx)); + if app.insights.is_empty() { + return section; + } let selected = app.action_target(); for (index, candidate) in app.insights.iter().enumerate() { let Some(node) = app.node_at(&candidate.crumbs) else { @@ -1857,7 +4449,7 @@ fn insight_text(app: &Disktree, candidate: &Candidate) -> (String, String) { let chain = tree .map_or_else(Vec::new, |tree| tree.resolve_chain(&candidate.crumbs)); let names: Vec<&str> = - chain.iter().skip(1).map(|node| &*node.name).collect(); + chain.iter().skip(1).map(|node| node.name()).collect(); let tail = names[names.len().saturating_sub(2)..].join("/"); match &candidate.finding { Finding::Reclaimable(reason) => (tail, reason.label().to_string()), @@ -1881,40 +4473,23 @@ fn insight_text(app: &Disktree, candidate: &Candidate) -> (String, String) { /// What is queued for removal, each with a way off the list. fn marked_section( app: &Disktree, + plan: &Plan, theme: &Theme, cx: &Context<'_, Disktree>, ) -> Div { - let plan = app.plan(); let count = app.marks.len(); - let header = div() + // The header leads, so it is the section's top edge: that is where + // `pinned_head` takes over from it. + let mut section = div() + .debug_selector(|| "marked-section".into()) .flex() - .flex_row() - .items_center() - .justify_between() - .child(widgets::eyebrow( - if count == 0 { - "Marked".to_string() - } else { - format!("Marked · {count}") - }, - cx, - )) - .when(count > 0, |this| { - this.child( - div() - .text_size(text::CAPTION) - .text_color(theme.secondary) - .child(human_bytes(plan.bytes())), - ) - }); - let mut section = div().flex().flex_col().gap(space::XS).child(header); + .flex_col() + .gap(space::XS) + .child(marked_head(app, theme, cx)) + .child(crate::semantics::status("marked-summary", format!("{} marked paths; {} listed bytes; {} included, {} blocked, {} covered. Estimated reclaimable: {}. Projections use only the measured volume.", + count, plan.bytes(), plan.targets.len(), plan.blocked.len(), plan.covered.len(), savings(plan.reclaimable_bytes(), plan.possible_bytes())))); if count == 0 { - return section.child( - div() - .text_size(text::CAPTION) - .text_color(theme.secondary) - .child("Space marks the tile you point at"), - ); + return section; } for (index, item) in app.marks.items().iter().take(MARKED_ROWS).enumerate() { @@ -1925,6 +4500,7 @@ fn marked_section( let path = item.path.clone(); section = section.child( div() + .debug_selector(move || format!("marked-row-{index}")) .flex() .flex_row() .items_center() @@ -1945,10 +4521,7 @@ fn marked_section( .whitespace_nowrap() .overflow_hidden() .text_ellipsis() - .child(crate::marks::display_path( - &item.path, - app.home.as_deref(), - )), + .child(app.display_path(&item.path)), ) .child( div() @@ -2000,14 +4573,12 @@ fn marked_section( /// Marked rows the panel lists before pointing at the review screen. const MARKED_ROWS: usize = 6; -/// The last thing that happened, or a scan error, above the disk. -fn notice_line(app: &Disktree, theme: &Theme, cx: &App) -> Option
{ - let (message, color) = if let Some(error) = &app.scan_error { - (error.clone(), theme.danger) - } else { - let (message, status) = app.notice.as_ref()?; - (message.clone(), widgets::alert_color(*status, cx)) - }; +/// Why the scan failed, above the disk. It stays while it holds: it +/// describes the scan, not something that just happened, which a toast +/// says (`toasts::notice`). +fn scan_error_line(app: &Disktree, theme: &Theme) -> Option
{ + let message = app.scan_error.clone()?; + let color = theme.danger; Some( div() .px(space::SM) @@ -2031,14 +4602,18 @@ fn privacy_line( theme: &Theme, cx: &Context<'_, Disktree>, ) -> Option
{ - if app.progress.errors == 0 || app.full_disk_access != Some(false) { + let errors = app + .progress + .errors + .saturating_sub(app.progress.service_errors); + if errors == 0 || app.full_disk_access != Some(false) { return None; } let color = theme.warning; - let errors = app.progress.errors; let noun = if errors == 1 { "item" } else { "items" }; Some( div() + .debug_selector(|| "privacy-hint".into()) .flex() .flex_col() .gap(space::SM) @@ -2048,9 +4623,10 @@ fn privacy_line( .border_color(color.opacity(0.5)) .text_size(text::CAPTION) .child(div().text_color(color).child(format!( - "macOS kept {} {noun} unreadable. Give disktree Full Disk \ + "macOS kept {} {noun} unreadable. Give PwrDisk Full Disk \ Access, or your terminal if you started it there, then \ - reopen it.", + reopen it. Filesystem permissions can still restrict \ + administrator-owned service stores.", widgets::human_count(errors) ))) .child( @@ -2060,7 +4636,7 @@ fn privacy_line( ButtonVariant::Outline, cx, ) - .tab_stop(false) + .tab_stop(true) .justify_center() .on_click(cx.listener( |this, _, window, cx| { @@ -2137,7 +4713,7 @@ fn administrator_line( ButtonVariant::Outline, cx, ) - .tab_stop(false) + .tab_stop(true) .justify_center() .on_click(cx.listener( |this, _, window, cx| { @@ -2149,9 +4725,61 @@ fn administrator_line( ) } -/// Free space on the volume now, and after the marks go. -fn disk_section( +/// What the removals since the scan freed, measured, with the estimates +/// beside it: removing no longer rescans, so the tree on screen is the +/// last scan's minus what went, and this is the running account. +fn freed_since_scan(app: &Disktree, theme: &Theme) -> Option
{ + let totals = + crate::ledger::Ledger::totals(app.ledger.since(app.scans_done))?; + let noun = if totals.count == 1 { + "removal" + } else { + "removals" + }; + let estimates = match totals.private { + Some(private) => format!( + "{} reported \u{b7} {} private", + human_bytes(totals.reported), + human_bytes(private) + ), + None => format!("{} reported", human_bytes(totals.reported)), + }; + Some( + div() + .debug_selector(|| "freed-since-scan".into()) + .flex() + .flex_col() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child( + div() + .flex() + .flex_row() + .gap(space::SM) + .child(format!( + "Freed since scan \u{b7} {} {noun}", + totals.count + )) + .child(div().flex_1()) + .children(totals.observed.map(|delta| { + div() + .font_weight(FontWeight::SEMIBOLD) + .text_color(if delta >= 0 { + theme.success + } else { + theme.warning + }) + .child(signed_bytes(delta)) + })), + ) + .child(estimates), + ) +} + +/// Free space on the volume now, and after the marks go. +fn disk_section( app: &Disktree, + plan: &Plan, theme: &Theme, cx: &Context<'_, Disktree>, ) -> Div { @@ -2173,13 +4801,18 @@ fn disk_section( .child(div().flex_1()) .child( button("volumes", "Source…", ButtonVariant::Secondary, cx) - .tab_stop(false) + .tab_stop(true) .on_click(cx.listener(|this, _, window, cx| { this.open_volumes(cx); this.apply_focus(window, cx); })), ); - let mut section = div().flex().flex_col().gap(space::SM).child(header); + let mut section = div() + .debug_selector(|| "disk-section".into()) + .flex() + .flex_col() + .gap(space::SM) + .child(header); let Some(space_info) = app.space else { return section.child( div() @@ -2188,10 +4821,13 @@ fn disk_section( .child("Free space is not available here"), ); }; - let plan = app.plan(); // The meter measures this volume, so it projects only the marks whose // bytes come back to it; the rest is said, never added. - let reclaiming = plan.reclaim(); + let reclaiming = if app.removal_mode == RemovalMode::OwnerCleanup { + 0 + } else { + plan.reclaim() + }; let after = space_info.after_removing(reclaiming); let highlight = palette::highlight(theme); let (number, unit) = @@ -2224,7 +4860,7 @@ fn disk_section( )) .text_color(highlight) .child(format!( - "→ {} free", + "→ ≈ {} free", human_bytes(after.available) )), ) @@ -2262,7 +4898,7 @@ fn disk_section( ), ), ); - if let Some(left_out) = not_counted(&plan) { + if let Some(left_out) = not_counted(plan) { section = section.child( div() .text_size(text::CAPTION) @@ -2281,10 +4917,152 @@ fn disk_section( .child(div().flex_1()) .child(format!("{} total", human_bytes(space_info.total))), ) - .children( - (!app.marks.is_empty()) - .then(|| review_button(app, reclaiming, theme, cx)), - ) + .children(freed_since_scan(app, theme)) +} + +/// The marks taken together, pinned above Disk so it never scrolls away: +/// how much is marked, what removing all of it frees, and the way to the +/// review. Marked clones free together what each frees little of alone, +/// so this is the number to decide by, not the selection's. +fn marked_total( + app: &Disktree, + plan: &Plan, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Option
{ + if app.marks.is_empty() { + return None; + } + let total = plan.bytes(); + // An SSH host's marks are an export, and its scan says nothing of what + // removal would free: no estimate is claimed. + let estimate = app.remote.is_none().then(|| { + let lower = plan.reclaimable_bytes().min(total); + (lower, plan.possible_bytes().clamp(lower, total)) + }); + let highlight = palette::highlight(theme); + let (number, unit) = widgets::split_size(&human_bytes(total)); + let figure = div() + .flex() + .flex_row() + .items_end() + .gap(space::SM) + .child(widgets::measure( + number, + text::FIGURE, + format!("{unit} marked"), + text::BODY, + cx, + )) + .child(div().flex_1()) + .when_some(estimate, |this, (lower, upper)| { + this.child( + div() + .debug_selector(|| "marked-frees".into()) + .text_size(text::TITLE) + .line_height(text::TITLE) + // Lifts the smaller line onto the figure's baseline: a + // fifth of the size gap is about the descender space the + // figure's line keeps below its digits. + .pb(gpui_kit::Rems((text::FIGURE.0 - text::TITLE.0) * 0.2)) + .text_color(highlight) + .whitespace_nowrap() + .child(if upper == total && lower == total { + format!("frees {}", human_bytes(total)) + } else { + format!("frees ≈ {}", savings(lower, upper)) + }), + ) + }); + let mut block = div() + .debug_selector(|| "marked-total".into()) + .flex() + .flex_col() + .gap(space::SM) + .flex_shrink_0() + .px(space::MD) + .py(space::SM) + .bg(theme.background) + .border_t_2() + .border_color(highlight) + .child(figure); + if let Some((lower, upper)) = estimate { + let share = + |bytes: u64| (bytes as f32 / total.max(1) as f32).clamp(0.0, 1.0); + let (frees, may) = (share(lower), share(upper) - share(lower)); + let stays = theme.foreground.opacity(0.16); + // What comes back is hatched, as on the Disk meter; what may is a + // wash of the same colour; the rest stays, held by clones elsewhere. + block = block.child( + div() + .relative() + .w_full() + .h(size::METER) + .bg(stays) + .child( + div() + .absolute() + .left_0() + .top_0() + .h_full() + .w(relative(frees)) + .bg(highlight.opacity(0.25)) + .child( + div() + .size_full() + .bg(pattern_slash(highlight, 1.0, 3.0)), + ), + ) + .child( + div() + .absolute() + .left(relative(frees)) + .top_0() + .h_full() + .w(relative(may)) + .bg(highlight.opacity(0.18)), + ), + ); + if upper < total { + let key = |swatch: Div, label: &'static str| { + div() + .flex() + .flex_row() + .items_center() + .gap(space::XS) + .child(swatch) + .child(label) + }; + block = block.child( + div() + .debug_selector(|| "marked-split".into()) + .flex() + .flex_row() + .flex_wrap() + .gap_x(space::MD) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(key( + widgets::hatch_swatch( + highlight, + highlight.opacity(0.25), + ), + "frees", + )) + .when(upper > lower, |this| { + this.child(key( + widgets::swatch(highlight.opacity(0.18)), + "may free", + )) + }) + .child(key( + widgets::swatch(stays), + "stays: clone data used elsewhere", + )), + ); + } + } + Some(block.child(review_button(app, theme, cx))) } /// What the volume meter leaves out, and why, when it leaves anything out: @@ -2311,7 +5089,6 @@ fn not_counted(plan: &Plan) -> Option { /// "Mark for removal" above it. fn review_button( app: &Disktree, - reclaiming: u64, theme: &Theme, cx: &Context<'_, Disktree>, ) -> impl IntoElement { @@ -2319,6 +5096,7 @@ fn review_button( let count = app.marks.len(); div() .id("review") + .debug_selector(|| "review".into()) .flex() .flex_row() .items_center() @@ -2332,6 +5110,7 @@ fn review_button( .hover(move |style| style.bg(highlight.opacity(0.18))) .active(move |style| style.bg(highlight.opacity(0.26))) .on_click(cx.listener(|this, _, window, cx| { + this.reread_disks(); this.screen = Screen::Review; cx.notify(); window.focus(&this.focus, cx); @@ -2345,10 +5124,7 @@ fn review_button( .whitespace_nowrap() .overflow_hidden() .text_ellipsis() - .child(format!( - "Review {count} marked · frees {}…", - human_bytes(reclaiming) - )), + .child(format!("Review {count} marked\u{2026}")), ) .child(gpui_omarchy::keycap("c", cx)) } @@ -2404,7 +5180,16 @@ fn key_bar(app: &Disktree, theme: &Theme, cx: &App) -> Div { ); } let scan = if app.scan.is_some() || app.remote_scan.is_some() { - "Indexing · incomplete".to_string() + app.scan_fraction().map_or_else( + || { + if app.scan_finalizing() { + "Building the treemap…".into() + } else { + "Indexing · incomplete".into() + } + }, + |fraction| format!("Indexing · ≈{:.0}% scanned", fraction * 100.0), + ) } else if app.progress.cancelled { format!( "scan cancelled \u{00b7} {} entries \u{00b7} r scans again", @@ -2510,7 +5295,19 @@ fn indexing_compact( .min_w_0() .truncate() .font_family(theme.mono_font.clone()) - .child(format!("{} measured", human_bytes(app.progress.bytes))), + .child(app.scan_fraction().map_or_else( + || { + if app.scan_finalizing() { + "Building treemap…".into() + } else { + format!( + "{} measured", + human_bytes(app.progress.bytes) + ) + } + }, + |fraction| format!("≈{:.0}% scanned", fraction * 100.0), + )), ) .child( button("cancel-scan", "Stop", ButtonVariant::Outline, cx).on_click( @@ -2530,6 +5327,7 @@ fn indexing_progress( cx: &Context<'_, Disktree>, ) -> Div { let elapsed = app.scan_started.map_or(0, |at| at.elapsed().as_secs()); + let fraction = app.scan_fraction(); let row = |label: &'static str, value: String, id: &'static str| { div() .flex() @@ -2557,18 +5355,11 @@ fn indexing_progress( || "Directory not reported yet".into(), |path| path.display().to_string(), ); - let mut parts = path - .map(|path| { - path.components() - .rev() - .take(3) - .map(|part| part.as_os_str().to_string_lossy().into_owned()) - .collect::>() - }) - .unwrap_or_default(); - parts.reverse(); - let short_path = if path.is_some_and(|path| path.components().count() > 3) { - format!("…/{}", parts.join("/")) + // Split by the scanned machine's rules: a Unix host's `a\b` is one name. + let names = path.map(|path| app.path_style().names(path)); + let names = names.as_deref().unwrap_or_default(); + let short_path = if names.len() > 3 { + format!("…/{}", names[names.len() - 3..].join("/")) } else { full_path.clone() }; @@ -2580,10 +5371,59 @@ fn indexing_progress( .gap(space::XS) .text_size(text::BODY) .text_color(theme.foreground) - .child(widgets::eyebrow("Indexing", cx)) + .child(section_head(widgets::eyebrow("Indexing", cx))) + .child( + div() + .debug_selector(|| "indexing-percent".into()) + .h(size::SCAN_STATUS) + .min_w_0() + .truncate() + .font_family(theme.mono_font.clone()) + .text_size(text::FIGURE) + // The default line height is ~1.6x the type, taller than + // this box, and `truncate` clips the overflow: descenders + // were cut off. A line the box's height fits it exactly. + .line_height(size::SCAN_STATUS) + .font_weight(FontWeight::SEMIBOLD) + .child(fraction.map_or_else( + || { + if app.scan_finalizing() { + "Finalizing…".into() + } else { + "Scanning…".into() + } + }, + |fraction| format!("≈{:.0}% scanned", fraction * 100.0), + )), + ) + .child(div().h(size::METER).child(widgets::bar( + fraction.unwrap_or(0.0), + theme.accent, + cx, + ))) + .child(with_tooltip( + div() + .id("indexing-estimate") + .h(size::PROGRESS_ROW) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(if fraction.is_some() { + "Used-space estimate" + } else if app.scan_finalizing() { + "Finishing totals and categories" + } else { + "Total scan size is unknown" + }), + "Measured file bytes ÷ drive used space at scan start. \ + Shared blocks, snapshots and unreadable paths affect this \ + estimate; it does not predict time remaining. \ + Folder and filtered scans have no known total.", + )) .child(div().h(size::PROGRESS_ROW).truncate().child( if app.remote.is_some() { app.remote_progress.stage.label() + } else if app.scan_finalizing() { + "Building the treemap" } else { "Reading this computer" }, @@ -2609,6 +5449,14 @@ fn indexing_progress( "indexing-errors", )) .child(row("Elapsed", format!("{elapsed} s"), "indexing-elapsed")) + .child(row( + "Average rate", + format!( + "{} files/s", + widgets::human_count(app.progress.files / elapsed.max(1)) + ), + "indexing-rate", + )) .child( div() .h(size::PROGRESS_ROW) @@ -2669,13 +5517,18 @@ fn find_field(app: &Disktree, theme: &Theme) -> Div { }; let highlight = palette::highlight(theme); div() + .child(crate::semantics::text("filter-status", format!("Filter by name: {}. {summary}. {hint}. Slash starts editing; Escape clears.", app.find))) .flex() .flex_row() .items_center() .gap(space::SM) .px(space::SM) .py(space::XS) + .debug_selector(|| "find-field".into()) + // Narrows with the window, and then clips its own content rather + // than drawing past its border. .min_w_0() + .overflow_hidden() .border_1() .border_color(if app.find_open { theme.accent @@ -2688,6 +5541,7 @@ fn find_field(app: &Disktree, theme: &Theme) -> Div { .text_size(text::BODY) .child( gpui_omarchy::icon(gpui_omarchy::IconName::Search) + .flex_shrink_0() .size(icon::SM) .text_color(if app.filter_applied { highlight @@ -2697,10 +5551,16 @@ fn find_field(app: &Disktree, theme: &Theme) -> Div { ) .child(if app.find.is_empty() { div() + .flex_shrink_0() + .whitespace_nowrap() .text_color(theme.secondary.opacity(0.7)) .child("Filter by name") } else { - div().text_color(theme.bright).child(app.find.clone()) + div() + .flex_shrink_0() + .whitespace_nowrap() + .text_color(theme.bright) + .child(app.find.clone()) }) .when(!summary.is_empty(), |this| { this.child( @@ -2711,21 +5571,28 @@ fn find_field(app: &Disktree, theme: &Theme) -> Div { } else { theme.secondary }) + .flex_shrink_0() .whitespace_nowrap() .child(summary), ) }) + // Last in the field, so it is what the field's clip takes when the + // row is too short even without the legend. No ellipsis: layout + // rounding can leave the hint half a pixel under its own width, and + // an ellipsis then cut it although the field had room. .child( div() + .debug_selector(|| "find-hint".into()) + .flex_shrink_0() + .whitespace_nowrap() .text_size(text::CAPTION) .text_color(theme.secondary.opacity(0.6)) - .whitespace_nowrap() .child(hint), ) } -fn short_name(path: &std::path::Path) -> String { - path.file_name().map_or_else( +fn short_name(path: &std::path::Path, style: PathStyle) -> String { + style.file_name(path).map_or_else( || path.display().to_string(), |name| name.to_string_lossy().into_owned(), ) @@ -2740,8 +5607,8 @@ fn marks_ancestor( app.marks .items() .iter() - .filter(|item| item.path != path && path.starts_with(&item.path)) - .map(|item| short_name(&item.path)) + .filter(|item| app.path_style().is_below(path, &item.path)) + .map(|item| short_name(&item.path, app.path_style())) .next() } @@ -2749,17 +5616,29 @@ fn marks_ancestor( fn review( app: &Disktree, + toasts: Option, window: &mut Window, cx: &mut Context<'_, Disktree>, ) -> Div { let theme = cx.omarchy().clone(); + let compact = window.viewport_size().width.as_f32() + / window.rem_size().as_f32() + < REVIEW_COLUMNS_REMS; let plan = app.plan(); - let items: Vec = app.marks.items().to_vec(); - let covered: Vec = plan.covered.clone(); - let blocked = plan.blocked.clone(); + let items = app.marks.items(); + let status = ReviewStatus::new(&plan); let mut list = div() .id("marked-list") + .role(gpui_kit::Role::List) + .aria_label(format!( + "{} marked paths; page {} of {}", + items.len(), + app.review_page + .min(items.len().saturating_sub(1) / LIST_LIMIT) + + 1, + items.len().div_ceil(LIST_LIMIT).max(1) + )) .flex() .flex_col() .flex_1() @@ -2767,7 +5646,8 @@ fn review( .overflow_y_scroll() .border_1() .border_color(theme.border) - .bg(theme.inset); + .bg(theme.inset) + .when(compact, gpui_kit::Styled::flex_none); if items.is_empty() { list = list.child( @@ -2778,22 +5658,59 @@ fn review( ); } - for (index, item) in items.iter().take(LIST_LIMIT).enumerate() { - let is_covered = - covered.iter().any(|covered| covered.path == item.path); - let blocked_reason = blocked + let page = app + .review_page + .min(items.len().saturating_sub(1) / LIST_LIMIT); + // Each row says what the scan made of it, read from a cache that + // lives as long as the tree: resolving indexes whole directories. + let kinds = app.kinds_of( + items .iter() - .find(|blocked| blocked.path == item.path) - .map(|blocked| blocked.reason.clone()); + .skip(page * LIST_LIMIT) + .take(LIST_LIMIT) + .map(|item| item.path.as_path()), + ); + let budget = crate::run_view::folder_budget( + window, + crate::run_view::REVIEW_ROW_FIXED_REMS, + ); + for ((index, item), (category, reclaim)) in items + .iter() + .enumerate() + .skip(page * LIST_LIMIT) + .take(LIST_LIMIT) + .zip(kinds) + { + let is_covered = status.covered(&item.path); + let blocked_reason = status.blocked(&item.path).map(str::to_owned); + #[cfg(test)] + { + use crate::marks::work; + work::REVIEW_ROWS.set(work::REVIEW_ROWS.get() + 1); + work::COVERED_ROWS + .set(work::COVERED_ROWS.get() + usize::from(is_covered)); + work::BLOCKED_ROWS.set( + work::BLOCKED_ROWS.get() + + usize::from(blocked_reason.is_some()), + ); + } list = list.child(mark_row( index, item, - is_covered, - blocked_reason, + MarkRow { + covered: is_covered, + blocked: blocked_reason, + category, + reclaim, + folder: crate::run_view::folder_line(app, &item.path, budget), + }, app, &theme, cx, )); + list = list.children(crate::cleanup_view::proposal( + app, index, &item.path, &theme, window, cx, + )); } if items.len() > LIST_LIMIT { list = list.child( @@ -2802,10 +5719,40 @@ fn review( .py(space::SM) .text_size(text::CAPTION) .text_color(theme.secondary) - .child(format!( - "{} more are marked and will be removed too. Unmark them in the treemap.", - items.len() - LIST_LIMIT - )), + .child( + button( + "review-previous", + "Previous marked paths", + ButtonVariant::Outline, + cx, + ) + .debug_selector(|| "review-previous".into()) + .semantic_disabled(page == 0) + .on_click(cx.listener( + move |this, _, window, cx| { + this.review_page = page.saturating_sub(1); + window.focus(&this.focus, cx); + cx.notify(); + }, + )), + ) + .child( + button( + "review-next", + "Next marked paths", + ButtonVariant::Outline, + cx, + ) + .debug_selector(|| "review-next".into()) + .semantic_disabled((page + 1) * LIST_LIMIT >= items.len()) + .on_click(cx.listener( + move |this, _, window, cx| { + this.review_page = page + 1; + window.focus(&this.focus, cx); + cx.notify(); + }, + )), + ), ); } @@ -2817,85 +5764,174 @@ fn review( .min_h_0() .child(screen_header( "Review", - &format!( - "{} marked \u{00b7} {} to free", - app.marks.len(), - human_bytes(plan.bytes()) - ), + &if app.removal_mode == RemovalMode::OwnerCleanup { + match app.cleanup_approved() { + Ok(approved) => cleanup_header(app, approved, &plan), + Err(_) => format!("{} marked \u{00b7} cache cleanup: check owners, then choose for each path", app.marks.len()), + } + } else { format!( + "{} marked \u{00b7} ≈ {} to free", app.marks.len(), + savings(plan.reclaimable_bytes(), plan.possible_bytes()) + ) }, &theme, cx, )) + .child(crate::semantics::text("review-readable-summary", format!("Review: {} marked paths; {} included; {} blocked; {} covered by another mark. Mode: {}. Estimated reclaimable: {}. Marking does not authorize removal.", + items.len(), plan.targets.len(), plan.blocked.len(), plan.covered.len(), + match app.removal_mode { RemovalMode::Trash => "Move to trash; recoverable until emptied", RemovalMode::Permanent => "Permanent deletion; not recoverable", RemovalMode::OwnerCleanup => "Cache cleanup, decided per path: skip, owner command or delete files; scope allocation is an upper bound, savings are unmeasured" }, + savings(plan.reclaimable_bytes(), plan.possible_bytes())))) .child( - div() - .flex() - .flex_row() - .gap(space::LG) - .p(space::LG) - .flex_1() - .min_h_0() - .child(list) - .child(summary), + // The toasts sit over the list's lower left, outside the + // scroll so they stay put, above the hints and the footer. + div().relative().flex().flex_col().flex_1().min_h_0() + .child(div().id("review-scroll") + .debug_selector(|| "review-scroll".into()) + .overflow_y_scroll().track_scroll(&app.review_scroll) + .flex() + .flex_row().when(compact, gpui_kit::Styled::flex_col) + .gap(space::LG) + .p(space::LG) + .flex_1() + .min_h_0() + .child(list) + .child(summary)) + .children(toasts), + ) + .when( + chrome::Platform::current() == chrome::Platform::Linux, + |screen| screen.child(review_hints(app, &theme, cx)), ) - .child(review_footer(app, &theme, cx)) + .child( + screen_footer(review_actions(app, &plan, cx), &theme) + .debug_selector(|| "review-footer".into()), + ) +} + +/// Review's reminder on a marked path the scan places in VM data. +const VM_CAUTION: &str = "may hold unique work"; + +/// What a review row says beyond the mark itself. +struct MarkRow { + covered: bool, + blocked: Option, + category: Category, + reclaim: Option, + /// The folder it is in, already shortened to fit. + folder: String, } -/// One marked path. Lanes are fixed, so names, bars and sizes line up down -/// the list and sizes can be compared by eye. +/// One marked path, drawn as Removing draws it so the list approved is +/// the list watched: the icon where Removing puts its checkbox, the kind's +/// colour, the name over its folder, why it is listed, then Review's own +/// lanes. Lanes are fixed, so names, bars and sizes line up down the list +/// and sizes can be compared by eye. fn mark_row( index: usize, item: &Target, - covered: bool, - blocked: Option, + row: MarkRow, app: &Disktree, theme: &Theme, cx: &Context<'_, Disktree>, -) -> Div { +) -> Stateful
{ + let MarkRow { + covered, + blocked, + category, + reclaim, + folder, + } = row; let root_value = app.tree().map_or(0, |tree| tree.bytes); - let path_text = crate::marks::display_path(&item.path, app.home.as_deref()); + let full = app.display_path(&item.path); + let accent = palette::category_accent(theme, category); + let kind = crate::run_list::kind(category, reclaim); let color = if blocked.is_some() || covered { theme.secondary } else { - theme.foreground + theme.bright }; - div() + let explanation = blocked.as_deref().unwrap_or(if covered { + "inside a marked directory" + } else { + "included in removal plan" + }); + // Repeated where removal is approved: VM data is detected, never + // suggested, and the inspector's guidance may not have been read. + let caution = (category == Category::VirtualMachine).then_some(VM_CAUTION); + let row = div() + .id(crate::file_list::path_id(&item.path)) + .debug_selector(move || format!("review-row-{index}")) + .role(gpui_kit::Role::ListItem) + .aria_label(format!( + "{}; {} bytes; {}{}marked; {explanation}", + item.path.display(), + item.bytes, + kind.map_or_else(String::new, |kind| format!("{kind}; ")), + caution.map_or_else(String::new, |caution| format!("{caution}; ")) + )) .flex() .flex_row() + .flex_wrap() + .flex_shrink_0() .items_center() .gap(space::MD) .px(space::MD) .py(space::SM) .border_b_1() .border_color(theme.divider()) + .when(covered, |row| row.opacity(0.6)) .child( - gpui_omarchy::icon(if item.is_dir { - gpui_omarchy::IconName::FolderOpen - } else { - gpui_omarchy::IconName::File - }) - .size(icon::SM) - .flex_shrink_0() - .text_color(theme.secondary), + // As wide as Removing's checkbox, which takes its place. + div() + .flex_shrink_0() + .size(icon::MD) + .flex() + .items_center() + .justify_center() + .child( + gpui_omarchy::icon(if item.is_dir { + gpui_omarchy::IconName::FolderOpen + } else { + gpui_omarchy::IconName::File + }) + .size(icon::SM) + .text_color(theme.secondary), + ), ) + .child(div().flex_shrink_0().w(px(2.)).h(space::XL).bg(accent)) .child( div() .flex() .flex_col() - .gap(space::XXS) - .min_w_0() + .min_w(relative(0.4)) .flex_1() .child( div() - .min_w_0() + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() .text_color(color) - .child(short_name(&item.path)), + .child(short_name(&item.path, app.path_style())), ) .child( div() .text_size(text::CAPTION) .text_color(theme.secondary) - .child(path_text), + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(folder), ), ) + .children(kind.map(|kind| { + widgets::chip(kind, accent, cx) + .flex_shrink_0() + .debug_selector(move || format!("review-kind-{index}")) + })) + .children(caution.map(|caution| { + widgets::chip(caution, theme.warning, cx) + .flex_shrink_0() + .debug_selector(move || format!("review-caution-{index}")) + })) .children(covered.then(|| { widgets::chip("Inside a marked directory", theme.secondary, cx) })) @@ -2928,11 +5964,13 @@ fn mark_row( ButtonVariant::Outline, cx, ) + .accessibility_label(format!("Unmark {}", item.path.display())) .on_click(cx.listener({ let path = item.path.clone(); move |this, _, _, cx| this.unmark(&path.clone(), cx) })), - ) + ); + with_tooltip(row, full) } fn review_summary( @@ -2941,10 +5979,14 @@ fn review_summary( theme: &Theme, window: &mut Window, cx: &mut Context<'_, Disktree>, -) -> Div { +) -> Stateful
{ // What comes back to the volume on screen, which is all its meter can // project; the totals below say what the removal does in full. - let reclaiming = plan.reclaim(); + let reclaiming = if app.removal_mode == RemovalMode::OwnerCleanup { + 0 + } else { + plan.reclaim() + }; // The part of the saving that lands elsewhere, said rather than added to // this volume's projection, so the two numbers cannot be confused. let left_out = not_counted(plan) @@ -2956,17 +5998,23 @@ fn review_summary( let mode = button_group( "removal-mode", vec![ - ChoiceItem::new("trash", "Move to trash").disabled(!trash), - ChoiceItem::new("permanent", "Delete permanently"), + ChoiceItem::new("trash", "Trash").disabled(!trash), + ChoiceItem::new("permanent", "Permanent"), + ChoiceItem::new("owner", "Cache cleanup"), ], - Some(usize::from(app.removal_mode == RemovalMode::Permanent)), + Some(match app.removal_mode { + RemovalMode::Trash => 0, + RemovalMode::Permanent => 1, + RemovalMode::OwnerCleanup => 2, + }), move |index, _, cx| { let _ = entity.update(cx, |this, cx| { - this.removal_mode = if index == 0 { - RemovalMode::Trash - } else { - RemovalMode::Permanent + this.removal_mode = match index { + 0 => RemovalMode::Trash, + 1 => RemovalMode::Permanent, + _ => RemovalMode::OwnerCleanup, }; + this.confirm_open = false; cx.notify(); }); }, @@ -2988,15 +6036,30 @@ fn review_summary( "Deleted at once, like rm -rf. Nothing is recoverable." .to_string() } + RemovalMode::OwnerCleanup => { + crate::cleanup_view::EXPLANATION.into() + } } }; + // Never taller than its space above the footer: in a short window, or + // at a larger interface zoom, the panel scrolls instead of running + // under the footer. let mut panel = div() + .id("review-summary") + .debug_selector(|| "review-summary".into()) .flex() .flex_col() .gap(space::XL) .w(size::REVIEW_SUMMARY) + .when( + window.viewport_size().width.as_f32() / window.rem_size().as_f32() + < REVIEW_COLUMNS_REMS, + |panel| panel.w_full().max_w_full(), + ) .flex_shrink_0() + .min_h_0() + .overflow_y_scroll() .p(space::LG) .border_1() .border_color(theme.border) @@ -3015,6 +6078,10 @@ fn review_summary( .child(explanation), ), ) + .children( + app.removal_gate(plan) + .map(|gate| over_limit_gate(app, &gate, theme, window, cx)), + ) .child( div() .flex() @@ -3042,13 +6109,41 @@ fn review_summary( cx, )) .child(widgets::row( - "Space freed", - human_bytes(plan.bytes()), + if app.removal_mode == RemovalMode::OwnerCleanup { + "Scope allocation (upper bound)" + } else if app.removal_mode == RemovalMode::Trash { + "After emptying trash (est.)" + } else { + "Estimated space freed" + }, + savings(plan.reclaimable_bytes(), plan.possible_bytes()), cx, )) .children(left_out), ); + if app.remote.is_none() { + let hint = app.marks.items().iter().find_map(|target| { + disktree_core::cleanup::inspection_reason(&target.path) + }); + if let Some(hint) = hint { + panel = panel.child( + div() + .text_size(text::CAPTION) + .text_color(theme.warning) + .child(hint), + ); + } + } + if app.removal_mode == RemovalMode::OwnerCleanup && app.remote.is_none() { + panel = + panel.child(crate::cleanup_view::summary(app, theme, window, cx)); + } + if cfg!(target_os = "macos") && app.remote.is_none() { + panel = panel.child(div().text_size(text::CAPTION) + .text_color(theme.secondary) + .child("Complete clone groups count shared data once. Remaining hardlinks retain file data. Ranges show unmeasured sharing; snapshots and open files can retain space. Rescan to update estimates.")); + } if let Some(volume) = app.space { panel = panel.child( div() @@ -3069,7 +6164,7 @@ fn review_summary( .text_color(theme.warning) .child(format!( "{}: {}", - short_name(&item.path), + short_name(&item.path, app.path_style()), item.reason )), ); @@ -3084,427 +6179,637 @@ fn review_summary( ); } + // The panel says what will happen; the footer below does it. panel - .child(div().flex_1()) - .children(notice_line(app, theme, cx)) - .child(export_controls(plan, cx)) - .children(app.remote.is_none().then(|| commit_controls(app, plan, cx))) + // Named for the test that scrolls to the panel's end: with no + // notice, nothing comes after it. + .child(div().flex_1().debug_selector(|| "review-summary-end".into())) + .children(scan_error_line(app, theme)) } /// The list handed on instead of acted on: saved as paths, or copied as a -/// prompt for a coding agent to do the cleanup with care. -fn export_controls( +/// prompt or script for a person or a coding agent to act on with care. +/// One menu, so four ways of handing it on don't outweigh the commit. +fn export_menu( + app: &Disktree, plan: &disktree_core::removal::Plan, cx: &Context<'_, Disktree>, -) -> Div { - div() - .flex() - .flex_col() - .justify_end() - .gap(space::SM) - .child( - button( - "save-list", - "Save list\u{2026}", - ButtonVariant::Secondary, - cx, - ) - .disabled(plan.is_empty()) - .on_click(cx.listener(|this, _, _, cx| { - this.save_delete_list(cx); +) -> impl IntoElement { + type Export = fn(&mut Disktree, &mut Context<'_, Disktree>); + let theme = cx.omarchy().clone(); + let rows: [(&'static str, &'static str, &'static str, Export); 4] = [ + ("save-list", "Save list\u{2026}", "s", |this, cx| { + this.save_delete_list(cx); + }), + ("copy-prompt", "Copy as prompt", "a", |this, cx| { + this.copy_agent_prompt(cx); + }), + ( + "save-script", + "Save delete script\u{2026}", + "e", + |this, cx| { + this.save_delete_script(cx); + }, + ), + ("copy-script", "Copy delete script", "y", |this, cx| { + this.copy_delete_script(cx); + }), + ]; + let menu = rows.into_iter().fold( + div() + .id("export-menu") + .debug_selector(|| "export-menu".into()) + // It opens over the marked list; without this the hit test + // reaches through it, and the row beneath raised its path + // tooltip over the menu. + .occlude() + .absolute() + // Above the button: the footer is the window's bottom edge. + .bottom_full() + .left_0() + .mb(space::XS) + .w(size::EXPORT_MENU) + .flex() + .flex_col() + .py(space::XS) + .border_1() + .border_color(theme.border) + .bg(theme.surface) + .shadow_lg() + .on_mouse_down_out(cx.listener(|this, _, _, cx| { + this.export_menu_open = false; + cx.notify(); })), + |menu, (id, label, key, run)| { + menu.child( + div() + .id(id) + .debug_selector(move || id.into()) + .flex() + .flex_row() + .items_center() + .gap(space::LG) + .px(space::MD) + .py(space::XS) + .cursor_pointer() + .hover(|row| row.bg(theme.hover_fill())) + .child( + div() + .flex_1() + .text_color(theme.foreground) + .child(label), + ) + .child( + div() + .font_family(theme.mono_font.clone()) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(key), + ) + .on_click(cx.listener(move |this, _, window, cx| { + this.export_menu_open = false; + run(this, cx); + window.focus(&this.focus, cx); + cx.notify(); + })), + ) + }, + ); + div() + .relative() + .flex_none() + .child( + button("export", "Export \u{25be}", ButtonVariant::Outline, cx) + .debug_selector(|| "export".into()) + .semantic_disabled(plan.is_empty()) + .selected(app.export_menu_open) + // Capture runs before the open menu's press-outside handler + // closes it, so a press on the button toggles. + .capture_any_mouse_down(cx.listener(|this, _, _, _| { + this.export_menu_was_open = this.export_menu_open; + })) + .on_click(cx.listener(|this, _, window, cx| { + this.export_menu_open = !this.export_menu_was_open; + // The keys stay the window's: the button is disabled + // once nothing is marked, and a disabled button that + // kept focus would swallow every key after it. + window.focus(&this.focus, cx); + cx.notify(); + })), ) + .when(app.export_menu_open, |export| export.child(deferred(menu))) +} + +/// Past the limit, Review asks again before the commit button wakes: each +/// disk past it with its share against the limit, then the phrase to type +/// or the box to tick that Settings › Safety picked. +fn over_limit_gate( + app: &Disktree, + gate: &Gate, + theme: &Theme, + window: &Window, + cx: &mut Context<'_, Disktree>, +) -> Stateful
{ + let phrase = app.gate_phrase(gate); + let policy = app.policy(); + let ask: AnyElement = match policy.confirm { + Confirm::Nothing => div() + .text_size(text::CAPTION) + .text_color(theme.foreground) + .child(format!( + "Your limit is {}% of a disk per removal. Settings \u{203a} \ + Safety asks nothing more past it.", + gate.limit + )) + .into_any_element(), + Confirm::Tick => { + let key = gate.ticked(app.removal_mode); + let ticked = app.over_ticked.as_ref() == Some(&key); + let verb = match app.removal_mode { + RemovalMode::Trash => "Move", + RemovalMode::Permanent => "Delete", + RemovalMode::OwnerCleanup => "Clean", + }; + let shares = crate::safety::series( + gate.percents().iter().map(|percent| format!("{percent}%")), + ); + let disks = if gate.over.len() > 1 { + "these disks" + } else { + "this disk" + }; + let entity = cx.entity().downgrade(); + div() + .flex() + .flex_col() + .gap(space::SM) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.foreground) + .child(format!( + "Your limit is {}% of a disk per removal.", + gate.limit + )), + ) + .child( + checkbox( + "over-limit-tick", + format!( + "{verb} {shares} of {disks}{}", + if app.removal_mode == RemovalMode::Trash { + " to the trash" + } else { + "" + } + ), + if ticked { + CheckboxState::Checked + } else { + CheckboxState::Unchecked + }, + cx, + ) + .debug_selector(|| "over-limit-tick".into()) + .tab_stop(true) + .on_change(move |_, _, _, cx| { + let key = key.clone(); + let _ = entity.update(cx, |this, cx| { + this.over_ticked = (!ticked).then_some(key); + cx.notify(); + }); + }), + ) + .into_any_element() + } + Confirm::Phrase => { + let matched = app.gate_met(gate, cx); + let field = app.over_phrase.as_ref().map(|input| { + gpui_omarchy::input("over-limit-phrase", input, window, cx) + .debug_selector(|| "over-limit-phrase".into()) + .aria_label(format!("Type {phrase} to confirm")) + }); + div() + .flex() + .flex_col() + .gap(space::SM) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.foreground) + .child(format!( + "Your limit is {}% of a disk per removal. To go \ + past it, type \u{201c}{phrase}\u{201d}.", + gate.limit + )), + ) + .children(field) + .when(matched, |this| { + this.child( + div() + .debug_selector(|| "over-limit-matched".into()) + .text_size(text::CAPTION) + .text_color(theme.success) + .child("\u{2713} Matches"), + ) + }) + .into_any_element() + } + }; + let heading = match gate.over.as_slice() { + [one] => format!("This removes {}% of a disk", one.share.percent), + many => format!( + "This removes more than {}% of {} disks", + gate.limit, + many.len() + ), + }; + div() + .id("over-limit-gate") + .debug_selector(|| "over-limit-gate".into()) + .role(gpui_kit::Role::Group) + .aria_label(format!( + "This removes {}, past the {}% limit", + gate.summary(), + gate.limit + )) + .flex() + .flex_col() + .gap(space::SM) + .p(space::MD) + .border_1() + .border_color(theme.warning) + .bg(theme.warning.opacity(0.07)) .child( - button( - "copy-prompt", - "Copy as prompt", - ButtonVariant::Secondary, - cx, - ) - .disabled(plan.is_empty()) - .on_click(cx.listener(|this, _, _, cx| { - this.copy_agent_prompt(cx); - })), + div() + .text_color(theme.bright) + .font_weight(FontWeight::SEMIBOLD) + .child(heading), ) + .children( + gate.over + .iter() + .enumerate() + .map(|(index, over)| over_limit_disk(index, over, theme)), + ) + .child(ask) +} + +/// One disk in the over-limit gate: where it is mounted, its share +/// against its capacity, and a meter with the limit's tick on it, so the +/// gap reads without arithmetic. +fn over_limit_disk(index: usize, over: &Over, theme: &Theme) -> Div { + let share = &over.share; + let fraction = + (share.bytes as f32 / share.capacity.max(1) as f32).clamp(0.0, 1.0); + let limit_at = f32::from(share.limit) / 100.0; + let meter = div() + .relative() + .h(size::METER) + .bg(theme.divider()) .child( - button( - "save-script", - "Save delete script…", - ButtonVariant::Secondary, - cx, - ) - .disabled(plan.is_empty()) - .on_click(cx.listener(|this, _, _, cx| { - this.save_delete_script(cx); - })), + div() + .absolute() + .top_0() + .bottom_0() + .left_0() + .w(gpui_kit::relative(fraction)) + .bg(theme.warning), ) .child( - button( - "copy-script", - "Copy delete script", - ButtonVariant::Secondary, - cx, - ) - .disabled(plan.is_empty()) - .on_click(cx.listener(|this, _, _, cx| { - this.copy_delete_script(cx); - })), + div() + .absolute() + .top(-size::METER) + .bottom(-size::METER) + .left(gpui_kit::relative(limit_at)) + .w(px(1.)) + .bg(theme.bright), + ); + div() + .debug_selector(move || format!("over-limit-disk-{index}")) + .flex() + .flex_col() + .gap(space::XS) + .child( + div() + .flex() + .flex_row() + .justify_between() + .gap(space::SM) + .text_size(text::CAPTION) + .child( + div() + .min_w_0() + .truncate() + .text_color(theme.foreground) + .child(over.name.clone()), + ) + .child(div().flex_none().child(format!( + "{} of {} \u{b7} {}%", + human_bytes(share.bytes), + human_bytes(share.capacity), + share.percent + ))), ) + .child(meter) } -/// The screen's one commitment. Moving to the trash is the default commit, -/// so it is the primary action; a permanent deletion is destructive, so it is -/// the danger action and asks first, which its ellipsis promises. -fn commit_controls( +/// The review screen's footer. Exporting and unmarking stay on the left, +/// since neither leaves the screen; Back and the commit end it, on the +/// right. Moving to the trash is the default commit, so it is the primary +/// action; a permanent deletion is the danger action and asks first, which +/// its ellipsis promises. Over SSH nothing is removed here: Back alone. +fn review_actions( app: &Disktree, plan: &disktree_core::removal::Plan, cx: &Context<'_, Disktree>, ) -> Div { - let count = plan.targets.len(); - let noun = if count == 1 { "item" } else { "items" }; - let (label, variant) = match app.removal_mode { - RemovalMode::Trash => ( - format!("Move {count} {noun} to trash"), - ButtonVariant::Primary, - ), - RemovalMode::Permanent => ( - format!("Delete {count} {noun}\u{2026}"), - ButtonVariant::Danger, - ), - }; + let unmark = button("unmark-all", "Unmark all", ButtonVariant::Outline, cx) + .debug_selector(|| "unmark-all".into()) + .semantic_disabled(app.marks.is_empty()) + .on_click(cx.listener(|this, _, window, cx| { + this.clear_marks(cx); + window.focus(&this.focus, cx); + })); + let back = button("back", "Back", ButtonVariant::Outline, cx) + .debug_selector(|| "back".into()) + .on_click(cx.listener(|this, _, window, cx| { + this.screen = Screen::Explore; + cx.notify(); + window.focus(&this.focus, cx); + })); let unavailable = plan.is_empty() || (app.removal_mode == RemovalMode::Trash - && !app.trash_backend.is_available()); - - div() - .flex() - .flex_row() - .justify_end() - .gap(space::SM) - .child( - button("back", "Back", ButtonVariant::Secondary, cx).on_click( - cx.listener(|this, _, window, cx| { - this.screen = Screen::Explore; - cx.notify(); - window.focus(&this.focus, cx); - }), + && !app.trash_backend.is_available()) + || app + .removal_gate(plan) + .is_some_and(|gate| !app.gate_met(&gate, cx)); + let commit = app.remote.is_none().then(|| { + let count = plan.targets.len(); + let noun = if count == 1 { "item" } else { "items" }; + let (label, variant) = match app.removal_mode { + RemovalMode::Trash => ( + format!("Move {count} {noun} to trash"), + ButtonVariant::Primary, ), - ) - .child( - button("commit", label, variant, cx) - .disabled(unavailable) + RemovalMode::Permanent => ( + format!("Delete {count} {noun}\u{2026}"), + ButtonVariant::Danger, + ), + RemovalMode::OwnerCleanup => ( + match app.cleanup_approved() { + Ok(approved) => format!( + "Clean up {} {}\u{2026}", + approved.steps.len(), + if approved.steps.len() == 1 { + "item" + } else { + "items" + } + ), + Err(_) if app.cleanup_ready().is_ok() => { + "Choose actions first".into() + } + Err(_) => "Check owners".into(), + }, + ButtonVariant::Danger, + ), + }; + button("commit", label, variant, cx) + .debug_selector(|| "commit".into()) + .semantic_disabled(unavailable) + .on_click(cx.listener(|this, _, window, cx| { + this.commit(false, cx); + this.apply_focus(window, cx); + })) + .into_any_element() + }); + // The same removal, then a full rescan, for exact figures afterwards. + // Secondary: a rescan of a whole disk takes minutes, and the tree is + // already right without one. + let rescan = (app.remote.is_none() + && app.removal_mode != RemovalMode::OwnerCleanup) + .then(|| { + let label = match app.removal_mode { + RemovalMode::Trash => "Move & rescan", + RemovalMode::Permanent => "Delete & rescan\u{2026}", + RemovalMode::OwnerCleanup => "Clean & rescan\u{2026}", + }; + button("commit-rescan", label, ButtonVariant::Outline, cx) + .debug_selector(|| "commit-rescan".into()) + .semantic_disabled(unavailable) .on_click(cx.listener(|this, _, window, cx| { - this.commit(cx); + this.commit(true, cx); this.apply_focus(window, cx); - })), - ) + })) + .into_any_element() + }); + let trailing = div() + .flex() + .flex_row() + .flex_wrap() + .gap(space::SM) + .child(back) + .children(rescan) + .into_any_element(); + dialog_footer( + [ + export_menu(app, plan, cx).into_any_element(), + unmark.into_any_element(), + ], + Some(trailing), + commit, + ) } -fn review_footer(app: &Disktree, theme: &Theme, cx: &App) -> Div { +/// Review's keys, on Linux, where Omarchy's apps keep them in view. macOS +/// and Windows have the buttons, their menus and `?` for the same keys. +fn review_hints(app: &Disktree, theme: &Theme, cx: &App) -> Div { let commit = match app.removal_mode { RemovalMode::Trash => "move to trash", RemovalMode::Permanent => "delete\u{2026}", + RemovalMode::OwnerCleanup => "cache cleanup\u{2026}", }; + let local = app.remote.is_none(); div() .flex() .flex_row() + .flex_wrap() .items_center() .gap(space::LG) .px(space::LG) - .py(space::SM) + .py(space::XS) .border_t_1() .border_color(theme.divider()) - .children( - app.remote - .is_none() - .then(|| widgets::hint("enter", commit, cx)), - ) - .children( - app.remote - .is_none() - .then(|| widgets::hint("m", "trash", cx)), - ) - .children( - app.remote - .is_none() - .then(|| widgets::hint("p", "permanent", cx)), - ) - .child(widgets::hint("e", "save script", cx)) - .child(widgets::hint("y", "copy script", cx)) + .children(local.then(|| widgets::hint("enter", commit, cx))) + .children(local.then(|| widgets::hint("shift enter", "& rescan", cx))) + .children(local.then(|| widgets::hint("m", "trash", cx))) + .children(local.then(|| widgets::hint("p", "permanent", cx))) .child(widgets::hint("!", "unmark all", cx)) - .child(widgets::hint("s", "save list", cx)) - .child(widgets::hint("a", "copy as prompt", cx)) + .child(widgets::hint("u", "undo", cx)) + .child(widgets::hint("s e a y", "export", cx)) .child(widgets::hint("esc", "back", cx)) - .child(div().flex_1()) - .child( - div() - .text_size(text::CAPTION) - .text_color(theme.secondary) - .child(format!( - "{} available", - app.space.map_or_else( - || "?".into(), - |space| human_bytes(space.available) - ) - )), - ) } -// ── running ───────────────────────────────────────────────────────────── +/// A screen's footer band: [`dialog_footer`]'s row across the window's +/// bottom edge. +pub fn screen_footer(row: Div, theme: &Theme) -> Div { + row.px(space::LG) + .py(space::SM) + .border_t_1() + .border_color(theme.divider()) +} + +/// `+1.2 GB` or `-300 MB`: a change in free space. +pub fn signed_bytes(delta: i64) -> String { + let sign = if delta >= 0 { '+' } else { '-' }; + format!("{sign}{}", human_bytes(delta.unsigned_abs())) +} -fn running(app: &Disktree, cx: &gpui_kit::Context<'_, Disktree>) -> Div { - let theme = cx.omarchy().clone(); - let summary = app.run_summary.clone(); - let done = summary.removed + summary.failed as u64; - let progress = if summary.total == 0 { - 0.0 - } else { - done as f32 / summary.total as f32 - }; +/// A wall-clock time, for the ledger's rows. +fn clock(at: std::time::SystemTime) -> String { + chrono::DateTime::::from(at) + .format("%H:%M") + .to_string() +} - let mut log = div() - .id("run-log") +/// Every removal since the scan, three ways, and their total: the last +/// row's observed figure runs from the first removal's start to the last +/// one's end, so it is measured rather than added up. +pub fn ledger_table( + cohorts: &[Cohort], + theme: &Theme, + cx: &gpui_kit::App, +) -> Div { + let figure = |text: String, color: gpui_kit::Hsla| { + div() + .w(size::LEDGER_FIGURE) + .flex_shrink_0() + .flex() + .justify_end() + .text_color(color) + .child(text) + }; + let row = |label: Div, + reported: String, + private: String, + observed: Option, + color: gpui_kit::Hsla| { + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .py(space::XXS) + .border_b_1() + .border_color(theme.divider()) + .child(label.flex_1().min_w_0()) + .child(figure(reported, color)) + .child(figure(private, color)) + .child(figure( + observed.map_or_else(|| "\u{2014}".into(), signed_bytes), + match observed { + Some(delta) if delta < 0 => theme.warning, + Some(_) => theme.success, + None => theme.secondary, + }, + )) + }; + let private = |bytes: Option| { + bytes.map_or_else(|| "unknown".into(), human_bytes) + }; + let label = |name: String, detail: String| { + div() + .flex() + .flex_row() + .gap(space::SM) + .overflow_hidden() + .child(div().flex_shrink_0().child(name)) + .child(div().text_color(theme.secondary).truncate().child(detail)) + }; + let heading = |text: &'static str| { + div() + .w(size::LEDGER_FIGURE) + .flex_shrink_0() + .flex() + .justify_end() + .child(text) + }; + let mut table = div() + .debug_selector(|| "removal-ledger".into()) .flex() .flex_col() - .flex_1() - .min_h_0() - .overflow_y_scroll() - .border_1() - .border_color(theme.border) - .bg(theme.inset); - for (path, outcome) in app.run_log.iter().rev().take(200) { - let ok = outcome.is_ok(); - log = log.child( + .text_size(text::CAPTION) + .child( div() .flex() .flex_row() - .items_center() .gap(space::SM) - .px(space::MD) - .py(space::XS) - .text_size(text::CAPTION) - .child( - gpui_omarchy::icon(if ok { - gpui_omarchy::IconName::Check - } else { - gpui_omarchy::IconName::X - }) - .size(icon::SM) - .text_color(if ok { - theme.success - } else { - theme.danger - }), - ) - .child( - div() - .flex_1() - .min_w_0() - .text_color(if ok { - theme.foreground - } else { - theme.danger - }) - .child(short_name(path)), - ) - .children(outcome.as_ref().err().map(|error| { - div() - .text_size(text::CAPTION) - .text_color(theme.warning) - .child(error.clone()) - })), - ); - } - - div() - .flex() - .flex_col() - .flex_1() - .min_h_0() - .child(screen_header( - "Removing", - &format!("{} of {} done", done, summary.total), - &theme, - cx, - )) - .child( - div() - .flex() - .flex_col() - .gap(space::MD) - .p(space::LG) - .flex_1() - .min_h_0() - .child(widgets::meter_row( - "progress", - format!( - "{} removed · {} to free", - summary.removed, - human_bytes(summary.bytes) - ), - progress, - if app.removal_mode == RemovalMode::Permanent { - theme.danger - } else { - theme.accent - }, - cx, - )) - .children( - app.space.map(|space| widgets::space_meter(space, 0, cx)), - ) - .child(log), - ) - .child( - div() - .flex() - .flex_row() - .items_center() - .gap(space::LG) - .px(space::LG) - .py(space::SM) - .border_t_1() + .pb(space::XXS) + .border_b_1() .border_color(theme.divider()) - .child(widgets::hint("esc", "stop after the current item", cx)), - ) -} - -// ── done ──────────────────────────────────────────────────────────────── - -fn done(app: &Disktree, cx: &gpui_kit::Context<'_, Disktree>) -> Div { - let theme = cx.omarchy().clone(); - let summary = app.run_summary.clone(); - let measured = match (app.space_baseline, app.space) { - (Some(before), Some(after)) => Some( - after - .available - .cast_signed() - .saturating_sub(before.available.cast_signed()), - ), - _ => None, - }; - - let mut failures = div().flex().flex_col().gap(space::XXS); - for (path, outcome) in app - .run_log - .iter() - .filter(|(_, outcome)| outcome.is_err()) - .take(40) - { - failures = failures.child( - div() - .flex() - .flex_row() - .gap(space::SM) - .text_size(text::CAPTION) - .child(div().text_color(theme.danger).child(short_name(path))) - .child(div().text_color(theme.secondary).child( - outcome.as_ref().err().cloned().unwrap_or_default(), - )), - ); - } - - let mut body = div() - .flex() - .flex_col() - .gap(space::MD) - .p(space::LG) - .flex_1() - .min_h_0() - .child( - div() - .flex() - .flex_row() - .gap(space::XXL) - .child(widgets::stat_colored( - "removed", - format!("{} items", summary.removed), - theme.success, - cx, - )) - .child(widgets::stat("bytes claimed", human_bytes(summary.bytes), cx)) - .child(widgets::stat_colored( - "failed", - format!("{}", summary.failed), - if summary.failed > 0 { - theme.danger - } else { - theme.secondary - }, - cx, - )) - .children(measured.map(|delta| { - widgets::stat_colored( - "volume freed", - if delta >= 0 { - format!("+{}", human_bytes(delta.unsigned_abs())) - } else { - format!("-{}", human_bytes(delta.unsigned_abs())) - }, - if delta >= 0 { theme.success } else { theme.warning }, - cx, - ) - })), - ) - .child( - div() - .text_size(text::CAPTION) .text_color(theme.secondary) - .child("The treemap is being re-scanned so the numbers on screen match the disk again."), + .child(div().flex_1().child("Since the last scan")) + .child(heading("reported")) + .child(heading("private")) + .child(heading("observed")), ); - - if let Some(space) = app.space { - body = body.child(widgets::space_meter(space, 0, cx)); - } - if app.scan.is_some() { - body = body.child(widgets::meter_row( - "re-scanning", - format!("{} files", widgets::human_count(app.progress.files)), - 0.0, - theme.accent, - cx, + for (index, cohort) in cohorts.iter().enumerate() { + let noun = if cohort.removed == 1 { "item" } else { "items" }; + let mode = match cohort.mode { + RemovalMode::Trash => "trash", + RemovalMode::Permanent => "permanent", + RemovalMode::OwnerCleanup => "cache cleanup", + }; + let latest = index + 1 == cohorts.len(); + table = table.child(row( + label( + format!("Removal {}", index + 1), + format!( + "{} \u{b7} {} {noun} \u{b7} {mode}", + clock(cohort.finished), + cohort.removed + ), + ), + human_bytes(cohort.reported), + private(cohort.private), + cohort.observed(), + if latest { + theme.bright + } else { + theme.foreground + }, )); } - if summary.failed > 0 { - body = body - .child(separator(cx)) - .child(widgets::section("what could not be removed", cx)) - .child(failures); + if let Some(totals) = + crate::ledger::Ledger::totals(cohorts).filter(|totals| totals.count > 1) + { + table = table.child( + row( + label( + "Total".into(), + format!( + "{} \u{2192} {}", + clock(totals.started), + clock(totals.finished) + ), + ), + human_bytes(totals.reported), + private(totals.private), + totals.observed, + theme.bright, + ) + .font_weight(FontWeight::SEMIBOLD), + ); } - - div() - .flex() - .flex_col() - .flex_1() - .min_h_0() - .child(screen_header("Done", "removal finished", &theme, cx)) - .child(body) - .child( - div() - .flex() - .flex_row() - .items_center() - .gap(space::LG) - .px(space::LG) - .py(space::SM) - .border_t_1() - .border_color(theme.divider()) - .child( - // An acknowledgement: the result is already on screen. - button("continue", "Done", ButtonVariant::Primary, cx) - .on_click(cx.listener(|this, _, window, cx| { - this.screen = Screen::Explore; - cx.notify(); - window.focus(&this.focus, cx); - })), - ) - .child(widgets::hint("enter", "continue", cx)), - ) + let _ = cx; + table } // ── shared ────────────────────────────────────────────────────────────── -fn screen_header( +pub fn screen_header( title: &str, subtitle: &str, theme: &Theme, @@ -3549,9 +6854,17 @@ pub fn cursor_tooltip( // Placement is in pixels because the pointer is; the card's own size and // gaps come from the rem scale so they follow interface zoom. const HEIGHT_REMS: f32 = 6.5; + // A clone split adds a caption line: its text and the card's gap. + const SPLIT_REMS: f32 = text::CAPTION.0 * 1.25 + space::XS.0; let rem = window.rem_size().as_f32(); let width = size::TOOLTIP.0 * rem; - let height = HEIGHT_REMS * rem; + let split = app + .hovered + .as_deref() + .and_then(|crumbs| app.node_at(crumbs)) + .and_then(clone_split) + .is_some(); + let height = (HEIGHT_REMS + if split { SPLIT_REMS } else { 0.0 }) * rem; let gap = space::MD.0 * rem; let edge = space::XS.0 * rem; @@ -3559,16 +6872,22 @@ pub fn cursor_tooltip( let content = hover_tooltip(app, cx)?; let origin = app.treemap_origin.get(); let window_size = window.bounds().size; + // The tooltip is placed in the root's coordinates, which a client-side + // frame insets from the window's by its resize ring and border. + let inset = &app.content_edges; + let content_width = (window_size.width - inset.left - inset.right).as_f32(); + let content_height = + (window_size.height - inset.top - inset.bottom).as_f32(); // Flip to the other side of the pointer rather than overflow the window. - let anchor_x = origin.x.as_f32() + pointer.x.as_f32(); - let anchor_y = origin.y.as_f32() + pointer.y.as_f32(); - let x = if anchor_x + gap + width > window_size.width.as_f32() { + let anchor_x = (origin.x + pointer.x - inset.left).as_f32(); + let anchor_y = (origin.y + pointer.y - inset.top).as_f32(); + let x = if anchor_x + gap + width > content_width { (anchor_x - gap - width).max(edge) } else { anchor_x + gap }; - let y = if anchor_y + gap + height > window_size.height.as_f32() { + let y = if anchor_y + gap + height > content_height { (anchor_y - gap - height).max(edge) } else { anchor_y + gap @@ -3576,6 +6895,7 @@ pub fn cursor_tooltip( Some( card_surface(cx) + .debug_selector(|| "cursor-tooltip".into()) .absolute() .left(px(x)) .top(px(y)) @@ -3628,13 +6948,28 @@ fn history_card(app: &Disktree, back: bool, cx: &gpui_kit::App) -> Div { /// The tooltip content for the hovered tile: everything the tile cannot show. pub fn hover_tooltip(app: &Disktree, cx: &gpui_kit::App) -> Option
{ let crumbs = app.hovered.as_deref()?; - let is_dir = app.node_at(crumbs)?.is_dir(); - let keys = if is_dir { - "space mark · enter open" + // Say what a click does here, naming what it opens: a click on a + // tile that is not selected only selects it, which looked like a + // click that failed to open. + let opens = app + .click_target(crumbs) + .and_then(|target| app.node_at(&target)) + .map(|node| node.name().to_string()); + let selected = app.selected.as_deref() == Some(crumbs); + // What was removed since the scan cannot be marked again. + let mark = if app.path_at(crumbs).is_some_and(|p| app.was_removed(&p)) { + "rescan to update" } else { "space mark" }; - node_card(app, crumbs, keys, cx) + let keys = match opens { + Some(name) if selected => format!("click opens {name} · {mark}"), + Some(name) => { + format!("click select · double-click opens {name} · {mark}") + } + None => format!("click select · {mark}"), + }; + node_card(app, crumbs, &keys, cx) } /// What is known about the node at `crumbs`, as a card: name, path, size and @@ -3650,91 +6985,110 @@ fn node_card( let path = app.path_at(crumbs); let parent = crumbs[..crumbs.len().saturating_sub(1)].to_vec(); let parent_value = app.node_at(&parent).map_or(0, |node| node.bytes); - let marked = path.as_deref().is_some_and(|path| app.marks.contains(path)); - let hidden = node.name.starts_with('.'); + let marked = path + .as_deref() + .is_some_and(|path| app.marks.contains(path, app.path_style())); + let hidden = node.name().starts_with('.'); let covered = marks_ancestor(app, path.as_deref()); + let removed = path.as_deref().is_some_and(|path| app.was_removed(path)); - let mut tip = div() - .flex() - .flex_col() - .gap(space::XS) - .child( - div() - .flex() - .flex_row() - .items_center() - .gap(space::XS) - .child( - gpui_omarchy::icon(if node.is_dir() { - gpui_omarchy::IconName::FolderOpen - } else { - gpui_omarchy::IconName::File - }) - .size(icon::SM) - .text_color(theme.secondary), - ) - .child( - div() - .min_w_0() - .font_weight(FontWeight::SEMIBOLD) - .text_color(theme.bright) - .child(node.name.to_string()), - ), - ) - .child( - div() - .text_size(text::CAPTION) - .text_color(theme.secondary) - .child(path.as_deref().map_or_else(String::new, |path| { - crate::marks::display_path(path, app.home.as_deref()) - })), - ) - .child( - div() - .flex() - .flex_row() - .items_center() - .gap(space::SM) - .child( - div() - .text_size(text::TITLE) - .font_weight(FontWeight::BOLD) - .text_color(theme.bright) - .child(human_bytes(node.bytes)), - ) - .child(widgets::glyph_bar( - node.bytes, - parent_value.max(1), - 10, - theme.secondary, - cx, - )) - .child( + let mut tip = + div() + .flex() + .flex_col() + .gap(space::XS) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(space::XS) + .child( + gpui_omarchy::icon(if node.is_dir() { + gpui_omarchy::IconName::FolderOpen + } else { + gpui_omarchy::IconName::File + }) + .size(icon::SM) + .text_color(theme.secondary), + ) + .child( + div() + .min_w_0() + .font_weight(FontWeight::SEMIBOLD) + .text_color(theme.bright) + .child(node.name().to_string()), + ), + ) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(path.as_deref().map_or_else(String::new, |path| { + app.display_path(path) + })), + ) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .child( + div() + .text_size(text::TITLE) + .font_weight(FontWeight::BOLD) + .text_color(theme.bright) + .child(human_bytes(node.bytes)), + ) + .child(widgets::glyph_bar( + node.bytes, + parent_value.max(1), + 10, + theme.secondary, + cx, + )) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(widgets::percent(node.bytes, parent_value)), + ), + ) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(format!( + "{} files · {} dirs · {} direct", + widgets::human_count(node.files), + widgets::human_count( + u64::from(node.dirs) + .saturating_sub(u64::from(node.is_dir())) + ), + human_bytes(node.own_bytes()) + )), + ) + .when_some(clone_split(node), |this, split| { + this.child( div() .text_size(text::CAPTION) .text_color(theme.secondary) - .child(widgets::percent(node.bytes, parent_value)), - ), - ) - .child( - div() - .text_size(text::CAPTION) - .text_color(theme.secondary) - .child(format!( - "{} files · {} dirs · {} direct", - widgets::human_count(node.files), - widgets::human_count( - u64::from(node.dirs) - .saturating_sub(u64::from(node.is_dir())) - ), - human_bytes(node.own_bytes()) - )), - ); + .child(split), + ) + }); let mut badges = div().flex().flex_row().gap(space::XS).flex_wrap(); if hidden { badges = badges.child(widgets::chip("Hidden", theme.secondary, cx)); } + if removed { + badges = badges.child(widgets::chip( + "Removed since the scan", + theme.secondary, + cx, + )); + } if marked { badges = badges.child(widgets::chip("Marked for removal", theme.danger, cx)); @@ -3775,13 +7129,23 @@ const MODIFIER_OPEN: &str = if cfg!(target_os = "macos") { "ctrl-o" }; -fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { +const MODIFIER_VIEW: &str = if cfg!(target_os = "macos") { + "\u{2318}1 / \u{2318}2" +} else { + "ctrl-1 / ctrl-2" +}; + +fn help_overlay(app: &Disktree, cx: &Context<'_, Disktree>) -> Stateful
{ let theme = cx.omarchy(); // Sentence case, and the tile a key acts on is always the one under the // pointer if the pointer moved last, else the keyboard selection. let rows = [ ("space / x", "Mark or unmark the tile you point at"), (MODIFIER_CLICK, "Mark without moving the selection"), + ( + "double-click", + "Open one level toward a tile; so does a click on the selection", + ), ("enter", "Open that directory, at any depth"), ("\u{232b} / esc", "Go up one directory"), ( @@ -3792,7 +7156,11 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { "\u{2190} \u{2191} \u{2193} \u{2192}", "Move between tiles at this level", ), - ("tab", "Next largest sibling"), + ( + "tab / shift-tab", + "Next or previous control; Escape returns to files", + ), + ("n / shift-n", "Next or previous largest sibling"), ("scroll", "Zoom toward a directory, then go into it"), ("shift-scroll", "Pan the magnified view"), ("[ / ]", "Draw fewer or more levels at once"), @@ -3802,8 +7170,16 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { "/", "Filter by name: only matches keep their colour; enter shows only them", ), + ( + "click legend", + "Show only a kind or age, then hide it; esc clears", + ), ("c", "Review the marked list"), ("t", "Size, files or age: what areas and colours say"), + ( + MODIFIER_VIEW, + "Treemap or file list; the list is read by screen readers", + ), ("r", "Scan again from the same root"), ("esc", "Stop a scan in progress"), ("v", "Scan another volume"), @@ -3822,92 +7198,642 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { "Show it in the file manager" }, ), - ("q", "Quit"), - ("", ""), ( - "Review screen", - "m trash \u{00b7} p permanent \u{00b7} ! unmark all \u{00b7} s save list \u{00b7} a copy as prompt", + "shift-u", + "Updates: the version, the release channel, check now", ), - ("", "enter commits \u{00b7} esc goes back"), - ("", "A permanent deletion always asks first"), + // A bare q only on Linux, where Omarchy's apps quit that way. + ( + if cfg!(target_os = "macos") { + "\u{2318}Q" + } else if cfg!(windows) { + "alt f4" + } else { + "q" + }, + "Quit", + ), + ("", ""), + ( + "Review screen", + "m trash \u{00b7} p permanent \u{00b7} ! unmark all \u{00b7} u undo \u{00b7} s save list \u{00b7} a copy as prompt", + ), + ("", "enter commits \u{00b7} esc goes back"), + ("", "A permanent deletion always asks first"), ]; - let mut keys = div().flex().flex_col().gap(space::SM); - for (key, label) in rows { + // The list scrolls inside the card when the window is too short for + // it; the title and Done stay in view. + let mut keys = div() + .id("help-scroll") + .debug_selector(|| "help-scroll".into()) + .role(gpui_kit::Role::Document) + .aria_label("Shortcut list; arrows scroll, PageUp/PageDown scroll a page, Home/End reaches either end") + .flex() + .flex_col() + .gap(space::SM) + .flex_1() + .min_h_0() + .overflow_y_scroll() + .track_scroll(&app.help_scroll); + for (index, (key, label)) in rows.into_iter().enumerate() { if key.is_empty() && label.is_empty() { continue; } keys = keys.child( - div() - .flex() - .flex_row() - .gap(space::MD) - .items_center() - .child( - div() - .w(size::KEY_LANE) - .flex_shrink_0() - .text_size(text::CAPTION) - .text_color(theme.accent) - .child(key.to_string()), - ) - .child( - div() - .text_size(text::BODY) - .text_color(theme.foreground) - .child(label.to_string()), - ), + crate::semantics::text( + ("help-shortcut", index), + format!("{key}: {label}"), + ) + .flex() + .flex_row() + .flex_shrink_0() + .gap(space::MD) + .items_start() + .child( + div() + .w(size::KEY_LANE) + .max_w(relative(0.35)) + .flex_shrink_0() + .text_size(text::CAPTION) + .text_color(theme.accent) + .child(key.to_string()), + ) + .child( + div() + .flex_1() + .min_w_0() + .text_size(text::BODY) + .text_color(theme.foreground) + .child(label.to_string()), + ), ); } - div() - .absolute() - .inset_0() + let close: CloseOverlay = |this| this.show_help = false; + let context = format!( + "{} · {}", + app.root_path.display(), + app.options.metric.label() + ); + let note = div() .flex() - .items_center() - .justify_center() - .bg(theme.background.opacity(0.86)) + .flex_col() + .min_w_0() + .child("↑↓ / PageUp / PageDown scroll · ? / Esc closes") .child( - div() - .flex() - .flex_col() - .gap(space::MD) - .w(size::HELP) - .p(space::XL) - .border_1() - .border_color(theme.border) - .bg(theme.surface) - .child( - div() - .flex() - .flex_row() - .items_center() - .gap(space::SM) - .child( - gpui_omarchy::icon( - gpui_omarchy::IconName::Keyboard, - ) + crate::semantics::text("help-context", context.clone()) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(context), + ); + overlay_backdrop( + "help-backdrop", + div() + .debug_selector(|| "help-overlay".into()) + .flex() + .flex_col() + .gap(space::MD) + .w(size::HELP) + .max_w_full() + .max_h_full() + .min_h_0() + .p(space::XL) + .border_1() + .border_color(theme.border) + .bg(theme.surface) + .child( + div() + .flex_shrink_0() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .child( + gpui_omarchy::icon(gpui_omarchy::IconName::Keyboard) .size(icon::MD) .text_color(theme.accent), + ) + .child( + crate::semantics::text( + "help-heading", + "Keyboard and mouse", ) - .child( - div() - .text_size(text::TITLE) - .font_weight(FontWeight::BOLD) - .text_color(theme.bright) - .child("Keyboard and mouse"), - ), + .role(gpui_kit::Role::Heading) + .text_size(text::TITLE) + .font_weight(FontWeight::BOLD) + .text_color(theme.bright) + .child("Keyboard and mouse"), + ), + ) + .child(keys) + .child(overlay_footer(note, close, cx).flex_shrink_0()), + close, + cx, + ) + .role(gpui_kit::Role::Dialog) + .aria_label("Keyboard and mouse shortcuts") + .aria_description("Escape closes and returns to the originating control") + .track_focus(&app.confirm_focus) + .tab_group() + .tab_stop(false) + .a11y_synthetic_children(|b| b.parent_node().set_modal()) +} + +/// A node's listed bytes split into private and APFS-clone-shared, as the +/// MCP rows read; `None` without clone blocks, so other systems and other +/// scans show nothing new. Tile weights stay the allocated bytes. +pub fn clone_split(node: disktree_core::tree::Node<'_>) -> Option { + disktree_link::Clones::of(node)?.split() +} + +/// Both ends are scan-derived; the meter uses the lower bound only. +fn savings(lower: u64, upper: u64) -> String { + disktree_core::size::human_bytes_range(lower, upper) +} + +// ── the menu, off macOS ───────────────────────────────────────────────── + +/// Whether the strip carries the menu button: off macOS, where there is no +/// global menu bar. Tests pin a frame to draw another system's strip. +fn frame_has_app_menu(pin: Option<&Frame>) -> bool { + pin.map_or(crate::chrome::Platform::current(), |frame| frame.platform) + != crate::chrome::Platform::MacOs +} + +/// The strip's menu button: the menu bar's place off macOS. +fn app_menu_button( + app: &Disktree, + cx: &Context<'_, Disktree>, +) -> impl IntoElement { + let theme = cx.omarchy().clone(); + with_tooltip( + div() + .id("app-menu-button") + .role(gpui_kit::Role::Button) + .aria_label("Application menu") + .aria_expanded(app.app_menu_open) + .focusable() + .tab_stop(true) + .focus_visible(|style| style.border_color(theme.accent)) + .debug_selector(|| "app-menu-button".into()) + .flex() + .items_center() + .justify_center() + .flex_shrink_0() + .size(size::MENU_BUTTON) + .mr(space::SM) + .border_1() + .border_color(if app.app_menu_open { + theme.border + } else { + theme.background.opacity(0.) + }) + .when(app.app_menu_open, |button| { + button.bg(theme.accent.opacity(0.18)) + }) + .hover(|button| button.bg(theme.hover_fill())) + .cursor_pointer() + .text_color(theme.bright) + .child( + gpui_omarchy::icon(gpui_omarchy::IconName::Menu).size(icon::MD), + ) + .on_click(cx.listener(|this, _, window, cx| { + this.toggle_app_menu(cx); + this.apply_focus(window, cx); + })) + .on_key_down(cx.listener( + |this, event: &KeyDownEvent, window, cx| { + if matches!(event.keystroke.key.as_str(), "enter" | "space") + { + this.toggle_app_menu(cx); + this.apply_focus(window, cx); + cx.stop_propagation(); + } + }, + )), + "Menu \u{b7} Alt", + ) +} + +/// The menu bar's template (`app_menu::menus`) as one dropdown, its menus +/// as headed groups rather than cascades: one level, nothing to aim at +/// diagonally. A row runs its action as the menu bar's would. +fn app_menu_dropdown( + app: &Disktree, + cx: &Context<'_, Disktree>, +) -> impl IntoElement { + use gpui_kit::MenuItem; + let theme = cx.omarchy().clone(); + let keymap = cx.key_bindings(); + let keymap = keymap.borrow(); + let mut list = div() + .id("app-menu") + .track_scroll(&app.menu_scroll) + .role(gpui_kit::Role::Menu) + .aria_label("Application menu") + .track_focus(&app.confirm_focus) + .tab_group() + .tab_stop(false) + .debug_selector(|| "app-menu".into()) + // It drops over the toolbar and the mosaic; without this a press + // on a heading selected the tile beneath and a scroll zoomed it. + // The list's own scroll still works: it is the hit element. + .occlude() + .flex() + .flex_col() + .w(size::APP_MENU) + .max_h(size::APP_MENU_HEIGHT) + .overflow_y_scroll() + .py(space::XS) + .border_1() + .border_color(theme.border) + .bg(theme.surface) + .shadow_lg() + .on_mouse_down_out(cx.listener(|this, _, window, cx| { + this.toggle_app_menu(cx); + this.apply_focus(window, cx); + })); + let menus = crate::app_menu::menus(crate::app_menu::Platform::Other); + let count = menus.len(); + let mut item_index = 0; + for (group, menu) in menus.into_iter().enumerate() { + list = list.child( + div() + .px(space::MD) + .pt(space::SM) + .pb(space::XXS) + .font_family(theme.mono_font.clone()) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(menu.name.to_uppercase()), + ); + for (index, item) in menu.items.into_iter().enumerate() { + let MenuItem::Action { name, action, .. } = item else { + continue; + }; + let shortcut = keymap + // The last binding wins, as the menu bar shows it; Edit's and + // zoom's are in the menu-only context, and count. + .bindings_for_action(action.as_ref()) + .next_back() + .map(|binding| { + binding + .keystrokes() + .iter() + .map(ToString::to_string) + .collect::>() + .join(" ") + }); + let id = format!("app-menu-{group}-{index}"); + let selected = item_index == app.app_menu_index; + item_index += 1; + list = list.child( + div() + .id(ElementId::Name(id.clone().into())) + .role(gpui_kit::Role::MenuItem).aria_label(name.clone()) + .when_some(shortcut.clone(), gpui_kit::StatefulInteractiveElement::aria_keyshortcuts) + .when(selected, gpui_kit::StatefulInteractiveElement::aria_active_descendant) + .debug_selector(move || id) + .flex() + .flex_row() + .items_center() + .gap(space::LG) + .px(space::MD) + .py(space::XXS) + .hover(|row| row.bg(theme.accent.opacity(0.18))) + .when(selected, |row| row.bg(theme.hover_fill())) + .cursor_pointer() + .child( + div().flex_1().text_color(theme.foreground).child(name), + ) + .children(shortcut.map(|keys| { + div() + .font_family(theme.mono_font.clone()) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(keys) + })) + .on_click(cx.listener(move |this, _, window, cx| { + this.app_menu_open = false; + this.focus_request = Some(crate::state::FocusTarget::Root); + this.apply_focus(window, cx); + window.dispatch_action(action.boxed_clone(), cx); + cx.notify(); + })), + ); + } + if group + 1 < count { + list = + list.child(div().my(space::XS).h(px(1.)).bg(theme.divider())); + } + } + deferred( + anchored() + .position(gpui_kit::point( + crate::ui::chrome::STOPLIGHT_ZONE, + crate::ui::chrome::STRIP, + )) + .child(list), + ) +} + +/// Who is driving the window, in the top bar: the agent's name and what it +/// last did. Only while an agent is connected; a click opens the overlay. +/// The strip's id for the update chip, for tests. +pub const UPDATE_CHIP_ID: &str = "strip-update"; + +/// "0.15.0 ready · Restart": the release Restart to update installs, offered +/// quietly on every screen, Later or not (design: Update Notices 3a). A +/// press is Restart to update, which waits for a running removal. At the +/// tightest bar it keeps only the verb. +fn update_chip( + app: &Disktree, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Option> { + let held = app.update_watch.ready()?; + let restarting = app.update_watch.seen().restarting; + let verb = match (restarting, held.switch_back) { + (true, _) => "Restarting\u{2026}", + (false, true) => "Switch", + (false, false) => "Restart", + }; + let action = if held.switch_back { "switch" } else { "update" }; + let label = format!("Restart to {action} to {}", held.version); + let tight = app.bar_fit == crate::toolbar::BarFit::Tight; + let lead = if tight { + format!("{} \u{00b7}", held.version) + } else { + format!("{} ready \u{00b7}", held.version) + }; + let hover = theme.accent.opacity(0.1); + Some(with_tooltip( + div() + .id(UPDATE_CHIP_ID) + .debug_selector(|| UPDATE_CHIP_ID.into()) + .role(gpui_kit::Role::Button) + .aria_label(label.clone()) + .focusable() + .tab_stop(true) + .flex() + .flex_row() + .flex_shrink_0() + .items_center() + .gap(space::XS) + .px(space::SM) + .py(space::XXS) + .mr(space::SM) + .border_1() + .border_color(theme.accent) + .font_family(theme.mono_font.clone()) + .text_size(text::CAPTION) + .whitespace_nowrap() + .cursor_pointer() + .hover(move |style| style.bg(hover)) + .focus_visible(|style| style.border_color(theme.focus_border())) + .on_key_down(cx.listener( + move |this, event: &KeyDownEvent, _, cx| { + if matches!(event.keystroke.key.as_str(), "enter" | "space") + { + if !this.update_watch.seen().restarting { + this.restart_to_update(cx); + } + cx.stop_propagation(); + } + }, + )) + .on_click(cx.listener(|this, _, _, cx| { + if !this.update_watch.seen().restarting { + this.restart_to_update(cx); + } + })) + .child( + div() + .size(size::SWATCH) + .rounded_full() + .flex_shrink_0() + .bg(theme.accent), + ) + .child(div().text_color(theme.secondary).child(lead)) + .child(div().text_color(theme.accent).underline().child(verb)), + label, + )) +} + +fn agent_pill(app: &Disktree, theme: &Theme) -> Option> { + let presence = app.agent.as_ref()?.presence.as_ref()?; + Some( + div() + .id("agent-pill") + .debug_selector(|| "agent-pill".into()) + .flex() + .flex_row() + .items_center() + .gap(space::XS) + .px(space::SM) + .py(space::XXS) + .border_1() + .border_color(theme.success.opacity(0.5)) + .text_size(text::CAPTION) + .cursor_pointer() + .hover(|style| style.bg(theme.success.opacity(0.1))) + .on_click(|_, _, cx| open_agents_settings(cx)) + .child(div().text_color(theme.success).child("\u{25cf}")) + .child( + div() + .text_color(theme.foreground) + .whitespace_nowrap() + .child(presence.client.clone()), + ) + .child( + div() + .text_color(theme.secondary) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .max_w(size::TOOLTIP) + .child(format!("\u{00b7} {}", presence.action)), + ), + ) +} + +/// The way to an agent, under the disk: who is connected, or how to +/// connect one. Quiet, since most sessions never need it. +fn agent_line( + app: &Disktree, + compact: bool, + theme: &Theme, +) -> Option> { + let presence = app.agent.as_ref().and_then(|agent| agent.presence.clone()); + // Idle, the line is an invitation; a short panel needs the room more, + // and Help › Connect an AI Agent (MCP)… is still the way in. + if compact && presence.is_none() { + return None; + } + let mut line = div() + .id("agent-line") + .debug_selector(|| "agent-line".into()) + .flex() + .flex_row() + .items_center() + .gap(space::XS) + .text_size(text::CAPTION) + .cursor_pointer() + .on_click(|_, _, cx| open_agents_settings(cx)); + match presence { + Some(presence) => { + line = line + .child(div().text_color(theme.success).child("\u{25cf}")) + .child( + div() + .text_color(theme.foreground) + .child(format!("{} is connected", presence.client)), ) - .child(keys) + .child(div().flex_1()) .child( div() - .text_size(text::CAPTION) .text_color(theme.secondary) - .child(format!( - "? or esc closes \u{00b7} {} \u{00b7} {}", - app.root_path.display(), - app.options.metric.label() - )), - ), - ) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(presence.action), + ); + } + None => { + line = line + .text_color(theme.secondary) + .hover(|style| style.text_color(theme.foreground)) + .child("Connect an AI agent (MCP) \u{203a}"); + } + } + Some(line) +} + +/// Settings › Agents (MCP): how to connect an agent, who is connected, +/// and what it may do. Deferred, since Settings may open a window. +fn open_agents_settings(cx: &mut App) { + cx.defer(|cx| crate::settings::open(crate::settings::Pane::Agents, cx)); +} + +fn app_menu_key( + app: &mut Disktree, + event: &KeyDownEvent, + window: &mut Window, + cx: &mut Context<'_, Disktree>, +) -> bool { + let actions: Vec<_> = + crate::app_menu::menus(crate::app_menu::Platform::Other) + .into_iter() + .flat_map(|menu| menu.items) + .filter_map(|item| { + if let gpui_kit::MenuItem::Action { action, .. } = item { + Some(action) + } else { + None + } + }) + .collect(); + let count = actions.len(); + if count == 0 { + return false; + } + match event.keystroke.key.as_str() { + "down" | "j" => app.app_menu_index = (app.app_menu_index + 1) % count, + "up" | "k" => { + app.app_menu_index = (app.app_menu_index + count - 1) % count; + } + "home" => app.app_menu_index = 0, + "end" => app.app_menu_index = count - 1, + "enter" | "space" => { + let action = + actions[app.app_menu_index.min(count - 1)].boxed_clone(); + app.app_menu_open = false; + app.focus_request = Some(crate::state::FocusTarget::Root); + app.apply_focus(window, cx); + window.dispatch_action(action, cx); + } + _ => return false, + } + let mut remaining = app.app_menu_index; + let mut row = app.app_menu_index + 1; + for menu in crate::app_menu::menus(crate::app_menu::Platform::Other) { + let count = menu + .items + .iter() + .filter(|item| matches!(item, gpui_kit::MenuItem::Action { .. })) + .count(); + if remaining < count { + break; + } + remaining -= count; + // Each preceding group contributes a heading and a separator. + row += 2; + } + app.menu_scroll.scroll_to_item(row); + cx.stop_propagation(); + cx.notify(); + true +} + +#[cfg(test)] +mod tests { + use super::*; + use disktree_core::removal::Blocked; + use std::path::PathBuf; + + #[test] + fn review_status_preserves_exact_paths_and_first_blocked_reason() { + let path = PathBuf::from("/synthetic/a/child"); + let mut plan = Plan::default(); + plan.covered.push(Target { + path: path.clone(), + bytes: 1, + is_dir: false, + hidden: false, + }); + plan.blocked.push(Blocked { + path: path.clone(), + reason: "first".into(), + }); + plan.blocked.push(Blocked { + path: path.clone(), + reason: "second".into(), + }); + let status = ReviewStatus::new(&plan); + assert!(status.covered(&path)); + assert!(!status.covered(Path::new("/synthetic/a/childish"))); + assert!(!status.covered(Path::new("/synthetic/A/child"))); + assert_eq!(status.blocked(&path), Some("first")); + assert_eq!( + status.blocked(Path::new("/synthetic/a/./child")), + Some("first") + ); + assert_eq!(status.blocked(Path::new("/synthetic/A/child")), None); + plan.blocked.clear(); + plan.covered.clear(); + let refreshed = ReviewStatus::new(&plan); + assert_eq!(refreshed.blocked(&path), None); + assert!(!refreshed.covered(&path)); + } + + #[cfg(unix)] + #[test] + fn review_status_keeps_non_utf8_paths_distinct() { + use std::os::unix::ffi::OsStrExt as _; + let path = Path::new("/synthetic") + .join(std::ffi::OsStr::from_bytes(b"not-\xff")); + let mut plan = Plan::default(); + plan.blocked.push(Blocked { + path: path.clone(), + reason: "blocked".into(), + }); + let status = ReviewStatus::new(&plan); + assert_eq!(status.blocked(&path), Some("blocked")); + assert_eq!( + status.blocked(Path::new(&path.to_string_lossy().into_owned())), + None + ); + } } diff --git a/crates/disktree-app/src/widgets.rs b/crates/disktree-app/src/widgets.rs index cc2927bf..83270538 100644 --- a/crates/disktree-app/src/widgets.rs +++ b/crates/disktree-app/src/widgets.rs @@ -11,9 +11,54 @@ use gpui_kit::{ App, Div, ElementId, FontWeight, Hsla, InteractiveElement as _, ParentElement, SharedString, Styled, div, relative, }; -use gpui_omarchy::{ActiveTheme, Status}; +use gpui_omarchy::ActiveTheme; -use crate::ui::{space, text}; +use crate::ui::{size, space, text}; + +/// How long the pointer rests on a control before its tooltip shows. +/// Omarchy's 400 ms fired while the pointer was still on its way across a +/// row of chips, so a tooltip popped up over the next one. +pub const TOOLTIP_DELAY: std::time::Duration = + std::time::Duration::from_millis(700); + +/// Omarchy's tooltip, out of the pointer's way. +/// +/// GPUI puts a tooltip's corner one pixel from the pointer's tip, so the +/// box sat under the cursor and over whatever was next to it: the next +/// chip, its "only" pill. The surface is drawn [`size::TOOLTIP_CLEARANCE`] +/// lower inside a transparent frame, which keeps it clear of the arrow. +/// Near the window's bottom GPUI flips the frame above the pointer; the +/// gap is then above the surface, which still clears the tip. +pub fn with_tooltip( + control: T, + text: impl Into, +) -> T { + let text = text.into(); + control + .tooltip_show_delay(TOOLTIP_DELAY) + .tooltip(move |_, cx| { + gpui_kit::AppContext::new(cx, |_| ClearTooltip(text.clone())).into() + }) +} + +struct ClearTooltip(SharedString); + +impl gpui_kit::Render for ClearTooltip { + fn render( + &mut self, + _: &mut gpui_kit::Window, + cx: &mut gpui_kit::Context<'_, Self>, + ) -> impl gpui_kit::IntoElement { + div() + .debug_selector(|| "app-tooltip".into()) + .pt(size::TOOLTIP_CLEARANCE) + .child( + div() + .debug_selector(|| "app-tooltip-surface".into()) + .child(gpui_omarchy::tooltip(self.0.clone(), cx)), + ) + } +} /// File counts, which is what a directory count is too. pub fn human_count(value: u64) -> String { @@ -21,64 +66,30 @@ pub fn human_count(value: u64) -> String { } /// The value to show for a node under the active metric. -pub fn short_value(node: &Node, metric: Metric) -> String { +pub fn short_value(node: Node<'_>, metric: Metric) -> String { match metric { Metric::Bytes => human_bytes_short(node.bytes), Metric::Files => human_count(node.files), } } -/// A dim label above a number, for the header strip. -pub fn stat( - label: impl Into, - value: impl Into, - cx: &App, -) -> Div { - let theme = cx.omarchy(); - div() - .flex() - .flex_col() - .gap(space::XXS) - .child( - div() - .text_size(text::CAPTION) - .text_color(theme.secondary.opacity(0.75)) - .child(label.into()), - ) - .child( - div() - .text_size(text::TITLE) - .font_weight(FontWeight::SEMIBOLD) - .text_color(theme.bright) - .child(value.into()), - ) -} - -/// A value with a status colour rather than the neutral one. -pub fn stat_colored( - label: impl Into, - value: impl Into, - color: Hsla, - cx: &App, -) -> Div { - let theme = cx.omarchy(); - div() - .flex() - .flex_col() - .gap(space::XXS) - .child( - div() - .text_size(text::CAPTION) - .text_color(theme.secondary.opacity(0.75)) - .child(label.into()), - ) - .child( - div() - .text_size(text::TITLE) - .font_weight(FontWeight::SEMIBOLD) - .text_color(color) - .child(value.into()), - ) +/// What part of `node` a filter shows, and all of it: "48G of 196G". +pub fn short_share( + node: Node<'_>, + bytes: u64, + files: u64, + metric: Metric, +) -> String { + match metric { + Metric::Bytes => format!( + "{} of {}", + human_bytes_short(bytes), + human_bytes_short(node.bytes) + ), + Metric::Files => { + format!("{} of {}", human_count(files), human_count(node.files)) + } + } } /// A square chip, used for counts and states. @@ -294,17 +305,6 @@ pub fn percent(part: u64, total: u64) -> String { } } -/// The status colour for an alert. -pub fn alert_color(status: Status, cx: &App) -> Hsla { - let theme = cx.omarchy(); - match status { - Status::Neutral => theme.secondary, - Status::Success => theme.success, - Status::Warning => theme.warning, - Status::Error => theme.danger, - } -} - /// A clickable breadcrumb segment. pub fn crumb( id: impl Into, @@ -444,6 +444,44 @@ pub fn signal(filled: usize, cx: &App) -> Div { bars } +/// The treemap view's glyph: the app's own mark in outline, one tall tile +/// and two stacked, so it reads as "tiles" beside the list's rows. +pub fn treemap_glyph(color: Hsla) -> Div { + let tile = || div().border_1().border_color(color); + div() + .flex_shrink_0() + .flex() + .flex_row() + .gap(space::XXS) + .w(crate::ui::icon::SM) + .h(crate::ui::size::VIEW_GLYPH_HEIGHT) + .child(tile().w(crate::ui::size::VIEW_GLYPH_TILE).h_full()) + .child( + div() + .flex() + .flex_col() + .flex_1() + .gap(space::XXS) + .child(tile().flex_1()) + .child(tile().flex_1()), + ) +} + +/// The list view's glyph: three rows. +pub fn list_glyph(color: Hsla) -> Div { + let row = || div().w_full().h(space::XXS).bg(color); + div() + .flex_shrink_0() + .flex() + .flex_col() + .justify_between() + .w(crate::ui::icon::SM) + .h(crate::ui::size::VIEW_GLYPH_HEIGHT) + .child(row()) + .child(row()) + .child(row()) +} + /// One bar per Power Efficiency preset. const SIGNAL_STEPS: usize = crate::power::PowerEfficiency::ALL.len(); diff --git a/crates/disktree-app/src/window_frame.rs b/crates/disktree-app/src/window_frame.rs new file mode 100644 index 00000000..1d4b0a39 --- /dev/null +++ b/crates/disktree-app/src/window_frame.rs @@ -0,0 +1,362 @@ +//! Where the main window opens: where the user last left it, else centred +//! on the display the user is working on (see `placement.rs`), and always +//! inside the display it opens on. +//! +//! The frame is kept in `window-frame.json` in the settings directory, with +//! the display it was on. GPUI reads a window's bounds relative to the +//! display it is given (macOS) or in the desktop's coordinates (Windows), +//! and reports them the same way, so the saved bounds go back to the same +//! display as `WindowOptions::display_id`. A display that is gone, or one +//! that shrank, still gets the whole window: the frame goes to the display +//! a new window would, is cut to that display's visible area and moved +//! inside it, so no edge opens under the +//! menu bar, the Dock or off the side, as 1440 points did on a laptop. +//! +//! The frame is remembered as the window moves and written once, as the app +//! quits; the window may already be gone by then. + +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, PoisonError}; + +use gpui_kit::{ + App, Bounds, DisplayId, Pixels, Size, Window, WindowBounds, point, px, size, +}; +use serde::{Deserialize, Serialize}; + +const FILE: &str = "window-frame.json"; + +/// The frame the window last had, waiting for the quit hook to write it. +static LATEST: Mutex> = Mutex::new(None); + +/// A main window's place, as saved. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +struct Frame { + /// The display's UUID; `None` where the platform has none to give. + display: Option, + state: State, + x: f32, + y: f32, + width: f32, + height: f32, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +enum State { + Windowed, + Maximized, + Fullscreen, +} + +/// Where the window opens, and its smallest size, both fitted to the +/// display it opens on. +pub struct Placement { + pub display: Option, + pub bounds: WindowBounds, + pub min_size: Size, +} + +/// The main window's placement: the saved frame if there is one, else +/// `default` centred on the display a new window opens on. +pub fn initial( + default: Size, + min: Size, + cx: &mut App, +) -> Placement { + let saved = path().and_then(|path| load(&path)); + let fallback = crate::placement::display_for_new_window(cx); + placement(saved, fallback, default, min, cx) +} + +/// [`initial`], given what was saved and `fallback`, the display for a +/// window with no saved display to return to (`None`: the primary one). +fn placement( + saved: Option, + fallback: Option, + default: Size, + min: Size, + cx: &App, +) -> Placement { + let display = saved + .as_ref() + .and_then(|frame| { + let uuid = frame.display.as_deref()?; + cx.displays().into_iter().find(|display| { + display.uuid().is_ok_and(|id| id.to_string() == uuid) + }) + }) + .or_else(|| fallback.and_then(|id| cx.find_display(id))); + let display_id = display.as_ref().map(|display| display.id()); + let area = display + .or_else(|| cx.primary_display()) + .map(|display| display.visible_bounds()); + let min_size = area.map_or(min, |area| min.min(&area.size)); + let bounds = match (saved, area) { + (Some(frame), Some(area)) => { + let fitted = fit(frame.bounds(), area); + match frame.state { + State::Windowed => WindowBounds::Windowed(fitted), + State::Maximized => WindowBounds::Maximized(fitted), + State::Fullscreen => WindowBounds::Fullscreen(fitted), + } + } + // No display to measure (a headless test): the saved size as is. + (Some(frame), None) => WindowBounds::Windowed(frame.bounds()), + // `centered` caps the size to the display's visible area itself. + (None, _) => { + WindowBounds::Windowed(Bounds::centered(display_id, default, cx)) + } + }; + Placement { + display: display_id, + bounds, + min_size, + } +} + +/// Note where the window is now, for [`save`] to write as the app quits. +pub fn remember(window: &Window, cx: &App) { + let display = window + .display(cx) + .and_then(|display| display.uuid().ok()) + .map(|uuid| uuid.to_string()); + // Inner: on Linux the outer bounds include the client-side frame's + // shadow, and opening with those would grow the window by it each + // launch. Elsewhere the two are the same. + let frame = Frame::new(display, window.inner_window_bounds()); + *LATEST.lock().unwrap_or_else(PoisonError::into_inner) = Some(frame); +} + +/// Write the frame [`remember`] last noted. Nothing moved, nothing written: +/// the frame saved last time still stands. +pub fn save() { + let Some(frame) = + LATEST.lock().unwrap_or_else(PoisonError::into_inner).take() + else { + return; + }; + let Some(path) = path() else { + return; + }; + if let Err(error) = write(&path, &frame) { + eprintln!("could not save the window's place: {error}"); + } +} + +fn path() -> Option { + crate::updater::settings_dir().map(|dir| dir.join(FILE)) +} + +/// `path`'s frame; a missing, unreadable or nonsensical file is none. +fn load(path: &Path) -> Option { + let text = std::fs::read_to_string(path).ok()?; + let frame: Frame = serde_json::from_str(&text).ok()?; + frame.is_usable().then_some(frame) +} + +fn write(path: &Path, frame: &Frame) -> std::io::Result<()> { + let dir = path.parent().ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "no settings directory", + ) + })?; + std::fs::create_dir_all(dir)?; + let mut text = + serde_json::to_string_pretty(frame).map_err(std::io::Error::other)?; + text.push('\n'); + // Atomic replacement: a failed write leaves the last frame intact. + let mut file = tempfile::NamedTempFile::new_in(dir)?; + file.write_all(text.as_bytes())?; + file.persist(path).map_err(|error| error.error)?; + Ok(()) +} + +impl Frame { + fn new(display: Option, bounds: WindowBounds) -> Self { + let (state, bounds) = match bounds { + WindowBounds::Windowed(bounds) => (State::Windowed, bounds), + WindowBounds::Maximized(bounds) => (State::Maximized, bounds), + WindowBounds::Fullscreen(bounds) => (State::Fullscreen, bounds), + }; + Self { + display, + state, + x: f32::from(bounds.origin.x), + y: f32::from(bounds.origin.y), + width: f32::from(bounds.size.width), + height: f32::from(bounds.size.height), + } + } + + fn bounds(&self) -> Bounds { + Bounds::new( + point(px(self.x), px(self.y)), + size(px(self.width), px(self.height)), + ) + } + + /// A hand-edited or damaged file must not open a window of no size, + /// or one GPUI cannot place. + fn is_usable(&self) -> bool { + [self.x, self.y, self.width, self.height] + .iter() + .all(|value| value.is_finite()) + && self.width >= 1.0 + && self.height >= 1.0 + } +} + +/// `frame` cut to `area`'s size and moved, as little as it takes, inside +/// it: a window that fitted stays exactly where it was. +fn fit(frame: Bounds, area: Bounds) -> Bounds { + let size = frame.size.min(&area.size); + // `size` is no larger than `area`, so each range is never empty. + let x = frame + .origin + .x + .max(area.origin.x) + .min(area.origin.x + area.size.width - size.width); + let y = frame + .origin + .y + .max(area.origin.y) + .min(area.origin.y + area.size.height - size.height); + Bounds::new(point(x, y), size) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn rect(x: f32, y: f32, width: f32, height: f32) -> Bounds { + Bounds::new(point(px(x), px(y)), size(px(width), px(height))) + } + + /// A 14-inch laptop at its default resolution, under its menu bar. + const LAPTOP: (f32, f32, f32, f32) = (0.0, 38.0, 1512.0, 944.0); + + fn laptop() -> Bounds { + rect(LAPTOP.0, LAPTOP.1, LAPTOP.2, LAPTOP.3) + } + + #[test] + fn a_window_that_fits_stays_where_it_was() { + let frame = rect(200.0, 100.0, 1100.0, 700.0); + assert_eq!(fit(frame, laptop()), frame); + } + + #[test] + fn the_old_default_no_longer_hangs_off_a_laptop() { + // 120 + 1440 ran 48 points past the right edge. + let fitted = fit(rect(120.0, 90.0, 1440.0, 900.0), laptop()); + assert_eq!(fitted, rect(72.0, 82.0, 1440.0, 900.0)); + } + + #[test] + fn a_window_from_a_larger_display_is_cut_to_this_one() { + let fitted = fit(rect(2400.0, 0.0, 2560.0, 1400.0), laptop()); + assert_eq!(fitted, laptop()); + } + + #[test] + fn a_window_left_off_the_top_left_comes_back() { + let fitted = fit(rect(-300.0, -50.0, 800.0, 600.0), laptop()); + assert_eq!(fitted, rect(0.0, 38.0, 800.0, 600.0)); + } + + #[test] + fn displays_to_the_left_keep_their_negative_coordinates() { + // Windows reports a monitor left of the primary below zero. + let left = rect(-1920.0, 0.0, 1920.0, 1040.0); + let frame = rect(-1700.0, 80.0, 1440.0, 900.0); + assert_eq!(fit(frame, left), frame); + } + + #[test] + fn the_frame_survives_a_round_trip_and_bad_files_are_ignored() { + let dir = tempfile::tempdir().expect("settings"); + let path = dir.path().join("nested").join(FILE); + assert_eq!(load(&path), None); + + let frame = Frame::new( + Some("37D8832A-2D66-02CA-B9F7-8F30A301B230".to_owned()), + WindowBounds::Maximized(rect(10.0, 40.0, 1200.0, 800.0)), + ); + write(&path, &frame).expect("write"); + assert_eq!(load(&path), Some(frame.clone())); + assert_eq!( + frame.bounds(), + rect(10.0, 40.0, 1200.0, 800.0), + "the restore bounds come back unchanged" + ); + + std::fs::write(&path, "{not json").expect("damage"); + assert_eq!(load(&path), None); + let empty = Frame { + width: 0.0, + ..frame + }; + write(&path, &empty).expect("write"); + assert_eq!(load(&path), None, "a window of no size is not opened"); + } + + #[gpui_kit::test] + fn a_saved_frame_returns_to_its_display_or_the_working_one( + cx: &gpui_kit::TestAppContext, + ) { + let default = size(px(1440.0), px(900.0)); + let min = size(px(900.0), px(600.0)); + cx.update(|cx| { + let display = cx.primary_display().expect("a test display"); + let uuid = display.uuid().expect("uuid").to_string(); + let area = display.visible_bounds(); + let saved = |display: &str| Frame { + display: Some(display.to_owned()), + state: State::Windowed, + x: 3000.0, + y: 40.0, + width: 1200.0, + height: 800.0, + }; + + let here = placement(Some(saved(&uuid)), None, default, min, cx); + assert_eq!(here.display, Some(display.id())); + let gone = + placement(Some(saved("unplugged")), None, default, min, cx); + assert_eq!(gone.display, None, "the primary display"); + // Either way the frame is pulled onto the display it opens on. + for placed in [here, gone] { + let WindowBounds::Windowed(bounds) = placed.bounds else { + panic!("still windowed"); + }; + assert_eq!(bounds.size, size(px(1200.0), px(800.0))); + assert_eq!( + bounds.origin.x + bounds.size.width, + area.origin.x + area.size.width + ); + } + + let fresh = placement(None, None, default, min, cx); + let WindowBounds::Windowed(bounds) = fresh.bounds else { + panic!("windowed"); + }; + assert_eq!(bounds.size, default); + assert_eq!(bounds.center(), area.center()); + assert_eq!(fresh.min_size, min); + + // The display the user is working on, when nothing saved + // names one still connected; a fallback since unplugged is + // the primary display again. + let working = Some(display.id()); + let fresh = placement(None, working, default, min, cx); + assert_eq!(fresh.display, working); + let gone = + placement(Some(saved("unplugged")), working, default, min, cx); + assert_eq!(gone.display, working); + let stale = Some(DisplayId::new(u64::from(display.id()) + 1)); + assert_eq!(placement(None, stale, default, min, cx).display, None); + }); + } +} diff --git a/crates/disktree-core/Cargo.toml b/crates/disktree-core/Cargo.toml index b4fc0d04..93191f6b 100644 --- a/crates/disktree-core/Cargo.toml +++ b/crates/disktree-core/Cargo.toml @@ -19,7 +19,7 @@ sha2 = "0.10" # rustix has no filesystem calls on Windows; `windows.rs` covers them there. [target.'cfg(not(windows))'.dependencies] -rustix = { version = "1.1", features = ["fs"] } +rustix = { version = "1.1", features = ["fs", "process"] } [target.'cfg(windows)'.dependencies] # The Recycle Bin, through the shell's own file operation. @@ -37,9 +37,11 @@ windows-sys = { version = "0.61", features = [ # without asking to control Finder. Only this backend is used; the crate's # Linux and Windows code is not built. [target.'cfg(target_os = "macos")'.dependencies] +libc = "0.2" trash = { version = "5.2.9", default-features = false } [dev-dependencies] +proptest = "1.12" tempfile = "3" # CPU-only sampling; the GUI dependency graph already pins this version. diff --git a/crates/disktree-core/examples/profile_remote.rs b/crates/disktree-core/examples/profile_remote.rs index 862c8a2d..ed541666 100644 --- a/crates/disktree-core/examples/profile_remote.rs +++ b/crates/disktree-core/examples/profile_remote.rs @@ -46,13 +46,12 @@ fn main() -> io::Result<()> { "decode" => { let snapshot = read_snapshot(&mut BufReader::new(File::open(path)?))?; - eprintln!( - "files={} bytes={}", - snapshot.tree.files, snapshot.tree.bytes - ); + let tree = snapshot.tree.root(); + eprintln!("files={} bytes={}", tree.files, tree.bytes); } "scan" => { let tree = scan(path, ScanOptions::default())?; + let tree = tree.root(); eprintln!("files={} bytes={}", tree.files, tree.bytes); } "ssh" | "ssh-plain" => { @@ -94,7 +93,7 @@ fn main() -> io::Result<()> { if !child.wait()?.success() { return Err(io::Error::other("fixture SSH failed")); } - eprintln!("files={}", snapshot.tree.files); + eprintln!("files={}", snapshot.tree.root().files); } "stream" => { let request = serde_json::to_vec(&serde_json::json!({ diff --git a/crates/disktree-core/examples/scan_accounting.rs b/crates/disktree-core/examples/scan_accounting.rs new file mode 100644 index 00000000..9b6e4e5b --- /dev/null +++ b/crates/disktree-core/examples/scan_accounting.rs @@ -0,0 +1,39 @@ +//! Compare clone accounting with the ordinary walk on the same tree: +//! `cargo run --release -p disktree-core --example scan_accounting -- PATH` +//! Append --no-clones to measure the baseline without private-size queries. + +use std::path::PathBuf; +use std::time::Instant; + +use disktree_core::scan::{ScanOptions, scan}; + +fn main() -> std::io::Result<()> { + let mut args = std::env::args_os().skip(1); + let root = args + .next() + .map_or_else(|| PathBuf::from("."), PathBuf::from); + let clones = args.next().is_none_or(|arg| arg != "--no-clones"); + let started = Instant::now(); + let tree = scan( + &root, + ScanOptions { + apfs_clone_metadata: clones, + ..ScanOptions::default() + }, + )?; + let tree = tree.root(); + println!( + "seconds={:.3} files={} listed={} clone_files={} clone_bytes={} duplicate_bytes={} private_bytes={} unknown_clones={} reclaim_lower={} reclaim_upper={}", + started.elapsed().as_secs_f64(), + tree.files, + tree.bytes, + tree.sharing().files, + tree.sharing().bytes, + tree.sharing().duplicate_bytes, + tree.sharing().private_bytes, + tree.sharing().unknown_files, + tree.sharing().reclaimable(tree.bytes), + tree.sharing().possible(tree.bytes) + ); + Ok(()) +} diff --git a/crates/disktree-core/examples/scan_workers.rs b/crates/disktree-core/examples/scan_workers.rs index 8b79eccb..35a7bc6b 100644 --- a/crates/disktree-core/examples/scan_workers.rs +++ b/crates/disktree-core/examples/scan_workers.rs @@ -50,6 +50,7 @@ fn main() { } std::thread::sleep(Duration::from_millis(20)); }; + let node = node.root(); let elapsed = start.elapsed().as_secs_f64(); let progress = handle.progress.snapshot(); println!( diff --git a/crates/disktree-core/examples/tree_digest.rs b/crates/disktree-core/examples/tree_digest.rs new file mode 100644 index 00000000..067404f4 --- /dev/null +++ b/crates/disktree-core/examples/tree_digest.rs @@ -0,0 +1,76 @@ +//! A digest of a scanned tree, to compare two builds of the scanner: +//! `cargo run --release -p disktree-core --example tree_digest -- PATH` +//! +//! Hashes every node's name, totals, category, reclaim reason, sharing +//! figures and allocation record depth first, in child order, then again +//! after re-ranking by file count, so two trees agree only if their shape, +//! figures and order all do. +//! +//! Which name of a hardlinked file is charged depends on which worker +//! reaches it first, so set `NODEDUP=1` to compare two builds exactly. +//! `DUMP=1` prints one line per node as well, to find where they differ. + +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::path::PathBuf; + +use disktree_core::scan::{ScanOptions, scan}; +use disktree_core::tree::{Metric, Node, aggregate}; + +fn digest(node: Node<'_>, hasher: &mut DefaultHasher) { + node.name().hash(hasher); + ( + node.bytes, + node.files, + node.dirs, + node.modified, + node.read_error, + ) + .hash(hasher); + format!("{:?}{:?}", node.category, node.reclaim).hash(hasher); + // Every sharing figure and the file's allocation record, private + // sizes and estimate bounds included: APFS clone accounting must not + // move any of them. + let sharing = node.sharing(); + format!("{sharing:?}{:?}", node.allocation()).hash(hasher); + if std::env::var_os("DUMP").is_some() { + println!( + "{} {} {} {} {} {} {:?} {:?} {} {} {}", + node.name(), + node.bytes, + node.files, + node.dirs, + node.modified, + node.read_error, + node.category, + node.reclaim, + sharing.files, + sharing.bytes, + node.children().len() + ); + } + node.children().len().hash(hasher); + for child in node.children() { + digest(child, hasher); + } +} + +fn main() -> std::io::Result<()> { + let root = std::env::args_os() + .nth(1) + .map_or_else(|| PathBuf::from("."), PathBuf::from); + let mut tree = scan( + &root, + ScanOptions { + dedup_hardlinks: std::env::var_os("NODEDUP").is_none(), + ..ScanOptions::default() + }, + )?; + let mut hasher = DefaultHasher::new(); + digest(tree.root(), &mut hasher); + let scanned = hasher.finish(); + aggregate(&mut tree, Metric::Files); + let mut hasher = DefaultHasher::new(); + digest(tree.root(), &mut hasher); + println!("scanned={scanned:016x} by_files={:016x}", hasher.finish()); + Ok(()) +} diff --git a/crates/disktree-core/examples/tree_memory.rs b/crates/disktree-core/examples/tree_memory.rs new file mode 100644 index 00000000..f534da1e --- /dev/null +++ b/crates/disktree-core/examples/tree_memory.rs @@ -0,0 +1,134 @@ +//! What a scanned tree costs to hold and to let go of, on macOS: +//! `cargo run --release -p disktree-core --example tree_memory -- PATH` +//! (`-- --no-clones PATH` scans without APFS clone metadata) +//! +//! Scans PATH, then reports the process's physical footprint (resident +//! plus compressed, what Activity Monitor calls Memory) after the scan and +//! at its highest so far; the time to copy the tree, to re-rank it as the +//! size/files toggle does, to derive its totals again and to classify it; +//! and the time and page faults of dropping each copy. Run it in a fresh +//! process each time: a drop's cost depends on what the allocator and the +//! compressor hold. + +#![allow( + unsafe_code, + reason = "getrusage and proc_pid_rusage, which std does not wrap" +)] +#![allow(clippy::cast_precision_loss, reason = "report figures")] + +#[cfg(target_os = "macos")] +fn main() -> std::io::Result<()> { + use std::path::PathBuf; + use std::time::Instant; + + use disktree_core::scan::{ScanOptions, scan}; + use disktree_core::tree::{Metric, aggregate, reorder}; + + let mut args: Vec<_> = std::env::args_os().skip(1).collect(); + let mut options = ScanOptions::default(); + if let Some(at) = args.iter().position(|arg| arg == "--no-clones") { + args.remove(at); + options.apfs_clone_metadata = false; + } + let root = args + .into_iter() + .next() + .map_or_else(|| PathBuf::from("."), PathBuf::from); + + let (before, _) = footprint_mib(); + let started = Instant::now(); + let tree = scan(&root, options)?; + let scanned = started.elapsed().as_secs_f64(); + let (now, peak) = footprint_mib(); + let storage = tree.storage_bytes(); + let (allocations, sharings, both) = tree.side_records(); + println!( + "scan={scanned:.2}s files={} dirs={} footprint+={:.0}MiB \ + peak+={:.0}MiB storage_used={:.0}MiB storage_reserved={:.0}MiB \ + allocations={allocations} sharings={sharings} both={both}", + tree.root().files, + tree.root().dirs, + now - before, + peak - before, + storage.used as f64 / MIB, + storage.reserved as f64 / MIB, + ); + + let started = Instant::now(); + let mut copy = tree.clone(); + let cloned = started.elapsed().as_secs_f64(); + let started = Instant::now(); + reorder(&mut copy, Metric::Files); + let reordered = started.elapsed().as_secs_f64(); + let started = Instant::now(); + aggregate(&mut copy, Metric::Files); + let aggregated = started.elapsed().as_secs_f64(); + let started = Instant::now(); + disktree_core::classify::classify(&mut copy); + let classified = started.elapsed().as_secs_f64(); + let (now, peak) = footprint_mib(); + println!( + "copy={cloned:.2}s reorder={reordered:.2}s aggregate={aggregated:.2}s \ + classify={classified:.3}s footprint+={:.0}MiB peak+={:.0}MiB", + now - before, + peak - before, + ); + timed_drop("copy", copy); + timed_drop("scanned tree", tree); + Ok(()) +} + +#[cfg(not(target_os = "macos"))] +fn main() { + eprintln!("tree_memory reads macOS process counters; it runs on macOS"); +} + +#[cfg(target_os = "macos")] +const MIB: f64 = 1024.0 * 1024.0; + +#[cfg(target_os = "macos")] +fn faults() -> (i64, i64) { + // SAFETY: getrusage fills the struct it is given. + let mut usage: libc::rusage = unsafe { std::mem::zeroed() }; + // SAFETY: as above. + unsafe { libc::getrusage(libc::RUSAGE_SELF, &raw mut usage) }; + (usage.ru_minflt, usage.ru_majflt) +} + +/// Resident plus compressed, now and at its highest: plain RSS leaves out +/// what the compressor holds, which on a large tree is most of it. +#[cfg(target_os = "macos")] +fn footprint_mib() -> (f64, f64) { + // SAFETY: proc_pid_rusage fills the v4 struct it is given. + let mut info: libc::rusage_info_v4 = unsafe { std::mem::zeroed() }; + let pid = i32::try_from(std::process::id()).expect("a pid fits"); + // SAFETY: as above. + let status = unsafe { + libc::proc_pid_rusage(pid, libc::RUSAGE_INFO_V4, (&raw mut info).cast()) + }; + // A zeroed struct would read as a footprint of nothing. + assert_eq!( + status, + 0, + "proc_pid_rusage: {}", + std::io::Error::last_os_error() + ); + ( + info.ri_phys_footprint as f64 / MIB, + info.ri_lifetime_max_phys_footprint as f64 / MIB, + ) +} + +#[cfg(target_os = "macos")] +fn timed_drop(label: &str, value: T) { + let (minor, major) = faults(); + let started = std::time::Instant::now(); + drop(value); + let seconds = started.elapsed().as_secs_f64(); + let (minor_after, major_after) = faults(); + println!( + "{label}: drop={seconds:.3}s minor_faults={} major_faults={}", + minor_after - minor, + major_after - major + ); +} diff --git a/crates/disktree-core/src/artifact.rs b/crates/disktree-core/src/artifact.rs new file mode 100644 index 00000000..18ea27b2 --- /dev/null +++ b/crates/disktree-core/src/artifact.rs @@ -0,0 +1,1092 @@ +//! Artifact identity is evidence about contents, never removal permission. +//! +//! Layout rules are shared with `DiskHound`. Only recognized roots receive +//! an assessment; a matching child never promotes its parent. VM ownership +//! takes precedence over cache names, including inside VM bundles. + +use std::path::Path; + +use rustc_hash::FxHashMap; +use serde::{Deserialize, Serialize}; + +use crate::classify::{Category, Reclaim}; +use crate::path_style::PathStyle; +use crate::tree::{Node, Tree}; + +mod rules; + +#[cfg(test)] +thread_local! { + static WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +#[cfg(test)] +fn step() { + WORK.set(WORK.get() + 1); +} + +#[cfg(not(test))] +const fn step() {} + +/// What was recognized, independently of whether cleanup is suggested. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Artifact { + Worktree, + NodeModules, + PackageCache, + RustTarget, + CargoRegistry, + JsBuild, + Python, + GoModule, + Jvm, + Dotnet, + CompilerCache, + CmakeBuild, + Terraform, + GitRepo, + DiagLogs, + VirtualMachine, + VmDisk, + VmSnapshot, + VmSuspend, +} + +impl Artifact { + pub const fn label(self) -> &'static str { + match self { + Self::Worktree => "worktree", + Self::NodeModules => "Node dependencies", + Self::PackageCache => "package cache", + Self::RustTarget => "Rust build cache", + Self::CargoRegistry => "Cargo registry", + Self::JsBuild => "frontend output", + Self::Python => "Python packages / cache", + Self::GoModule => "Go modules / cache", + Self::Jvm => "Gradle / JVM cache", + Self::Dotnet => ".NET packages / intermediates", + Self::CompilerCache => "compiler cache", + Self::CmakeBuild => "CMake intermediates", + Self::Terraform => "Terraform providers", + Self::GitRepo => "Git history", + Self::DiagLogs => "diagnostic logs", + Self::VirtualMachine => "virtual machine data", + Self::VmDisk => "VM disk image", + Self::VmSnapshot => "VM snapshot", + Self::VmSuspend => "VM saved memory / suspend state", + } + } + + pub const fn is_vm(self) -> bool { + matches!( + self, + Self::VirtualMachine + | Self::VmDisk + | Self::VmSnapshot + | Self::VmSuspend + ) + } +} + +/// Strength of identification, not a confidence score for deletion. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Evidence { + /// A distinctive tool name or file extension can still be a lookalike. + Name, + /// Multiple path components follow a documented tool layout. + Layout, +} + +/// Whether the recognized contents are a plausible cleanup candidate. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Disposition { + Detected, + Suggested, +} + +/// A path's identity and the independent assessment of cleanup suitability. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Detection { + pub kind: Artifact, + pub evidence: Evidence, + pub disposition: Disposition, +} + +impl Detection { + /// A protected descendant can make the whole directory unsuitable for + /// suggestion even though its path still identifies an artifact. + #[must_use] + pub fn assessed(mut self, node: Node<'_>) -> Self { + if node.reclaim.is_none() { + self.disposition = Disposition::Detected; + } + self + } + + const fn new(kind: Artifact, evidence: Evidence) -> Self { + let disposition = match kind { + Artifact::Worktree + | Artifact::GitRepo + | Artifact::DiagLogs + | Artifact::VirtualMachine + | Artifact::VmDisk + | Artifact::VmSnapshot + | Artifact::VmSuspend => Disposition::Detected, + _ => Disposition::Suggested, + }; + Self { + kind, + evidence, + disposition, + } + } + + pub const fn status(self) -> &'static str { + match self.disposition { + Disposition::Detected => "Detected", + Disposition::Suggested => "Suggested for review", + } + } + + pub const fn evidence_label(self) -> &'static str { + match self.evidence { + Evidence::Name => "name convention", + Evidence::Layout => "tool layout", + } + } + + pub const fn guidance(self) -> &'static str { + match self.kind { + Artifact::VmDisk | Artifact::VirtualMachine => { + "May contain unique work. Manage this VM or container in its owner app. Listed bytes are not guaranteed recoverable space." + } + Artifact::VmSnapshot => { + "Review and consolidate snapshots in the VM app. Disks can depend on snapshot chains; do not remove individual snapshot files." + } + Artifact::VmSuspend => { + "Saved memory may belong to a suspended VM or a checkpoint. Resume the VM and shut it down normally; let the VM app release the state." + } + Artifact::GitRepo => { + "Git history may contain unpushed commits and recovery data. Inspect it with Git; detection is not a cleanup suggestion." + } + Artifact::Worktree => { + "Check uncommitted and unpushed work, then manage the worktree with Git. Age and size do not establish disposability." + } + Artifact::DiagLogs => { + "Review whether these logs are needed for diagnosis and whether their owner is still writing them." + } + Artifact::NodeModules | Artifact::Python => { + "Review local edits and stop builds or running environments first. Reinstalling packages or rebuilding may require network access." + } + Artifact::RustTarget + | Artifact::JsBuild + | Artifact::CompilerCache + | Artifact::CmakeBuild => { + "Recognized build or cache layout. Review local changes and stop builds first; use the build tool's clean operation. The next build can be slower." + } + _ => { + "Recognized dependency or cache layout. Review local edits and use the owner's cleanup operation. Downloads or rebuilding may be needed again." + } + } + } + + pub const fn reclaim(self) -> Option { + if matches!(self.disposition, Disposition::Detected) { + return None; + } + Some(match self.kind { + Artifact::NodeModules => Reclaim::Reinstallable, + Artifact::Python + | Artifact::GoModule + | Artifact::Jvm + | Artifact::Dotnet => Reclaim::Regenerable, + Artifact::RustTarget + | Artifact::JsBuild + | Artifact::CompilerCache + | Artifact::CmakeBuild => Reclaim::BuildOutput, + _ => Reclaim::PackageStore, + }) + } + + pub const fn category(self) -> Category { + if self.kind.is_vm() { + Category::VirtualMachine + } else { + match self.kind { + Artifact::GitRepo => Category::Git, + Artifact::Worktree => Category::AgentScratch, + _ => Category::Cache, + } + } + } +} + +/// Inspect a path using the scanned machine's path rules, without I/O. +pub fn detect( + path: &Path, + style: PathStyle, + is_dir: bool, +) -> Option { + let names = style.names(path); + let parts: Vec<&str> = names.iter().map(AsRef::as_ref).collect(); + detect_parts(&parts, is_dir) +} + +/// Assess a displayed node. Ownership in the scanned tree wins when the +/// display path is an alias that does not name the owning VM or Git store. +pub fn assess( + path: &Path, + style: PathStyle, + node: Node<'_>, +) -> Option { + let detection = detect(path, style, node.is_dir()); + let detection = match node.category { + Category::VirtualMachine => { + Some(detection.filter(|d| d.kind.is_vm()).unwrap_or_else(|| { + Detection::new(Artifact::VirtualMachine, Evidence::Layout) + })) + } + Category::Git => Some( + detection + .filter(|d| d.kind == Artifact::GitRepo) + .unwrap_or_else(|| { + Detection::new(Artifact::GitRepo, Evidence::Name) + }), + ), + _ => detection, + }; + detection.map(|mut d| { + if d.kind == Artifact::PackageCache + && crate::classify::is_pnpm_store(node) + { + d.evidence = Evidence::Layout; + } + d.assessed(node) + }) +} + +fn detect_parts(parts: &[&str], is_dir: bool) -> Option { + if let Some(detection) = vm(parts, is_dir) { + return Some(detection); + } + // A path ending in a regular file named `node_modules` is not an + // installed dependency tree. All developer roots are directories. + let directories = if is_dir { + parts + } else { + parts.get(..parts.len().saturating_sub(1))? + }; + if directories + .iter() + .any(|name| name.eq_ignore_ascii_case(".git")) + { + return Some(Detection::new(Artifact::GitRepo, Evidence::Name)); + } + if let Some(end) = pnpm_store_end(directories) { + return Some(Detection::new( + Artifact::PackageCache, + evidence(&directories[..end]), + )); + } + let (end, kind) = developer(directories)?; + Some(Detection::new(kind, evidence(&directories[..end]))) +} + +/// The owning store, rather than any cache that happens to contain it. +fn pnpm_store_end(parts: &[&str]) -> Option { + parts.iter().enumerate().find_map(|(i, name)| { + step(); + if name.eq_ignore_ascii_case(".pnpm-store") { + Some(i + 1) + } else if name.eq_ignore_ascii_case("pnpm") + && parts + .get(i + 1) + .is_some_and(|s| s.eq_ignore_ascii_case("store")) + { + Some(i + 2) + } else { + None + } + }) +} + +fn developer(parts: &[&str]) -> Option<(usize, Artifact)> { + let mut found = rules::classify_parts(parts, 0)?; + // A worktree is inventory, but its installed dependencies can still be + // reviewed separately without suggesting the checkout itself. + while found.1 == Artifact::Worktree && found.0 < parts.len() { + let Some(inner) = rules::classify_parts(parts, found.0) else { + break; + }; + found = inner; + } + Some(found) +} + +fn excluded_tool_contents(parts: &[&str]) -> bool { + parts.iter().enumerate().any(|(i, part)| { + step(); + let Some(next) = parts.get(i + 1) else { + return false; + }; + let next = next.to_ascii_lowercase(); + let after = parts.get(i + 2); + match part.to_ascii_lowercase().as_str() { + ".yarn" => match next.as_str() { + "cache" | "unplugged" => false, + "berry" => { + after.is_some_and(|s| !s.eq_ignore_ascii_case("cache")) + } + _ => true, + }, + ".bun" => { + next != "install" + || after.is_some_and(|s| !s.eq_ignore_ascii_case("cache")) + } + ".gradle" => { + next != "caches" + && !rules::numeric_version(&next, 2, 3) + && (next != "wrapper" + || after + .is_some_and(|s| !s.eq_ignore_ascii_case("dists"))) + } + ".m2" => next != "repository", + ".nuget" => next != "packages", + ".vercel" => !matches!(next.as_str(), "cache" | "output"), + ".netlify" => next != "cache", + ".output" => !matches!(next.as_str(), "public" | "server"), + _ => false, + } + }) +} + +fn evidence(parts: &[&str]) -> Evidence { + let last = parts.last().copied().unwrap_or_default(); + if matches!( + last.to_ascii_lowercase().as_str(), + "node_modules" + | ".pnpm-store" + | ".next" + | ".nuxt" + | ".turbo" + | ".parcel-cache" + | ".svelte-kit" + | "__pycache__" + | ".mypy_cache" + | ".pytest_cache" + | ".ruff_cache" + | "cmakefiles" + | ".zig-cache" + | ".git" + | "diagoutputdir" + | "rdclientautotrace" + ) { + Evidence::Name + } else { + Evidence::Layout + } +} + +fn vm(parts: &[&str], is_dir: bool) -> Option { + let name = parts.last()?.to_ascii_lowercase(); + let extension = name.rsplit_once('.').map_or("", |(_, ext)| ext); + let kind = + match extension { + "avhd" | "avhdx" | "vmsn" => Some(Artifact::VmSnapshot), + "vmss" | "vmem" | "vmrs" | "sav" => Some(Artifact::VmSuspend), + "vdi" | "vmdk" | "vhd" | "vhdx" | "qcow" | "qcow2" | "qed" + | "hds" => Some(Artifact::VmDisk), + "vbox" | "vbox-prev" | "vmx" | "vmxf" | "vmsd" | "vmcx" + | "vmgs" | "hdd" | "pvm" | "vmwarevm" | "utm" | "ova" | "ovf" + | "xva" => Some(Artifact::VirtualMachine), + _ => None, + }; + let owned = parts.iter().enumerate().any(|(i, part)| { + step(); + let at = |offset: usize, wanted: &str| { + parts + .get(i + offset) + .is_some_and(|s| s.eq_ignore_ascii_case(wanted)) + }; + let part = part.to_ascii_lowercase(); + part.rsplit_once('.').is_some_and(|(_, extension)| { + matches!(extension, "vmwarevm" | "pvm" | "utm" | "hdd") + }) || (part == ".tart" && at(1, "vms") && i + 2 < parts.len()) + || (part == "virtualbox vms" && i + 1 < parts.len()) + || (part == ".minikube" && at(1, "machines") && i + 2 < parts.len()) + || (part == "com.docker.docker" + && at(1, "data") + && at(2, "vms") + && i + 3 < parts.len()) + || (!is_dir + && matches!( + name.as_str(), + "diffdisk" | "basedisk" | "cidata.iso" + ) + && ((part == ".lima" + && i + 3 == parts.len() + && !parts[i + 1].starts_with('_')) + || (part == ".colima" + && at(1, "_lima") + && i + 4 == parts.len()))) + }); + // .sav is also used for game saves. Only VM ownership establishes it. + let kind = if extension == "sav" && !owned { + None + } else if (extension == "vmdk" + && name.strip_suffix(".vmdk").is_some_and(|stem| { + let stem = stem + .strip_suffix("-delta") + .or_else(|| stem.strip_suffix("-sesparse")) + .unwrap_or(stem); + stem.rsplit_once('-').is_some_and(|(_, number)| { + number.len() == 6 && number.bytes().all(|b| b.is_ascii_digit()) + }) + })) + || (owned && is_dir && name == "snapshots") + { + Some(Artifact::VmSnapshot) + } else { + kind + }; + if owned || (!is_dir && kind.is_some()) { + Some(Detection::new( + kind.unwrap_or(Artifact::VirtualMachine), + if owned { + Evidence::Layout + } else { + Evidence::Name + }, + )) + } else { + None + } +} + +fn possible_vm_file(name: &str) -> bool { + // Most files need no path processing. Keep the common case allocation + // free; the longest recognized extension is nine ASCII bytes. + let extension = name.rsplit_once('.').map_or("", |(_, ext)| ext); + let mut buffer = [0_u8; 10]; + let Some(lower) = buffer.get_mut(..extension.len()) else { + return false; + }; + lower.copy_from_slice(extension.as_bytes()); + lower.make_ascii_lowercase(); + matches!( + &*lower, + b"vdi" + | b"vmdk" + | b"vhd" + | b"vhdx" + | b"qcow" + | b"qcow2" + | b"qed" + | b"avhd" + | b"avhdx" + | b"vmsn" + | b"vmss" + | b"vmem" + | b"vmrs" + | b"sav" + | b"vbox" + | b"vbox-prev" + | b"vmx" + | b"vmxf" + | b"vmsd" + | b"vmcx" + | b"vmgs" + | b"hds" + | b"hdd" + | b"pvm" + | b"vmwarevm" + | b"utm" + | b"ova" + | b"ovf" + | b"xva" + | b"iso" + ) || name.eq_ignore_ascii_case("diffdisk") + || name.eq_ignore_ascii_case("basedisk") +} + +/// Temporary overrides by node id. No field is added to every stored node. +#[derive(Debug, Default)] +pub(crate) struct Roots(FxHashMap); + +impl Roots { + pub fn find(tree: &Tree, path: &Path, style: PathStyle) -> Self { + let names = style.names(path); + let mut parts: Vec<&str> = names.iter().map(AsRef::as_ref).collect(); + let mut roots = Self::default(); + if let Some(mut detection) = detect_parts(&parts, tree.root().is_dir()) + { + // A narrow scan cannot verify a store above its root. Seeing a + // versioned layout inside this subtree does not verify that owner. + if detection.kind == Artifact::PackageCache + && pnpm_store_end(&parts).is_some_and(|end| end < parts.len()) + { + detection.disposition = Disposition::Detected; + } + roots.insert(tree.root(), detection); + if detection.kind.is_vm() || detection.kind == Artifact::GitRepo { + return roots; + } + } + let excluded = excluded_tool_contents(&parts); + // The root was judged with its full path. A bounded lookback here + // could lose its enclosing ownership and overwrite that assessment. + for child in tree.root().children() { + parts.push(child.name()); + Self::visit(child, &mut parts, excluded, &mut roots); + parts.pop(); + } + roots + } + + fn visit<'a>( + node: Node<'a>, + parts: &mut Vec<&'a str>, + excluded: bool, + roots: &mut Self, + ) { + step(); + // VM ownership is propagated once; the rule window is bounded even + // in deeply nested dependency trees or repeated ambiguous segments. + let tail = &parts[parts.len().saturating_sub(6)..]; + // Preserve tool-home exclusions after their names leave the bounded + // window; installed plugins/settings are not dependency caches. + let excluded = + excluded || (node.is_dir() && excluded_tool_contents(tail)); + let machine = if node.is_dir() || possible_vm_file(node.name()) { + vm(tail, node.is_dir()) + } else { + None + }; + let detection = machine.or_else(|| { + if node.is_dir() && node.name().eq_ignore_ascii_case(".git") { + return Some(Detection::new(Artifact::GitRepo, Evidence::Name)); + } + if !node.is_dir() || excluded { + return None; + } + if pnpm_store_end(tail) == Some(tail.len()) { + return Some(Detection::new( + Artifact::PackageCache, + evidence(tail), + )); + } + let (end, kind) = developer(tail)?; + (end == tail.len()).then(|| Detection::new(kind, evidence(tail))) + }); + if let Some(detection) = detection { + roots.insert(node, detection); + } + // A VM subtree is protected by its inherited category. Its files + // need no additional overrides or path checks. + if machine.is_some() + || detection.is_some_and(|d| d.kind == Artifact::GitRepo) + { + return; + } + for child in node.children() { + parts.push(child.name()); + Self::visit(child, parts, excluded, roots); + parts.pop(); + } + } + + pub fn get(&self, id: u32) -> Option { + self.0.get(&id).copied() + } + + fn insert(&mut self, node: Node<'_>, mut detection: Detection) { + // PwrDisk can inspect the scanned entries, so retain its stronger + // store check rather than promoting a name-only DiskHound match. + if detection.kind == Artifact::PackageCache + && (node.name().eq_ignore_ascii_case("store") + || node.name().eq_ignore_ascii_case(".pnpm-store")) + && !crate::classify::is_pnpm_store(node) + { + detection.disposition = Disposition::Detected; + } + self.0.insert(node.id(), detection); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::classify::classify_at; + use crate::tree::{Draft, NodeKind}; + + #[derive(Deserialize)] + struct Fixture { + path: String, + root: Option, + kind: Option, + } + + #[test] + fn diskhound_corpus_matches_across_case_and_separator_variants() { + let fixtures: Vec = + serde_json::from_str(include_str!("artifact/classification.json")) + .unwrap(); + assert!(fixtures.len() >= 350); + for fixture in fixtures { + for path in [ + fixture.path.clone(), + fixture.path.to_ascii_uppercase(), + fixture.path.replace('/', "\\"), + ] { + let parts: Vec<&str> = + path.split(['/', '\\']).filter(|s| !s.is_empty()).collect(); + let actual = rules::classify_parts(&parts, 0); + assert_eq!( + actual.map(|(_, kind)| kind), + fixture.kind, + "{path}" + ); + if let Some((end, _)) = actual { + let expected: Vec<_> = fixture + .root + .as_ref() + .unwrap() + .split(['/', '\\']) + .filter(|s| !s.is_empty()) + .map(str::to_ascii_lowercase) + .collect(); + let root: Vec<_> = parts[..end] + .iter() + .map(|s| s.to_ascii_lowercase()) + .collect(); + assert_eq!(root, expected, "{path}"); + } + } + } + } + + fn detection(path: &str, is_dir: bool) -> Option { + detect(Path::new(path), PathStyle::Posix, is_dir) + } + + #[test] + fn identity_evidence_and_cleanup_are_independent() { + let dependencies = detection("/project/node_modules", true).unwrap(); + assert_eq!(dependencies.evidence, Evidence::Name); + assert_eq!(dependencies.disposition, Disposition::Suggested); + let rust = detection("/project/target/debug/deps", true).unwrap(); + assert_eq!(rust.evidence, Evidence::Layout); + assert_eq!(rust.disposition, Disposition::Suggested); + let git = detection("/project/.git/objects/pack", true).unwrap(); + assert_eq!(git.disposition, Disposition::Detected); + assert_eq!(git.reclaim(), None); + for path in [ + "/project/target", + "/project/build", + "/project/dist", + "/project/node_modules", + ] { + assert_eq!( + detection(path, false), + None, + "a name is not a directory: {path}" + ); + } + assert_eq!(detection("/project/target", true), None); + assert_eq!(detection("/project/venv/bin", true), None); + assert_eq!(detection("/project/.yarn/patches", true), None); + assert_eq!(detection("/project/vendor/cache", true), None); + } + + #[test] + fn vm_disks_checkpoints_and_memory_are_detected_only() { + for (path, kind) in [ + ("/VM/guest.qcow2", Artifact::VmDisk), + ("/VM/guest.vhdx", Artifact::VmDisk), + ("/VM/guest.avhdx", Artifact::VmSnapshot), + ("/VM/guest-000001.vmdk", Artifact::VmSnapshot), + ("/VM/guest-000001-delta.vmdk", Artifact::VmSnapshot), + ("/VM/guest-s001.vmdk", Artifact::VmDisk), + ("/VM/guest.vmsn", Artifact::VmSnapshot), + ("/VM/guest.vmss", Artifact::VmSuspend), + ("/VM/guest.vmem", Artifact::VmSuspend), + ("/VM/guest.vmrs", Artifact::VmSuspend), + ("/VM/guest.vmwarevm/cache/blob", Artifact::VirtualMachine), + ( + "/home/test/.tart/vms/node_modules", + Artifact::VirtualMachine, + ), + ( + "/home/test/VirtualBox VMs/node_modules", + Artifact::VirtualMachine, + ), + ( + "/home/test/.lima/default/diffdisk", + Artifact::VirtualMachine, + ), + ( + "/home/test/.colima/_lima/default/basedisk", + Artifact::VirtualMachine, + ), + ] { + let d = detection(path, false).unwrap(); + assert_eq!(d.kind, kind, "{path}"); + assert_eq!(d.disposition, Disposition::Detected); + assert_eq!(d.reclaim(), None); + } + for path in [ + "/photos/photo.raw", + "/images/disk.img", + "/games/slot.sav", + "/source/vms/image.img", + "/VM/guest.vmwarevm-backup/disk.img", + "/source/folder\\guest.vmdk/notes", + ] { + assert_eq!(detection(path, false), None, "{path}"); + } + let memory = detection("/VM/guest.vmss", false).unwrap(); + assert!(memory.guidance().contains("shut it down normally")); + assert!( + detection("/VM/guest.avhdx", false) + .unwrap() + .guidance() + .contains("snapshot chains") + ); + } + + fn dir(name: &str, children: Vec) -> Draft { + let mut draft = Draft::directory(name); + draft.children = children; + draft + } + + fn file(name: &str) -> Draft { + Draft::entry(name, NodeKind::File, 100) + } + + #[test] + fn mixed_project_output_does_not_promote_parents_or_settings() { + let mut tree = Tree::from(dir( + "project", + vec![ + file("Cargo.toml"), + dir( + "target", + vec![ + file("notes.txt"), + dir( + "debug", + vec![ + file("my-program"), + dir("deps", vec![file("lib.rlib")]), + ], + ), + dir("scala-3.3", vec![file("App.class")]), + ], + ), + dir( + ".yarn", + vec![ + dir("patches", vec![file("local.patch")]), + dir("cache", vec![file("package.zip")]), + ], + ), + dir( + ".terraform", + vec![ + file("terraform.tfstate"), + dir("providers", vec![file("provider")]), + ], + ), + ], + )); + classify_at(&mut tree, Path::new("/project"), PathStyle::Posix); + let root = tree.root(); + let target = root.child_named("target").unwrap(); + assert_eq!(target.reclaim, None); + assert_eq!(target.child_named("notes.txt").unwrap().reclaim, None); + let debug = target.child_named("debug").unwrap(); + assert_eq!(debug.reclaim, None); + assert_eq!(debug.child_named("my-program").unwrap().reclaim, None); + assert_eq!( + debug.child_named("deps").unwrap().reclaim, + Some(Reclaim::BuildOutput) + ); + assert!(target.child_named("scala-3.3").unwrap().reclaim.is_some()); + let yarn = root.child_named(".yarn").unwrap(); + assert_eq!(yarn.reclaim, None); + assert_eq!(yarn.child_named("patches").unwrap().reclaim, None); + assert!(yarn.child_named("cache").unwrap().reclaim.is_some()); + let terraform = root.child_named(".terraform").unwrap(); + assert_eq!( + terraform.child_named("terraform.tfstate").unwrap().reclaim, + None + ); + assert!( + terraform + .child_named("providers") + .unwrap() + .reclaim + .is_some() + ); + } + + #[test] + fn vm_ownership_protects_nested_cache_names_and_enclosing_candidates() { + let vm = dir( + "guest.utm", + vec![ + dir("node_modules", vec![file("local-work")]), + dir("cache", vec![file("state")]), + ], + ); + let mut tree = Tree::from(dir( + "home", + vec![dir(".cache", vec![vm, file("other-cache")])], + )); + classify_at(&mut tree, Path::new("/home"), PathStyle::Posix); + let cache = tree.root().child_named(".cache").unwrap(); + assert_eq!( + cache.reclaim, None, + "a parent cannot swallow protected data" + ); + let vm = cache.child_named("guest.utm").unwrap(); + assert_eq!(vm.category, Category::VirtualMachine); + assert_eq!(vm.reclaim, None); + assert_eq!(vm.child_named("node_modules").unwrap().reclaim, None); + assert_eq!(vm.child_named("cache").unwrap().reclaim, None); + let mut narrow = Tree::from(vm.to_draft()); + classify_at( + &mut narrow, + Path::new("/home/guest.utm/deep/inside"), + PathStyle::Posix, + ); + assert_eq!(narrow.root().category, Category::VirtualMachine); + assert_eq!(narrow.root().child_named("cache").unwrap().reclaim, None); + } + + #[test] + fn git_metadata_cannot_inherit_a_cleanup_suggestion_even_without_subdirectories() + { + let mut tree = Tree::from(dir( + "home", + vec![dir( + ".cache", + vec![ + dir(".git", vec![file("HEAD"), file("index")]), + file("cache-data"), + ], + )], + )); + classify_at(&mut tree, Path::new("/home"), PathStyle::Posix); + let cache = tree.root().child_named(".cache").unwrap(); + assert_eq!(cache.reclaim, None); + let git = cache.child_named(".git").unwrap(); + assert_eq!(git.category, Category::Git); + assert_eq!(git.reclaim, None); + assert_eq!(git.child_named("HEAD").unwrap().reclaim, None); + assert!(cache.child_named("cache-data").unwrap().reclaim.is_some()); + let mut narrow = Tree::from(git.to_draft()); + classify_at(&mut narrow, Path::new("/home/.git"), PathStyle::Posix); + assert_eq!(narrow.root().category, Category::Git); + assert_eq!(narrow.root().child_named("index").unwrap().reclaim, None); + let mut bare = Tree::from(dir( + "cache", + vec![ + file("HEAD"), + dir("refs", vec![]), + dir("objects", vec![file("pack")]), + ], + )); + classify_at( + &mut bare, + Path::new("/home/.cache/pip/cache"), + PathStyle::Posix, + ); + assert_eq!(bare.root().category, Category::Git); + assert_eq!(bare.root().child_named("HEAD").unwrap().reclaim, None); + let mut service = + Tree::from(dir(".Spotlight-V100", vec![file("index")])); + classify_at( + &mut service, + Path::new("/home/.cache/pip/.Spotlight-V100"), + PathStyle::Posix, + ); + assert_eq!(service.root().category, Category::Spotlight); + assert_eq!(service.root().child_named("index").unwrap().reclaim, None); + } + + #[test] + fn narrow_git_scans_keep_enclosing_ownership_over_cache_names() { + use crate::query::Filter; + + for path in [ + "/repo/node_modules/pkg/.git/objects", + "/home/.cache/pip/pkg/.git/objects", + "/repo/node_modules/pkg/.git/a/b/c/d/e/f/objects", + ] { + let path = Path::new(path); + let mut tree = Tree::from(dir( + "objects", + vec![file("pack"), dir("node_modules", vec![file("index")])], + )); + classify_at(&mut tree, path, PathStyle::Posix); + let root = tree.root(); + for node in [root, root.child_named("node_modules").unwrap()] { + assert_eq!(node.category, Category::Git, "{path:?}"); + assert_eq!(node.reclaim, None, "{path:?}"); + } + let assessment = assess(path, PathStyle::Posix, root).unwrap(); + assert_eq!(assessment.kind, Artifact::GitRepo); + assert_eq!(assessment.disposition, Disposition::Detected); + let mut candidates = Vec::new(); + Filter { + reclaimable: true, + ..Filter::default() + } + .collect(path, root, &mut candidates); + assert!(candidates.is_empty(), "{path:?}: {candidates:?}"); + } + } + + #[test] + fn narrow_pnpm_scans_require_evidence_at_the_owning_store() { + use crate::query::Filter; + + for owner in [ + "/home/me/.pnpm-store", + "/home/me/pnpm/store", + "/repo/node_modules/pkg/.pnpm-store", + ] { + let owner = Path::new(owner); + for verified in [false, true] { + let mut children = vec![dir("local-work", vec![file("notes")])]; + if verified { + children + .push(dir("v10", vec![dir("files", vec![file("ab")])])); + } + let mut tree = Tree::from(dir( + owner.file_name().unwrap().to_str().unwrap(), + children, + )); + classify_at(&mut tree, owner, PathStyle::Posix); + let expected = verified.then_some(Reclaim::PackageStore); + assert_eq!(tree.root().reclaim, expected, "{owner:?}"); + assert_eq!( + tree.root().child_named("local-work").unwrap().reclaim, + expected, + "{owner:?}" + ); + } + // Even a descendant named `store` with a versioned layout cannot + // verify an owning store that lies outside the scanned tree. + for relative in ["local-work", "a/b/c/d/e/f/local-work", "store"] { + let path = PathStyle::Posix.join(owner, relative); + let mut tree = Tree::from(dir( + relative.rsplit('/').next().unwrap(), + vec![ + file("notes"), + dir("v10", vec![dir("files", vec![file("ab")])]), + ], + )); + classify_at(&mut tree, &path, PathStyle::Posix); + let root = tree.root(); + assert_eq!(root.reclaim, None, "{path:?}"); + let assessment = assess(&path, PathStyle::Posix, root).unwrap(); + assert_eq!(assessment.kind, Artifact::PackageCache); + assert_eq!(assessment.disposition, Disposition::Detected); + let mut candidates = Vec::new(); + Filter { + reclaimable: true, + ..Filter::default() + } + .collect(&path, root, &mut candidates); + assert!(candidates.is_empty(), "{path:?}: {candidates:?}"); + } + } + // Other recognized package caches do not require pnpm's layout. + let mut tree = Tree::from(dir("subtree", vec![file("cache-data")])); + classify_at( + &mut tree, + Path::new("/home/me/.cache/electron/subtree"), + PathStyle::Posix, + ); + assert_eq!(tree.root().reclaim, Some(Reclaim::PackageStore)); + } + + #[test] + fn tool_home_exclusions_survive_deep_paths_and_worktree_caches_stay_separate() + { + let output = || { + dir( + "target", + vec![dir("debug", vec![dir("deps", vec![file("lib.rlib")])])], + ) + }; + let mut plugin = output(); + for name in ["f", "e", "d", "c", "b", "a"] { + plugin = dir(name, vec![plugin]); + } + let mut tree = Tree::from(dir( + "project", + vec![ + dir(".yarn", vec![dir("plugins", vec![plugin])]), + dir(".worktrees", vec![dir("feature", vec![output()])]), + ], + )); + classify_at(&mut tree, Path::new("/project"), PathStyle::Posix); + let root = tree.root(); + let (_, plugin) = root + .descend(Path::new(".yarn/plugins/a/b/c/d/e/f/target/debug/deps")) + .unwrap(); + assert_eq!(plugin.reclaim, None); + let (_, cache) = root + .descend(Path::new(".worktrees/feature/target/debug/deps")) + .unwrap(); + assert_eq!(cache.reclaim, Some(Reclaim::BuildOutput)); + let detection = assess( + Path::new("/project/.worktrees/feature/target/debug/deps"), + PathStyle::Posix, + cache, + ) + .unwrap(); + assert_eq!(detection.kind, Artifact::RustTarget); + assert_eq!(detection.disposition, Disposition::Suggested); + assert_eq!(root.child_named(".worktrees").unwrap().reclaim, None); + } + + #[test] + fn finding_roots_has_bounded_work_per_node() { + let run = |count| { + let tree = Tree::from(dir( + "projects", + (0..count) + .map(|i| { + dir( + &format!("p{i}"), + vec![dir( + "target", + vec![dir( + "debug", + vec![dir("deps", vec![file("lib.rlib")])], + )], + )], + ) + }) + .collect(), + )); + WORK.set(0); + let roots = + Roots::find(&tree, Path::new("/projects"), PathStyle::Posix); + assert_eq!(roots.0.len(), count); + WORK.get() + }; + let small = run(100); + let large = run(800); + assert!(large <= small * 16, "{small} -> {large}"); + assert!(large <= 800 * 100, "{large}"); + } +} diff --git a/crates/disktree-core/src/artifact/classification.json b/crates/disktree-core/src/artifact/classification.json new file mode 100644 index 00000000..261c0a3d --- /dev/null +++ b/crates/disktree-core/src/artifact/classification.json @@ -0,0 +1,1752 @@ +[ + { + "path": "/mono/target", + "root": null, + "kind": null + }, + { + "path": "/mono/target/a.txt", + "root": null, + "kind": null + }, + { + "path": "/mono/target/classes/Foo.class", + "root": null, + "kind": null + }, + { + "path": "/mono/target/test-classes/Foo.class", + "root": null, + "kind": null + }, + { + "path": "/mono/target/doc/index.html", + "root": null, + "kind": null + }, + { + "path": "/mono/target/debug/notes.txt", + "root": null, + "kind": null + }, + { + "path": "/mono/target/release/app", + "root": null, + "kind": null + }, + { + "path": "/mono/target/incremental/notes", + "root": null, + "kind": null + }, + { + "path": "/mono/build/Foo.class", + "root": null, + "kind": null + }, + { + "path": "/mono/dist/app.jar", + "root": null, + "kind": null + }, + { + "path": "/mono/out/native.o", + "root": null, + "kind": null + }, + { + "path": "/mono/target/scala-source/main.scala", + "root": null, + "kind": null + }, + { + "path": "/mono/target/scala-3x/classes/Foo.class", + "root": null, + "kind": null + }, + { + "path": "/mono/target/scala-2/classes/Foo.class", + "root": null, + "kind": null + }, + { + "path": "/mono/target/scala-2.13backup/Foo", + "root": null, + "kind": null + }, + { + "path": "/mono/target/scala-3./Foo", + "root": null, + "kind": null + }, + { + "path": "/mono/target/not-a-triple/debug/notes", + "root": null, + "kind": null + }, + { + "path": "/mono/target/debug/deps-backup/a", + "root": null, + "kind": null + }, + { + "path": "/mono/targeted/debug/deps/a", + "root": null, + "kind": null + }, + { + "path": "/mono/target/scala-2.13/debug/deps/a", + "root": "/mono/target/scala-2.13", + "kind": "jvm" + }, + { + "path": "/mono/src/jvm/public-api/target/scala-2.13/classes/Foo.class", + "root": "/mono/src/jvm/public-api/target/scala-2.13", + "kind": "jvm" + }, + { + "path": "/mono/project/target/scala-2.12/sbt-1.0/classes/Build.class", + "root": "/mono/project/target/scala-2.12", + "kind": "jvm" + }, + { + "path": "/mono/target/scala-3.3.1/test-classes/Foo.class", + "root": "/mono/target/scala-3.3.1", + "kind": "jvm" + }, + { + "path": "/mono/target/scala-3/classes/Foo.class", + "root": "/mono/target/scala-3", + "kind": "jvm" + }, + { + "path": "/mono/target/maven-status/compiler/x", + "root": "/mono/target/maven-status", + "kind": "jvm" + }, + { + "path": "/mono/target/maven-archiver/pom.properties", + "root": "/mono/target/maven-archiver", + "kind": "jvm" + }, + { + "path": "/mono/target/debug/deps/libfoo.rlib", + "root": "/mono/target/debug/deps", + "kind": "rust-target" + }, + { + "path": "/mono/target/release/.fingerprint/foo/x", + "root": "/mono/target/release/.fingerprint", + "kind": "rust-target" + }, + { + "path": "/mono/target/debug/incremental/foo/x", + "root": "/mono/target/debug/incremental", + "kind": "rust-target" + }, + { + "path": "/mono/target/aarch64-apple-darwin/release/deps/libfoo.rlib", + "root": "/mono/target/aarch64-apple-darwin/release/deps", + "kind": "rust-target" + }, + { + "path": "/mono/target/x86_64-unknown-linux-gnu/debug/incremental/foo/x", + "root": "/mono/target/x86_64-unknown-linux-gnu/debug/incremental", + "kind": "rust-target" + }, + { + "path": "/mono/target/node_modules/x/index.js", + "root": "/mono/target/node_modules", + "kind": "node-modules" + }, + { + "path": "/mono/build/.next/cache/x", + "root": "/mono/build/.next", + "kind": "js-build" + }, + { + "path": "/mono/node_modules/x/target/scala-3/classes/Foo.class", + "root": "/mono/node_modules", + "kind": "node-modules" + }, + { + "path": "/mono/target/a-b--/debug/deps/a", + "root": null, + "kind": null + }, + { + "path": "/mono/target/-b-c/debug/deps/a", + "root": null, + "kind": null + }, + { + "path": "/mono/target/a--c/debug/deps/a", + "root": null, + "kind": null + }, + { + "path": "/mono/target/a-b-/debug/deps/a", + "root": null, + "kind": null + }, + { + "path": "/mono/target/a-b-c.txt/debug/deps/a", + "root": null, + "kind": null + }, + { + "path": "/mono/target/scala-2.13-backup/debug/deps/a", + "root": null, + "kind": null + }, + { + "path": "/mono/.venv/lib/python3.12/site-packages/pkg/a.py", + "root": "/mono/.venv/lib/python3.12/site-packages", + "kind": "python" + }, + { + "path": "/mono/venv/Lib/site-packages/pkg/a.py", + "root": "/mono/venv/Lib/site-packages", + "kind": "python" + }, + { + "path": "/mono/.venv/lib/python3.13t/site-packages/pkg/a.py", + "root": "/mono/.venv/lib/python3.13t/site-packages", + "kind": "python" + }, + { + "path": "/mono/.tox/py312/lib/python3.12/site-packages/pkg/a.py", + "root": "/mono/.tox/py312/lib/python3.12/site-packages", + "kind": "python" + }, + { + "path": "/mono/.tox/py312/Lib/site-packages/pkg/a.py", + "root": "/mono/.tox/py312/Lib/site-packages", + "kind": "python" + }, + { + "path": "/mono/__pycache__/data", + "root": "/mono/__pycache__", + "kind": "python" + }, + { + "path": "/mono/.mypy_cache/data", + "root": "/mono/.mypy_cache", + "kind": "python" + }, + { + "path": "/mono/.pytest_cache/data", + "root": "/mono/.pytest_cache", + "kind": "python" + }, + { + "path": "/mono/.ruff_cache/data", + "root": "/mono/.ruff_cache", + "kind": "python" + }, + { + "path": "/mono/.yarn/cache/pkg.zip", + "root": "/mono/.yarn/cache", + "kind": "package-cache" + }, + { + "path": "/mono/.yarn/unplugged/pkg/index.js", + "root": "/mono/.yarn/unplugged", + "kind": "package-cache" + }, + { + "path": "/mono/.bun/install/cache/pkg/index.js", + "root": "/mono/.bun/install/cache", + "kind": "package-cache" + }, + { + "path": "/mono/.pnpm-store/v3/files/a", + "root": "/mono/.pnpm-store", + "kind": "package-cache" + }, + { + "path": "/mono/pnpm/store/v10/files/a", + "root": "/mono/pnpm/store", + "kind": "package-cache" + }, + { + "path": "/mono/.cache/yarn/v6/pkg/a", + "root": "/mono/.cache/yarn", + "kind": "package-cache" + }, + { + "path": "/mono/.cache/pnpm/v10/a", + "root": "/mono/.cache/pnpm", + "kind": "package-cache" + }, + { + "path": "/mono/.gradle/caches/modules-2/files-2.1/a.jar", + "root": "/mono/.gradle/caches", + "kind": "jvm" + }, + { + "path": "/mono/.gradle/wrapper/dists/gradle-8.10/bin/a", + "root": "/mono/.gradle/wrapper/dists", + "kind": "jvm" + }, + { + "path": "/mono/.m2/repository/org/example/1/a.jar", + "root": "/mono/.m2/repository", + "kind": "jvm" + }, + { + "path": "/mono/.nuget/packages/newtonsoft.json/13/lib/a.dll", + "root": "/mono/.nuget/packages", + "kind": "dotnet" + }, + { + "path": "/mono/obj/Debug/net8.0/App.dll", + "root": "/mono/obj/Debug/net8.0", + "kind": "dotnet" + }, + { + "path": "/mono/obj/Release/net48/App.dll", + "root": "/mono/obj/Release/net48", + "kind": "dotnet" + }, + { + "path": "/mono/obj/Debug/netstandard2.0/a.dll", + "root": "/mono/obj/Debug/netstandard2.0", + "kind": "dotnet" + }, + { + "path": "/mono/obj/Debug/netcoreapp3.1/a.dll", + "root": "/mono/obj/Debug/netcoreapp3.1", + "kind": "dotnet" + }, + { + "path": "/mono/obj/Release/net8.0-windows10.0.19041.0/a.dll", + "root": "/mono/obj/Release/net8.0-windows10.0.19041.0", + "kind": "dotnet" + }, + { + "path": "/mono/.cache/ccache/a/b", + "root": "/mono/.cache/ccache", + "kind": "compiler-cache" + }, + { + "path": "/mono/.cache/sccache/a/b", + "root": "/mono/.cache/sccache", + "kind": "compiler-cache" + }, + { + "path": "/mono/Library/Caches/ccache/a/b", + "root": "/mono/Library/Caches/ccache", + "kind": "compiler-cache" + }, + { + "path": "/mono/Library/Caches/sccache/a/b", + "root": "/mono/Library/Caches/sccache", + "kind": "compiler-cache" + }, + { + "path": "/mono/AppData/Local/ccache/a/b", + "root": "/mono/AppData/Local/ccache", + "kind": "compiler-cache" + }, + { + "path": "/mono/AppData/Local/sccache/a/b", + "root": "/mono/AppData/Local/sccache", + "kind": "compiler-cache" + }, + { + "path": "/mono/cmake-build-debug/CMakeFiles/app.dir/a.o", + "root": "/mono/cmake-build-debug/CMakeFiles", + "kind": "cmake-build" + }, + { + "path": "/mono/custom-build/CMakeFiles/app.dir/a.o", + "root": "/mono/custom-build/CMakeFiles", + "kind": "cmake-build" + }, + { + "path": "/mono/go/pkg/mod/github.com/org/pkg@v1.2.3/a.go", + "root": "/mono/go/pkg/mod/github.com/org/pkg@v1.2.3", + "kind": "go-module" + }, + { + "path": "/mono/go/pkg/mod/cache/download/github.com/org/pkg/@v/v1.2.3.zip", + "root": "/mono/go/pkg/mod/cache/download", + "kind": "go-module" + }, + { + "path": "/mono/.cargo/registry/src/pkg/a.rs", + "root": "/mono/.cargo/registry", + "kind": "cargo-registry" + }, + { + "path": "/mono/.next/cache/a", + "root": "/mono/.next", + "kind": "js-build" + }, + { + "path": "/mono/.nuxt/cache/a", + "root": "/mono/.nuxt", + "kind": "js-build" + }, + { + "path": "/mono/.turbo/cache/a", + "root": "/mono/.turbo", + "kind": "js-build" + }, + { + "path": "/mono/.parcel-cache/cache/a", + "root": "/mono/.parcel-cache", + "kind": "js-build" + }, + { + "path": "/mono/.svelte-kit/cache/a", + "root": "/mono/.svelte-kit", + "kind": "js-build" + }, + { + "path": "/mono/.vercel/output/a", + "root": "/mono/.vercel/output", + "kind": "js-build" + }, + { + "path": "/mono/.vercel/cache/a", + "root": "/mono/.vercel/cache", + "kind": "js-build" + }, + { + "path": "/mono/.netlify/cache/a", + "root": "/mono/.netlify/cache", + "kind": "js-build" + }, + { + "path": "/mono/.output/server/a", + "root": "/mono/.output/server", + "kind": "js-build" + }, + { + "path": "/mono/.output/public/a", + "root": "/mono/.output/public", + "kind": "js-build" + }, + { + "path": "/mono/.terraform/providers/registry/a", + "root": "/mono/.terraform/providers", + "kind": "terraform" + }, + { + "path": "/mono/.terraform/plugins/registry/a", + "root": "/mono/.terraform/plugins", + "kind": "terraform" + }, + { + "path": "/mono/.terraform.d/plugin-cache/registry/a", + "root": "/mono/.terraform.d/plugin-cache", + "kind": "terraform" + }, + { + "path": "/mono/.worktrees/feature/src/a", + "root": "/mono/.worktrees/feature", + "kind": "worktree" + }, + { + "path": "/mono/DiagOutputDir/a.etl", + "root": "/mono/DiagOutputDir", + "kind": "diag-logs" + }, + { + "path": "/mono/RdClientAutoTrace/a.etl", + "root": "/mono/RdClientAutoTrace", + "kind": "diag-logs" + }, + { + "path": "/mono/venv", + "root": null, + "kind": null + }, + { + "path": "/mono/venv/notes.txt", + "root": null, + "kind": null + }, + { + "path": "/mono/.venv/src/app.py", + "root": null, + "kind": null + }, + { + "path": "/mono/.venv/bin/python", + "root": null, + "kind": null + }, + { + "path": "/mono/.venv/lib/python3x12/site-packages/a", + "root": null, + "kind": null + }, + { + "path": "/mono/.venv/lib/python3.12-backup/site-packages/a", + "root": null, + "kind": null + }, + { + "path": "/mono/.venv/lib/python3.12/site-packages-old/a", + "root": null, + "kind": null + }, + { + "path": "/mono/.tox/notes.txt", + "root": null, + "kind": null + }, + { + "path": "/mono/.tox/py312/src/app.py", + "root": null, + "kind": null + }, + { + "path": "/mono/.tox/py312/lib/python3/site-packages/a", + "root": null, + "kind": null + }, + { + "path": "/mono/.yarn", + "root": null, + "kind": null + }, + { + "path": "/mono/.yarn/patches/pkg.patch", + "root": null, + "kind": null + }, + { + "path": "/mono/.yarn/releases/yarn.cjs", + "root": null, + "kind": null + }, + { + "path": "/mono/.yarn/plugins/plugin.cjs", + "root": null, + "kind": null + }, + { + "path": "/mono/.yarn/sdks/typescript/lib/a.js", + "root": null, + "kind": null + }, + { + "path": "/mono/.yarn/versions/pkg.yml", + "root": null, + "kind": null + }, + { + "path": "/mono/.yarn/cache-old/a", + "root": null, + "kind": null + }, + { + "path": "/mono/.yarn/patches/node_modules/a/index.js", + "root": null, + "kind": null + }, + { + "path": "/mono/.bun", + "root": null, + "kind": null + }, + { + "path": "/mono/.bun/bin/bun", + "root": null, + "kind": null + }, + { + "path": "/mono/.bun/install/global/node_modules/a/index.js", + "root": null, + "kind": null + }, + { + "path": "/mono/.bun/install/cache-old/a", + "root": null, + "kind": null + }, + { + "path": "/mono/.gradle", + "root": null, + "kind": null + }, + { + "path": "/mono/.gradle/gradle.properties", + "root": null, + "kind": null + }, + { + "path": "/mono/.gradle/init.d/init.gradle", + "root": null, + "kind": null + }, + { + "path": "/mono/.gradle/wrapper/gradle-wrapper.properties", + "root": null, + "kind": null + }, + { + "path": "/mono/.gradle/caches-old/a", + "root": null, + "kind": null + }, + { + "path": "/mono/.gradle/init.d/node_modules/a.js", + "root": null, + "kind": null + }, + { + "path": "/mono/.m2", + "root": null, + "kind": null + }, + { + "path": "/mono/.m2/settings.xml", + "root": null, + "kind": null + }, + { + "path": "/mono/.m2/toolchains.xml", + "root": null, + "kind": null + }, + { + "path": "/mono/.m2/repository-old/a", + "root": null, + "kind": null + }, + { + "path": "/mono/.nuget", + "root": null, + "kind": null + }, + { + "path": "/mono/.nuget/NuGet.Config", + "root": null, + "kind": null + }, + { + "path": "/mono/.nuget/plugins/plugin.exe", + "root": null, + "kind": null + }, + { + "path": "/mono/.nuget/packages-old/a", + "root": null, + "kind": null + }, + { + "path": "/mono/obj", + "root": null, + "kind": null + }, + { + "path": "/mono/obj/model.obj", + "root": null, + "kind": null + }, + { + "path": "/mono/obj/Debug/App.dll", + "root": null, + "kind": null + }, + { + "path": "/mono/obj/Debug/network/App.dll", + "root": null, + "kind": null + }, + { + "path": "/mono/obj/Debug/net8x0/a", + "root": null, + "kind": null + }, + { + "path": "/mono/obj/Debug/net8.0-backup2-x/a", + "root": null, + "kind": null + }, + { + "path": "/mono/obj/Debug/netstandard20/a", + "root": null, + "kind": null + }, + { + "path": "/mono/bin/Release/net8.0/App.dll", + "root": null, + "kind": null + }, + { + "path": "/mono/cmake-build-debug", + "root": null, + "kind": null + }, + { + "path": "/mono/cmake-build-release/notes.txt", + "root": null, + "kind": null + }, + { + "path": "/mono/custom-build/CMakeLists.txt", + "root": null, + "kind": null + }, + { + "path": "/mono/CMakeFiles-old/a.o", + "root": null, + "kind": null + }, + { + "path": "/mono/ccache", + "root": null, + "kind": null + }, + { + "path": "/mono/ccache/src/a.c", + "root": null, + "kind": null + }, + { + "path": "/mono/sccache/src/a.rs", + "root": null, + "kind": null + }, + { + "path": "/mono/Library/Caches/ccache-old/a", + "root": null, + "kind": null + }, + { + "path": "/mono/AppData/Roaming/ccache/notes", + "root": null, + "kind": null + }, + { + "path": "/mono/go/pkg/mod-old/a.go", + "root": null, + "kind": null + }, + { + "path": "/mono/go/pkg/modules/a.go", + "root": null, + "kind": null + }, + { + "path": "/mono/go/mod/pkg/a.go", + "root": null, + "kind": null + }, + { + "path": "/mono/.cargo/bin/cargo", + "root": null, + "kind": null + }, + { + "path": "/mono/.cargo/credentials.toml", + "root": null, + "kind": null + }, + { + "path": "/mono/.vercel/project.json", + "root": null, + "kind": null + }, + { + "path": "/mono/.vercel/README.txt", + "root": null, + "kind": null + }, + { + "path": "/mono/.netlify/state.json", + "root": null, + "kind": null + }, + { + "path": "/mono/.netlify/functions-source/a.js", + "root": null, + "kind": null + }, + { + "path": "/mono/.output/notes.txt", + "root": null, + "kind": null + }, + { + "path": "/mono/.terraform/terraform.tfstate", + "root": null, + "kind": null + }, + { + "path": "/mono/.terraform/environment", + "root": null, + "kind": null + }, + { + "path": "/mono/.terraform/modules/modules.json", + "root": null, + "kind": null + }, + { + "path": "/mono/.terraform.d/plugins/vendor/plugin", + "root": null, + "kind": null + }, + { + "path": "/mono/node_modules-old/pkg/a", + "root": null, + "kind": null + }, + { + "path": "/mono/__pycache__-old/a.py", + "root": null, + "kind": null + }, + { + "path": "/mono/.pytest_cache-old/data", + "root": null, + "kind": null + }, + { + "path": "/mono/.pnpm-store-old/data", + "root": null, + "kind": null + }, + { + "path": "/mono/venv/.m2/settings.xml", + "root": null, + "kind": null + }, + { + "path": "/mono/target/venv/notes.txt", + "root": null, + "kind": null + }, + { + "path": "/mono/node_modules/pkg/.gradle/gradle.properties", + "root": "/mono/node_modules", + "kind": "node-modules" + }, + { + "path": "/mono/node_modules/pkg/.venv/lib/python3.12/site-packages/a", + "root": "/mono/node_modules", + "kind": "node-modules" + }, + { + "path": "/mono/node_modules/pkg/obj/Debug/net8.0/a.dll", + "root": "/mono/node_modules", + "kind": "node-modules" + }, + { + "path": "/mono/node_modules/pkg/CMakeFiles/a.o", + "root": "/mono/node_modules", + "kind": "node-modules" + }, + { + "path": "/mono/go/pkg/mod/example.com/team/module/v2@v2.0.0/file.go", + "root": "/mono/go/pkg/mod/example.com/team/module/v2@v2.0.0", + "kind": "go-module" + }, + { + "path": "/mono/go/pkg/mod/golang.org/x/sys@v0.0.0-20250320123456-abcdef123456/file.go", + "root": "/mono/go/pkg/mod/golang.org/x/sys@v0.0.0-20250320123456-abcdef123456", + "kind": "go-module" + }, + { + "path": "/mono/go/pkg/mod/gopkg.in/yaml.v3@v3.0.1/file.go", + "root": "/mono/go/pkg/mod/gopkg.in/yaml.v3@v3.0.1", + "kind": "go-module" + }, + { + "path": "/mono/go/pkg/mod/github.com/!azure/sdk@v1.2.3+incompatible/file.go", + "root": "/mono/go/pkg/mod/github.com/!azure/sdk@v1.2.3+incompatible", + "kind": "go-module" + }, + { + "path": "/mono/pkg/mod", + "root": null, + "kind": null + }, + { + "path": "/mono/pkg/mod/module.go", + "root": null, + "kind": null + }, + { + "path": "/mono/go/pkg/mod/example.com/org/repo@v1.2/file.go", + "root": null, + "kind": null + }, + { + "path": "/mono/go/pkg/mod/cache/notes.txt", + "root": null, + "kind": null + }, + { + "path": "/mono/go/pkg/mod/example.com/org/repo@v1.2.3-backup_/file.go", + "root": null, + "kind": null + }, + { + "path": "/mono/go/pkg/mod/example.com/org/repo@v1.2.3+/file.go", + "root": null, + "kind": null + }, + { + "path": "/mono/.wor\u212atrees/feature/a", + "root": null, + "kind": null + }, + { + "path": "/mono/CMa\u212aeFiles/a.o", + "root": null, + "kind": null + }, + { + "path": "/mono/go/pkg/mod/example.com/pac\u212aage@v1.2.3/a.go", + "root": null, + "kind": null + }, + { + "path": "/mono/Library/Caches/Mozilla.sccache/a/b", + "root": "/mono/Library/Caches/Mozilla.sccache", + "kind": "compiler-cache" + }, + { + "path": "/mono/AppData/Local/Mozilla/sccache/a/b", + "root": "/mono/AppData/Local/Mozilla/sccache", + "kind": "compiler-cache" + }, + { + "path": "/mono/Mozilla.sccache/src/a.rs", + "root": null, + "kind": null + }, + { + "path": "/mono/Mozilla/sccache/src/a.rs", + "root": null, + "kind": null + }, + { + "path": "/mono/AppData/Roaming/Mozilla/sccache/a", + "root": null, + "kind": null + }, + { + "path": "/mono/Library/Application Support/Mozilla.sccache/config", + "root": null, + "kind": null + }, + { + "path": "/mono/android/.gradle/8.10/fileHashes/data.bin", + "root": "/mono/android/.gradle/8.10", + "kind": "jvm" + }, + { + "path": "/mono/android/.gradle/9.0.0/checksums/data.bin", + "root": "/mono/android/.gradle/9.0.0", + "kind": "jvm" + }, + { + "path": "/mono/android/.gradle/8.10-notes/a.txt", + "root": null, + "kind": null + }, + { + "path": "/mono/obj/Debug/net8.0-backup/notes.txt", + "root": null, + "kind": null + }, + { + "path": "/mono/obj/Debug/net8.0-windows.10/notes.txt", + "root": null, + "kind": null + }, + { + "path": "/mono/obj/Debug/net8.0-android34.0/a.dll", + "root": "/mono/obj/Debug/net8.0-android34.0", + "kind": "dotnet" + }, + { + "path": "/mono/obj/Debug/net9.0-ios18.0/a.dll", + "root": "/mono/obj/Debug/net9.0-ios18.0", + "kind": "dotnet" + }, + { + "path": "/home/dev/.yarn/berry/cache/data.bin", + "root": "/home/dev/.yarn/berry/cache", + "kind": "package-cache" + }, + { + "path": "/home/dev/.yarn/berry/metadata/state.json", + "root": null, + "kind": null + }, + { + "path": "/mono/target/debug/build/webrtc-sys-53d1d4d2126137c6/out/lib.a", + "root": "/mono/target/debug/build/webrtc-sys-53d1d4d2126137c6", + "kind": "rust-target" + }, + { + "path": "/mono/target/aarch64-apple-darwin/release/build/crate_2-0123456789abcdef/data.bin", + "root": "/mono/target/aarch64-apple-darwin/release/build/crate_2-0123456789abcdef", + "kind": "rust-target" + }, + { + "path": "/mono/target/debug/build", + "root": null, + "kind": null + }, + { + "path": "/mono/target/debug/build/source/main.rs", + "root": null, + "kind": null + }, + { + "path": "/mono/target/debug/build/crate-0123456789abcdeg/out/file", + "root": null, + "kind": null + }, + { + "path": "/mono/target/debug/build/crate-12345678/out/file", + "root": null, + "kind": null + }, + { + "path": "/mono/target/notes/build/crate-0123456789abcdef/out/file", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.cache/pip/data.bin", + "root": "/home/dev/.cache/pip", + "kind": "python" + }, + { + "path": "/Users/dev/Library/Caches/pip/data.bin", + "root": "/Users/dev/Library/Caches/pip", + "kind": "python" + }, + { + "path": "/projects/pip/src/index.ts", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Application Support/pip/settings.json", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.cache/uv/data.bin", + "root": "/home/dev/.cache/uv", + "kind": "python" + }, + { + "path": "/Users/dev/Library/Caches/uv/data.bin", + "root": "/Users/dev/Library/Caches/uv", + "kind": "python" + }, + { + "path": "/projects/uv/src/index.ts", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Application Support/uv/settings.json", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.cache/go-build/data.bin", + "root": "/home/dev/.cache/go-build", + "kind": "go-module" + }, + { + "path": "/Users/dev/Library/Caches/go-build/data.bin", + "root": "/Users/dev/Library/Caches/go-build", + "kind": "go-module" + }, + { + "path": "/projects/go-build/src/index.ts", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Application Support/go-build/settings.json", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.cache/Coursier/data.bin", + "root": "/home/dev/.cache/Coursier", + "kind": "jvm" + }, + { + "path": "/Users/dev/Library/Caches/Coursier/data.bin", + "root": "/Users/dev/Library/Caches/Coursier", + "kind": "jvm" + }, + { + "path": "/projects/Coursier/src/index.ts", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Application Support/Coursier/settings.json", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.cache/vscode-cpptools/data.bin", + "root": "/home/dev/.cache/vscode-cpptools", + "kind": "compiler-cache" + }, + { + "path": "/Users/dev/Library/Caches/vscode-cpptools/data.bin", + "root": "/Users/dev/Library/Caches/vscode-cpptools", + "kind": "compiler-cache" + }, + { + "path": "/projects/vscode-cpptools/src/index.ts", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Application Support/vscode-cpptools/settings.json", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.cache/electron/data.bin", + "root": "/home/dev/.cache/electron", + "kind": "package-cache" + }, + { + "path": "/Users/dev/Library/Caches/electron/data.bin", + "root": "/Users/dev/Library/Caches/electron", + "kind": "package-cache" + }, + { + "path": "/projects/electron/src/index.ts", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Application Support/electron/settings.json", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.cache/electron-builder/data.bin", + "root": "/home/dev/.cache/electron-builder", + "kind": "package-cache" + }, + { + "path": "/Users/dev/Library/Caches/electron-builder/data.bin", + "root": "/Users/dev/Library/Caches/electron-builder", + "kind": "package-cache" + }, + { + "path": "/projects/electron-builder/src/index.ts", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Application Support/electron-builder/settings.json", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.cache/ms-playwright/data.bin", + "root": "/home/dev/.cache/ms-playwright", + "kind": "package-cache" + }, + { + "path": "/Users/dev/Library/Caches/ms-playwright/data.bin", + "root": "/Users/dev/Library/Caches/ms-playwright", + "kind": "package-cache" + }, + { + "path": "/projects/ms-playwright/src/index.ts", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Application Support/ms-playwright/settings.json", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.cache/Cypress/data.bin", + "root": "/home/dev/.cache/Cypress", + "kind": "package-cache" + }, + { + "path": "/Users/dev/Library/Caches/Cypress/data.bin", + "root": "/Users/dev/Library/Caches/Cypress", + "kind": "package-cache" + }, + { + "path": "/projects/Cypress/src/index.ts", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Application Support/Cypress/settings.json", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.cache/Homebrew/data.bin", + "root": "/home/dev/.cache/Homebrew", + "kind": "package-cache" + }, + { + "path": "/Users/dev/Library/Caches/Homebrew/data.bin", + "root": "/Users/dev/Library/Caches/Homebrew", + "kind": "package-cache" + }, + { + "path": "/projects/Homebrew/src/index.ts", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Application Support/Homebrew/settings.json", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.cache/puppeteer/data.bin", + "root": "/home/dev/.cache/puppeteer", + "kind": "package-cache" + }, + { + "path": "/Users/dev/Library/Caches/puppeteer/data.bin", + "root": "/Users/dev/Library/Caches/puppeteer", + "kind": "package-cache" + }, + { + "path": "/projects/puppeteer/src/index.ts", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Application Support/puppeteer/settings.json", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.cache/node-gyp/data.bin", + "root": "/home/dev/.cache/node-gyp", + "kind": "package-cache" + }, + { + "path": "/Users/dev/Library/Caches/node-gyp/data.bin", + "root": "/Users/dev/Library/Caches/node-gyp", + "kind": "package-cache" + }, + { + "path": "/projects/node-gyp/src/index.ts", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Application Support/node-gyp/settings.json", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.cache/org.swift.swiftpm/data.bin", + "root": "/home/dev/.cache/org.swift.swiftpm", + "kind": "package-cache" + }, + { + "path": "/Users/dev/Library/Caches/org.swift.swiftpm/data.bin", + "root": "/Users/dev/Library/Caches/org.swift.swiftpm", + "kind": "package-cache" + }, + { + "path": "/projects/org.swift.swiftpm/src/index.ts", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Application Support/org.swift.swiftpm/settings.json", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.npm/_cacache/data.bin", + "root": "/home/dev/.npm/_cacache", + "kind": "package-cache" + }, + { + "path": "/home/dev/.npm/config.json", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.npm/_npx/custom/src/main.ts", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.local/share/NuGet/http-cache/data.bin", + "root": "/home/dev/.local/share/NuGet/http-cache", + "kind": "dotnet" + }, + { + "path": "/home/dev/.local/share/NuGet/v3-cache/data.bin", + "root": "/home/dev/.local/share/NuGet/v3-cache", + "kind": "dotnet" + }, + { + "path": "/home/dev/.local/share/NuGet/plugins-cache/data.bin", + "root": "/home/dev/.local/share/NuGet/plugins-cache", + "kind": "dotnet" + }, + { + "path": "/home/dev/.local/share/NuGet/NuGet.Config", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/AppData/Local/NuGet/http-cache/data.bin", + "root": "/Users/dev/AppData/Local/NuGet/http-cache", + "kind": "dotnet" + }, + { + "path": "/Users/dev/AppData/Local/NuGet/v3-cache/data.bin", + "root": "/Users/dev/AppData/Local/NuGet/v3-cache", + "kind": "dotnet" + }, + { + "path": "/Users/dev/AppData/Local/NuGet/plugins-cache/data.bin", + "root": "/Users/dev/AppData/Local/NuGet/plugins-cache", + "kind": "dotnet" + }, + { + "path": "/Users/dev/AppData/Local/NuGet/NuGet.Config", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/.tart/vms/work/disk.img", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Containers/com.docker.docker/Data/vms/0/Docker.raw", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/.codex/worktrees/a/project/src/main.ts", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/project/.git/objects/pack/a.pack", + "root": "/Users/dev/project/.git", + "kind": "git-repo" + }, + { + "path": "/Users/dev/Pictures/Photos Library.photoslibrary/database/Photos.sqlite", + "root": null, + "kind": null + }, + { + "path": "/Applications/Editor.app/Contents/Resources/app/dist/main.js", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/.vscode/extensions/tool/dist/main.js", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Caches/unknown-tool/precious.txt", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Caches/pip-backup/source.py", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.cache/__proto__/source", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.cache/constructor/source", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.npm/_npx/abc/node_modules/pkg/index.js", + "root": "/home/dev/.npm/_npx/abc/node_modules", + "kind": "node-modules" + }, + { + "path": "/home/dev/.gem/specs/item.bin", + "root": "/home/dev/.gem/specs", + "kind": "package-cache" + }, + { + "path": "/home/dev/.gem/ruby/3.4.0/cache/item.bin", + "root": "/home/dev/.gem/ruby/3.4.0/cache", + "kind": "package-cache" + }, + { + "path": "/project/vendor/bundle/ruby/3.4.0/cache/item.bin", + "root": "/project/vendor/bundle/ruby/3.4.0/cache", + "kind": "package-cache" + }, + { + "path": "/home/dev/.cache/gem/specs/item.bin", + "root": "/home/dev/.cache/gem/specs", + "kind": "package-cache" + }, + { + "path": "/home/dev/.cache/gem/gems/item.bin", + "root": "/home/dev/.cache/gem/gems", + "kind": "package-cache" + }, + { + "path": "/home/dev/.cache/composer/item.bin", + "root": "/home/dev/.cache/composer", + "kind": "package-cache" + }, + { + "path": "/Users/dev/Library/Caches/composer/item.bin", + "root": "/Users/dev/Library/Caches/composer", + "kind": "package-cache" + }, + { + "path": "/home/dev/.composer/cache/item.bin", + "root": "/home/dev/.composer/cache", + "kind": "package-cache" + }, + { + "path": "/Users/dev/AppData/Local/Composer/files/item.bin", + "root": "/Users/dev/AppData/Local/Composer/files", + "kind": "package-cache" + }, + { + "path": "/Users/dev/AppData/Local/Composer/repo/item.bin", + "root": "/Users/dev/AppData/Local/Composer/repo", + "kind": "package-cache" + }, + { + "path": "/Users/dev/AppData/Local/Composer/vcs/item.bin", + "root": "/Users/dev/AppData/Local/Composer/vcs", + "kind": "package-cache" + }, + { + "path": "/home/dev/.pub-cache/hosted/item.bin", + "root": "/home/dev/.pub-cache/hosted", + "kind": "package-cache" + }, + { + "path": "/home/dev/.pub-cache/git/cache/item.bin", + "root": "/home/dev/.pub-cache/git/cache", + "kind": "package-cache" + }, + { + "path": "/Users/dev/AppData/Local/Pub/Cache/hosted/item.bin", + "root": "/Users/dev/AppData/Local/Pub/Cache/hosted", + "kind": "package-cache" + }, + { + "path": "/home/dev/.hex/packages/item.bin", + "root": "/home/dev/.hex/packages", + "kind": "package-cache" + }, + { + "path": "/project/.dart_tool/flutter_build/item.bin", + "root": "/project/.dart_tool/flutter_build", + "kind": "compiler-cache" + }, + { + "path": "/Users/dev/Library/Developer/Xcode/DerivedData/item.bin", + "root": "/Users/dev/Library/Developer/Xcode/DerivedData", + "kind": "compiler-cache" + }, + { + "path": "/project/.stack-work/dist/item.bin", + "root": "/project/.stack-work/dist", + "kind": "compiler-cache" + }, + { + "path": "/project/dist-newstyle/build/item.bin", + "root": "/project/dist-newstyle/build", + "kind": "compiler-cache" + }, + { + "path": "/project/dist-newstyle/cache/item.bin", + "root": "/project/dist-newstyle/cache", + "kind": "compiler-cache" + }, + { + "path": "/project/.zig-cache/item.bin", + "root": "/project/.zig-cache", + "kind": "compiler-cache" + }, + { + "path": "/home/dev/.cache/zig/item.bin", + "root": "/home/dev/.cache/zig", + "kind": "compiler-cache" + }, + { + "path": "/Users/dev/Library/Caches/zig/item.bin", + "root": "/Users/dev/Library/Caches/zig", + "kind": "compiler-cache" + }, + { + "path": "/project/_build/dev/lib/my_app/ebin/Elixir.MyApp.beam", + "root": "/project/_build/dev/lib/my_app/ebin", + "kind": "compiler-cache" + }, + { + "path": "/project/_build/test/lib/my_app/ebin/Elixir.MyApp.beam", + "root": "/project/_build/test/lib/my_app/ebin", + "kind": "compiler-cache" + }, + { + "path": "/project/_build/prod/lib/my_app/ebin/Elixir.MyApp.beam", + "root": "/project/_build/prod/lib/my_app/ebin", + "kind": "compiler-cache" + }, + { + "path": "/project/_build/shared/lib/my_app/ebin/Elixir.MyApp.beam", + "root": "/project/_build/shared/lib/my_app/ebin", + "kind": "compiler-cache" + }, + { + "path": "/project/vendor/cache/my-vendored-fork.rb", + "root": null, + "kind": null + }, + { + "path": "/project/vendor/bundle/ruby/3.4.0/gems/mygem/src.rb", + "root": null, + "kind": null + }, + { + "path": "/project/vendor/bundle/ruby/3.4/cache/file", + "root": null, + "kind": null + }, + { + "path": "/project/vendor/bundle/ruby/next/cache/file", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.gem/credentials", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.gem/ruby/3.4.0/bin/tool", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.cache/gem/config.yml", + "root": null, + "kind": null + }, + { + "path": "/project/vendor/composer/installed.json", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.composer/auth.json", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.composer/vendor/my/plugin.php", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/AppData/Local/Composer/auth.json", + "root": null, + "kind": null + }, + { + "path": "/project/composer/src/main.php", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.pub-cache/bin/tool", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.pub-cache/global_packages/pkg/pubspec.yaml", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.pub-cache/git/edited-checkout/lib/main.dart", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/AppData/Local/Pub/Cache/bin/tool", + "root": null, + "kind": null + }, + { + "path": "/project/.dart_tool/package_config.json", + "root": null, + "kind": null + }, + { + "path": "/project/flutter_build/main.dart", + "root": null, + "kind": null + }, + { + "path": "/project/build/flutter_assets/user-data", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Developer/Xcode/Archives/App.xcarchive/file", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Developer/Xcode/UserData/profile", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Developer/CoreSimulator/Devices/uuid/data", + "root": null, + "kind": null + }, + { + "path": "/project/DerivedData/source.swift", + "root": null, + "kind": null + }, + { + "path": "/project/.build/checkouts/edited/Sources/main.swift", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.hex/hex.config", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.mix/archives/tool", + "root": null, + "kind": null + }, + { + "path": "/project/deps/my_app/lib/main.ex", + "root": null, + "kind": null + }, + { + "path": "/project/_build/dev/lib/my_app/src/main.erl", + "root": null, + "kind": null + }, + { + "path": "/project/_build/dev/lib/my_app/priv/data", + "root": null, + "kind": null + }, + { + "path": "/project/_build/custom/lib/my_app/ebin/a.beam", + "root": null, + "kind": null + }, + { + "path": "/project/_build/dev/lib/9app/ebin/a.beam", + "root": null, + "kind": null + }, + { + "path": "/project/_build/dev/lib/my-app/ebin/a.beam", + "root": null, + "kind": null + }, + { + "path": "/project/_build/dev/lib/my_app/ebin-backup/a.beam", + "root": null, + "kind": null + }, + { + "path": "/project/.stack-work/source/Main.hs", + "root": null, + "kind": null + }, + { + "path": "/project/dist-newstyle/src/Main.hs", + "root": null, + "kind": null + }, + { + "path": "/project/dist/build/Main.hs", + "root": null, + "kind": null + }, + { + "path": "/home/dev/.stack/config.yaml", + "root": null, + "kind": null + }, + { + "path": "/project/zig-out/bin/server", + "root": null, + "kind": null + }, + { + "path": "/project/zig-cache/source.zig", + "root": null, + "kind": null + }, + { + "path": "/project/.zig-cache-backup/source.zig", + "root": null, + "kind": null + }, + { + "path": "/project/zig/lib/std.zig", + "root": null, + "kind": null + }, + { + "path": "/project/vendor/bundle/ruby/3.4.0/cache-backup/a.gem", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Developer/Xcode/DerivedData-backup/source.swift", + "root": null, + "kind": null + }, + { + "path": "/Users/dev/Library/Developer/Xcode/DerivedDat\u212a/source.swift", + "root": null, + "kind": null + } +] diff --git a/crates/disktree-core/src/artifact/rules.rs b/crates/disktree-core/src/artifact/rules.rs new file mode 100644 index 00000000..5e5d8313 --- /dev/null +++ b/crates/disktree-core/src/artifact/rules.rs @@ -0,0 +1,561 @@ +//! Structural rules ported from `DiskHound`. See licenses/bundled.txt. + +use super::Artifact; + +pub(super) fn numeric_version( + value: &str, + min_parts: usize, + max_parts: usize, +) -> bool { + let mut count = 0; + for part in value.split('.') { + count += 1; + if part.is_empty() || !part.bytes().all(|b| b.is_ascii_digit()) { + return false; + } + } + (min_parts..=max_parts).contains(&count) +} + +fn dotnet_framework(value: &str) -> bool { + let (framework, platform) = value + .split_once('-') + .map_or((value, None), |(a, b)| (a, Some(b))); + let Some(version) = framework.strip_prefix("net") else { + return false; + }; + let valid = if let Some(version) = version + .strip_prefix("standard") + .or_else(|| version.strip_prefix("coreapp")) + { + numeric_version(version, 2, 2) + } else { + numeric_version(version, 1, 2) + }; + valid + && platform.is_none_or(|platform| { + let letters = + platform.bytes().take_while(u8::is_ascii_lowercase).count(); + matches!( + &platform[..letters], + "windows" + | "android" + | "ios" + | "macos" + | "maccatalyst" + | "tvos" + | "browser" + ) && (letters == platform.len() + || numeric_version(&platform[letters..], 1, usize::MAX)) + }) +} + +fn go_module_version(name: &str) -> bool { + let Some((module, version)) = name.split_once("@v") else { + return false; + }; + if module.is_empty() + || !module + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b".!_-".contains(&b)) + { + return false; + } + let suffix = version.find(['-', '+']); + let base = suffix.map_or(version, |i| &version[..i]); + numeric_version(base, 3, 3) + && suffix.is_none_or(|i| { + let suffix = &version[i + 1..]; + !suffix.is_empty() + && suffix + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b".+-".contains(&b)) + }) +} + +fn cache_tool_kind(tool: &str) -> Option { + match tool { + "pip" | "uv" => Some(Artifact::Python), + "go-build" => Some(Artifact::GoModule), + "zig" => Some(Artifact::CompilerCache), + "coursier" => Some(Artifact::Jvm), + "ccache" | "sccache" | "mozilla.sccache" | "vscode-cpptools" => { + Some(Artifact::CompilerCache) + } + "composer" | "yarn" | "pnpm" | "electron" | "electron-builder" + | "ms-playwright" | "cypress" | "homebrew" | "puppeteer" + | "node-gyp" | "org.swift.swiftpm" => Some(Artifact::PackageCache), + _ => None, + } +} + +// Fixed-width structural checks, matching TypeScript. No filesystem probes. +fn language_layout( + parts: &[&str], + i: usize, + lower: &str, +) -> Option<(usize, Artifact)> { + if !matches!( + lower, + "library" + | "appdata" + | ".cache" + | ".pub-cache" + | ".dart_tool" + | ".composer" + | ".gem" + | "vendor" + | ".hex" + | "_build" + | ".stack-work" + | "dist-newstyle" + ) { + return None; + } + let at = |offset: usize, value: &str| { + parts + .get(i + offset) + .is_some_and(|s| s.eq_ignore_ascii_case(value)) + }; + let next = parts + .get(i + 1) + .map(|s| s.to_ascii_lowercase()) + .unwrap_or_default(); + if lower == "library" + && next == "developer" + && at(2, "xcode") + && at(3, "deriveddata") + { + return Some((i + 4, Artifact::CompilerCache)); + } + if matches!( + (lower, next.as_str()), + (".pub-cache", "hosted") + | (".composer", "cache") + | (".gem", "specs") + | (".hex", "packages") + ) { + return Some((i + 2, Artifact::PackageCache)); + } + if lower == ".pub-cache" && next == "git" && at(2, "cache") { + return Some((i + 3, Artifact::PackageCache)); + } + if lower == "appdata" + && next == "local" + && at(2, "pub") + && at(3, "cache") + && at(4, "hosted") + { + return Some((i + 5, Artifact::PackageCache)); + } + if lower == "appdata" + && next == "local" + && at(2, "composer") + && (at(3, "files") || at(3, "repo") || at(3, "vcs")) + { + return Some((i + 4, Artifact::PackageCache)); + } + if lower == ".cache" && next == "gem" && (at(2, "specs") || at(2, "gems")) { + return Some((i + 3, Artifact::PackageCache)); + } + let ruby = if lower == ".gem" && next == "ruby" { + Some(i + 1) + } else if lower == "vendor" && next == "bundle" && at(2, "ruby") { + Some(i + 2) + } else { + None + }; + if let Some(ruby) = ruby + && parts + .get(ruby + 1) + .is_some_and(|s| numeric_version(s, 3, 3)) + && parts + .get(ruby + 2) + .is_some_and(|s| s.eq_ignore_ascii_case("cache")) + { + return Some((ruby + 3, Artifact::PackageCache)); + } + if matches!( + (lower, next.as_str()), + (".dart_tool", "flutter_build") + | (".stack-work", "dist") + | ("dist-newstyle", "build" | "cache") + ) { + return Some((i + 2, Artifact::CompilerCache)); + } + if lower == "_build" + && matches!(next.as_str(), "dev" | "test" | "prod" | "shared") + && at(2, "lib") + && at(4, "ebin") + && parts.get(i + 3).is_some_and(|name| { + name.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) + && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') + }) + { + return Some((i + 5, Artifact::CompilerCache)); + } + None +} + +pub(super) fn classify_parts( + parts: &[&str], + start: usize, +) -> Option<(usize, Artifact)> { + for i in start..parts.len() { + super::step(); + let lower = parts[i].to_ascii_lowercase(); + if let Some((end, kind)) = language_layout(parts, i, &lower) { + return Some((end, kind)); + } + if matches!( + lower.as_str(), + ".cache" | "library" | ".local" | "appdata" | ".npm" + ) { + let next = parts + .get(i + 1) + .map(|s| s.to_ascii_lowercase()) + .unwrap_or_default(); + let after = parts + .get(i + 2) + .map(|s| s.to_ascii_lowercase()) + .unwrap_or_default(); + let cache_tool = if lower == ".cache" { + Some(i + 1) + } else if lower == "library" && next == "caches" { + Some(i + 2) + } else { + None + }; + if let Some(tool) = cache_tool + && let Some(kind) = parts + .get(tool) + .and_then(|s| cache_tool_kind(&s.to_ascii_lowercase())) + { + return Some((tool + 1, kind)); + } + if ((lower == ".local" && next == "share") + || (lower == "appdata" && next == "local")) + && after == "nuget" + && parts.get(i + 3).is_some_and(|s| { + matches!( + s.to_ascii_lowercase().as_str(), + "http-cache" | "v3-cache" | "plugins-cache" + ) + }) + { + return Some((i + 4, Artifact::Dotnet)); + } + if lower == ".npm" { + if next == "_cacache" { + return Some((i + 2, Artifact::PackageCache)); + } + continue; + } + } + if matches!( + lower.as_str(), + ".yarn" + | ".bun" + | ".gradle" + | ".m2" + | ".nuget" + | ".vercel" + | ".netlify" + | ".output" + | ".venv" + | "venv" + | ".tox" + | "obj" + ) { + let next = parts + .get(i + 1) + .map(|s| s.to_ascii_lowercase()) + .unwrap_or_default(); + let after = parts + .get(i + 2) + .map(|s| s.to_ascii_lowercase()) + .unwrap_or_default(); + // Only generated/cache children, not whole tool homes. + match lower.as_str() { + ".yarn" => { + if next == "berry" && after == "cache" { + return Some((i + 3, Artifact::PackageCache)); + } + return matches!(next.as_str(), "cache" | "unplugged") + .then(|| (i + 2, Artifact::PackageCache)); + } + ".bun" => { + return (next == "install" && after == "cache") + .then(|| (i + 3, Artifact::PackageCache)); + } + ".gradle" => { + if next == "caches" || numeric_version(&next, 2, 3) { + return Some((i + 2, Artifact::Jvm)); + } + return (next == "wrapper" && after == "dists") + .then(|| (i + 3, Artifact::Jvm)); + } + ".m2" => { + return (next == "repository") + .then(|| (i + 2, Artifact::Jvm)); + } + ".nuget" => { + return (next == "packages") + .then(|| (i + 2, Artifact::Dotnet)); + } + ".vercel" | ".netlify" | ".output" => { + let output = match lower.as_str() { + ".vercel" => { + matches!(next.as_str(), "cache" | "output") + } + ".netlify" => next == "cache", + _ => matches!(next.as_str(), "public" | "server"), + }; + return output.then(|| (i + 2, Artifact::JsBuild)); + } + ".venv" | "venv" | ".tox" => { + let lib = i + if lower == ".tox" { 2 } else { 1 }; + if parts + .get(lib) + .is_some_and(|s| s.eq_ignore_ascii_case("lib")) + { + let version = parts + .get(lib + 1) + .map(|s| s.to_ascii_lowercase()) + .unwrap_or_default(); + let packages = if version == "site-packages" { + Some(lib + 1) + } else if version.strip_prefix("python").is_some_and( + |v| { + numeric_version( + v.strip_suffix('t').unwrap_or(v), + 2, + 2, + ) + }, + ) { + Some(lib + 2) + } else { + None + }; + if let Some(packages) = packages + && parts.get(packages).is_some_and(|s| { + s.eq_ignore_ascii_case("site-packages") + }) + { + return Some((packages + 1, Artifact::Python)); + } + } + } + "obj" + if matches!(next.as_str(), "debug" | "release") + && dotnet_framework(&after) => + { + return Some((i + 3, Artifact::Dotnet)); + } + _ => {} + } + continue; + } + if matches!(lower.as_str(), "ccache" | "sccache" | "mozilla.sccache") { + let parent = i.checked_sub(1).and_then(|j| parts.get(j)); + let grandparent = i.checked_sub(2).and_then(|j| parts.get(j)); + if parent.zip(grandparent).is_some_and(|(p, gp)| { + (p.eq_ignore_ascii_case("caches") + && gp.eq_ignore_ascii_case("library")) + || (p.eq_ignore_ascii_case("local") + && gp.eq_ignore_ascii_case("appdata")) + || (lower == "sccache" + && p.eq_ignore_ascii_case("mozilla") + && gp.eq_ignore_ascii_case("local") + && i.checked_sub(3) + .and_then(|j| parts.get(j)) + .is_some_and(|s| s.eq_ignore_ascii_case("appdata"))) + }) { + return Some((i + 1, Artifact::CompilerCache)); + } + continue; + } + if lower == "target" { + // Match only tool-specific subtrees, never a whole ambiguous + // target/profile tree or an ancestor's project language. + let next = parts + .get(i + 1) + .map(|s| s.to_ascii_lowercase()) + .unwrap_or_default(); + let scala = next.strip_prefix("scala-").is_some_and(|version| { + let mut components = version.split('.'); + let major = components.next().unwrap_or_default(); + let rest: Vec<_> = components.collect(); + (major == "3" || (major == "2" && !rest.is_empty())) + && rest.iter().all(|s| { + !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) + }) + }); + if scala + || matches!(next.as_str(), "maven-status" | "maven-archiver") + { + return Some((i + 2, Artifact::Jvm)); + } + let triple = next.split('-').count() >= 3 + && next.split('-').take(2).all(|s| !s.is_empty()) + && next.bytes().all(|b| { + b.is_ascii_lowercase() + || b.is_ascii_digit() + || b == b'_' + || b == b'-' + }) + && next.splitn(3, '-').nth(2).is_some_and(|s| { + s.as_bytes().first().is_some_and(|b| { + b.is_ascii_alphanumeric() || *b == b'_' + }) + }); + let profile = if matches!(next.as_str(), "debug" | "release") { + i + 1 + } else if triple { + i + 2 + } else { + continue; + }; + if parts.get(profile).is_some_and(|s| { + s.eq_ignore_ascii_case("debug") + || s.eq_ignore_ascii_case("release") + }) && parts.get(profile + 1).is_some_and(|s| { + matches!( + s.to_ascii_lowercase().as_str(), + "deps" | "incremental" | ".fingerprint" + ) + }) { + return Some((profile + 2, Artifact::RustTarget)); + } + if parts.get(profile).is_some_and(|s| { + s.eq_ignore_ascii_case("debug") + || s.eq_ignore_ascii_case("release") + }) && parts + .get(profile + 1) + .is_some_and(|s| s.eq_ignore_ascii_case("build")) + && parts.get(profile + 2).is_some_and(|s| { + s.rsplit_once('-').is_some_and(|(name, hash)| { + !name.is_empty() + && (name.as_bytes()[0].is_ascii_alphanumeric() + || name.as_bytes()[0] == b'_') + && name.bytes().all(|b| { + b.is_ascii_alphanumeric() + || b == b'_' + || b == b'-' + }) + && hash.len() == 16 + && hash.bytes().all(|b| b.is_ascii_hexdigit()) + }) + }) + { + return Some((profile + 3, Artifact::RustTarget)); + } + continue; + } + if lower == ".cargo" + && i + 1 < parts.len() + && parts[i + 1].eq_ignore_ascii_case("registry") + { + return Some((i + 2, Artifact::CargoRegistry)); + } + if lower == "pkg" + && parts + .get(i + 1) + .is_some_and(|s| s.eq_ignore_ascii_case("mod")) + { + if parts + .get(i + 2) + .is_some_and(|s| s.eq_ignore_ascii_case("cache")) + && parts + .get(i + 3) + .is_some_and(|s| s.eq_ignore_ascii_case("download")) + { + return Some((i + 4, Artifact::GoModule)); + } + // Same bounded layout search as ARTIFACT_ROOT_LOOKBACK in TS. + if parts.get(i + 2).is_some_and(|s| s.contains('.')) { + for (end, part) in + parts.iter().enumerate().take(i + 6).skip(i + 2) + { + super::step(); + if go_module_version(&part.to_ascii_lowercase()) { + return Some((end + 1, Artifact::GoModule)); + } + } + } + continue; + } + // pnpm's global store outside a `.pnpm-store` folder: + // `$PNPM_HOME/store`. Same rule as `classifyArtifactPath` in + // src/shared/devArtifacts.ts. + if lower == "pnpm" + && i + 1 < parts.len() + && parts[i + 1].eq_ignore_ascii_case("store") + { + return Some((i + 2, Artifact::PackageCache)); + } + if lower == ".cache" && i + 1 < parts.len() { + let next = parts[i + 1].to_ascii_lowercase(); + if matches!(next.as_str(), "ccache" | "sccache" | "yarn" | "pnpm") { + let kind = if next == "yarn" || next == "pnpm" { + Artifact::PackageCache + } else { + Artifact::CompilerCache + }; + return Some((i + 2, kind)); + } + } + // Only the provider downloads, which `terraform init` puts back + // from the lock file. The rest of .terraform records the selected + // workspace and the last backend config, so it stays. + if lower == ".terraform" && i + 1 < parts.len() { + let next = parts[i + 1].to_ascii_lowercase(); + if matches!(next.as_str(), "providers" | "plugins") { + return Some((i + 2, Artifact::Terraform)); + } + } + // The documented plugin_cache_dir. `.terraform.d/plugins` holds + // providers installed by hand, so it stays. + if lower == ".terraform.d" + && i + 1 < parts.len() + && parts[i + 1].eq_ignore_ascii_case("plugin-cache") + { + return Some((i + 2, Artifact::Terraform)); + } + // The repo's history, not its working files. Every file here is + // below a `.git` folder; a linked worktree's or submodule's `.git` + // is a file and ends the path, so it never matches. + if lower == ".git" && i + 1 < parts.len() { + return Some((i + 1, Artifact::GitRepo)); + } + if let Some(kind) = mapped_kind(&lower) { + let depth = + if matches!(kind, Artifact::Worktree) && i + 1 < parts.len() { + i + 2 + } else { + i + 1 + }; + return Some((depth, kind)); + } + } + None +} + +fn mapped_kind(lower: &str) -> Option { + Some(match lower { + "node_modules" => Artifact::NodeModules, + ".pnpm-store" => Artifact::PackageCache, + ".next" | ".nuxt" | ".turbo" | ".parcel-cache" | ".svelte-kit" => { + Artifact::JsBuild + } + "__pycache__" | ".mypy_cache" | ".pytest_cache" | ".ruff_cache" => { + Artifact::Python + } + "cmakefiles" => Artifact::CmakeBuild, + ".zig-cache" => Artifact::CompilerCache, + ".worktrees" => Artifact::Worktree, + "diagoutputdir" | "rdclientautotrace" => Artifact::DiagLogs, + _ => return None, + }) +} diff --git a/crates/disktree-core/src/classify.rs b/crates/disktree-core/src/classify.rs index bfe24a7f..39e1078e 100644 --- a/crates/disktree-core/src/classify.rs +++ b/crates/disktree-core/src/classify.rs @@ -1,21 +1,21 @@ -//! What a directory *is*, and whether its space can be had back. +//! What a directory is, and whether it is a cleanup candidate to review. //! -//! Colour in the treemap means a kind of data, and a hatch means reclaimable -//! space, so the two questions a cleanup tool exists to answer — "what is it" -//! and "can I delete it" — can be read off a tile at a glance. +//! Colour identifies a kind of data; a hatch suggests review of potentially +//! regenerable contents. Neither names nor layouts prove that data is safe +//! to lose or that removing it will recover its listed bytes. Structural +//! developer-artifact rules live in [`crate::artifact`]. //! -//! Both come from names. A short lookup of well-known directory names covers -//! most of a home directory; anything unmatched takes its parent's kind, and a -//! top-level directory with an unknown name takes the kind of its largest -//! recognisable child (`~/world` is mostly `.git`, so it is git). Reclaimable -//! space is the same idea, plus a sibling check where a name alone is too -//! common to trust: `target` is only a build directory beside a `Cargo.toml`. +//! Unmatched names inherit their parent's kind without guessing from +//! unrelated descendants. VM and Git ownership override cleanup heuristics. use std::borrow::Cow; +use std::path::Path; use rayon::prelude::*; -use crate::tree::Node; +use crate::artifact::Roots; +use crate::path_style::PathStyle; +use crate::tree::{Block, Node, Tree}; /// A kind of data, for colour. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] @@ -36,6 +36,12 @@ pub enum Category { Documents, /// Caches and other regenerable state. Cache, + /// macOS's persistent record of filesystem changes. + FilesystemEvents, + /// macOS's on-volume search database. + Spotlight, + /// VM/container disks and state; detection never suggests raw removal. + VirtualMachine, /// Nothing recognisable. #[default] Other, @@ -43,7 +49,7 @@ pub enum Category { impl Category { /// The categories the legend lists, in its order. - pub const LEGEND: [Self; 8] = [ + pub const LEGEND: [Self; 11] = [ Self::Code, Self::AgentScratch, Self::Toolchain, @@ -52,8 +58,38 @@ impl Category { Self::Media, Self::Documents, Self::Cache, + Self::FilesystemEvents, + Self::Spotlight, + Self::VirtualMachine, ]; + /// The label lowercased, as an agent reads and writes it. + pub const fn name(self) -> &'static str { + match self { + Self::Code => "code", + Self::AgentScratch => "agent scratch", + Self::Toolchain => "toolchain", + Self::Synced => "synced", + Self::Git => "git", + Self::Media => "media", + Self::Documents => "documents", + Self::Cache => "cache", + Self::FilesystemEvents => "fsevents", + Self::Spotlight => "spotlight", + Self::VirtualMachine => "virtual machines", + Self::Other => "other", + } + } + + /// The category with this [`Self::name`], if any. + pub fn named(name: &str) -> Option { + Self::LEGEND + .iter() + .copied() + .chain(std::iter::once(Self::Other)) + .find(|category| category.name() == name) + } + pub const fn label(self) -> &'static str { match self { Self::Code => "Code", @@ -64,15 +100,19 @@ impl Category { Self::Media => "Media", Self::Documents => "Documents", Self::Cache => "Cache", + Self::FilesystemEvents => "FSEvents history", + Self::Spotlight => "Spotlight index", + Self::VirtualMachine => "Virtual machines", Self::Other => "Other", } } } -/// Why a directory's space can be had back. +/// Why contents may be a relatively lower-risk cleanup candidate. +/// This is a heuristic assessment, independent of removal authorization. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Reclaim { - /// A cache: whatever wrote it will write it again. + /// A cache inspection candidate; its name is not deletion permission. Regenerable, /// A sync client's old versions of files. SyncHistory, @@ -82,10 +122,6 @@ pub enum Reclaim { BuildOutput, /// Installed dependencies beside their manifest. Reinstallable, - /// Container or sandbox image layers. - SandboxLayers, - /// Sandbox or VM snapshots. - Snapshots, /// Already deleted, still on disk. Trash, /// Scratch space meant to be thrown away. @@ -101,8 +137,6 @@ impl Reclaim { Self::PackageStore => "package store", Self::BuildOutput => "build output", Self::Reinstallable => "reinstallable", - Self::SandboxLayers => "sandbox layers", - Self::Snapshots => "snapshots", Self::Trash => "trash", Self::Temporary => "temporary", } @@ -132,7 +166,14 @@ pub fn category_of_name(name: &str) -> Option { let lower = lowered(name, &mut buffer); // Windows: a work or school account's folder carries the organisation, // `OneDrive - Contoso`, and Dropbox's does the same, `Dropbox (Contoso)`. - if lower.starts_with("onedrive - ") || lower.starts_with("dropbox (") { + if lower.starts_with("onedrive - ") + || lower.starts_with("dropbox (") + // Legacy Google Drive roots predate File Provider. Match the wrapper, + // never the account name inside it. + || ["my drive (", "google drive ("] + .iter() + .any(|prefix| lower.starts_with(prefix) && lower.ends_with(')')) + { return Some(Category::Synced); } let category = match &*lower { @@ -153,7 +194,7 @@ pub fn category_of_name(name: &str) -> Option { // macOS: Xcode's and the simulators' state in ~/Library/Developer. // Not `Developer` itself: ~/Developer is where Apple puts projects. | "xcode" | "coresimulator" => Category::Toolchain, - "sync" | "dropbox" | "nextcloud" | "google drive" | "onedrive" + "sync" | "dropbox" | "nextcloud" | "google drive" | "my drive" | "onedrive" | "pclouddrive" | "mega" | ".stversions" // macOS: iCloud Drive, and the File Provider clients (Dropbox, // Google Drive, OneDrive) since macOS 12. @@ -161,6 +202,8 @@ pub fn category_of_name(name: &str) -> Option { // Windows: iCloud for Windows. | "iclouddrive" => Category::Synced, ".git" => Category::Git, + ".fseventsd" => Category::FilesystemEvents, + ".spotlight-v100" => Category::Spotlight, "pictures" | "photos" | "music" | "videos" | "movies" | "steam" | "steamlibrary" | "steamapps" | "emulation" | "models" | ".ollama" | ".lmstudio" | "games" | "wineprefix" => { @@ -180,11 +223,11 @@ pub fn category_of_name(name: &str) -> Option { Some(category) } -/// Whether a directory's space can be had back, judged from its name, the +/// Whether a directory is a cleanup candidate, judged from its name, the /// kind of the directory holding it, and its siblings' names. pub fn reclaim_of( name: &str, - parent: Category, + _parent: Category, has_sibling: impl Fn(&str) -> bool, ) -> Option { let mut buffer = [0; LOWERED]; @@ -200,19 +243,13 @@ pub fn reclaim_of( // next time that device is plugged in. | "ios devicesupport" | "watchos devicesupport" => Reclaim::Regenerable, ".stversions" => Reclaim::SyncHistory, - ".pnpm-store" | "pnpm" => Reclaim::PackageStore, "__pycache__" | ".pytest_cache" | ".mypy_cache" | ".ruff_cache" | ".next" | ".turbo" | ".parcel-cache" // Xcode's build products and indexes, rebuilt on the next build. | "deriveddata" => Reclaim::BuildOutput, // ~/Library/Logs, told apart from a project's logs by its neighbour. "logs" if has_sibling("Application Support") => Reclaim::Temporary, - // Too common to trust alone: only a build directory beside a manifest. - "target" if has_sibling("Cargo.toml") => Reclaim::BuildOutput, "node_modules" if has_sibling("package.json") => Reclaim::Reinstallable, - // Layers and snapshots are only disposable inside sandbox state. - "layers" if parent == Category::AgentScratch => Reclaim::SandboxLayers, - "snapshots" if parent == Category::AgentScratch => Reclaim::Snapshots, "trash" | ".trash" | "$recycle.bin" => Reclaim::Trash, // `Temp` is where Windows puts temporary files, in AppData\Local; // `CrashDumps` beside it holds dumps of programs that crashed. @@ -226,139 +263,269 @@ pub fn reclaim_of( /// /// Top-down: a node's own name wins, otherwise it inherits. Reclaimable /// space is inherited too, so everything under a cache is hatched. -pub fn classify(root: &mut Node) { - root.category = Category::Other; - root.reclaim = None; - for index in 0..root.children.len() { - let siblings = &root.children; - let has_sibling = - |wanted: &str| siblings.iter().any(|name| &*name.name == wanted); - let child = &siblings[index]; - // A top-level directory with an unknown name takes the kind of its - // largest recognisable child: `~/world` is mostly `.git`. - let category = category_of_name(&child.name) - .or_else(|| is_git_store(child).then_some(Category::Git)) - .or_else(|| dominant_child_category(child)) - .unwrap_or(Category::Other); - let reclaim = child - .is_dir() - .then(|| reclaim_of(&child.name, Category::Other, has_sibling)) - .flatten(); - classify_below(&mut root.children[index], category, reclaim, 1); +/// +/// Two passes, so that both can spread across workers. Writing kinds sees +/// one directory's children at a time, but a git or pnpm store shows what +/// it is two levels down, so a pass that only reads finds those first. +pub fn classify(tree: &mut Tree) { + let name = tree.root().name().to_owned(); + classify_at(tree, Path::new(&name), PathStyle::Native); +} + +/// Classify using the scan root's full path, including tool ownership above +/// that root. SSH callers pass POSIX rules even on Windows. +pub fn classify_at(tree: &mut Tree, path: &Path, style: PathStyle) { + let artifacts = Roots::find(tree, path, style); + let stores = Stores::find(tree, artifacts); + let root = tree.root(); + // Protected stores win over any cache identity inferred from a parent + // above this scan root. Narrow scans retain the same ownership rules. + let own = category_of_name(root.name()) + .filter(|category| { + matches!(category, Category::FilesystemEvents | Category::Spotlight) + }) + .map(|category| (category, None)) + .or_else(|| stores.is_git(root.id()).then_some((Category::Git, None))) + .or_else(|| { + stores + .artifacts + .get(root.id()) + .map(|d| (d.category(), d.reclaim())) + }) + .or_else(|| { + is_pnpm_store(root) + .then_some((Category::Toolchain, Some(Reclaim::PackageStore))) + }); + tree.par_top_down( + |facts, mut block| { + if let Some((category, reclaim)) = own { + facts.category = category; + facts.reclaim = reclaim; + decide(&mut block, category, reclaim, &stores); + } else { + facts.category = Category::Other; + facts.reclaim = None; + decide_top(&mut block, &stores); + } + }, + |facts, mut block| { + decide(&mut block, facts.category, facts.reclaim, &stores); + }, + ); + // A generic cache can contain protected data. Never suggest the whole + // parent when a descendant overrides its inherited cleanup assessment. + tree.par_bottom_up( + |_| {}, + |facts, block| { + if facts.reclaim.is_some() + && block.iter().any(|child| child.reclaim.is_none()) + { + facts.reclaim = None; + } + }, + ); +} + +/// The children of a root that is nothing in particular: each takes only +/// its own evidence, as `kind_of` gives it for a parent of no kind, except +/// that a file directly in the root takes a kind from its own name too. +fn decide_top(block: &mut Block<'_>, stores: &Stores) { + for index in 0..block.len() { + let child = block.at(index); + let (category, reclaim) = + if let Some(d) = stores.artifacts.get(block.id(index)) { + (d.category(), d.reclaim()) + } else if child.kind.is_dir() { + kind_of(block, index, Category::Other, None, stores) + } else { + ( + category_of_name(child.name).unwrap_or(Category::Other), + None, + ) + }; + let facts = block.facts_mut(index); + facts.category = category; + facts.reclaim = reclaim; } } -fn classify_below( - node: &mut Node, +/// The children of a directory that is `category`, and `reclaim`. +fn decide( + block: &mut Block<'_>, category: Category, reclaim: Option, - depth: usize, + stores: &Stores, ) { - node.category = category; - node.reclaim = reclaim; // Most directories hold only files, which take this one's kind as - // they are: no list of kinds to build, no call per file. - if !node.children.iter().any(Node::is_dir) { - for child in &mut node.children { - child.category = category; - child.reclaim = reclaim; - } + // they are: no call per file. + if !block.iter().enumerate().any(|(index, child)| { + child.kind.is_dir() || stores.artifacts.get(block.id(index)).is_some() + }) { + block.for_each_facts_mut(|facts| { + facts.category = category; + facts.reclaim = reclaim; + }); return; } - // See `tree::PARALLEL_LEVELS`: parallel only near the top. Deeper, the - // children are decided and descended one at a time, with no list of - // decisions: there are half a million directories to get through. - if depth < crate::tree::PARALLEL_LEVELS { - let kinds: Vec<(Category, Option)> = (0..node.children.len()) - .map(|index| kind_of(&node.children, index, category, reclaim)) - .collect(); - node.children.par_iter_mut().zip(kinds).for_each( - |(child, (category, reclaim))| { - classify_below(child, category, reclaim, depth + 1); - }, - ); - } else { - for index in 0..node.children.len() { - let (category, reclaim) = - kind_of(&node.children, index, category, reclaim); - classify_below( - &mut node.children[index], - category, - reclaim, - depth + 1, - ); - } + for index in 0..block.len() { + let (category, reclaim) = + kind_of(block, index, category, reclaim, stores); + let facts = block.facts_mut(index); + facts.category = category; + facts.reclaim = reclaim; } } /// What the child at `index` is, given what its parent is: its own name /// wins, otherwise it inherits. A file always inherits. fn kind_of( - siblings: &[Node], + siblings: &Block<'_>, index: usize, category: Category, reclaim: Option, + stores: &Stores, ) -> (Category, Option) { - let child = &siblings[index]; - if !child.is_dir() { + let child = siblings.at(index); + // These stores belong to macOS even when an internal folder is named + // `cache` or `tmp`; raw deletion is not an appropriate cleanup method. + if matches!( + category, + Category::FilesystemEvents + | Category::Spotlight + | Category::VirtualMachine + | Category::Git + ) { + return (category, None); + } + let id = siblings.id(index); + if stores.is_git(id) { + return (Category::Git, None); + } + if let Some(detection) = stores.artifacts.get(id) { + return (detection.category(), detection.reclaim()); + } + if !child.kind.is_dir() { return (category, reclaim); } let has_sibling = - |wanted: &str| siblings.iter().any(|name| &*name.name == wanted); - let child_category = category_of_name(&child.name) - .or_else(|| is_git_store(child).then_some(Category::Git)) + |wanted: &str| siblings.iter().any(|sibling| sibling.name == wanted); + let child_category = category_of_name(child.name) + .or_else(|| stores.is_git(id).then_some(Category::Git)) .unwrap_or(category); - let child_reclaim = - reclaim.or_else(|| reclaim_of(&child.name, category, has_sibling)); + let child_reclaim = if matches!( + child_category, + Category::FilesystemEvents + | Category::Spotlight + | Category::Git + | Category::VirtualMachine + ) { + None + } else { + reclaim + .or_else(|| reclaim_of(child.name, category, has_sibling)) + .or_else(|| stores.is_pnpm(id).then_some(Reclaim::PackageStore)) + }; (child_category, child_reclaim) } -/// The kind of an unknown directory, from what fills it: the first -/// recognisable name down the largest children, a few levels deep. -fn dominant_child_category(node: &Node) -> Option { - let mut node = node; - for _ in 0..3 { - if let Some(category) = node - .children - .iter() - .filter(|child| child.is_dir()) - .find_map(|child| { - category_of_name(&child.name) - .or_else(|| is_git_store(child).then_some(Category::Git)) - }) - { - return Some(category); +/// The directories whose kind is in their shape rather than their name, +/// by [`Node::id`], in order. There are few: a store per repository. +struct Stores { + shapes: Vec, + artifacts: Roots, +} + +#[derive(Clone, Copy)] +struct Shape { + id: u32, + git: bool, + pnpm: bool, +} + +impl Stores { + fn find(tree: &Tree, artifacts: Roots) -> Self { + // An ordered parallel collect keeps the ids ascending. + Self { + artifacts, + shapes: tree + .par_nodes() + .filter(|node| node.is_dir()) + .filter_map(|node| { + let git = is_git_store(node); + let pnpm = is_pnpm_store(node); + (git || pnpm).then(|| Shape { + id: node.id(), + git, + pnpm, + }) + }) + .collect(), } - node = node.children.iter().find(|child| child.is_dir())?; } - None + + fn get(&self, id: u32) -> Option { + let found = self + .shapes + .binary_search_by_key(&id, |shape| shape.id) + .ok()?; + Some(self.shapes[found]) + } + + fn is_git(&self, id: u32) -> bool { + self.get(id).is_some_and(|shape| shape.git) + } + + fn is_pnpm(&self, id: u32) -> bool { + self.get(id).is_some_and(|shape| shape.pnpm) + } +} + +/// pnpm's versioned content-addressable store, not its installation prefix. +/// `pnpm` also holds its executable, global tools and `.tools`; only a +/// store with a version directory containing `files` is a cleanup candidate. +pub(crate) fn is_pnpm_store(node: Node<'_>) -> bool { + node.is_dir() + && matches!(node.name(), "store" | ".pnpm-store") + && node.children().iter().any(|version| { + version.is_dir() + && version.name().strip_prefix('v').is_some_and(|number| { + !number.is_empty() + && number.bytes().all(|c| c.is_ascii_digit()) + }) + && version + .children() + .iter() + .any(|child| child.is_dir() && child.name() == "files") + }) } /// A git object store by its shape, whatever it is called: a bare /// repository, or a `.git` directory, has `objects`, `refs` and `HEAD`. -pub fn is_git_store(node: &Node) -> bool { - let has = - |wanted: &str| node.children.iter().any(|child| &*child.name == wanted); +pub fn is_git_store(node: Node<'_>) -> bool { + let has = |wanted: &str| { + node.children().iter().any(|child| child.name() == wanted) + }; node.is_dir() && has("objects") && has("refs") && has("HEAD") } #[cfg(test)] mod tests { use super::*; + use crate::tree::{Draft, Tree}; use crate::tree::{Metric, NodeKind, aggregate}; - fn file(name: &str, bytes: u64) -> Node { - Node::entry(name, NodeKind::File, bytes) + fn file(name: &str, bytes: u64) -> Draft { + Draft::entry(name, NodeKind::File, bytes) } - fn dir(name: &str, children: Vec) -> Node { - let mut node = Node::directory(name); + fn dir(name: &str, children: Vec) -> Draft { + let mut node = Draft::directory(name); node.children = children; node } - fn home() -> Node { - let mut home = dir( + fn home() -> Tree { + let home = dir( "tobi", vec![ dir( @@ -409,18 +576,19 @@ mod tests { ), ], ); + let mut home = Tree::from(home); aggregate(&mut home, Metric::Bytes); classify(&mut home); home } - fn named<'a>(node: &'a Node, path: &[&str]) -> &'a Node { + fn named<'a>(node: Node<'a>, path: &[&str]) -> Node<'a> { let mut node = node; for part in path { node = node - .children + .children() .iter() - .find(|child| &*child.name == *part) + .find(|child| child.name() == *part) .unwrap_or_else(|| panic!("no {part}")); } node @@ -431,7 +599,7 @@ mod tests { /// as cache. #[test] fn a_steam_library_on_another_drive_is_media_not_its_temp_folder() { - let mut root = dir( + let root = dir( "data", vec![dir( "SteamLibrary", @@ -444,11 +612,16 @@ mod tests { )], )], ); + let mut root = Tree::from(root); aggregate(&mut root, Metric::Bytes); classify(&mut root); - let library = &root.children[0]; + let library = root.root().children().at(0); assert_eq!(library.category, Category::Media); - let common = library.children[0].child_named("common").expect("common"); + let common = library + .children() + .at(0) + .child_named("common") + .expect("common"); assert_eq!(common.category, Category::Media); assert_eq!(common.reclaim, None, "installed games are not hatched"); } @@ -464,75 +637,243 @@ mod tests { #[test] fn names_announce_their_kind_and_children_inherit_it() { let home = home(); - assert_eq!(named(&home, &["src"]).category, Category::Code); + assert_eq!(named(home.root(), &["src"]).category, Category::Code); // `tries` is agent scratch even inside code: it is what agents write. assert_eq!( - named(&home, &["src", "tries"]).category, + named(home.root(), &["src", "tries"]).category, Category::AgentScratch ); assert_eq!( - named(&home, &["src", "tries", "2026-09-01"]).category, + named(home.root(), &["src", "tries", "2026-09-01"]).category, Category::AgentScratch, "an unknown name inherits" ); assert_eq!( - named(&home, &["src", "tries", "2026-09-01", "a"]).category, + named(home.root(), &["src", "tries", "2026-09-01", "a"]).category, Category::AgentScratch, "files inherit too" ); } #[test] - fn an_unknown_top_level_directory_takes_its_largest_known_child() { + fn unknown_aggregates_do_not_guess_from_descendants() { let home = home(); - assert_eq!(named(&home, &["world"]).category, Category::Git); - assert_eq!(named(&home, &["mystery"]).category, Category::Other); + assert_eq!(named(home.root(), &["world"]).category, Category::Other); + assert_eq!(named(home.root(), &["mystery"]).category, Category::Other); + assert_eq!( + named(home.root(), &["world", "README"]).category, + Category::Other + ); // A bare repository is git by its shape, whatever it is called. - assert_eq!(named(&home, &["monorepo"]).category, Category::Git); - assert_eq!(named(&home, &["monorepo", "git"]).category, Category::Git); + assert_eq!(named(home.root(), &["monorepo"]).category, Category::Other); + assert_eq!( + named(home.root(), &["monorepo", "git"]).category, + Category::Git + ); + } + + #[test] + fn pnpm_installations_are_not_package_stores() { + let store = || { + dir( + "store", + vec![dir( + "v10", + vec![ + dir( + "files", + vec![dir("ab", vec![file("package", 10)])], + ), + dir("index", vec![]), + ], + )], + ) + }; + let root = dir( + "Library", + vec![ + dir( + "pnpm", + vec![ + file("pnpm", 1), + dir("global", vec![file("tool", 2)]), + dir(".tools", vec![file("pnpm", 3)]), + store(), + ], + ), + dir(".pnpm-store", vec![file("unverified", 4)]), + dir(".PNPM-STORE", vec![file("unverified", 4)]), + ], + ); + let mut root = Tree::from(root); + classify(&mut root); + for path in [ + vec!["pnpm"], + vec!["pnpm", "pnpm"], + vec!["pnpm", "global", "tool"], + vec!["pnpm", ".tools", "pnpm"], + vec![".pnpm-store", "unverified"], + vec![".PNPM-STORE", "unverified"], + ] { + assert_eq!(named(root.root(), &path).reclaim, None, "{path:?}"); + } + assert_eq!( + named( + root.root(), + &["pnpm", "store", "v10", "files", "ab", "package"] + ) + .reclaim, + Some(Reclaim::PackageStore) + ); + let mut standalone = store(); + standalone.name = ".pnpm-store".into(); + let mut standalone = Tree::from(standalone); + classify(&mut standalone); + assert_eq!(standalone.root().reclaim, Some(Reclaim::PackageStore)); + assert_eq!(reclaim_of("pnpm", Category::Toolchain, |_| false), None); + for contents in [ + dir("version", vec![dir("files", vec![])]), + dir("v", vec![dir("files", vec![])]), + dir("v3-backup", vec![dir("files", vec![])]), + dir("v3", vec![file("files", 1)]), + ] { + let unverified = dir(".pnpm-store", vec![contents]); + let mut unverified = Tree::from(unverified); + classify(&mut unverified); + assert_eq!(unverified.root().reclaim, None); + assert_eq!(unverified.root().children().at(0).reclaim, None); + } + } + + #[test] + fn a_whole_root_scan_keeps_categories_and_filters_local_to_evidence() { + use crate::query::{Filter, find}; + use std::path::Path; + let root = dir( + "/", + vec![dir( + "Users", + vec![dir( + "fixture", + vec![ + dir( + ".codex", + vec![dir("scratch", vec![file("experiment", 100)])], + ), + dir( + "Library", + vec![ + dir("VM data", vec![file("disk", 30)]), + dir("snapshots", vec![file("vm-snapshot", 20)]), + ], + ), + dir( + "My Drive (Fixture Account)", + vec![dir( + "client files", + vec![file("document", 10)], + )], + ), + ], + )], + )], + ); + let mut root = Tree::from(root); + aggregate(&mut root, Metric::Bytes); + classify(&mut root); + for path in [ + vec!["Users"], + vec!["Users", "fixture"], + vec!["Users", "fixture", "Library", "VM data", "disk"], + vec!["Users", "fixture", "Library", "snapshots"], + ] { + let node = named(root.root(), &path); + assert_eq!(node.category, Category::Other, "{path:?}"); + assert_eq!(node.reclaim, None, "{path:?}"); + } + for (category, expected) in [ + (Category::AgentScratch, "/Users/fixture/.codex"), + ( + Category::Synced, + "/Users/fixture/My Drive (Fixture Account)", + ), + ] { + let found = find( + Path::new("/"), + root.root(), + &Filter { + category: Some(category), + ..Filter::default() + }, + 20, + ); + assert_eq!(found.count, 1); + assert_eq!(found.matches[0].0, Path::new(expected)); + } + assert_eq!( + named( + root.root(), + &[ + "Users", + "fixture", + "My Drive (Fixture Account)", + "client files", + "document" + ] + ) + .category, + Category::Synced + ); + for name in [ + "My Drive", + "My Drive (Another Account)", + "Google Drive (work)", + ] { + assert_eq!(category_of_name(name), Some(Category::Synced)); + } + for name in ["My Driver", "My Drive (unfinished", "My Drive backups"] { + assert_eq!(category_of_name(name), None); + } } #[test] fn caches_are_reclaimable_all_the_way_down() { let home = home(); assert_eq!( - named(&home, &[".cache"]).reclaim, + named(home.root(), &[".cache"]).reclaim, Some(Reclaim::Regenerable) ); assert_eq!( - named(&home, &[".cache", "kache", "store"]).reclaim, + named(home.root(), &[".cache", "kache", "store"]).reclaim, Some(Reclaim::Regenerable) ); assert_eq!( - named(&home, &["Sync", ".stversions"]).reclaim, + named(home.root(), &["Sync", ".stversions"]).reclaim, Some(Reclaim::SyncHistory) ); - assert_eq!(named(&home, &["src"]).reclaim, None); + assert_eq!(named(home.root(), &["src"]).reclaim, None); } #[test] - fn target_is_build_output_only_beside_a_cargo_manifest() { + fn a_manifest_does_not_promote_a_whole_target_directory() { let home = home(); - assert_eq!( - named(&home, &["rust-thing", "target"]).reclaim, - Some(Reclaim::BuildOutput) - ); - assert_eq!(named(&home, &["js-thing", "target"]).reclaim, None); + assert_eq!(named(home.root(), &["rust-thing", "target"]).reclaim, None); + assert_eq!(named(home.root(), &["js-thing", "target"]).reclaim, None); } #[test] - fn sandbox_layers_and_snapshots_are_reclaimable_only_in_sandbox_state() { + fn snapshots_are_not_suggested_from_agent_scratch_ancestry() { let home = home(); // .microsandbox/cache is already a regenerable cache, so its layers // inherit that; the snapshots are judged on their own. assert!( - named(&home, &[".microsandbox", "cache", "layers"]) + named(home.root(), &[".microsandbox", "cache", "layers"]) .reclaim .is_some() ); assert_eq!( - named(&home, &[".microsandbox", "snapshots"]).reclaim, - Some(Reclaim::Snapshots) + named(home.root(), &[".microsandbox", "snapshots"]).reclaim, + None ); assert_eq!( reclaim_of("snapshots", Category::Documents, |_| false), @@ -607,6 +948,81 @@ mod tests { assert_eq!(category_of_name("OneDriveSetup"), None); } + #[test] + fn macos_stores_are_named_without_suggesting_raw_deletion() { + for (name, category) in [ + (".fseventsd", Category::FilesystemEvents), + (".Spotlight-V100", Category::Spotlight), + ] { + let store = dir(name, vec![dir("cache", vec![file("blob", 123)])]); + let mut store = Tree::from(store); + aggregate(&mut store, Metric::Bytes); + classify(&mut store); + let root = store.root(); + assert_eq!(root.category, category); + assert_eq!(root.children().at(0).category, category); + assert_eq!( + root.children().at(0).children().at(0).category, + category + ); + assert_eq!(root.children().at(0).reclaim, None); + assert_eq!(root.bytes, 123); + let volume = + dir("volume", vec![root.to_draft(), dir("ordinary", vec![])]); + let mut volume = Tree::from(volume); + classify(&mut volume); + let volume = volume.root(); + assert_eq!(volume.children().at(0).category, category); + assert_eq!(volume.children().at(1).category, Category::Other); + assert_eq!(volume.children().at(0).reclaim, None); + } + } + + /// What lies directly in the root is judged by its own evidence only: + /// its name, or its shape for a store, never its parent's kind. + #[test] + fn the_roots_children_take_only_their_own_evidence() { + let root = dir( + "volume", + vec![ + file("tmp", 1), + file("README", 1), + dir( + "bare", + vec![ + dir("objects", vec![]), + dir("refs", vec![]), + file("HEAD", 1), + ], + ), + dir("store", vec![dir("v3", vec![dir("files", vec![])])]), + dir("Caches", vec![file("blob", 1)]), + dir("plain", vec![file("tmp", 1)]), + ], + ); + let mut root = Tree::from(root); + classify(&mut root); + let kind = |path: &[&str]| { + let node = named(root.root(), path); + (node.category, node.reclaim) + }; + // A file directly in the root takes a kind from its name, but + // never a reclaim reason; deeper, a file only inherits. + assert_eq!(kind(&["tmp"]), (Category::Cache, None)); + assert_eq!(kind(&["README"]), (Category::Other, None)); + assert_eq!(kind(&["plain", "tmp"]), (Category::Other, None)); + assert_eq!(kind(&["bare"]), (Category::Git, None)); + assert_eq!(kind(&["bare", "HEAD"]), (Category::Git, None)); + assert_eq!( + kind(&["store"]), + (Category::Other, Some(Reclaim::PackageStore)) + ); + assert_eq!( + kind(&["Caches", "blob"]), + (Category::Cache, Some(Reclaim::Regenerable)) + ); + } + #[test] fn the_legend_lists_every_named_category_once() { let mut seen = std::collections::HashSet::new(); diff --git a/crates/disktree-core/src/cleanup.rs b/crates/disktree-core/src/cleanup.rs new file mode 100644 index 00000000..cbb369a4 --- /dev/null +++ b/crates/disktree-core/src/cleanup.rs @@ -0,0 +1,1652 @@ +//! Cache cleanup, decided item by item. +//! +//! Classification is an inspection hint, never permission to delete. For +//! each marked path the person picks Skip, the owner's exact allowlisted +//! command, or deliberately deleting the files; nothing else ever builds a +//! write, and one never stands in for another. See `docs/owner-cleanup.md`. + +use std::collections::BTreeMap; +use std::fmt::Write as _; +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; + +use serde::{Deserialize, Serialize}; + +use crate::removal::{Plan, Target}; + +mod process; +mod recognize; +#[cfg(test)] +mod tests; + +pub use recognize::inspection_reason; + +// Preflight must bound queued paths as well as visited entries so one +// enormous flat directory cannot exhaust memory before the limit is seen. +const MAX_PREFLIGHT_ENTRIES: usize = 2_000_000; + +/// Cache classifications never silently reach the recursive remover. Check +/// descendants too: deleting a wrapper must not bypass an owner's policy. +#[allow( + clippy::unnecessary_debug_formatting, + reason = "Quote paths and expose controls in safety refusals" +)] +pub fn check_raw(targets: &[Target]) -> Result<(), String> { + let environment = Environment::current()?; + for target in targets { + if let Some(reason) = + recognize::inspection_with(&target.path, &environment) + { + return Err(format!("{:?}: {reason}", target.path)); + } + } + let mut pending: Vec<_> = + targets.iter().map(|target| target.path.clone()).collect(); + let mut visited = 0; + while let Some(path) = pending.pop() { + visited += 1; + if visited > MAX_PREFLIGHT_ENTRIES { + return Err("Raw removal inspection exceeded its bound; inspect a smaller selection".into()); + } + let meta = match std::fs::symlink_metadata(&path) { + Ok(meta) => meta, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + continue; + } + Err(error) => return Err(error.to_string()), + }; + if meta.is_dir() { + if let Some(reason) = + recognize::inspection_with(&path, &environment) + { + return Err(format!("{path:?}: {reason}")); + } + for entry in + std::fs::read_dir(&path).map_err(|error| error.to_string())? + { + if visited + pending.len() >= MAX_PREFLIGHT_ENTRIES { + return Err("Raw removal inspection exceeded its bound; inspect a smaller selection".into()); + } + pending.push(entry.map_err(|error| error.to_string())?.path()); + } + } + } + Ok(()) +} + +/// Deliberately separate npm's two independently managed caches. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Owner { + Npm, + Npx, + Uv, + Pip, + Cypress, + Pnpm, + Homebrew, + Playwright, + Puppeteer, +} + +impl Owner { + pub const fn label(self) -> &'static str { + match self { + Self::Npm => "npm package cache", + Self::Npx => "npm npx cache", + Self::Uv => "uv cache", + Self::Pip => "pip cache", + Self::Cypress => "Cypress binary cache", + Self::Pnpm => "pnpm store", + Self::Homebrew => "Homebrew cache", + Self::Playwright => "Playwright browser cache", + Self::Puppeteer => "Puppeteer browser cache", + } + } + + const fn executable(self) -> &'static str { + match self { + Self::Npm | Self::Npx => "npm", + Self::Uv => "uv", + Self::Pip => "pip", + Self::Cypress => "cypress", + Self::Pnpm => "pnpm", + Self::Homebrew => "brew", + Self::Playwright => "playwright", + Self::Puppeteer => "puppeteer", + } + } + + /// The command a person would recognize, for a button's label. + pub const fn command_label(self) -> &'static str { + match self { + Self::Npm => "npm cache clean", + Self::Npx => "npm cache npx rm", + Self::Uv => "uv cache clean", + Self::Pip => "pip cache purge", + Self::Cypress => "cypress cache clear", + Self::Pnpm + | Self::Homebrew + | Self::Playwright + | Self::Puppeteer => "owner command", + } + } + + pub const fn unsupported(self) -> Option<&'static str> { + match self { + Self::Pnpm => Some( + "pnpm prune can also change metadata, dlx/runtime caches and global virtual-store state outside the selected store; inspect with pnpm. This scope is not supported.", + ), + Self::Homebrew => Some( + "brew cleanup also removes old installed formula versions and lock files outside the cache; cache-only cleanup is not supported.", + ), + Self::Playwright => Some( + "playwright uninstall changes browser installations and package-reference state; selected-cache-only cleanup is not supported.", + ), + Self::Puppeteer => Some( + "Puppeteer has a browser cleanup API, but its installed API, JavaScript configuration and interactive CLI scope are not resolved by this version of PwrDisk. Inspect with the owning installation.", + ), + _ => None, + } + } +} + +/// The exact invocation shown before consent. No shell, executable or +/// argument can be supplied by an MCP caller. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Command { + pub executable: PathBuf, + pub arguments: Vec, + pub environment: BTreeMap, + pub working_directory: PathBuf, +} + +/// One actual scope, which can be wider than the selected subtree. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Operation { + pub owner: Owner, + pub version: String, + pub selected: Vec, + pub cache_root: PathBuf, + pub scope: PathBuf, + pub command: Command, + pub effects: String, + pub limitations: String, +} + +impl Operation { + /// The command acts on more than was marked: unselected siblings too. + pub fn wider(&self) -> bool { + self.selected.iter().any(|selected| *selected != self.scope) + } + + #[allow( + clippy::unnecessary_debug_formatting, + reason = "Consent must expose argument boundaries and control characters" + )] + pub fn description(&self) -> String { + // Debug quoting exposes control characters and argument boundaries. + let mut text = format!( + "{} ({})\nSelected: {:?}\nConfigured cache root: {:?}\nActual scope: {:?}\nExecutable: {:?}\nArguments: {:?}\nEnvironment overrides: {:?}\nWorking directory: {:?}\n", + self.owner.label(), + self.version, + self.selected, + self.cache_root, + self.scope, + self.command.executable, + self.command.arguments, + self.command.environment, + self.command.working_directory, + ); + if self.wider() { + text.push_str("Wider than selected: the command acts on the whole scope, including unselected siblings.\n"); + } + text.push_str(&self.effects); + text.push('\n'); + text.push_str(&self.limitations); + text.push('\n'); + text.push_str(OWNER_RECOVERABILITY); + text + } +} + +/// What an owner command leaves to recover from, stated before consent. +pub const OWNER_RECOVERABILITY: &str = "Recoverability: none through PwrDisk or Trash. The owner downloads or rebuilds entries when they are next needed."; + +/// Why a proposal or a step could not do what was asked. One vocabulary +/// for the window, the agent and the results, so a failure reads the same +/// wherever it is reported. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Problem { + /// No executable of that name on PwrDisk's PATH, or it cannot start. + NotFound, + /// A shim, proxy or launcher PwrDisk will not invoke. + UnsupportedLauncher, + UnsupportedVersion, + VersionCheckFailed, + ConfigCheckFailed, + /// A recognized owner with no audited cache-only command. + NoCommand, + /// No supported owner resolves to this path. + UnknownOwner, + /// The owner's configured cache is somewhere else. + NotConfiguredCache, + /// Removal guards, scope checks or bounds refuse it. + Refused, + /// The whole run is past the capacity limit. + OverLimit, + /// Owner, version, executable or configured root changed since preview. + Changed, + InUse, + CommandFailed, + /// Stopped or timed out; it may have done part of its work. + Cancelled, + /// Deleting or trashing the files failed. + RemovalFailed, +} + +impl Problem { + pub const fn label(self) -> &'static str { + match self { + Self::NotFound => "not found on PATH", + Self::UnsupportedLauncher => "unsupported launcher", + Self::UnsupportedVersion => "unsupported version", + Self::VersionCheckFailed => "version check failed", + Self::ConfigCheckFailed => "configuration check failed", + Self::NoCommand => "no cleanup command", + Self::UnknownOwner => "unknown owner", + Self::NotConfiguredCache => "not the configured cache", + Self::Refused => "refused by guards", + Self::OverLimit => "over the capacity limit", + Self::Changed => "changed since preview", + Self::InUse => "in use", + Self::CommandFailed => "command failed", + Self::Cancelled => "cancelled or timed out", + Self::RemovalFailed => "removal failed", + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Issue { + pub problem: Problem, + pub detail: String, +} + +impl Issue { + pub fn new(problem: Problem, detail: impl Into) -> Self { + Self { + problem, + detail: detail.into(), + } + } + + pub fn description(&self) -> String { + format!("{}: {}", self.problem.label(), self.detail) + } +} + +/// The person's choice for one marked path. Skip is the default: nothing +/// runs for a path nobody chose an action for. +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, +)] +#[serde(rename_all = "snake_case")] +pub enum Decision { + #[default] + Skip, + /// Run the exact owner command shown for it. + Owner, + /// Delete exactly this path directly, without its owner. + DeleteFiles, +} + +/// What a step does, or did. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Action { + Skip, + Owner, + Trash, + Permanent, +} + +impl Action { + pub const fn label(self) -> &'static str { + match self { + Self::Skip => "skip", + Self::Owner => "owner command", + Self::Trash => "move files to Trash", + Self::Permanent => "delete files permanently", + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Outcome { + Succeeded, + Failed, + /// Stopped while running; it may have done part of its work. + Cancelled, + /// The person chose Skip; nothing ran. + Skipped, + /// Stopped before this step started. + NotReached, +} + +/// What Delete files means for one path, said before it is chosen. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Disclosure { + pub path: PathBuf, + /// Recognized caches inside it, whose owners are bypassed as well. + pub contains: Vec, + pub warning: String, +} + +impl Disclosure { + #[allow( + clippy::unnecessary_debug_formatting, + reason = "Consent must expose path control characters" + )] + pub fn description(&self, action: Action) -> String { + let mut text = format!("{:?}: {}", self.path, self.warning); + if !self.contains.is_empty() { + text.push_str(" It contains "); + text.push_str(&self.contains.join("; ")); + text.push_str(", whose owners are not involved either."); + } + let recovery = files_recoverability(action); + if !recovery.is_empty() { + text.push(' '); + text.push_str(recovery); + } + text + } +} + +/// What deleting files directly leaves to recover from. +pub const fn files_recoverability(action: Action) -> &'static str { + match action { + Action::Trash => { + "Moved to Trash: recoverable until the Trash is emptied, and its space returns only then." + } + Action::Permanent => { + "Deleted permanently: cannot be undone through PwrDisk or Trash." + } + Action::Skip | Action::Owner => "", + } +} + +/// One marked path and what can be done with it. A failure to resolve its +/// owner is this proposal's status, never the whole preview's. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Proposal { + pub selected: PathBuf, + pub bytes: u64, + pub is_dir: bool, + /// Why it is treated as a cache. None for an ordinary path. + pub hint: Option, + pub owner: Option, + /// Indices into [`Prepared::operations`]; empty when none can run. + pub operations: Vec, + /// Why the owner's command is not offered, or is only partly offered. + pub issue: Option, + /// What Delete files means, when it is offered. + pub delete: Option, + /// Why Delete files is not offered. + pub delete_issue: Option, +} + +impl Proposal { + pub const fn allows(&self, decision: Decision) -> bool { + match decision { + Decision::Skip => true, + Decision::Owner => !self.operations.is_empty(), + Decision::DeleteFiles => self.delete.is_some(), + } + } +} + +/// Command outcome and volume observations are independent of allocation. +/// Even a failed/cancelled command can have changed the cache already. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Report { + pub action: Action, + pub owner: Option, + /// An owner step's actual scope; otherwise the selected path. + pub path: PathBuf, + pub outcome: Outcome, + pub problem: Option, + pub error: Option, + pub scope_allocation_at_preview: u64, + pub available_before: Option, + pub available_after: Option, + pub observed_change: Option, +} + +impl Report { + /// A few words on how this step ended, for a list of results. + pub const fn outcome_label(&self) -> &'static str { + match (self.action, self.outcome) { + (_, Outcome::Skipped) => "skipped by you", + (_, Outcome::NotReached) => "not reached", + (_, Outcome::Cancelled) => "cancelled; may be partly done", + (_, Outcome::Failed) => "failed", + (Action::Owner, Outcome::Succeeded) => "command succeeded", + (Action::Trash, Outcome::Succeeded) => "moved to Trash", + (_, Outcome::Succeeded) => "deleted", + } + } + + #[allow( + clippy::unnecessary_debug_formatting, + reason = "Reports must expose path control characters" + )] + pub fn description(&self) -> String { + let who = self.owner.map_or("", Owner::label); + let what = match (self.action, self.outcome) { + (_, Outcome::Skipped) => { + "skipped by the person; nothing ran".to_string() + } + (_, Outcome::NotReached) => "not reached; nothing ran".to_string(), + (Action::Owner, Outcome::Succeeded) => { + "owner command exited successfully".to_string() + } + (Action::Trash, Outcome::Succeeded) => { + "files moved to Trash".to_string() + } + (Action::Permanent, Outcome::Succeeded) => { + "files deleted permanently".to_string() + } + (_, Outcome::Cancelled) => { + "cancelled; it may have done part of its work".to_string() + } + (_, _) => "failed".to_string(), + }; + let mut text = + format!("{} {who} {:?}: {what}.", self.action.label(), self.path); + if let Some(error) = &self.error { + let problem = self.problem.map_or("error", Problem::label); + let _ = write!(text, " {problem}: {error}."); + } + if matches!(self.outcome, Outcome::Skipped | Outcome::NotReached) { + return text; + } + let _ = write!( + text, + " Scope allocation at preview: {} bytes (not savings). Volume available before: {:?}; after: {:?}; observed change: {:?} bytes. Other activity can change this measurement; open files, hardlinks, APFS clones and snapshots can retain blocks.", + self.scope_allocation_at_preview, + self.available_before, + self.available_after, + self.observed_change + ); + if self.action == Action::Owner && self.outcome != Outcome::Succeeded { + text.push_str(" Nothing else was deleted. Deleting these files instead needs its own choice in a new review."); + } + text + } + + fn of( + action: Action, + owner: Option, + path: &Path, + bytes: u64, + before: Option, + after: Option, + outcome: Result<(), &Issue>, + ) -> Self { + let observed_change = before.zip(after).map(|(before, after)| { + i64::try_from(i128::from(after) - i128::from(before)).unwrap_or({ + if after >= before { i64::MAX } else { i64::MIN } + }) + }); + let (outcome, problem, error) = match outcome { + Ok(()) => (Outcome::Succeeded, None, None), + Err(issue) => ( + if issue.problem == Problem::Cancelled { + Outcome::Cancelled + } else { + Outcome::Failed + }, + Some(issue.problem), + Some(issue.detail.clone()), + ), + }; + Self { + action, + owner, + path: path.to_owned(), + outcome, + problem, + error, + scope_allocation_at_preview: bytes, + available_before: before, + available_after: after, + observed_change, + } + } +} + +/// Prepared on a worker. The environment is captured and replayed so an +/// approved invocation cannot silently acquire different configuration. +#[derive(Clone, Debug)] +pub struct Prepared { + pub proposals: Vec, + /// Commands that resolved and passed every scope check, by scope. + pub operations: Vec, + /// Each operation's whole scope, measured at preview. + pub scope_bytes: Vec, + pub root: PathBuf, + environment: Environment, + identities: Vec, +} + +#[derive(Clone, Debug)] +pub(crate) struct Environment { + pub home: PathBuf, + pub variables: BTreeMap, +} + +impl Environment { + fn current() -> Result { + let mut variables: BTreeMap<_, _> = std::env::vars_os() + .map(|(key, value)| { + Ok((key.into_string().map_err(|_| "Non-UTF-8 environment keys are unsupported for cleanup")?, + value.into_string().map_err(|_| "Non-UTF-8 environment values are unsupported for cleanup")?)) + }).collect::>()?; + if let Some(path) = variables.get_mut("PATH") { + *path = std::env::join_paths( + std::env::split_paths(path) + .filter(|directory| directory.is_absolute()), + ) + .map_err(|error| error.to_string())? + .into_string() + .map_err(|_| "Non-UTF-8 executable PATH is unsupported")?; + } + Ok(Self { + home: std::env::home_dir() + .ok_or("Cannot identify this user's home")?, + variables, + }) + } +} + +pub(crate) trait Probe { + fn executable( + &mut self, + name: &str, + env: &Environment, + ) -> Result; + fn output( + &mut self, + command: &Command, + env: &Environment, + ) -> Result; +} + +/// Read-only resolution, best effort per marked path. No cleanup command +/// runs and nothing is deleted until a separately confirmed worker starts. +pub fn prepare(targets: &[Target], root: &Path) -> Result { + let environment = Environment::current()?; + prepare_with(targets, root, environment, &mut process::SystemProbe) + .map(where_checkable) +} + +/// [`prepare`] with `path` as the only place owners are looked for, for +/// checking against a known set of executables, such as test fixtures. +/// Execution replays the same environment, so it uses them too. +pub fn prepare_on_path( + targets: &[Target], + root: &Path, + path: &str, +) -> Result { + let mut environment = Environment::current()?; + environment.variables.insert("PATH".into(), path.into()); + prepare_with(targets, root, environment, &mut process::SystemProbe) + .map(where_checkable) +} + +/// Delete files is checked for programs using the path right before it +/// runs. Where that check is unavailable the step would always be refused, +/// so it is not offered at all rather than offered and then failed. +fn where_checkable(mut prepared: Prepared) -> Prepared { + if !process::ACTIVE_USE_CHECKED { + for proposal in &mut prepared.proposals { + if proposal.delete.take().is_some() { + proposal.delete_issue = Some(Issue::new( + Problem::Refused, + "Delete files needs PwrDisk's check for programs using \ + the path, which runs only on macOS and Linux", + )); + } + } + } + prepared +} + +fn prepare_with( + targets: &[Target], + root: &Path, + environment: Environment, + probe: &mut impl Probe, +) -> Result { + if targets.is_empty() { + return Err("Nothing is marked".into()); + } + let selection = crate::removal::plan(targets, root); + let mut operations: Vec = Vec::new(); + let mut proposals = Vec::with_capacity(targets.len()); + for target in targets { + let hinted = recognize::hinted(&target.path, &environment); + let mut proposal = Proposal { + selected: target.path.clone(), + bytes: target.bytes, + is_dir: target.is_dir, + hint: recognize::inspection_with(&target.path, &environment), + owner: hinted.as_ref().map(|(owner, _)| *owner), + operations: vec![], + issue: None, + delete: None, + delete_issue: None, + }; + if let Some(blocked) = selection + .blocked + .iter() + .find(|blocked| blocked.path == target.path) + { + let issue = Issue::new(Problem::Refused, blocked.reason.clone()); + proposal.issue = Some(issue.clone()); + proposal.delete_issue = Some(issue); + proposals.push(proposal); + continue; + } + match resolve(&target.path, hinted.as_ref(), &environment, probe) { + Ok(found) => { + for operation in found { + proposal.owner.get_or_insert(operation.owner); + let index = if let Some(index) = operations + .iter() + .position(|existing| existing.scope == operation.scope) + { + operations[index].selected.push(target.path.clone()); + index + } else { + operations.push(operation); + operations.len() - 1 + }; + proposal.operations.push(index); + } + } + Err(issue) => proposal.issue = Some(issue), + } + proposals.push(proposal); + } + + // Every operation is checked on its own; a failure is reported on the + // proposals that asked for it and leaves the others offered. + let mut failures: Vec> = vec![None; operations.len()]; + let mut order: Vec = (0..operations.len()).collect(); + order.sort_by(|left, right| { + operations[*left].scope.cmp(&operations[*right].scope) + }); + // Overlapping commands would make both consent and byte accounting + // ambiguous. npm's sibling scopes intentionally do not overlap. + for pair in order.windows(2) { + if operations[pair[1]] + .scope + .starts_with(&operations[pair[0]].scope) + { + for index in pair { + failures[*index] = Some(Issue::new( + Problem::Refused, + "Overlapping owner cleanup scopes; review them separately", + )); + } + } + } + let mut checked = vec![None; operations.len()]; + for (index, operation) in operations.iter().enumerate() { + if failures[index].is_none() { + match check_scope(operation, root) { + Ok(result) => checked[index] = Some(result), + Err(issue) => failures[index] = Some(issue), + } + } + } + let mut remap = vec![None; operations.len()]; + let mut kept = Vec::new(); + let mut scope_bytes = Vec::new(); + let mut identities = Vec::new(); + for index in order { + if let Some((bytes, identity)) = checked[index].take() { + remap[index] = Some(kept.len()); + kept.push(operations[index].clone()); + scope_bytes.push(bytes); + identities.push(identity); + } + } + for proposal in &mut proposals { + let failed = proposal + .operations + .iter() + .find_map(|index| failures[*index].clone()); + proposal.operations = proposal + .operations + .iter() + .filter_map(|index| remap[*index]) + .collect(); + if proposal.issue.is_none() { + proposal.issue = failed; + } + if proposal.delete_issue.is_none() { + match disclose(proposal, &environment) { + Ok(disclosure) => proposal.delete = Some(disclosure), + Err(issue) => proposal.delete_issue = Some(issue), + } + } + } + Ok(Prepared { + proposals, + operations: kept, + scope_bytes, + root: root.to_owned(), + environment, + identities, + }) +} + +/// An owner's whole scope must pass the same guards as any removal, stay +/// on one volume without external links, and be measurable. +fn check_scope( + operation: &Operation, + root: &Path, +) -> Result<(u64, process::Identity), Issue> { + let refused = |detail: String| Issue::new(Problem::Refused, detail); + let scope = Target { + path: operation.scope.clone(), + bytes: 0, + is_dir: true, + hidden: false, + }; + let plan = crate::removal::plan(std::slice::from_ref(&scope), root); + if let Some(blocked) = plan.blocked.first() { + return Err(refused(format!( + "Actual owner scope fails removal guards: {}", + blocked.reason + ))); + } + if plan.targets.len() != 1 { + return Err(refused("Actual owner scope fails removal guards".into())); + } + process::check_tree(&operation.scope).map_err(refused)?; + let bytes = crate::removal_limit::measured(&plan.targets) + .map_err(refused)? + .first() + .map_or(0, |target| target.bytes); + let identity = process::Identity::read(&operation.command.executable) + .map_err(|detail| Issue::new(Problem::NotFound, detail))?; + Ok((bytes, identity)) +} + +/// What Delete files means for this path. Never "safe": an unknown cache is +/// said to be unknown, and a recognized one is said to bypass its owner. +fn disclose( + proposal: &Proposal, + env: &Environment, +) -> Result { + let contains = recognize::contained(&proposal.selected, env) + .map_err(|detail| Issue::new(Problem::Refused, detail))?; + let warning = match (proposal.owner, &proposal.hint) { + (Some(owner), _) => format!( + "Deletes exactly this path and its contents directly; the {} is not involved. Anything it expects to find there must be downloaded or rebuilt, and installed environments that link into it can break until reinstalled.", + owner.label() + ), + (None, Some(_)) => "No verified owner: PwrDisk does not know that this is disposable. It may be installed runtime or application state, and software that needs it can break. Inspect it before choosing this.".to_owned(), + (None, None) => "Not recognized as a cache. Deletes exactly this path and its contents, as any other marked path.".to_owned(), + }; + Ok(Disclosure { + path: proposal.selected.clone(), + contains, + warning, + }) +} + +#[allow( + clippy::unnecessary_debug_formatting, + reason = "Safety errors quote selected paths including controls" +)] +fn resolve( + path: &Path, + hint: Option<&(Owner, PathBuf)>, + env: &Environment, + probe: &mut impl Probe, +) -> Result, Issue> { + if let Some(reason) = hint.and_then(|(owner, _)| owner.unsupported()) { + return Err(Issue::new(Problem::NoCommand, reason)); + } + // Probe all supported owners for nonstandard roots configured in user + // settings. A name is insufficient, and a default path is not authority. + let owners = hint.map_or_else( + || { + vec![ + Owner::Npm, + Owner::Npx, + Owner::Uv, + Owner::Pip, + Owner::Cypress, + ] + }, + |(owner, _)| vec![*owner], + ); + let mut failures = Vec::new(); + let mut found = Vec::new(); + for owner in owners { + match resolve_owner(owner, path, env, probe) { + Ok(Some(operation)) => found.push(operation), + Ok(None) => {} + Err(issue) => failures.push(Issue::new( + issue.problem, + format!("{}: {}", owner.label(), issue.detail), + )), + } + } + if !found.is_empty() { + if found.iter().any(|operation| { + operation.owner == Owner::Npm + && operation.cache_root == path + && operation.cache_root.join("_npx").is_dir() + }) && !found.iter().any(|operation| operation.owner == Owner::Npx) + { + return Err(Issue::new( + Problem::NoCommand, + format!( + "The npm wrapper also contains an npx cache without a supported cleanup command. Select _cacache explicitly or inspect with a supported npm version. {}", + failures + .iter() + .map(|issue| issue.detail.as_str()) + .collect::>() + .join("; ") + ), + )); + } + return Ok(found); + } + if let Some((owner, _)) = hint { + // The one owner asked either failed, which says why, or reported + // a configured cache elsewhere, which is never redirected to. + return Err(failures.into_iter().next().unwrap_or_else(|| { + Issue::new( + Problem::NotConfiguredCache, + format!( + "The {}'s configured cache is elsewhere, so its command would not clean {path:?}. Inspect it.", + owner.label() + ), + ) + })); + } + Err(Issue::new( + Problem::UnknownOwner, + format!( + "No supported owner cleanup resolves to {:?}. Inspect the cache and its owning installation. Software may be installed outside PwrDisk's PATH; an unavailable command does not prove it is absent. {}", + path, + failures + .iter() + .map(|issue| issue.detail.as_str()) + .collect::>() + .join("; ") + ), + )) +} + +fn resolve_owner( + owner: Owner, + selected: &Path, + env: &Environment, + probe: &mut impl Probe, +) -> Result, Issue> { + let executable = probe.executable(owner.executable(), env)?; + let mut command = Command { + executable, + arguments: vec![], + environment: BTreeMap::new(), + working_directory: env.home.clone(), + }; + // npm rotates logs even with logs-max=0. Sending the log directory to + // a non-directory prevents that unapproved side effect for probes and + // cleanup alike. pip's configured log file is similarly overridden. + if owner == Owner::Pip { + command.environment.extend([ + ("PIP_LOG".into(), "/dev/null".into()), + ("PIP_DISABLE_PIP_VERSION_CHECK".into(), "1".into()), + ("PIP_NO_INPUT".into(), "1".into()), + ]); + } + if matches!(owner, Owner::Npm | Owner::Npx) { + command.environment.extend([ + ("npm_config_logs_dir".into(), "/dev/null".into()), + ("npm_config_logs_max".into(), "0".into()), + ("npm_config_update_notifier".into(), "false".into()), + ("npm_config_timing".into(), "false".into()), + ]); + } + if owner == Owner::Uv + && env + .variables + .get("UV_LINK_MODE") + .is_some_and(|mode| mode == "symlink") + { + return Err(Issue::new( + Problem::Refused, + "UV_LINK_MODE=symlink couples installed environments to this cache; inspect with uv before cleanup", + )); + } + let version_args = if owner == Owner::Cypress { + vec!["version", "--component", "package"] + } else { + vec!["--version"] + }; + command.arguments = strings(&version_args); + let version = probe + .output(&command, env) + .map_err(|detail| Issue::new(Problem::VersionCheckFailed, detail))? + .trim() + .to_owned(); + supported_version(owner, &version) + .map_err(|detail| Issue::new(Problem::UnsupportedVersion, detail))?; + let inspection_only = + || Issue::new(Problem::NoCommand, "Owner is inspection-only"); + command.arguments = strings(match owner { + Owner::Npm | Owner::Npx => &["config", "get", "cache"], + Owner::Uv | Owner::Pip => &["cache", "dir"], + Owner::Cypress => &["cache", "path"], + _ => return Err(inspection_only()), + }); + let output = probe + .output(&command, env) + .map_err(|detail| Issue::new(Problem::ConfigCheckFailed, detail))?; + let config = |detail: &str| Issue::new(Problem::ConfigCheckFailed, detail); + // Remove the CLI's line terminator, never whitespace that can be part + // of a real directory name. Guessing here can select a different tree. + // The supported Unix adapters emit LF. A CR is ambiguous with a + // literal path character, so refuse it rather than guess at CRLF. + let value = output.strip_suffix('\n').unwrap_or(&output); + let cache_root = PathBuf::from(value); + if !cache_root.is_absolute() || value.contains('\n') || value.contains('\r') + { + return Err(config( + "Owner returned an ambiguous or relative cache root", + )); + } + if cache_root + .components() + .any(|component| matches!(component, std::path::Component::ParentDir)) + { + return Err(config( + "Owner cache root contains parent traversal; inspect its absolute configured path", + )); + } + let scope = match owner { + Owner::Npm => cache_root.join("_cacache"), + Owner::Npx => cache_root.join("_npx"), + _ => cache_root.clone(), + }; + // Never redirect an old/default cache selection into the active cache + // elsewhere. Also never interpret the npm wrapper as just one cache. + let npm_wrapper = matches!(owner, Owner::Npm | Owner::Npx) + && selected == cache_root + && scope.is_dir(); + if !selected.starts_with(&scope) && !npm_wrapper { + return Ok(None); + } + let root_arg = cache_root + .to_str() + .ok_or_else(|| config("Non-UTF-8 cache roots are unsupported"))? + .to_owned(); + command.arguments = match owner { + Owner::Npm => vec![ + "cache".into(), + "clean".into(), + "--force".into(), + "--cache".into(), + root_arg, + ], + Owner::Npx => vec![ + "cache".into(), + "npx".into(), + "rm".into(), + "--force".into(), + "--cache".into(), + root_arg, + ], + Owner::Uv => vec![ + "cache".into(), + "clean".into(), + "--cache-dir".into(), + root_arg, + ], + Owner::Pip => vec![ + "--cache-dir".into(), + root_arg, + "cache".into(), + "purge".into(), + ], + Owner::Cypress => { + command + .environment + .insert("CYPRESS_CACHE_FOLDER".into(), root_arg); + strings(&["cache", "clear"]) + } + _ => return Err(inspection_only()), + }; + let effects = match owner { + Owner::Npm => { + "Clears the entire npm package cache (_cacache); does not clear the separate npx cache. Later installs may download packages again." + } + Owner::Npx => { + "Clears the entire npx execution cache (_npx); does not clear npm's package cache. Cached npx environments must be downloaded/recreated." + } + Owner::Uv => { + "Clears all uv cache entries, preserving uv's lock protocol. Later operations may download/build again. Environments installed with symlink link mode can break; inspect that configuration before approval." + } + Owner::Pip => { + "Purges pip's HTTP and wheel caches. Later installs may download/build again; other files in the cache root may remain." + } + Owner::Cypress => { + "Removes ALL cached Cypress binary versions, including versions other projects use. Tests require reinstalling their matching binary." + } + _ => "", + }; + Ok(Some(Operation { + owner, + version, + selected: vec![selected.to_owned()], + cache_root, + scope, + command, + effects: effects.into(), + limitations: OWNER_LIMITATIONS.into(), + })) +} + +/// What every owner command shares, whatever its owner. +const OWNER_LIMITATIONS: &str = "The command acts on the WHOLE scope, including unselected siblings. Listed allocation is an upper bound, not promised savings. Other activity, open files, hardlinks, APFS clones and snapshots can retain blocks. Active-use detection is best effort; stop the owning tools first. PwrDisk rescans afterwards. If it fails, nothing else is deleted."; + +fn strings(items: &[&str]) -> Vec { + items.iter().map(|item| (*item).to_owned()).collect() +} + +fn supported_version(owner: Owner, output: &str) -> Result<(), String> { + let text = match owner { + Owner::Uv => output.strip_prefix("uv "), + Owner::Pip => output.strip_prefix("pip "), + _ => Some(output), + } + .and_then(|text| text.split_whitespace().next()) + .ok_or("Unrecognized version output")?; + let parts: Vec<_> = text + .split('.') + .map(str::parse::) + .collect::>() + .map_err(|_| "Prerelease or unrecognized version is unsupported")?; + let supported = match (owner, parts.as_slice()) { + (Owner::Npm, [major, _, _]) => (9..=11).contains(major), + (Owner::Npx, [11, minor, _]) => *minor >= 2, + (Owner::Uv, [0, minor, _]) => *minor == 11, + (Owner::Pip, [major, ..]) => (23..=26).contains(major), + (Owner::Cypress, [major, _, _]) => (13..=15).contains(major), + _ => false, + }; + let runs = match owner { + Owner::Npm => "npm 9 to 11", + Owner::Npx => "npm 11.2 or later 11.x", + Owner::Uv => "uv 0.11.x", + Owner::Pip => "pip 23 to 26", + Owner::Cypress => "Cypress 13 to 15", + _ => "no version", + }; + if supported { + Ok(()) + } else { + Err(format!( + "{} {text} is not a version PwrDisk runs ({runs}). Update it, or clean it with the owner yourself", + owner.label() + )) + } +} + +/// Confirmation phrases, one per combination of the two intents. Owner +/// cleanup and deleting files are confirmed separately and named apart. +pub const RUN_OWNER_CLEANUP: &str = "RUN OWNER CLEANUP"; +pub const DELETE_CACHE_FILES: &str = "DELETE CACHE FILES"; +pub const TRASH_CACHE_FILES: &str = "TRASH CACHE FILES"; +pub const RUN_AND_DELETE: &str = "RUN OWNER CLEANUP AND DELETE CACHE FILES"; +pub const RUN_AND_TRASH: &str = "RUN OWNER CLEANUP AND TRASH CACHE FILES"; +pub const CONFIRMATIONS: [&str; 5] = [ + RUN_OWNER_CLEANUP, + DELETE_CACHE_FILES, + TRASH_CACHE_FILES, + RUN_AND_DELETE, + RUN_AND_TRASH, +]; + +impl Prepared { + #[allow( + clippy::unnecessary_debug_formatting, + reason = "Consent must expose path control characters" + )] + pub fn proposal_description(&self, index: usize) -> String { + let Some(proposal) = self.proposals.get(index) else { + return String::new(); + }; + let mut text = format!( + "{}. {:?} ({} bytes)", + index + 1, + proposal.selected, + proposal.bytes + ); + if let Some(hint) = &proposal.hint { + let _ = write!(text, "\n Treated as a cache: {hint}"); + } + for operation in &proposal.operations { + if let Some(operation) = self.operations.get(*operation) { + text.push_str("\n Owner command (choose owner):\n "); + text.push_str(&operation.description().replace('\n', "\n ")); + } + } + if let Some(issue) = &proposal.issue { + let _ = write!( + text, + "\n Owner command {}: {}", + if proposal.operations.is_empty() { + "unavailable" + } else { + "partly unavailable" + }, + issue.description() + ); + } + match (&proposal.delete, &proposal.delete_issue) { + (Some(disclosure), _) => { + let _ = write!( + text, + "\n Delete files (choose delete_files): {}", + disclosure.description(Action::Skip) + ); + } + (None, Some(issue)) => { + let _ = write!( + text, + "\n Delete files unavailable: {}", + issue.description() + ); + } + (None, None) => {} + } + text + } + + /// Every proposal, for the window's caption and an agent's preview. + pub fn description(&self) -> String { + (0..self.proposals.len()) + .map(|index| self.proposal_description(index)) + .collect::>() + .join("\n\n") + } + + /// An agent names a decision per path; map them onto the proposals. + /// Every marked path must be named exactly once, so nothing is decided + /// by omission or by an ambiguous duplicate. + pub fn decisions_for( + &self, + named: &[(PathBuf, Decision)], + ) -> Result, String> { + let mut decisions = vec![None; self.proposals.len()]; + for (path, decision) in named { + let index = self + .proposals + .iter() + .position(|proposal| proposal.selected == *path) + .ok_or_else(|| { + format!("{} is not a marked path", path.display()) + })?; + if decisions[index].replace(*decision).is_some() { + return Err(format!( + "{} is named more than once", + path.display() + )); + } + } + decisions + .into_iter() + .zip(&self.proposals) + .map(|(decision, proposal)| { + decision.ok_or_else(|| { + format!( + "Choose skip, owner or delete_files for {}", + proposal.selected.display() + ) + }) + }) + .collect() + } + + /// Turn the person's decisions into the steps to run. Refuses any + /// choice the proposal did not offer, and any pair of choices that + /// would act on the same files twice or on a path left on Skip. + pub fn approve( + &self, + decisions: &[Decision], + files: Action, + ) -> Result { + if decisions.len() != self.proposals.len() { + return Err("Choose an action for every marked path".into()); + } + if !matches!(files, Action::Trash | Action::Permanent) + && decisions.contains(&Decision::DeleteFiles) + { + return Err( + "Delete files needs Trash or permanent deletion chosen".into(), + ); + } + let mut owners: Vec = Vec::new(); + let mut raw = Vec::new(); + for (proposal, decision) in self.proposals.iter().zip(decisions) { + if !proposal.allows(*decision) { + return Err(format!( + "{} cannot be chosen for {}", + match decision { + Decision::Owner => "An owner command", + Decision::DeleteFiles => "Delete files", + Decision::Skip => "Skip", + }, + proposal.selected.display() + )); + } + match decision { + Decision::Owner => { + for index in &proposal.operations { + if !owners.contains(index) { + owners.push(*index); + } + } + } + Decision::DeleteFiles => raw.push(Target { + path: proposal.selected.clone(), + bytes: proposal.bytes, + is_dir: proposal.is_dir, + hidden: false, + }), + Decision::Skip => {} + } + } + owners.sort_unstable(); + // Paths each action reaches. A path left on Skip, or given another + // action, must not overlap one: Skip means nothing happens to it. + let reached: Vec<(&Path, Decision)> = + owners + .iter() + .map(|index| { + (self.operations[*index].scope.as_path(), Decision::Owner) + }) + .chain(raw.iter().map(|target| { + (target.path.as_path(), Decision::DeleteFiles) + })) + .collect(); + for (proposal, decision) in self.proposals.iter().zip(decisions) { + for (path, action) in &reached { + // Either way round: an action inside a skipped path changes + // it too, and so does one around it. + let overlaps = proposal.selected.starts_with(path) + || path.starts_with(&proposal.selected); + if overlaps && *decision != *action { + return Err(format!( + "{} is inside what another choice acts on ({}); choose the same action for both", + proposal.selected.display(), + path.display() + )); + } + } + } + let raw_plan = crate::removal::plan(&raw, &self.root); + if let Some(blocked) = raw_plan.blocked.first() { + return Err(format!( + "{}: {}", + blocked.path.display(), + blocked.reason + )); + } + let mut steps = Vec::new(); + let mut targets = Vec::new(); + for index in &owners { + steps.push(Step::Owner(*index)); + targets.push(Target { + path: self.operations[*index].scope.clone(), + bytes: self.scope_bytes[*index], + is_dir: true, + hidden: false, + }); + } + for target in raw_plan.targets { + let proposal = self + .proposals + .iter() + .position(|proposal| { + crate::removal::normalize(&proposal.selected) == target.path + }) + .ok_or("Delete files lost track of a chosen path")?; + steps.push(Step::Files { + proposal, + action: files, + }); + targets.push(target); + } + if steps.is_empty() { + return Err("Nothing chosen: every marked path is skipped".into()); + } + let skipped = self + .proposals + .iter() + .zip(decisions) + .filter(|(_, decision)| **decision == Decision::Skip) + .map(|(proposal, _)| Report { + action: Action::Skip, + owner: proposal.owner, + path: proposal.selected.clone(), + outcome: Outcome::Skipped, + problem: proposal.issue.as_ref().map(|issue| issue.problem), + error: proposal + .issue + .as_ref() + .map(|issue| issue.detail.clone()), + scope_allocation_at_preview: 0, + available_before: None, + available_after: None, + observed_change: None, + }) + .collect(); + // Planned whole so the run shows guards and volumes as any removal + // does; the steps above were already checked not to overlap. + let plan = crate::removal::plan(&targets, &self.root); + if plan.targets.len() != targets.len() || !plan.blocked.is_empty() { + return Err("Chosen actions fail removal guards".into()); + } + let steps = plan + .targets + .iter() + .map(|target| { + targets + .iter() + .position(|chosen| { + crate::removal::normalize(&chosen.path) == target.path + }) + .map(|index| steps[index]) + .ok_or("Chosen actions lost track of a path") + }) + .collect::>()?; + Ok(Approved { + prepared: self.clone(), + decisions: decisions.to_vec(), + files, + steps, + plan, + skipped, + }) + } + + /// Re-probe against the captured environment right before this + /// command, then recheck its scope and whether its owner is running. + pub(crate) fn preflight_operation( + &self, + index: usize, + ) -> Result<(), Issue> { + let changed = |detail: &str| Issue::new(Problem::Changed, detail); + let operation = self + .operations + .get(index) + .ok_or_else(|| changed("Missing owner operation"))?; + let identity = + process::Identity::read(&operation.command.executable) + .map_err(|detail| Issue::new(Problem::Changed, detail))?; + if self.identities.get(index) != Some(&identity) { + return Err(changed( + "Owner executable changed after preview; obtain new approval", + )); + } + let fresh = resolve_owner( + operation.owner, + &operation.scope, + &self.environment, + &mut process::SystemProbe, + ) + .map_err(|issue| { + Issue::new(issue.problem, format!("Since the preview: {}", issue.detail)) + })? + .ok_or_else(|| { + changed("Configured cache root changed after preview; obtain new approval") + })?; + if fresh.command != operation.command + || fresh.version != operation.version + || fresh.scope != operation.scope + { + return Err(changed( + "Owner command, version or cache scope changed; obtain new approval", + )); + } + process::check_tree(&operation.scope) + .map_err(|detail| Issue::new(Problem::Refused, detail))?; + process::check_active(operation) + .map_err(|detail| Issue::new(Problem::InUse, detail)) + } + + /// Runs only the allowlisted command. A failure never calls a remover, + /// even when the owner partially changed the cache. + pub(crate) fn execute( + &self, + index: usize, + cancel: &AtomicBool, + ) -> Result<(), Issue> { + let operation = self.operations.get(index).ok_or_else(|| { + Issue::new(Problem::Changed, "Missing owner operation") + })?; + process::run( + &operation.command, + &self.environment, + cancel, + std::time::Duration::from_mins(10), + ) + .map(|_| ()) + } +} + +/// One step of an approved cleanup. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Step { + /// Index into [`Prepared::operations`]. + Owner(usize), + /// Delete one proposal's exact selected path directly. + Files { proposal: usize, action: Action }, +} + +/// The person's decisions, turned into steps aligned with `plan.targets`. +/// Carried intact to the removal worker, which checks each step again. +#[derive(Clone, Debug)] +pub struct Approved { + pub prepared: Prepared, + pub decisions: Vec, + /// How Delete files removes: Trash or permanently. + pub files: Action, + pub steps: Vec, + pub plan: Plan, + /// Proposals left on Skip, reported so every path has a result. + pub skipped: Vec, +} + +impl Approved { + pub fn action(&self, index: usize) -> Action { + match self.steps.get(index) { + Some(Step::Owner(_)) => Action::Owner, + Some(Step::Files { action, .. }) => *action, + None => Action::Skip, + } + } + + pub fn owner_steps(&self) -> usize { + self.steps + .iter() + .filter(|step| matches!(step, Step::Owner(_))) + .count() + } + + pub fn file_steps(&self) -> usize { + self.steps.len() - self.owner_steps() + } + + /// The text that confirms exactly these intents, and no others. + pub fn confirmation(&self) -> &'static str { + match (self.owner_steps() > 0, self.file_steps() > 0, self.files) { + (true, false, _) => RUN_OWNER_CLEANUP, + (false, true, Action::Trash) => TRASH_CACHE_FILES, + (false, _, _) => DELETE_CACHE_FILES, + (true, true, Action::Trash) => RUN_AND_TRASH, + (true, true, _) => RUN_AND_DELETE, + } + } + + /// Everything the person confirms: each command verbatim, each path + /// deleted directly with what that means, and what is left alone. + #[allow( + clippy::unnecessary_debug_formatting, + reason = "Consent must expose path control characters" + )] + pub fn description(&self) -> String { + let mut text = String::new(); + if self.owner_steps() > 0 { + let _ = writeln!( + text, + "Run owner commands ({}), exactly as shown:", + self.owner_steps() + ); + for step in &self.steps { + if let Step::Owner(index) = step + && let Some(operation) = + self.prepared.operations.get(*index) + { + text.push_str(&operation.description()); + text.push_str("\n\n"); + } + } + } + if self.file_steps() > 0 { + let _ = writeln!( + text, + "Delete files directly, not through their owner ({}) \u{2014} {}:", + self.file_steps(), + self.files.label() + ); + for step in &self.steps { + if let Step::Files { proposal, action } = step + && let Some(proposal) = + self.prepared.proposals.get(*proposal) + && let Some(disclosure) = &proposal.delete + { + let _ = writeln!( + text, + "{} ({})", + disclosure.description(*action), + crate::size::human_bytes(proposal.bytes) + ); + } + } + text.push('\n'); + } + if !self.skipped.is_empty() { + let _ = + writeln!(text, "Nothing happens to ({}):", self.skipped.len()); + for report in &self.skipped { + let _ = writeln!(text, "{:?}", report.path); + } + } + text.trim_end().to_owned() + } + + /// Re-measure each step on the worker. A path that can no longer be + /// measured is refused alone; past the capacity limit the whole run is. + pub(crate) fn admit( + &self, + limit: &crate::removal_limit::Ceilings, + ) -> Result>, String> { + let mut refusals = vec![None; self.plan.targets.len()]; + let mut measured = Vec::new(); + for (index, target) in self.plan.targets.iter().enumerate() { + match crate::removal_limit::measured(std::slice::from_ref(target)) { + Ok(mut fresh) => measured.append(&mut fresh), + Err(reason) => { + refusals[index] = + Some(Issue::new(Problem::Refused, reason)); + } + } + } + limit.check(&measured)?; + Ok(refusals) + } + + /// Checked again right before the step: an owner's command, version, + /// executable and scope; for direct deletion, whether it is in use. + pub(crate) fn preflight(&self, index: usize) -> Result<(), Issue> { + match self.steps.get(index) { + Some(Step::Owner(operation)) => { + self.prepared.preflight_operation(*operation) + } + Some(Step::Files { proposal, .. }) => { + let proposal = &self.prepared.proposals[*proposal]; + process::check_path_active(&proposal.selected, proposal.owner) + .map_err(|detail| Issue::new(Problem::InUse, detail)) + } + None => Err(Issue::new(Problem::Changed, "Missing cleanup step")), + } + } + + pub(crate) fn report( + &self, + index: usize, + before: Option, + after: Option, + outcome: Result<(), &Issue>, + ) -> Report { + let (owner, path, bytes) = match self.steps.get(index) { + Some(Step::Owner(operation)) => { + let operation = &self.prepared.operations[*operation]; + ( + Some(operation.owner), + operation.scope.clone(), + self.plan + .targets + .get(index) + .map_or(0, |target| target.bytes), + ) + } + Some(Step::Files { proposal, .. }) => { + let proposal = &self.prepared.proposals[*proposal]; + (proposal.owner, proposal.selected.clone(), proposal.bytes) + } + None => (None, PathBuf::new(), 0), + }; + Report::of( + self.action(index), + owner, + &path, + bytes, + before, + after, + outcome, + ) + } + + pub(crate) fn not_reached(&self, index: usize) -> Report { + let mut report = self.report(index, None, None, Ok(())); + report.outcome = Outcome::NotReached; + report + } +} diff --git a/crates/disktree-core/src/cleanup/process.rs b/crates/disktree-core/src/cleanup/process.rs new file mode 100644 index 00000000..9d75010a --- /dev/null +++ b/crates/disktree-core/src/cleanup/process.rs @@ -0,0 +1,503 @@ +//! Bounded, cancellable direct process invocation. Never invokes a shell or +//! downloads a missing CLI. Full output is drained but only a prefix retained. + +use std::io::Read as _; +use std::path::{Path, PathBuf}; +use std::process::{Command as Process, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc; +use std::time::{Duration, Instant, SystemTime}; + +use super::{Command, Environment, Issue, Operation, Owner, Probe, Problem}; + +const OUTPUT_LIMIT: u64 = 64 * 1024; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct Identity { + length: u64, + modified: SystemTime, +} + +impl Identity { + pub(super) fn read(path: &Path) -> Result { + let meta = std::fs::metadata(path).map_err(|error| { + format!("Owner executable unavailable: {error}") + })?; + if !meta.is_file() { + return Err("Owner executable is not a file".into()); + } + Ok(Self { + length: meta.len(), + modified: meta.modified().map_err(|error| error.to_string())?, + }) + } +} + +pub(super) struct SystemProbe; + +impl Probe for SystemProbe { + fn executable( + &mut self, + name: &str, + env: &Environment, + ) -> Result { + resolve_executable(name, env, 0) + } + + fn output( + &mut self, + command: &Command, + env: &Environment, + ) -> Result { + let output = run( + command, + env, + &AtomicBool::new(false), + Duration::from_secs(10), + ) + .map_err(|issue| issue.detail)?; + if output.len() as u64 >= OUTPUT_LIMIT { + Err("Owner probe output exceeded its bound".into()) + } else { + String::from_utf8(output).map_err(|_| "Owner probe returned non-UTF-8 output; cannot resolve an exact cache root".into()) + } + } +} + +#[allow( + clippy::unnecessary_debug_formatting, + reason = "Executable refusals must expose path controls" +)] +fn resolve_executable( + name: &str, + env: &Environment, + depth: usize, +) -> Result { + let launcher = + |detail: &str| Issue::new(Problem::UnsupportedLauncher, detail); + if depth > 4 { + return Err(launcher( + "Unsupported recursive CLI interpreter; expose the installed executable directly", + )); + } + // Windows .cmd launchers need a shell and have different quoting + // rules. Do not quietly run them through cmd.exe. + if cfg!(windows) { + return Err(launcher( + "Owner-command execution is currently supported on macOS and Linux; Windows launchers require a separate audited adapter", + )); + } + let candidates = if name == "pip" { + vec!["pip", "pip3"] + } else { + vec![name] + }; + for candidate in candidates { + for dir in std::env::split_paths( + env.variables.get("PATH").map_or("", String::as_str), + ) { + // Relative PATH entries could resolve a different project CLI. + if !dir.is_absolute() { + continue; + } + let path = dir.join(candidate); + if path.is_file() { + let resolved = + std::fs::canonicalize(&path).map_err(|error| { + Issue::new(Problem::NotFound, error.to_string()) + })?; + if is_shim(&path) || is_shim(&resolved) { + return Err(launcher( + "Version-manager shim unavailable for cleanup; expose the installed executable directly on PATH. PwrDisk does not auto-install missing tools", + )); + } + // npm's distributed CLI resolves to npm-cli.js. A proxy + // such as Corepack can download npm even for --version. + if name == "npm" + && resolved + .file_name() + .is_none_or(|name| name != "npm-cli.js") + { + return Err(launcher( + "npm proxy/wrapper launchers are unsupported; expose the installed npm-cli.js through its npm symlink on PATH", + )); + } + validate_interpreter(&resolved, env, depth)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + if std::fs::metadata(&path) + .map_err(|error| { + Issue::new(Problem::NotFound, error.to_string()) + })? + .permissions() + .mode() + & 0o111 + == 0 + { + return Err(Issue::new( + Problem::NotFound, + format!( + "Executable found but not executable: {path:?}" + ), + )); + } + } + return Ok(resolved); + } + } + } + Err(Issue::new( + Problem::NotFound, + format!( + "{name} command unavailable on PwrDisk's PATH (software may still be installed)" + ), + )) +} + +fn is_shim(path: &Path) -> bool { + path.components().any(|part| part.as_os_str() == "shims") + || path.file_name().is_some_and(|name| name == "volta-shim") + || path + .parent() + .and_then(Path::file_name) + .is_some_and(|name| name == "bin") + && path + .parent() + .and_then(Path::parent) + .and_then(Path::file_name) + .is_some_and(|name| name == ".volta") +} + +fn validate_interpreter( + path: &Path, + env: &Environment, + depth: usize, +) -> Result<(), Issue> { + let launcher = + |detail: &str| Issue::new(Problem::UnsupportedLauncher, detail); + // An npm or Cypress script can use env's node, which must not silently + // dispatch through a version manager that installs a runtime on demand. + let mut prefix = [0; 512]; + let length = std::fs::File::open(path) + .and_then(|mut file| file.read(&mut prefix)) + .map_err(|error| Issue::new(Problem::NotFound, error.to_string()))?; + let header = String::from_utf8_lossy(&prefix[..length]); + let Some(shebang) = header + .lines() + .next() + .and_then(|line| line.strip_prefix("#!")) + else { + return Ok(()); + }; + let words: Vec<_> = shebang.split_whitespace().collect(); + if words.first().is_some_and(|program| { + Path::new(program) + .file_name() + .is_some_and(|name| name == "env") + }) { + let [_, runtime] = words.as_slice() else { + return Err(launcher( + "Unsupported env interpreter arguments; expose a direct installed CLI", + )); + }; + resolve_executable(runtime, env, depth + 1)?; + } else if words + .first() + .is_some_and(|program| is_shim(Path::new(program))) + { + return Err(launcher( + "CLI interpreter is a version-manager shim; expose the installed runtime directly", + )); + } + Ok(()) +} + +pub(super) fn run( + command: &Command, + env: &Environment, + cancel: &AtomicBool, + timeout: Duration, +) -> Result, Issue> { + let failed = |detail: String| Issue::new(Problem::CommandFailed, detail); + if cancel.load(Ordering::Relaxed) { + return Err(Issue::new( + Problem::Cancelled, + "Cancelled before command start", + )); + } + let mut process = Process::new(&command.executable); + process + .args(&command.arguments) + .env_clear() + .envs(&env.variables) + .envs(&command.environment) + .current_dir(&command.working_directory) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + // Kill a subprocess group on cancellation, so a launcher cannot leave + // a cleaning child behind. Every supported adapter is Unix-only. + #[cfg(unix)] + { + use std::os::unix::process::CommandExt as _; + process.process_group(0); + } + let mut child = process.spawn().map_err(|error| { + Issue::new( + Problem::NotFound, + format!("Owner command could not start: {error}"), + ) + })?; + let stdout = child + .stdout + .take() + .ok_or_else(|| failed("Missing owner stdout".into()))?; + let stderr = child + .stderr + .take() + .ok_or_else(|| failed("Missing owner stderr".into()))?; + let read = |mut pipe: Box| { + let mut bytes = Vec::new(); + let result = (&mut pipe).take(OUTPUT_LIMIT).read_to_end(&mut bytes); + let _ = std::io::copy(&mut pipe, &mut std::io::sink()); + result.map(|_| bytes) + }; + let (out_send, out_recv) = mpsc::channel(); + let (err_send, err_recv) = mpsc::channel(); + std::thread::spawn(move || { + let _ = out_send.send(read(Box::new(stdout))); + }); + std::thread::spawn(move || { + let _ = err_send.send(read(Box::new(stderr))); + }); + let start = Instant::now(); + let mut status = None; + let mut output = None; + let mut errors = None; + loop { + if cancel.load(Ordering::Relaxed) || start.elapsed() >= timeout { + terminate(&mut child); + return Err(Issue::new( + Problem::Cancelled, + "Owner command cancelled or timed out; it may have partially cleaned the cache. Nothing else was deleted; inspect and preview again", + )); + } + if status.is_none() { + match child.try_wait() { + Ok(value) => status = value, + Err(error) => { + terminate(&mut child); + return Err(failed(format!( + "Cannot observe owner command: {error}" + ))); + } + } + } + if output.is_none() { + output = out_recv.try_recv().ok(); + } + if errors.is_none() { + errors = err_recv.try_recv().ok(); + } + if let (Some(status), Some(output), Some(errors)) = + (status, output.as_ref(), errors.as_ref()) + { + let errors = + errors.as_ref().map_err(|error| failed(error.to_string()))?; + if !status.success() { + return Err(failed(format!( + "Owner command failed ({status}): {}. It may have partially cleaned the cache. Nothing else was deleted", + String::from_utf8_lossy(errors).escape_debug() + ))); + } + let output = + output.as_ref().map_err(|error| failed(error.to_string()))?; + return Ok(output.clone()); + } + std::thread::sleep(Duration::from_millis(40)); + } +} + +fn terminate(child: &mut std::process::Child) { + #[cfg(unix)] + if let Ok(pid) = i32::try_from(child.id()) + && let Some(pid) = rustix::process::Pid::from_raw(pid) + { + let _ = rustix::process::kill_process_group( + pid, + rustix::process::Signal::KILL, + ); + } + let _ = child.kill(); + let _ = child.wait(); +} + +/// Owners can follow links internally. Refuse any link or volume boundary +/// inside their actual scope, rather than assuming their traversal matches +/// PwrDisk's unlink semantics. Bound the walk and fail closed on read errors. +#[allow( + clippy::unnecessary_debug_formatting, + reason = "Safety errors must expose path controls" +)] +pub(super) fn check_tree(root: &Path) -> Result<(), String> { + let volume = + crate::space::device_for(root).ok_or("Cannot identify cache volume")?; + let mut pending = vec![root.to_owned()]; + let mut visited = 0; + while let Some(path) = pending.pop() { + visited += 1; + if visited > super::MAX_PREFLIGHT_ENTRIES { + return Err("Cache is too large for bounded owner preflight; inspect manually".into()); + } + let meta = std::fs::symlink_metadata(&path) + .map_err(|error| error.to_string())?; + if meta.is_symlink() { + if path == root { + return Err( + "Owner cache scope is a symlink; inspect its actual root" + .into(), + ); + } + let destination = + std::fs::canonicalize(&path).map_err(|error| { + format!("Cannot resolve cache symlink: {error}") + })?; + let real_root = std::fs::canonicalize(root) + .map_err(|error| error.to_string())?; + if !destination.starts_with(real_root) { + return Err(format!( + "Owner scope contains an external symlink: {path:?}; inspect manually" + )); + } + } + if meta.is_dir() { + if crate::space::device_for(&path).as_deref() + != Some(volume.as_str()) + { + return Err("Owner scope crosses a volume boundary".into()); + } + for entry in + std::fs::read_dir(&path).map_err(|error| error.to_string())? + { + if visited + pending.len() >= super::MAX_PREFLIGHT_ENTRIES { + return Err("Cache is too large for bounded owner preflight; inspect manually".into()); + } + pending.push(entry.map_err(|error| error.to_string())?.path()); + } + } + } + Ok(()) +} + +/// Whether [`check_in_use`] can look at running processes here. +pub(super) const ACTIVE_USE_CHECKED: bool = + cfg!(any(target_os = "macos", target_os = "linux")); + +pub(super) fn check_active(operation: &Operation) -> Result<(), String> { + check_in_use( + &operation.scope, + &operation.cache_root, + Some(operation.owner), + Some(&operation.command.executable), + ) +} + +/// Deleting files directly has no owner command, but the same live writers +/// matter: a process running from or inside the path, one naming it, and +/// for a recognized cache any running instance of its owner. +pub(super) fn check_path_active( + path: &Path, + owner: Option, +) -> Result<(), String> { + check_in_use(path, path, owner, None) +} + +fn check_in_use( + scope: &Path, + cache: &Path, + owner: Option, + executable: Option<&Path>, +) -> Result<(), String> { + #[cfg(any(target_os = "macos", target_os = "linux"))] + { + let mut system = sysinfo::System::new(); + system.refresh_processes_specifics( + sysinfo::ProcessesToUpdate::All, + sysinfo::ProcessRefreshKind::everything(), + ); + if system.processes().is_empty() { + return Err("Cannot check active processes".into()); + } + let cache = cache.to_str().ok_or("Unsupported cache path")?; + for (pid, process) in system.processes() { + if pid.as_u32() == std::process::id() { + continue; + } + let in_scope = process + .exe() + .is_some_and(|path| path.starts_with(scope)) + || process.cwd().is_some_and(|path| path.starts_with(scope)); + let using_cache = process.cmd().iter().any(|argument| { + let argument = argument.to_string_lossy(); + argument.contains(cache) + || owner.is_some_and(|owner| { + owner_named(owner, executable, &argument) + }) + }); + if in_scope || using_cache { + return Err(format!( + "{} may be in use (process {pid}); stop it and prepare a new preview", + owner.map_or("This path", Owner::label) + )); + } + } + Ok(()) + } + #[cfg(not(any(target_os = "macos", target_os = "linux")))] + { + let _ = (scope, cache, owner, executable); + Err("Active-use checking is unsupported on this platform".into()) + } +} + +/// Node launchers appear as `node .../npm-cli.js`, Python installations +/// commonly expose pip3 or pip3.12, and uv's tool runner is uvx. Comparing +/// only the friendly owner name misses those live writers even though +/// their configured cache is the same. +#[cfg(any(target_os = "macos", target_os = "linux", test))] +pub(super) fn owner_named( + owner: Owner, + executable: Option<&Path>, + argument: &str, +) -> bool { + let path = Path::new(argument); + let name = path.file_name(); + executable.is_some_and(|executable| path == executable) + || name.is_some_and(|name| { + name == owner.executable() + || executable.is_some_and(|executable| { + Some(name) == executable.file_name() + }) + || (matches!(owner, Owner::Npm | Owner::Npx) + && matches!( + name.to_str(), + Some("npm" | "npx" | "npm-cli.js" | "npx-cli.js") + )) + || (owner == Owner::Uv && name == "uvx") + || (owner == Owner::Pip + && name.to_str().is_some_and(versioned_pip)) + }) +} + +/// `pip3`, and the `pip3.12` beside it that python.org and Homebrew +/// install: the same pip writing the same cache. +#[cfg(any(target_os = "macos", target_os = "linux", test))] +fn versioned_pip(name: &str) -> bool { + name.strip_prefix("pip3").is_some_and(|rest| { + rest.is_empty() + || rest.strip_prefix('.').is_some_and(|minor| { + !minor.is_empty() && minor.bytes().all(|b| b.is_ascii_digit()) + }) + }) +} diff --git a/crates/disktree-core/src/cleanup/recognize.rs b/crates/disktree-core/src/cleanup/recognize.rs new file mode 100644 index 00000000..c648d657 --- /dev/null +++ b/crates/disktree-core/src/cleanup/recognize.rs @@ -0,0 +1,234 @@ +//! Cheap inspection hints. The owner's own query must confirm a root before +//! a command can act on it. These checks never authorize deletion. + +use std::path::{Path, PathBuf}; + +use super::{Environment, Owner}; + +pub(super) fn owner( + path: &Path, + env: &Environment, +) -> Option<(Owner, PathBuf)> { + let cache = env + .variables + .get("XDG_CACHE_HOME") + .map_or_else(|| env.home.join(".cache"), PathBuf::from); + let library = env.home.join("Library/Caches"); + let mut roots = vec![ + (Owner::Npm, env.home.join(".npm/_cacache")), + (Owner::Npx, env.home.join(".npm/_npx")), + (Owner::Uv, cache.join("uv")), + (Owner::Pip, cache.join("pip")), + (Owner::Pip, library.join("pip")), + (Owner::Cypress, cache.join("Cypress")), + (Owner::Cypress, library.join("Cypress")), + (Owner::Pnpm, env.home.join(".local/share/pnpm/store")), + (Owner::Pnpm, env.home.join("Library/pnpm/store")), + (Owner::Homebrew, library.join("Homebrew")), + (Owner::Homebrew, cache.join("Homebrew")), + (Owner::Playwright, cache.join("ms-playwright")), + (Owner::Playwright, library.join("ms-playwright")), + (Owner::Puppeteer, cache.join("puppeteer")), + ]; + if let Some(local) = env.variables.get("LOCALAPPDATA") { + let local = PathBuf::from(local); + roots.extend([ + (Owner::Npm, local.join("npm-cache/_cacache")), + (Owner::Npx, local.join("npm-cache/_npx")), + (Owner::Uv, local.join("uv/cache")), + (Owner::Pip, local.join("pip/Cache")), + (Owner::Playwright, local.join("ms-playwright")), + ]); + } + for (key, owner) in [ + ("UV_CACHE_DIR", Owner::Uv), + ("PIP_CACHE_DIR", Owner::Pip), + ("CYPRESS_CACHE_FOLDER", Owner::Cypress), + ("HOMEBREW_CACHE", Owner::Homebrew), + ("PLAYWRIGHT_BROWSERS_PATH", Owner::Playwright), + ("PUPPETEER_CACHE_DIR", Owner::Puppeteer), + ] { + if let Some(value) = env.variables.get(key) { + let root = PathBuf::from(value); + if root.is_absolute() { + roots.push((owner, root)); + } + } + } + for key in ["npm_config_cache", "NPM_CONFIG_CACHE"] { + if let Some(root) = env.variables.get(key) { + roots.push((Owner::Npm, PathBuf::from(root).join("_cacache"))); + roots.push((Owner::Npx, PathBuf::from(root).join("_npx"))); + } + } + roots + .into_iter() + .find(|(_, root)| path.starts_with(root)) + .or_else(|| { + path.ancestors().find_map(|root| { + let name = root.file_name()?.to_str()?; + let owner = match name { + "_cacache" => Owner::Npm, + "_npx" => Owner::Npx, + ".pnpm-store" => Owner::Pnpm, + "ms-playwright" => Owner::Playwright, + _ => return None, + }; + Some((owner, root.to_owned())) + }) + }) +} + +pub(super) fn shape_owner(root: &Path) -> Option { + if root.join("wheels").is_dir() + && (root.join("http-v2").is_dir() || root.join("http").is_dir()) + { + return Some(Owner::Pip); + } + // Versioned stores and binary caches can be relocated to arbitrary + // names. Read only a bounded immediate listing for recognition; the + // installed owner must still verify the exact configured root. + let entries = std::fs::read_dir(root).ok()?; + for entry in entries.take(32).flatten() { + let path = entry.path(); + let name = entry.file_name(); + let name = name.to_str()?; + if name.strip_prefix('v').is_some_and(|version| { + !version.is_empty() + && version.bytes().all(|byte| byte.is_ascii_digit()) + }) && path.join("files").is_dir() + { + return Some(Owner::Pnpm); + } + if name.split('.').count() == 3 + && name + .bytes() + .all(|byte| byte.is_ascii_digit() || byte == b'.') + && (path.join("Cypress.app").is_dir() + || path.join("Cypress/Cypress").is_file()) + { + return Some(Owner::Cypress); + } + } + None +} + +/// Suitable for review and for raw-removal preflight. An ancestor named +/// cache is a reason to inspect, never evidence that raw deletion is safe. +pub fn inspection_reason(path: &Path) -> Option { + let env = Environment::current().ok()?; + inspection_with(path, &env) +} + +pub(super) fn inspection_with( + path: &Path, + env: &Environment, +) -> Option { + if let Some((owner, _)) = owner(path, env) { + return Some(format!( + "{} requires owner-managed cleanup; no raw deletion fallback", + owner.label() + )); + } + path.ancestors().find_map(|ancestor| { + let name = ancestor.file_name()?.to_str()?.to_ascii_lowercase(); + matches!(name.as_str(), "cache" | "caches" | ".cache" | ".npm" | "npm-cache" | ".pnpm-store" | "codex-runtimes") + .then(|| "Cache/runtime state requires inspection and an owner cleanup preview; a cache name or regenerable classification does not authorize raw deletion".into()) + }).or_else(|| { + // An opaque cache tag is a refusal hint for relocated caches too; + // it is never enough evidence to build an owner cleanup command. + path.ancestors().find_map(|ancestor| { + (ancestor.join("CACHEDIR.TAG").is_file() + || shape_owner(ancestor).is_some()) + .then(|| "Opaque cache/store layout requires inspection and owner cleanup; no raw deletion fallback".into()) + }) + }) +} + +/// The owner a path most likely belongs to: a known or configured root +/// containing it, or a recognizable layout a few levels up. A hint picks +/// which owner to ask; only that owner's own query confirms a root. +pub(super) fn hinted( + path: &Path, + env: &Environment, +) -> Option<(Owner, PathBuf)> { + owner(path, env).or_else(|| { + path.ancestors().take(4).find_map(|root| { + shape_owner(root).map(|owner| (owner, root.to_owned())) + }) + }) +} + +// Enough to name the caches inside a wrapper such as ~/.cache without +// walking every file of every cache in it on the preview worker. +const CONTAINED_DEPTH: usize = 3; +const CONTAINED_DIRECTORIES: usize = 20_000; +const CONTAINED_LISTED: usize = 8; + +/// Recognized caches strictly inside `path`, for the disclosure shown +/// before deleting it directly: their owners are bypassed too. Bounded, +/// and fails closed so a disclosure is never silently incomplete. +pub(super) fn contained( + path: &Path, + env: &Environment, +) -> Result, String> { + let mut found = Vec::new(); + let mut pending = vec![(path.to_owned(), 0)]; + let mut visited = 0; + while let Some((directory, depth)) = pending.pop() { + let entries = match std::fs::read_dir(&directory) { + Ok(entries) => entries, + Err(error) if directory == path => { + // A file or a vanished path contains nothing. + if error.kind() == std::io::ErrorKind::NotFound + || error.kind() == std::io::ErrorKind::NotADirectory + || path.is_file() + { + return Ok(found); + } + return Err(format!("Cannot inspect contents: {error}")); + } + Err(error) => { + return Err(format!( + "Cannot inspect {}: {error}", + directory.display() + )); + } + }; + for entry in entries { + let entry = entry.map_err(|error| error.to_string())?; + let child = entry.path(); + if !entry.file_type().is_ok_and(|kind| kind.is_dir()) { + continue; + } + visited += 1; + if visited > CONTAINED_DIRECTORIES { + return Err("Too many folders to list the caches inside; inspect a smaller selection".into()); + } + let label = owner(&child, env) + .filter(|(_, root)| *root == child) + .map(|(owner, _)| owner.label().to_owned()) + .or_else(|| { + shape_owner(&child).map(|owner| owner.label().to_owned()) + }) + .or_else(|| { + child + .join("CACHEDIR.TAG") + .is_file() + .then(|| "tagged cache".to_owned()) + }); + if let Some(label) = label { + if found.len() < CONTAINED_LISTED { + found.push(format!("{label} at {}", child.display())); + } + // Its own contents belong to it; no need to look inside. + continue; + } + if depth + 1 < CONTAINED_DEPTH { + pending.push((child, depth + 1)); + } + } + } + found.sort(); + Ok(found) +} diff --git a/crates/disktree-core/src/cleanup/tests.rs b/crates/disktree-core/src/cleanup/tests.rs new file mode 100644 index 00000000..a18ad56d --- /dev/null +++ b/crates/disktree-core/src/cleanup/tests.rs @@ -0,0 +1,1589 @@ +use std::collections::BTreeMap; +#[cfg(unix)] +use std::sync::atomic::{AtomicBool, Ordering}; +#[cfg(unix)] +use std::time::{Duration, Instant}; + +use super::*; +use Decision::{DeleteFiles, Owner as Run, Skip}; + +mod properties; + +// These tests deliberately create live processes named uv. Serialize them +// so one fixture cannot trip another fixture's active-owner guard. +#[cfg(unix)] +static EXECUTION: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +struct Fixture { + _temp: tempfile::TempDir, + root: PathBuf, + env: Environment, + executable: PathBuf, +} + +impl Fixture { + fn new() -> Self { + #[cfg(unix)] + let temp = tempfile::tempdir_in("/tmp").expect("scratch fixture"); + #[cfg(not(unix))] + let temp = tempfile::tempdir().expect("fixture"); + let root = std::fs::canonicalize(temp.path()).expect("real root"); + let home = root.join("home"); + std::fs::create_dir(&home).expect("home"); + let executable = root.join("fixture-cli"); + std::fs::write(&executable, "mock identity") + .expect("executable identity"); + let env = Environment { + home, + variables: BTreeMap::new(), + }; + Self { + _temp: temp, + root, + env, + executable, + } + } + + fn dir(&self, name: &str) -> PathBuf { + let path = self.env.home.join(name); + std::fs::create_dir_all(&path).expect("cache"); + std::fs::write(path.join("payload"), vec![0; 8192]).expect("payload"); + path + } + + fn probe(&self, name: &str, version: &str, cache: &Path) -> MockProbe { + MockProbe { + executable: self.executable.clone(), + name: name.into(), + version: version.into(), + cache: cache.to_owned(), + calls: vec![], + } + } +} + +struct MockProbe { + executable: PathBuf, + name: String, + version: String, + cache: PathBuf, + calls: Vec, +} + +impl Probe for MockProbe { + fn executable( + &mut self, + name: &str, + _: &Environment, + ) -> Result { + if name == self.name { + Ok(self.executable.clone()) + } else { + Err(Issue::new( + Problem::NotFound, + format!( + "{name} unavailable on PATH; software may still be installed" + ), + )) + } + } + + fn output( + &mut self, + command: &Command, + _: &Environment, + ) -> Result { + self.calls.push(command.clone()); + match command + .arguments + .iter() + .map(String::as_str) + .collect::>() + .as_slice() + { + ["--version"] | ["version", "--component", "package"] => { + Ok(self.version.clone()) + } + ["config", "get", "cache"] | ["cache", "dir" | "path"] => { + Ok(self.cache.to_str().expect("UTF-8").into()) + } + _ => panic!("Preview attempted a write: {command:?}"), + } + } +} + +/// Why the only marked path has no owner command. Preparation is best +/// effort, so a refusal is that proposal's status, never an error. +#[cfg(unix)] +fn owner_error(prepared: Result) -> String { + owner_issue(prepared).detail +} + +fn owner_issue(prepared: Result) -> Issue { + let prepared = prepared.expect("preparation reports per path"); + let proposal = &prepared.proposals[0]; + assert!(proposal.operations.is_empty(), "no command: {proposal:?}"); + proposal.issue.clone().expect("the proposal says why") +} + +/// The person chose the owner command for every marked path. +#[cfg(unix)] +fn owners(prepared: &Prepared) -> Approved { + prepared + .approve( + &vec![Decision::Owner; prepared.proposals.len()], + Action::Skip, + ) + .expect("owner commands approved") +} + +fn target(path: &Path) -> Target { + Target { + path: path.to_owned(), + bytes: 1, + is_dir: true, + hidden: false, + } +} + +#[test] +fn npm_package_and_npx_have_separate_commands_scopes_and_versions() { + let fixture = Fixture::new(); + let cache = fixture.env.home.join(".npm"); + let package = fixture.dir(".npm/_cacache"); + let npx = fixture.dir(".npm/_npx"); + for (path, owner, expected) in [ + ( + &package, + Owner::Npm, + strings(&["cache", "clean", "--force", "--cache"]), + ), + ( + &npx, + Owner::Npx, + strings(&["cache", "npx", "rm", "--force", "--cache"]), + ), + ] { + let mut probe = fixture.probe("npm", "11.6.2", &cache); + let prepared = prepare_with( + &[target(path)], + &fixture.root, + fixture.env.clone(), + &mut probe, + ) + .expect("preview"); + let operation = &prepared.operations[0]; + assert_eq!(operation.owner, owner); + assert_eq!(&operation.scope, path); + let mut expected = expected; + expected.push(cache.to_str().expect("cache").into()); + assert_eq!(operation.command.arguments, expected); + assert_eq!( + operation.command.environment["npm_config_logs_dir"], + "/dev/null" + ); + assert_eq!( + probe.calls.len(), + 2, + "only version and configuration probes" + ); + assert!(path.join("payload").exists()); + } + let mut probe = fixture.probe("npm", "11.6.2", &cache); + let prepared = prepare_with( + &[target(&cache)], + &fixture.root, + fixture.env.clone(), + &mut probe, + ) + .expect("both caches explicitly previewed"); + assert_eq!(prepared.operations.len(), 2); + assert_eq!(prepared.scope_bytes.len(), 2); + assert_eq!(prepared.proposals[0].operations, [0, 1]); + assert_eq!(prepared.operations[0].scope, package); + assert_eq!(prepared.operations[1].scope, npx); +} + +#[test] +fn custom_roots_are_queried_and_subtrees_expand_only_to_the_verified_scope() { + let fixture = Fixture::new(); + let cache = fixture.dir("custom data; $(touch sentinel)"); + let selected = cache.join("one-package"); + std::fs::create_dir(&selected).expect("selected"); + let mut probe = fixture.probe("uv", "uv 0.11.0 (fixture)", &cache); + let prepared = prepare_with( + &[target(&selected)], + &fixture.root, + fixture.env.clone(), + &mut probe, + ) + .expect("configured root"); + let operation = &prepared.operations[0]; + assert_eq!(operation.scope, cache); + assert_eq!(operation.selected, [selected]); + assert_eq!( + operation.command.arguments, + [ + "cache", + "clean", + "--cache-dir", + cache.to_str().expect("path") + ] + ); + assert!( + prepared.scope_bytes[0] >= 8192, + "includes unselected siblings" + ); + assert!(operation.description().contains("WHOLE scope")); + assert!(operation.description().contains("APFS")); + assert!(!fixture.env.home.join("sentinel").exists()); + let mut probe = fixture.probe("uv", "uv 0.11.0", &cache); + let other = fixture.dir(".cache/uv"); + assert_eq!( + owner_issue(prepare_with( + &[target(&other)], + &fixture.root, + fixture.env.clone(), + &mut probe + )) + .problem, + Problem::NotConfiguredCache, + "do not clean the configured cache instead of a stale default selection" + ); +} + +#[test] +fn pip_and_cypress_pin_the_resolved_root_in_arguments_or_environment() { + let fixture = Fixture::new(); + for (name, version, relative, owner) in [ + ( + "pip", + "pip 26.0.1 from /fixture/pip (python 3.14)", + "Library/Caches/pip", + Owner::Pip, + ), + ( + "cypress", + "15.5.0", + "Library/Caches/Cypress", + Owner::Cypress, + ), + ] { + let cache = fixture.dir(relative); + let mut probe = fixture.probe(name, version, &cache); + let prepared = prepare_with( + &[target(&cache)], + &fixture.root, + fixture.env.clone(), + &mut probe, + ) + .expect("preview"); + let operation = &prepared.operations[0]; + assert_eq!(operation.owner, owner); + if owner == Owner::Pip { + assert_eq!( + operation.command.arguments, + [ + "--cache-dir", + cache.to_str().expect("path"), + "cache", + "purge" + ] + ); + } else { + assert_eq!(operation.command.arguments, ["cache", "clear"]); + assert_eq!( + operation.command.environment["CYPRESS_CACHE_FOLDER"], + cache.to_str().expect("path") + ); + assert!(operation.effects.contains("other projects")); + } + } +} + +#[test] +fn unknown_unsupported_and_missing_owners_do_not_produce_a_write() { + let fixture = Fixture::new(); + let uv = fixture.dir(".cache/uv"); + let mut missing = fixture.probe("absent", "", &uv); + let issue = owner_issue(prepare_with( + &[target(&uv)], + &fixture.root, + fixture.env.clone(), + &mut missing, + )); + assert_eq!(issue.problem, Problem::NotFound); + assert!(issue.detail.contains("software may still be installed")); + for name in [ + "Library/pnpm/store", + "Library/Caches/Homebrew", + "Library/Caches/ms-playwright", + ".cache/puppeteer", + ".cache/codex-runtimes", + ".cache/gh", + "Library/Caches/Electron", + "Library/Caches/vscode-cpptools", + ] { + let path = fixture.dir(name); + let mut probe = fixture.probe("absent", "", &path); + let prepared = prepare_with( + &[target(&path)], + &fixture.root, + fixture.env.clone(), + &mut probe, + ) + .expect("per-path status"); + let proposal = &prepared.proposals[0]; + assert!(proposal.operations.is_empty(), "{name}"); + let problem = proposal.issue.as_ref().expect("why").problem; + // Known owners without an audited command, or no verified owner. + assert!( + matches!(problem, Problem::NoCommand | Problem::UnknownOwner), + "{name}: {problem:?}" + ); + let warning = &proposal.delete.as_ref().expect("offered").warning; + if problem == Problem::UnknownOwner { + assert!( + warning.contains("does not know that this is disposable"), + "{name}: unknown caches are never labelled safe" + ); + } + assert!(path.join("payload").exists()); + } +} + +#[test] +fn version_bounds_and_prereleases_are_explicit() { + for (owner, version) in [ + (Owner::Npx, "11.1.0"), + (Owner::Npm, "12.0.0"), + (Owner::Uv, "uv 0.10.0"), + (Owner::Pip, "pip 27.0 from /fixture"), + (Owner::Cypress, "16.0.0"), + (Owner::Npm, "11.6.2-beta.1"), + (Owner::Pip, "unknown"), + ] { + assert!( + supported_version(owner, version).is_err(), + "{owner:?} {version}" + ); + } + for (owner, version) in [ + (Owner::Npx, "11.2.0"), + (Owner::Npm, "9.0.0"), + (Owner::Uv, "uv 0.11.0"), + (Owner::Pip, "pip 23.0 from /fixture"), + (Owner::Cypress, "13.0.0"), + ] { + supported_version(owner, version).expect("audited family"); + } +} + +#[test] +fn actual_scope_must_be_beneath_scan_and_must_not_be_the_scan_root() { + let fixture = Fixture::new(); + let cache = fixture.dir(".cache/uv"); + let selected = cache.join("selected"); + std::fs::create_dir(&selected).expect("selected"); + for root in [&selected, &cache] { + let mut probe = fixture.probe("uv", "uv 0.11.0", &cache); + let issue = owner_issue(prepare_with( + &[target(&selected)], + root, + fixture.env.clone(), + &mut probe, + )); + assert_eq!(issue.problem, Problem::Refused); + } + let mut probe = + fixture.probe("uv", "uv 0.11.0", Path::new("relative-cache")); + let issue = owner_issue(prepare_with( + &[target(&cache)], + &fixture.root, + fixture.env.clone(), + &mut probe, + )); + assert_eq!(issue.problem, Problem::ConfigCheckFailed); + assert!(issue.detail.contains("relative")); +} + +#[test] +fn raw_removal_refuses_cache_wrappers_and_descendants_but_accepts_build_output() +{ + let fixture = Fixture::new(); + let cache = fixture.dir("wrapper/.cache/unknown-runtime"); + assert!(check_raw(&[target(&cache)]).is_err()); + assert!(check_raw(&[target(&fixture.env.home.join("wrapper"))]).is_err()); + let build = fixture.dir("project/target/debug"); + check_raw(&[target(&build)]).expect("ordinary build output"); + assert!(cache.join("payload").exists()); +} + +#[test] +fn relocated_cache_ancestors_protect_subtrees_and_files() { + let fixture = Fixture::new(); + let tagged = fixture.dir("uv-data/archive-v0/one/two"); + std::fs::write( + fixture.env.home.join("uv-data/CACHEDIR.TAG"), + "Signature: 8a477f597d28d172789f06886806bc55", + ) + .expect("cache tag"); + let pip = fixture.dir("pip-data/wheels/deep/entries"); + fixture.dir("pip-data/http-v2"); + let pnpm = fixture.dir("pnpm-data/v10/files/deep/entries"); + let cypress = fixture.dir("browser-data/15.0.0/Cypress.app/deep/entries"); + for path in [tagged, pip, pnpm, cypress] { + for selected in [path.clone(), path.join("payload")] { + assert!( + recognize::inspection_with(&selected, &fixture.env).is_some(), + "relocated ancestor must protect {selected:?}" + ); + assert!(check_raw(&[target(&selected)]).is_err()); + assert!(selected.exists(), "inspection cannot delete"); + } + } + let ordinary = fixture.dir("ordinary/project/target"); + check_raw(&[target(&ordinary)]).expect("unrelated build output"); +} + +#[cfg(unix)] +#[test] +fn external_cache_links_are_refused_while_internal_layout_links_are_allowed() { + let fixture = Fixture::new(); + let cache = fixture.dir(".cache/uv"); + std::os::unix::fs::symlink(cache.join("payload"), cache.join("internal")) + .expect("internal link"); + process::check_tree(&cache).expect("internal link"); + let outside = fixture.dir("outside"); + std::os::unix::fs::symlink(&outside, cache.join("external")) + .expect("external link"); + assert!( + process::check_tree(&cache) + .expect_err("external link") + .contains("external symlink") + ); + assert!(outside.join("payload").exists()); +} + +#[cfg(unix)] +fn executable_fixture() -> Fixture { + use std::os::unix::fs::PermissionsExt as _; + let mut fixture = Fixture::new(); + let cache = fixture.dir(".cache/uv"); + let bin = fixture.root.join("bin"); + std::fs::create_dir(&bin).expect("bin"); + fixture.executable = bin.join("uv"); + std::fs::write(&fixture.executable, r#"#!/bin/sh +case "$1 $2" in + '--version ') printf '%s\n' 'uv 0.11.0';; + 'cache dir') if [ -f "$HOME/cache-root" ]; then /bin/cat "$HOME/cache-root"; else printf '%s\n' "$UV_CACHE_DIR"; fi;; + 'cache clean') + printf '%s\n' "$@" > "$HOME/invocation" + if [ "$FIXTURE_WAIT" = 1 ]; then /bin/sleep 20; fi + if [ "$FIXTURE_FAIL" = 1 ]; then printf '%s\n' 'fixture owner failure' >&2; exit 17; fi + printf '%s\n' 'fixture success; root remains';; + 'hold ') /bin/sleep 20;; + *) exit 97;; +esac +"#).expect("fixture CLI"); + std::fs::set_permissions( + &fixture.executable, + std::fs::Permissions::from_mode(0o755), + ) + .expect("executable"); + fixture.env.variables.extend([ + ("PATH".into(), format!("{}:/usr/bin:/bin", bin.display())), + ( + "HOME".into(), + fixture.env.home.to_str().expect("home").into(), + ), + ("UV_CACHE_DIR".into(), cache.to_str().expect("cache").into()), + ]); + fixture +} + +#[cfg(unix)] +fn collect( + handle: &crate::removal::RemovalHandle, +) -> Vec { + let deadline = Instant::now() + Duration::from_secs(20); + let mut events = Vec::new(); + loop { + if let Some(event) = handle.poll() { + let done = + matches!(event, crate::removal::RemovalEvent::Done { .. }); + events.push(event); + if done { + return events; + } + } + assert!(Instant::now() < deadline, "fixture worker timed out"); + std::thread::sleep(Duration::from_millis(10)); + } +} + +#[cfg(unix)] +#[test] +fn owner_failure_reports_error_without_deletion_and_success_does_not_mean_root_removed() + { + let _execution = EXECUTION + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + for fail in [true, false] { + let mut fixture = executable_fixture(); + if fail { + fixture + .env + .variables + .insert("FIXTURE_FAIL".into(), "1".into()); + } + let cache = fixture.env.home.join(".cache/uv"); + let prepared = prepare_with( + &[target(&cache)], + &fixture.root, + fixture.env.clone(), + &mut process::SystemProbe, + ) + .expect("fixture preview"); + assert!( + !fixture.env.home.join("invocation").exists(), + "preview is read-only" + ); + let events = collect(&crate::removal::spawn_cleanup( + owners(&prepared), + crate::removal_limit::Limit::default().into(), + )); + let outcome = events + .iter() + .find_map(|event| { + if let crate::removal::RemovalEvent::Item { outcome, .. } = + event + { + Some(outcome) + } else { + None + } + }) + .expect("item result"); + assert_eq!(outcome.is_err(), fail, "{events:?}"); + if fail { + assert!( + outcome + .as_ref() + .expect_err("failed") + .contains("Nothing else was deleted"), + "{events:?}" + ); + } + assert!( + cache.join("payload").exists(), + "owner result never substitutes raw removal" + ); + assert!( + fixture.env.home.join("invocation").exists(), + "mock owner was invoked" + ); + } +} + +#[cfg(unix)] +#[test] +fn owner_worker_applies_confirmed_ceilings_only_to_the_named_volume() { + use crate::removal::{RemovalEvent, spawn_cleanup}; + use crate::removal_limit::{Ceilings, Limit, volume_of}; + + let _execution = EXECUTION + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let fixture = executable_fixture(); + let cache = fixture.env.home.join(".cache/uv"); + let prepared = prepare_with( + &[target(&cache)], + &fixture.root, + fixture.env.clone(), + &mut process::SystemProbe, + ) + .expect("fixture preview"); + let mut prepared = owners(&prepared); + let (volume, capacity) = volume_of(&cache).expect("fixture volume"); + // Charge a share just past 5% without allocating gigabytes of data. + // Worker measurement must preserve this conservative preview charge. + prepared.plan.targets[0].bytes = capacity / 20 + 1; + let other = Ceilings::from(Limit::default()).raise( + format!("{volume}-other-fixture"), + Limit::new(100).expect("100%"), + ); + let refused = collect(&spawn_cleanup(prepared.clone(), other)); + assert!(refused.iter().any(|event| matches!(event, + RemovalEvent::Item { outcome: Err(reason), .. } + if reason.contains("5% per-operation")))); + assert!(!fixture.env.home.join("invocation").exists()); + + let approved = Ceilings::from(Limit::default()) + .raise(volume, Limit::new(10).expect("10%")); + let completed = collect(&spawn_cleanup(prepared, approved)); + assert!(completed.iter().any(|event| matches!( + event, + RemovalEvent::Item { + outcome: Ok(()), + .. + } + ))); + assert!(fixture.env.home.join("invocation").exists()); + assert!( + cache.join("payload").exists(), + "mock never deletes the cache" + ); +} + +#[cfg(unix)] +#[test] +fn cancellation_stops_the_owner_process_group_without_raw_deletion() { + let _execution = EXECUTION + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let mut fixture = executable_fixture(); + fixture + .env + .variables + .insert("FIXTURE_WAIT".into(), "1".into()); + let cache = fixture.env.home.join(".cache/uv"); + let prepared = prepare_with( + &[target(&cache)], + &fixture.root, + fixture.env.clone(), + &mut process::SystemProbe, + ) + .expect("preview"); + let handle = crate::removal::spawn_cleanup( + owners(&prepared), + crate::removal_limit::Limit::default().into(), + ); + let start = Instant::now(); + while !fixture.env.home.join("invocation").exists() { + assert!(start.elapsed() < Duration::from_secs(10)); + std::thread::sleep(Duration::from_millis(10)); + } + handle.cancel(); + let events = collect(&handle); + assert!(start.elapsed() < Duration::from_secs(10)); + assert!(events.iter().any(|event| matches!(event, crate::removal::RemovalEvent::Item { outcome: Err(reason), .. } if reason.contains("cancelled")))); + assert!(cache.join("payload").exists()); +} + +#[cfg(unix)] +#[test] +fn changed_executable_and_active_owner_revoke_execution() { + let _execution = EXECUTION + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let fixture = executable_fixture(); + let cache = fixture.env.home.join(".cache/uv"); + let prepared = prepare_with( + &[target(&cache)], + &fixture.root, + fixture.env.clone(), + &mut process::SystemProbe, + ) + .expect("preview"); + let mut active = std::process::Command::new(&fixture.executable) + .arg("hold") + .spawn() + .expect("fixture active owner"); + std::thread::sleep(Duration::from_millis(100)); + let active_check = prepared.preflight_operation(0); + active.kill().expect("stop fixture"); + active.wait().expect("wait fixture"); + assert_eq!( + active_check.expect_err("active owner").problem, + Problem::InUse + ); + std::fs::write(&fixture.executable, "changed fixture binary") + .expect("replace executable"); + assert_eq!( + prepared + .preflight_operation(0) + .expect_err("changed executable") + .problem, + Problem::Changed + ); + assert!(!fixture.env.home.join("invocation").exists()); +} + +#[cfg(unix)] +#[test] +fn cancelled_before_start_and_unavailable_commands_do_not_execute() { + let fixture = executable_fixture(); + let command = Command { + executable: fixture.executable.clone(), + arguments: strings(&["cache", "clean"]), + environment: BTreeMap::new(), + working_directory: fixture.env.home.clone(), + }; + let cancel = AtomicBool::new(true); + assert!( + process::run(&command, &fixture.env, &cancel, Duration::from_secs(1)) + .expect_err("cancelled") + .detail + .contains("before command") + ); + cancel.store(false, Ordering::Relaxed); + let mut unavailable = command; + unavailable.executable = fixture.root.join("missing"); + assert!( + process::run( + &unavailable, + &fixture.env, + &cancel, + Duration::from_secs(1) + ) + .expect_err("unavailable") + .detail + .contains("could not start") + ); + assert!(!fixture.env.home.join("invocation").exists()); +} + +#[cfg(unix)] +#[test] +fn changed_configuration_and_capacity_failure_do_not_invoke_cleanup() { + let _execution = EXECUTION + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let fixture = executable_fixture(); + let cache = fixture.env.home.join(".cache/uv"); + let prepared = prepare_with( + &[target(&cache)], + &fixture.root, + fixture.env.clone(), + &mut process::SystemProbe, + ) + .expect("preview"); + let mut approved = owners(&prepared); + approved.plan.targets[0].bytes = u64::MAX; + assert!( + approved + .admit(&crate::removal_limit::Limit::default().into()) + .is_err(), + "the capacity limit covers the entire actual scope" + ); + let other = fixture.dir("other-cache"); + std::fs::write( + fixture.env.home.join("cache-root"), + format!("{}\n", other.display()), + ) + .expect("changed config"); + assert_eq!( + prepared + .preflight_operation(0) + .expect_err("changed root") + .problem, + Problem::Changed + ); + assert!(!fixture.env.home.join("invocation").exists()); + assert!(cache.join("payload").exists()); + assert!(other.join("payload").exists()); +} + +#[test] +fn observed_space_can_decrease_and_never_equals_scope_allocation_by_assumption() +{ + let path = Path::new("/fixture/cache"); + let success = Report::of( + Action::Owner, + Some(Owner::Uv), + path, + 50_000, + Some(100), + Some(90), + Ok(()), + ); + assert_eq!(success.outcome, Outcome::Succeeded); + assert_eq!(success.scope_allocation_at_preview, 50_000); + assert_eq!(success.observed_change, Some(-10)); + assert!(success.description().contains("not savings")); + let failure = Report::of( + Action::Owner, + Some(Owner::Uv), + path, + 50_000, + Some(100), + Some(105), + Err(&Issue::new(Problem::CommandFailed, "owner exit 17")), + ); + assert_eq!(failure.outcome, Outcome::Failed); + assert_eq!(failure.problem, Some(Problem::CommandFailed)); + assert_eq!( + failure.observed_change, + Some(5), + "partial failure can still change free space" + ); + assert_eq!(failure.error.as_deref(), Some("owner exit 17")); + assert!(failure.description().contains("Nothing else was deleted")); + let cancelled = Report::of( + Action::Owner, + Some(Owner::Uv), + path, + 50_000, + None, + None, + Err(&Issue::new(Problem::Cancelled, "stopped")), + ); + assert_eq!(cancelled.outcome, Outcome::Cancelled); +} + +#[test] +fn active_owner_detection_recognizes_node_launchers_and_pip3() { + let owned = |operation: &Operation, argument: &str| { + process::owner_named( + operation.owner, + Some(&operation.command.executable), + argument, + ) + }; + let mut operation = Operation { + owner: Owner::Npm, + version: "11.6.2".into(), + selected: vec![], + cache_root: "/fixture/.npm".into(), + scope: "/fixture/.npm/_cacache".into(), + command: Command { + executable: "/fixture/npm-cli.js".into(), + arguments: vec![], + environment: BTreeMap::new(), + working_directory: "/fixture".into(), + }, + effects: String::new(), + limitations: String::new(), + }; + assert!(owned(&operation, "/other-install/npm-cli.js")); + assert!(owned(&operation, "/other-install/npx-cli.js")); + assert!(!owned(&operation, "/fixture/unrelated.js")); + operation.owner = Owner::Pip; + assert!(owned(&operation, "/fixture/bin/pip3")); + assert!(owned(&operation, "pip")); + // Found by a_running_owner_is_recognized_in_every_launcher_form. + assert!(owned(&operation, "/opt/bin/pip3.12")); + assert!(!owned(&operation, "/opt/bin/pip3.x")); + operation.owner = Owner::Uv; + assert!(owned(&operation, "/opt/bin/uvx")); +} + +#[cfg(unix)] +#[test] +fn executable_resolution_uses_pip3_and_refuses_nonexecutable_files() { + use std::os::unix::fs::PermissionsExt as _; + let fixture = executable_fixture(); + let bin = fixture.executable.parent().expect("bin"); + let pip3 = bin.join("pip3"); + std::fs::write(&pip3, "fixture executable identity").expect("pip3"); + std::fs::set_permissions(&pip3, std::fs::Permissions::from_mode(0o755)) + .expect("executable"); + let mut env = fixture.env.clone(); + env.variables + .insert("PATH".into(), format!("relative:{}", bin.display())); + assert_eq!( + process::SystemProbe + .executable("pip", &env) + .expect("pip3 fallback"), + pip3 + ); + std::fs::set_permissions( + &fixture.executable, + std::fs::Permissions::from_mode(0o644), + ) + .expect("not executable"); + assert!( + process::SystemProbe + .executable("uv", &env) + .expect_err("unavailable command") + .detail + .contains("not executable") + ); +} + +#[cfg(unix)] +#[test] +fn preparation_refuses_installing_shims_and_shimmed_env_interpreters() { + use std::os::unix::fs::PermissionsExt as _; + let mut fixture = executable_fixture(); + let cache = fixture.env.home.join(".cache/uv"); + let shims = fixture.root.join("shims"); + std::fs::create_dir(&shims).expect("shim directory"); + let shim = shims.join("uv"); + std::fs::write( + &shim, + "#!/bin/sh\nprintf installed > \"$HOME/unwanted-install\"\n", + ) + .expect("installing shim fixture"); + std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755)) + .expect("executable shim"); + fixture + .env + .variables + .insert("PATH".into(), shims.to_str().expect("path").into()); + let issue = owner_issue(prepare_with( + &[target(&cache)], + &fixture.root, + fixture.env.clone(), + &mut process::SystemProbe, + )); + assert_eq!(issue.problem, Problem::UnsupportedLauncher); + assert!(issue.detail.contains("shim")); + assert!(!fixture.env.home.join("unwanted-install").exists()); + + let bin = fixture.executable.parent().expect("bin"); + std::fs::write( + &fixture.executable, + "#!/usr/bin/env node\nprintf installed > \"$HOME/unwanted-install\"\n", + ) + .expect("env runtime fixture"); + std::os::unix::fs::symlink(&shim, bin.join("node")).expect("shimmed node"); + fixture + .env + .variables + .insert("PATH".into(), bin.to_str().expect("bin").into()); + assert!( + owner_error(prepare_with( + &[target(&cache)], + &fixture.root, + fixture.env.clone(), + &mut process::SystemProbe + )) + .contains("shim"), + "do not dispatch env node through a shim" + ); + assert!(!fixture.env.home.join("unwanted-install").exists()); +} + +#[cfg(unix)] +#[test] +fn npm_installing_proxy_is_not_invoked_even_for_version_discovery() { + use std::os::unix::fs::PermissionsExt as _; + let mut fixture = executable_fixture(); + let cache = fixture.dir(".npm/_cacache"); + let bin = fixture.executable.parent().expect("bin"); + let proxy = bin.join("npm"); + std::fs::write( + &proxy, + "#!/bin/sh\nprintf installed > \"$HOME/unwanted-install\"\n", + ) + .expect("proxy fixture"); + std::fs::set_permissions(&proxy, std::fs::Permissions::from_mode(0o755)) + .expect("executable proxy"); + fixture + .env + .variables + .insert("PATH".into(), bin.to_str().expect("bin").into()); + let error = owner_error(prepare_with( + &[target(&cache)], + &fixture.root, + fixture.env.clone(), + &mut process::SystemProbe, + )); + assert!(error.contains("proxy/wrapper")); + assert!(!fixture.env.home.join("unwanted-install").exists()); +} + +#[cfg(unix)] +#[test] +fn configured_root_whitespace_cannot_redirect_cleanup_to_a_similar_path() { + let fixture = Fixture::new(); + let selected = fixture.dir("custom-cache"); + let configured = fixture.dir("custom-cache "); + for suffix in ["\r\n", "\n\n"] { + let ambiguous = + PathBuf::from(format!("{}{suffix}", selected.display())); + let mut probe = fixture.probe("uv", "uv 0.11.0", &ambiguous); + owner_issue(prepare_with( + &[target(&selected)], + &fixture.root, + fixture.env.clone(), + &mut probe, + )); + } + let mut probe = fixture.probe("uv", "uv 0.11.0", &configured); + // A trailing space is part of the configured path, not output padding: + // no supported owner claims the selection, so none is offered. + assert_eq!( + owner_issue(prepare_with( + &[target(&selected)], + &fixture.root, + fixture.env.clone(), + &mut probe, + )) + .problem, + Problem::UnknownOwner + ); + let mut probe = fixture.probe("uv", "uv 0.11.0", &configured); + let prepared = prepare_with( + &[target(&configured)], + &fixture.root, + fixture.env.clone(), + &mut probe, + ) + .expect("exact configured path"); + assert_eq!(prepared.operations[0].scope, configured); + assert_eq!( + prepared.operations[0] + .command + .arguments + .last() + .expect("cache argument"), + configured.to_str().expect("path") + ); + assert!(selected.join("payload").exists()); + assert!(configured.join("payload").exists()); +} + +#[cfg(unix)] +#[test] +fn non_utf8_probe_output_is_refused_without_lossy_path_conversion() { + let fixture = executable_fixture(); + let cache = fixture.env.home.join(".cache/uv"); + std::fs::write(&fixture.executable, "#!/bin/sh\nprintf '\\377\\n'\n") + .expect("non-UTF-8 fixture probe"); + let error = owner_error(prepare_with( + &[target(&cache)], + &fixture.root, + fixture.env.clone(), + &mut process::SystemProbe, + )); + assert!(error.contains("non-UTF-8")); + assert!(cache.join("payload").exists()); + assert!(!fixture.env.home.join("invocation").exists()); +} + +/// Three marked paths, three different answers: one owner resolves, one +/// owner has no audited command, one has no verified owner at all. +fn mixed(fixture: &Fixture) -> (Prepared, [PathBuf; 3]) { + let uv = fixture.dir(".cache/uv"); + let pnpm = fixture.dir("Library/pnpm/store"); + let runtime = fixture.dir(".cache/codex-runtimes"); + let mut probe = fixture.probe("uv", "uv 0.11.0", &uv); + let prepared = prepare_with( + &[target(&uv), target(&pnpm), target(&runtime)], + &fixture.root, + fixture.env.clone(), + &mut probe, + ) + .expect("best-effort preview"); + (prepared, [uv, pnpm, runtime]) +} + +#[test] +fn one_failure_is_one_proposal_and_the_other_paths_stay_offered() { + let fixture = Fixture::new(); + let (prepared, [uv, pnpm, runtime]) = mixed(&fixture); + assert_eq!(prepared.proposals.len(), 3); + assert_eq!(prepared.operations.len(), 1); + assert_eq!(prepared.operations[0].scope, uv); + let [ready, inspection, unknown] = &prepared.proposals[..] else { + panic!("three proposals"); + }; + assert_eq!(ready.operations, [0]); + assert!(ready.issue.is_none()); + assert_eq!(inspection.selected, pnpm); + assert_eq!( + inspection.issue.as_ref().map(|issue| issue.problem), + Some(Problem::NoCommand) + ); + assert_eq!(unknown.selected, runtime); + assert_eq!( + unknown.issue.as_ref().map(|issue| issue.problem), + Some(Problem::UnknownOwner) + ); + // Delete files is offered everywhere the guards allow it, and says + // what it bypasses; an unknown runtime is never called disposable. + for proposal in &prepared.proposals { + assert!(proposal.allows(Decision::DeleteFiles)); + assert!(proposal.allows(Decision::Skip)); + } + assert!( + ready + .delete + .as_ref() + .expect("offered") + .warning + .contains("uv cache is not involved") + ); + assert!( + unknown + .delete + .as_ref() + .expect("offered") + .warning + .contains("does not know that this is disposable") + ); + let text = prepared.description(); + assert!(text.contains("Owner command (choose owner)")); + assert!(text.contains("no cleanup command")); + assert!(text.contains("unknown owner")); + for path in [uv, pnpm, runtime] { + assert!(path.join("payload").exists(), "preview is read-only"); + } + + let unsupported = fixture.dir("other/.cache/uv"); + let mut env = fixture.env.clone(); + env.variables + .insert("UV_CACHE_DIR".into(), unsupported.display().to_string()); + let mut probe = fixture.probe("uv", "uv 0.10.4", &unsupported); + let issue = owner_issue(prepare_with( + &[target(&unsupported)], + &fixture.root, + env, + &mut probe, + )); + assert_eq!(issue.problem, Problem::UnsupportedVersion); + assert!(issue.detail.contains("0.10.4"), "{issue:?}"); + assert!(issue.detail.contains("uv 0.11.x"), "says what runs"); +} + +#[test] +fn decisions_are_explicit_and_each_intent_has_its_own_confirmation() { + let fixture = Fixture::new(); + let (prepared, [uv, pnpm, runtime]) = mixed(&fixture); + assert!( + prepared + .approve(&[Skip, Skip, Skip], Action::Trash) + .expect_err("nothing chosen") + .contains("Nothing chosen") + ); + assert!(prepared.approve(&[Run, Skip], Action::Trash).is_err()); + assert!( + prepared + .approve(&[Skip, Run, Skip], Action::Trash) + .expect_err("pnpm offers no command") + .contains("owner command") + ); + assert!( + prepared + .approve(&[Skip, Skip, DeleteFiles], Action::Owner) + .expect_err("delete needs a mode") + .contains("Trash or permanent") + ); + + let owner = prepared + .approve(&[Run, Skip, Skip], Action::Skip) + .expect("owner"); + assert_eq!(owner.confirmation(), RUN_OWNER_CLEANUP); + assert_eq!(owner.steps, [Step::Owner(0)]); + let trash = prepared + .approve(&[Skip, Skip, DeleteFiles], Action::Trash) + .expect("trash files"); + assert_eq!(trash.confirmation(), TRASH_CACHE_FILES); + assert_eq!( + prepared + .approve(&[Skip, DeleteFiles, Skip], Action::Permanent) + .expect("delete files") + .confirmation(), + DELETE_CACHE_FILES + ); + + let both = prepared + .approve(&[Run, Skip, DeleteFiles], Action::Permanent) + .expect("both intents"); + assert_eq!(both.confirmation(), RUN_AND_DELETE); + assert_eq!(both.owner_steps(), 1); + assert_eq!(both.file_steps(), 1); + assert_eq!(both.plan.targets.len(), 2); + // Owner approval reaches the owner's scope; deletion reaches exactly + // the selected path and nothing wider. + let paths: Vec<_> = both + .plan + .targets + .iter() + .map(|target| &target.path) + .collect(); + assert!(paths.contains(&&uv)); + assert!(paths.contains(&&runtime)); + assert!(!paths.contains(&&pnpm)); + assert_eq!(both.skipped.len(), 1); + assert_eq!(both.skipped[0].path, pnpm); + assert_eq!(both.skipped[0].outcome, Outcome::Skipped); + assert_eq!(both.skipped[0].problem, Some(Problem::NoCommand)); + let text = both.description(); + assert!(text.contains("Run owner commands (1)")); + assert!( + text.contains("Delete files directly, not through their owner (1)") + ); + assert!(text.contains("cannot be undone")); + assert!(text.contains("Nothing happens to (1)")); + assert_eq!(CONFIRMATIONS.len(), 5); + for path in [uv, pnpm, runtime] { + assert!(path.join("payload").exists(), "approval runs nothing"); + } +} + +#[test] +fn skip_means_nothing_happens_even_inside_a_chosen_scope() { + let fixture = Fixture::new(); + let uv = fixture.dir(".cache/uv"); + let archive = fixture.dir(".cache/uv/archive-v0"); + let wheels = fixture.dir(".cache/uv/wheels-v5"); + let mut probe = fixture.probe("uv", "uv 0.11.0", &uv); + let prepared = prepare_with( + &[target(&archive), target(&wheels)], + &fixture.root, + fixture.env.clone(), + &mut probe, + ) + .expect("preview"); + assert_eq!(prepared.operations.len(), 1, "one scope, asked twice"); + assert!(prepared.operations[0].wider()); + for refused in [[Run, Skip], [Run, DeleteFiles], [DeleteFiles, Run]] { + assert!( + prepared + .approve(&refused, Action::Permanent) + .expect_err("overlapping choices") + .contains("choose the same action"), + "{refused:?}" + ); + } + let approved = prepared + .approve(&[Run, Run], Action::Skip) + .expect("same choice"); + assert_eq!(approved.steps, [Step::Owner(0)], "the command runs once"); + + let decisions = prepared + .decisions_for(&[(wheels.clone(), Run), (archive.clone(), Run)]) + .expect("by path"); + assert_eq!(decisions, [Run, Run]); + assert!(prepared.decisions_for(&[(archive.clone(), Run)]).is_err()); + assert!( + prepared + .decisions_for(&[ + (archive.clone(), Run), + (archive.clone(), Skip), + (wheels, Run) + ]) + .is_err() + ); + assert!( + prepared + .decisions_for(&[(archive, Run), (uv, Run)]) + .is_err(), + "only marked paths" + ); +} + +#[test] +fn delete_files_names_the_caches_it_would_bypass() { + let fixture = Fixture::new(); + let wrapper = fixture.env.home.join(".cache"); + let uv = fixture.dir(".cache/uv"); + let tagged = fixture.dir(".cache/tool/data"); + std::fs::write( + tagged.join("CACHEDIR.TAG"), + "Signature: 8a477f597d28d172789f06886806bc55", + ) + .expect("tag"); + let mut probe = fixture.probe("absent", "", &uv); + let prepared = prepare_with( + &[target(&wrapper)], + &fixture.root, + fixture.env.clone(), + &mut probe, + ) + .expect("preview"); + let disclosure = prepared.proposals[0].delete.as_ref().expect("offered"); + assert_eq!(disclosure.path, wrapper); + assert!( + disclosure + .contains + .iter() + .any(|item| item.starts_with("uv cache")), + "{disclosure:?}" + ); + assert!( + disclosure + .contains + .iter() + .any(|item| item.starts_with("tagged cache")), + "{disclosure:?}" + ); + let text = disclosure.description(Action::Trash); + assert!(text.contains("owners are not involved either")); + assert!(text.contains("recoverable until the Trash is emptied")); + assert!(uv.join("payload").exists()); +} + +#[test] +fn guarded_paths_offer_neither_command_nor_deletion() { + let fixture = Fixture::new(); + let cache = fixture.dir(".cache/uv"); + let mut probe = fixture.probe("uv", "uv 0.11.0", &cache); + // The scan root itself is never removable, whatever is chosen. + let prepared = + prepare_with(&[target(&cache)], &cache, fixture.env, &mut probe) + .expect("preview"); + let proposal = &prepared.proposals[0]; + assert!(!proposal.allows(Decision::Owner)); + assert!(!proposal.allows(Decision::DeleteFiles)); + assert_eq!( + proposal.delete_issue.as_ref().map(|issue| issue.problem), + Some(Problem::Refused) + ); + assert!( + prepared + .approve(&[Decision::DeleteFiles], Action::Permanent) + .is_err() + ); +} + +#[cfg(unix)] +fn run_fixture( + fixture: &Fixture, + marks: &[PathBuf], + decisions: &[Decision], + files: Action, +) -> (Approved, crate::removal::RemovalHandle) { + // Only the fixture CLI is reachable, so no real tool is ever probed. + let mut env = fixture.env.clone(); + let bin = fixture.executable.parent().expect("bin"); + env.variables + .insert("PATH".into(), bin.to_str().expect("bin").into()); + let targets: Vec<_> = marks.iter().map(|path| target(path)).collect(); + let prepared = + prepare_with(&targets, &fixture.root, env, &mut process::SystemProbe) + .expect("preview"); + let approved = prepared.approve(decisions, files).expect("decisions"); + let handle = crate::removal::spawn_cleanup( + approved.clone(), + crate::removal_limit::Limit::default().into(), + ); + (approved, handle) +} + +#[cfg(unix)] +fn reports( + events: &[crate::removal::RemovalEvent], +) -> Vec<(PathBuf, Action, Outcome, Option)> { + events + .iter() + .filter_map(|event| match event { + crate::removal::RemovalEvent::Cleanup(report) => Some(( + report.path.clone(), + report.action, + report.outcome, + report.problem, + )), + _ => None, + }) + .collect() +} + +#[cfg(unix)] +#[test] +fn a_failed_owner_command_stays_local_and_deletion_runs_only_where_chosen() { + let _execution = EXECUTION + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let mut fixture = executable_fixture(); + fixture + .env + .variables + .insert("FIXTURE_FAIL".into(), "1".into()); + let uv = fixture.env.home.join(".cache/uv"); + let stale = fixture.dir(".cache/stale-tool"); + let kept = fixture.dir(".cache/kept-tool"); + let (_, handle) = run_fixture( + &fixture, + &[uv.clone(), stale.clone(), kept.clone()], + &[Run, DeleteFiles, Skip], + Action::Permanent, + ); + let events = collect(&handle); + let reports = reports(&events); + assert!( + reports.contains(&( + kept.clone(), + Action::Skip, + Outcome::Skipped, + Some(Problem::UnknownOwner) + )), + "{reports:?}" + ); + assert!( + reports.contains(&( + uv.clone(), + Action::Owner, + Outcome::Failed, + Some(Problem::CommandFailed) + )), + "{reports:?}" + ); + assert!( + reports.contains(&( + stale.clone(), + Action::Permanent, + Outcome::Succeeded, + None + )), + "{reports:?}" + ); + assert!(events.iter().any(|event| matches!( + event, + crate::removal::RemovalEvent::Done { + removed: 1, + failed: 1, + .. + } + ))); + assert!(fixture.env.home.join("invocation").exists(), "owner ran"); + assert!( + uv.join("payload").exists(), + "a failed owner never falls back" + ); + assert!(!stale.exists(), "the deliberate choice ran"); + assert!(kept.join("payload").exists(), "skip touched nothing"); +} + +#[cfg(unix)] +#[test] +fn stop_cancels_the_running_command_and_reports_the_rest_not_reached() { + let _execution = EXECUTION + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let mut fixture = executable_fixture(); + fixture + .env + .variables + .insert("FIXTURE_WAIT".into(), "1".into()); + let uv = fixture.env.home.join(".cache/uv"); + // Sorted after the cache, so it is still waiting when Stop arrives. + let later = fixture.dir("zz-stale-output"); + let (_, handle) = run_fixture( + &fixture, + &[uv.clone(), later.clone()], + &[Decision::Owner, Decision::DeleteFiles], + Action::Permanent, + ); + let start = Instant::now(); + while !fixture.env.home.join("invocation").exists() { + assert!(start.elapsed() < Duration::from_secs(10)); + std::thread::sleep(Duration::from_millis(10)); + } + handle.cancel(); + let reports = reports(&collect(&handle)); + assert!( + reports.contains(&( + uv.clone(), + Action::Owner, + Outcome::Cancelled, + Some(Problem::Cancelled) + )), + "{reports:?}" + ); + assert!( + reports.contains(&( + later.clone(), + Action::Permanent, + Outcome::NotReached, + None + )), + "{reports:?}" + ); + assert!(uv.join("payload").exists()); + assert!( + later.join("payload").exists(), + "not reached means untouched" + ); +} + +#[cfg(unix)] +#[test] +fn deleting_files_in_use_is_refused_on_the_worker() { + let _execution = EXECUTION + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let fixture = executable_fixture(); + let busy = fixture.dir("busy-output"); + let mut holder = std::process::Command::new("/bin/sh") + // A trailing command keeps the shell, and its argument naming the + // path, alive instead of exec-ing sleep in its place. + .args(["-c", "/bin/sleep 20; :", "holder"]) + .arg(&busy) + .current_dir(&busy) + .spawn() + .expect("fixture holder"); + std::thread::sleep(Duration::from_millis(100)); + let (_, handle) = run_fixture( + &fixture, + std::slice::from_ref(&busy), + &[Decision::DeleteFiles], + Action::Permanent, + ); + let reports = reports(&collect(&handle)); + holder.kill().expect("stop holder"); + holder.wait().expect("wait holder"); + assert_eq!( + reports, + [( + busy.clone(), + Action::Permanent, + Outcome::Failed, + Some(Problem::InUse) + )] + ); + assert!(busy.join("payload").exists()); +} + +/// Deleting files by Trash in a cleanup needs the Trash found for it; an +/// owner-only cleanup never looks. +#[test] +fn a_cleanup_finds_the_trash_only_when_files_go_there() { + use crate::removal::{RemovalMode, TrashBackend, backend_for}; + let fixture = Fixture::new(); + let (prepared, _) = mixed(&fixture); + let trash = prepared + .approve(&[Skip, Skip, DeleteFiles], Action::Trash) + .expect("trash files"); + assert_eq!( + backend_for(RemovalMode::OwnerCleanup, Some(&trash)), + crate::removal::detect_trash_backend() + ); + let owner = prepared + .approve(&[Run, Skip, Skip], Action::Trash) + .expect("owner only"); + assert_eq!( + backend_for(RemovalMode::OwnerCleanup, Some(&owner)), + TrashBackend::Unavailable + ); + let permanent = prepared + .approve(&[Skip, Skip, DeleteFiles], Action::Permanent) + .expect("permanent files"); + assert_eq!( + backend_for(RemovalMode::OwnerCleanup, Some(&permanent)), + TrashBackend::Unavailable + ); +} + +/// Skip on a parent means nothing happens inside it either: deleting a +/// marked child under a skipped parent is refused until both agree. +#[test] +fn a_skipped_parent_protects_a_marked_child() { + let fixture = Fixture::new(); + let wrapper = fixture.dir("tools"); + let child = fixture.dir("tools/stale"); + let mut probe = fixture.probe("absent", "", &wrapper); + let prepared = prepare_with( + &[target(&wrapper), target(&child)], + &fixture.root, + fixture.env.clone(), + &mut probe, + ) + .expect("preview"); + assert!( + prepared + .approve(&[Skip, DeleteFiles], Action::Permanent) + .expect_err("overlap") + .contains("choose the same action") + ); + let both = prepared + .approve(&[DeleteFiles, DeleteFiles], Action::Permanent) + .expect("same action"); + assert_eq!(both.steps.len(), 1, "the child is inside the parent"); + assert!(child.join("payload").exists()); +} diff --git a/crates/disktree-core/src/cleanup/tests/properties.rs b/crates/disktree-core/src/cleanup/tests/properties.rs new file mode 100644 index 00000000..12530fa6 --- /dev/null +++ b/crates/disktree-core/src/cleanup/tests/properties.rs @@ -0,0 +1,933 @@ +//! Rules of cache cleanup checked against many generated cases rather +//! than a few chosen ones. Each test states the promise it holds, builds +//! cases from a seed, and names the seed when a case breaks the rule: +//! `PWRDISK_SEED= cargo test -p disktree-core ` replays it. + +use std::collections::BTreeSet; + +use super::*; +use crate::test_rng::Rng; + +/// This run's seeds, `runs` of them. They start at `PWRDISK_SEED` to +/// replay a failure, at the clock otherwise, so every run tries cases no +/// earlier run tried. +fn seeds(runs: u64) -> impl Iterator { + let first = std::env::var("PWRDISK_SEED") + .ok() + .and_then(|seed| seed.parse().ok()) + .unwrap_or_else(|| { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default(); + now.as_secs().wrapping_mul(1_000_003) + ^ u64::from(now.subsec_nanos()) + }); + (0..runs).map(move |run| first.wrapping_add(run)) +} + +fn pick<'a, T>(rng: &mut Rng, items: &'a [T]) -> &'a T { + &items[usize::try_from(rng.below(items.len() as u64)).expect("index")] +} + +fn count(rng: &mut Rng, low: u64, high: u64) -> usize { + usize::try_from(low + rng.below(high - low + 1)).expect("count") +} + +/// A directory name that can hold the characters a cache root's name may +/// legally have, the ones a careless parser strips or splits on included. +#[cfg(unix)] +fn awkward_name(rng: &mut Rng) -> String { + const PLAIN: [char; 8] = ['a', 'b', '-', '_', '.', 'é', ' ', '\t']; + const ENDINGS: [&str; 7] = ["", "", "", " ", "\t", "\r", " \r"]; + loop { + let mut name: String = + (0..count(rng, 1, 6)).map(|_| *pick(rng, &PLAIN)).collect(); + if rng.percent(15) { + name.insert(0, *pick(rng, &['\r', '\n'])); + } + name.push_str(pick(rng, &ENDINGS)); + let trimmed = name.trim_end(); + if !matches!(name.as_str(), "." | "..") + && !matches!(trimmed, "" | "." | "..") + { + return name; + } + } +} + +/// An owner that prints exactly `output` for its cache root and the +/// given version, and refuses anything that would change something. +#[cfg(unix)] +struct Printed { + executable: PathBuf, + version: String, + output: String, +} + +#[cfg(unix)] +impl Probe for Printed { + fn executable( + &mut self, + _: &str, + _: &Environment, + ) -> Result { + Ok(self.executable.clone()) + } + + fn output( + &mut self, + command: &Command, + _: &Environment, + ) -> Result { + match command + .arguments + .iter() + .map(String::as_str) + .collect::>() + .as_slice() + { + ["--version"] | ["version", "--component", "package"] => { + Ok(self.version.clone()) + } + ["config", "get", "cache"] | ["cache", "dir" | "path"] => { + Ok(self.output.clone()) + } + _ => panic!("Preview attempted a write: {command:?}"), + } + } +} + +/// The cache root an owner command acts on is exactly the one the owner +/// printed, never a similar path found by trimming or splitting its +/// output; and a root printed plainly, with one LF, is always accepted. +/// +/// The oracle is the generator: it knows the real root, and puts the +/// marked path either inside it or inside a look-alike next to it. +#[cfg(unix)] +#[test] +fn an_owner_command_acts_only_on_the_root_the_owner_printed() { + const OWNERS: [(Owner, &str); 5] = [ + (Owner::Uv, "uv 0.11.0"), + (Owner::Pip, "pip 24.0 from /fixture (python 3.12)"), + (Owner::Cypress, "14.0.0"), + (Owner::Npm, "10.8.0"), + (Owner::Npx, "11.6.2"), + ]; + let scope_of = |owner: Owner, root: &Path| match owner { + Owner::Npm => root.join("_cacache"), + Owner::Npx => root.join("_npx"), + _ => root.to_owned(), + }; + for seed in seeds(150) { + let rng = &mut Rng::new(seed); + let fixture = Fixture::new(); + let (owner, version) = *pick(rng, &OWNERS); + let mut parent = fixture.env.home.clone(); + if rng.percent(40) { + parent.push(awkward_name(rng)); + } + let name = awkward_name(rng); + let root = parent.join(&name); + // What a parser that trims or drops a CR would read instead. + let look_alike = parent.join(name.trim_end()); + let marked_root = if look_alike != root && rng.percent(50) { + &look_alike + } else { + &root + }; + let mut selected = scope_of(owner, marked_root); + if rng.percent(50) { + selected.push("entries"); + } + for directory in [scope_of(owner, &root), selected.clone()] { + std::fs::create_dir_all(&directory).expect("cache fixture"); + } + let printed = root.to_str().expect("UTF-8 root"); + let terminator = *pick(rng, &["\n", "\n", "\n", "\r\n", "", "\n\n"]); + let mut probe = Printed { + executable: fixture.executable.clone(), + version: version.into(), + output: format!("{printed}{terminator}"), + }; + let case = format!( + "seed {seed}: {owner:?} printed {:?}, marked {selected:?}", + probe.output + ); + let resolved = + resolve_owner(owner, &selected, &fixture.env, &mut probe); + let plain = terminator == "\n" + && !printed.contains(['\n', '\r']) + && marked_root == &root; + match &resolved { + Ok(Some(operation)) => { + assert_eq!(operation.cache_root, root, "{case}"); + assert_eq!(operation.scope, scope_of(owner, &root), "{case}"); + let named = operation + .command + .arguments + .iter() + .chain(operation.command.environment.values()) + .any(|argument| argument == printed); + assert!(named, "{case}: {:?}", operation.command); + } + Ok(None) | Err(_) => { + assert!(!plain, "{case}: refused a plain root: {resolved:?}"); + } + } + if let Err(issue) = &resolved { + assert_eq!(issue.problem, Problem::ConfigCheckFailed, "{case}"); + } + } +} + +/// Signs of a cache that no name gives away. Each is put on a directory +/// in the generated tree; the decoys look close but are not caches. +#[derive(Clone, Copy, Debug)] +enum Sign { + Tag, + Pip, + Pnpm, + Cypress, + TagDirectory, + WheelsOnly, + EmptyPnpmVersion, + ShortCypressVersion, +} + +const SIGNS: [Sign; 8] = [ + Sign::Tag, + Sign::Pip, + Sign::Pnpm, + Sign::Cypress, + Sign::TagDirectory, + Sign::WheelsOnly, + Sign::EmptyPnpmVersion, + Sign::ShortCypressVersion, +]; + +fn put(sign: Sign, at: &Path, rng: &mut Rng) { + let dir = |path: PathBuf| std::fs::create_dir_all(path).expect("sign"); + match sign { + Sign::Tag => { + std::fs::write( + at.join("CACHEDIR.TAG"), + "Signature: 8a477f597d28d172789f06886806bc55", + ) + .expect("tag"); + } + Sign::Pip => { + dir(at.join("wheels")); + dir(at.join(pick(rng, &["http", "http-v2"]))); + } + Sign::Pnpm => dir(at.join(format!("v{}/files", rng.below(20)))), + Sign::Cypress => { + let version = format!("{}.{}.0", 10 + rng.below(6), rng.below(9)); + if rng.percent(50) { + dir(at.join(version).join("Cypress.app")); + } else { + dir(at.join(&version).join("Cypress")); + std::fs::write(at.join(version).join("Cypress/Cypress"), "") + .expect("binary"); + } + } + Sign::TagDirectory => dir(at.join("CACHEDIR.TAG")), + Sign::WheelsOnly => dir(at.join("wheels")), + Sign::EmptyPnpmVersion => dir(at.join("v7")), + Sign::ShortCypressVersion => dir(at.join("14.0/Cypress.app")), + } +} + +/// The oracle: does this directory itself carry a cache's sign? Reads +/// every entry, where the code under test reads a bounded few. +fn signed(directory: &Path) -> bool { + let is_dir = |name: &str| directory.join(name).is_dir(); + if directory.join("CACHEDIR.TAG").is_file() + || (is_dir("wheels") && (is_dir("http") || is_dir("http-v2"))) + { + return true; + } + std::fs::read_dir(directory) + .into_iter() + .flatten() + .flatten() + .any(|entry| { + let name = entry.file_name().to_string_lossy().into_owned(); + let path = entry.path(); + let pnpm = name.strip_prefix('v').is_some_and(|digits| { + !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) + }) && path.join("files").is_dir(); + let parts: Vec<_> = name.split('.').collect(); + let cypress = parts.len() == 3 + && parts.iter().all(|part| { + !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()) + }) + && (path.join("Cypress.app").is_dir() + || path.join("Cypress/Cypress").is_file()); + pnpm || cypress + }) +} + +fn directories_under(path: &Path) -> Vec { + let mut found = vec![]; + let mut pending = vec![path.to_owned()]; + while let Some(directory) = pending.pop() { + if !directory.is_dir() { + continue; + } + for entry in std::fs::read_dir(&directory).expect("listing") { + pending.push(entry.expect("entry").path()); + } + found.push(directory); + } + found +} + +/// A cache's sign on any directory protects everything under it: Review +/// treats the path as a cache, and raw removal refuses it, however deep +/// the path is. Raw removal also refuses a path with a cache inside it. +/// Anything with no sign above or inside it stays removable. +/// +/// The oracle walks every ancestor up to the fixture and every directory +/// below the path, reading each one whole. +#[test] +fn a_cache_sign_protects_everything_under_it_and_nothing_else() { + for seed in seeds(120) { + let rng = &mut Rng::new(seed); + let fixture = Fixture::new(); + let mut chain = vec![fixture.env.home.join(format!("n{seed:x}"))]; + for level in 0..count(rng, 1, 5) { + let next = chain.last().expect("level").join(format!("n{level}")); + chain.push(next); + } + let deepest = chain.last().expect("deepest"); + std::fs::create_dir_all(deepest).expect("chain"); + std::fs::write(deepest.join("payload"), [0; 64]).expect("payload"); + for (level, directory) in chain.iter().enumerate() { + if rng.percent(30) { + std::fs::create_dir(directory.join(format!("m{level}"))) + .expect("neighbour"); + } + if rng.percent(20) { + put(*pick(rng, &SIGNS), directory, rng); + } + } + let selected = if rng.percent(25) { + deepest.join("payload") + } else { + pick(rng, &chain).clone() + }; + let above = selected + .ancestors() + .take_while(|ancestor| ancestor.starts_with(&fixture.root)) + .any(signed); + let inside = directories_under(&selected).iter().any(|d| signed(d)); + let case = format!("seed {seed}: {selected:?}"); + let hint = recognize::inspection_with(&selected, &fixture.env); + assert_eq!(hint.is_some(), above, "{case}: {hint:?}"); + let raw = check_raw(&[target(&selected)]); + assert_eq!(raw.is_err(), above || inside, "{case}: {raw:?}"); + assert!(selected.exists(), "{case}: checking cannot delete"); + } +} + +/// How the owner's executable is reached on PATH. +#[cfg(unix)] +#[derive(Clone, Copy, Debug)] +enum Reach { + /// A file in an ordinary directory. + Direct, + /// A link into an installation, as npm's own `npm -> npm-cli.js`. + Installed, + /// A file in a `shims` directory on PATH. + InShims, + /// A link into some `shims` directory. + LinkToShims, + /// A link to Volta's dispatcher. + VoltaShim, + /// A file in `~/.volta/bin`. + VoltaBin, +} + +/// What runs the script, read from its first line. +#[cfg(unix)] +#[derive(Clone, Copy, Debug)] +enum Interpreter { + Shell, + /// `env node`, with node on PATH reached as given. + Env(Reach), + /// `env node --flag`: arguments env would pass on. + EnvWithArguments, + /// A shim named directly on the first line. + ShimPath, +} + +#[cfg(unix)] +const fn installs(reach: Reach) -> bool { + matches!( + reach, + Reach::InShims + | Reach::LinkToShims + | Reach::VoltaShim + | Reach::VoltaBin + ) +} + +/// Write a script that records that it ran and prints `version`, and put +/// it on a PATH directory as `name`, reached as `reach`. Returns the PATH +/// directory it is reachable from. +#[cfg(unix)] +fn place( + root: &Path, + name: &str, + target_name: &str, + reach: Reach, + first_line: &str, + version: &str, +) -> PathBuf { + use std::os::unix::fs::PermissionsExt as _; + let ran = root.join("ran"); + let script = |path: &Path| { + std::fs::create_dir_all(path.parent().expect("parent")).expect("dir"); + std::fs::write( + path, + format!( + concat!( + "{first_line}\n", + "printf '%s\\n' \"$0\" >> '{ran}'\n", + "printf '%s\\n' '{version}'\n", + ), + first_line = first_line, + ran = ran.display(), + version = version, + ), + ) + .expect("script"); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)) + .expect("executable"); + }; + let link = |from: &Path, to: &Path| { + std::fs::create_dir_all(from.parent().expect("parent")).expect("dir"); + std::os::unix::fs::symlink(to, from).expect("link"); + }; + let path_dir = |dir: &str| root.join(format!("{dir}-{name}")); + match reach { + Reach::Direct => { + let dir = path_dir("bin"); + script(&dir.join(name)); + dir + } + Reach::Installed => { + let dir = path_dir("bin"); + let installed = path_dir("lib").join("dist").join(target_name); + script(&installed); + link(&dir.join(name), &installed); + dir + } + Reach::InShims => { + let dir = path_dir("version-manager").join("shims"); + script(&dir.join(name)); + dir + } + Reach::LinkToShims => { + let dir = path_dir("bin"); + let shim = path_dir("version-manager").join("shims").join(name); + script(&shim); + link(&dir.join(name), &shim); + dir + } + Reach::VoltaShim => { + let dir = path_dir("bin"); + let shim = path_dir("volta").join("volta-shim"); + script(&shim); + link(&dir.join(name), &shim); + dir + } + Reach::VoltaBin => { + let dir = path_dir("home").join(".volta").join("bin"); + script(&dir.join(name)); + dir + } + } +} + +/// Finding an owner's executable never runs one that could install +/// software on demand: a version manager's shim, Volta's dispatcher, an +/// npm that is not npm's own `npm-cli.js`, or a script whose interpreter +/// is any of those. Everything else is found, and its version probed. +/// +/// The oracle is the generator's own record of what each layout is, and +/// every generated script writes down that it ran. +#[cfg(unix)] +#[test] +fn probing_never_runs_a_launcher_that_could_install() { + const REACHES: [Reach; 6] = [ + Reach::Direct, + Reach::Installed, + Reach::InShims, + Reach::LinkToShims, + Reach::VoltaShim, + Reach::VoltaBin, + ]; + const OWNERS: [(Owner, &str, &str); 5] = [ + (Owner::Uv, "uv", "uv 0.11.0"), + (Owner::Pip, "pip", "pip 24.0 from /fixture (python 3.12)"), + (Owner::Pip, "pip3", "pip 24.0 from /fixture (python 3.12)"), + (Owner::Cypress, "cypress", "14.0.0"), + (Owner::Npm, "npm", "10.8.0"), + ]; + // Generated owners are real processes named like real owners, which + // another test's in-use check would see. + let _execution = EXECUTION + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + for seed in seeds(60) { + let rng = &mut Rng::new(seed); + let fixture = Fixture::new(); + let (owner, name, version) = *pick(rng, &OWNERS); + let reach = *pick(rng, &REACHES); + let interpreter = match rng.below(4) { + 0 => Interpreter::Env(*pick(rng, &REACHES)), + 1 if rng.percent(50) => Interpreter::EnvWithArguments, + 1 => Interpreter::ShimPath, + _ => Interpreter::Shell, + }; + let root = &fixture.root; + let mut path = vec![]; + let first_line = match interpreter { + Interpreter::Shell => "#!/bin/sh".to_owned(), + Interpreter::Env(node) => { + path.push(place( + root, + "node", + "node", + node, + "#!/bin/sh", + version, + )); + "#!/usr/bin/env node".to_owned() + } + Interpreter::EnvWithArguments => { + "#!/usr/bin/env node --flag".into() + } + Interpreter::ShimPath => { + let shims = place( + root, + "node", + "node", + Reach::InShims, + "#!/bin/sh", + version, + ); + format!("#!{}", shims.join("node").display()) + } + }; + // npm's distribution names its entry point npm-cli.js; a link + // to anything else is a proxy such as Corepack. + let target_name = if owner == Owner::Npm && rng.percent(60) { + "npm-cli.js" + } else { + name + }; + path.insert( + 0, + place(root, name, target_name, reach, &first_line, version), + ); + let reached_npm_cli = + matches!(reach, Reach::Installed) && target_name == "npm-cli.js"; + let unsafe_launcher = installs(reach) + || (owner == Owner::Npm && !reached_npm_cli) + || match interpreter { + Interpreter::Shell => false, + Interpreter::Env(node) => installs(node), + Interpreter::EnvWithArguments | Interpreter::ShimPath => true, + }; + let mut env = fixture.env.clone(); + env.variables.extend([ + ( + "PATH".into(), + std::env::join_paths(&path) + .expect("PATH") + .into_string() + .expect("UTF-8"), + ), + ("HOME".into(), env.home.to_str().expect("home").into()), + ]); + let cache = env.home.join("cache"); + let case = format!( + "seed {seed}: {name} reached {reach:?}, run by {interpreter:?}, \ + linked to {target_name}" + ); + let resolved = + resolve_owner(owner, &cache, &env, &mut process::SystemProbe); + let ran = std::fs::read_to_string(root.join("ran")).unwrap_or_default(); + let issue = resolved.expect_err(&case); + if unsafe_launcher { + assert_eq!(issue.problem, Problem::UnsupportedLauncher, "{case}"); + assert_eq!(ran, "", "{case}: ran before it was refused"); + } else { + // Our scripts print a version for a cache root, so the root + // check fails after the probe: proof that the probe ran. + assert_eq!(issue.problem, Problem::ConfigCheckFailed, "{case}"); + assert_ne!(ran, "", "{case}: an ordinary launcher was not run"); + } + } +} + +/// A running owner is recognized whatever form launched it: the friendly +/// name, a versioned name such as `pip3.12`, the companion runner such as +/// `uvx`, the node entry points npm runs through, or the exact executable +/// the command names. Programs that only share a prefix are not. +/// +/// The oracle is the list of each owner's launcher names. +#[test] +fn a_running_owner_is_recognized_in_every_launcher_form() { + const OTHERS: [&str; 10] = [ + "node", + "python3", + "python3.12", + "bash", + "unrelated.js", + "npm-cli.json", + "pipx", + "uvicorn", + "cypress.json", + "pip3.x", + ]; + const OWNERS: [Owner; 5] = [ + Owner::Npm, + Owner::Npx, + Owner::Uv, + Owner::Pip, + Owner::Cypress, + ]; + const DIRECTORIES: [&str; 4] = [ + "", + "/usr/local/bin/", + "/opt/tool/lib/node_modules/npm/bin/", + "/install/bin/", + ]; + let launchers = |owner: Owner| -> Vec { + match owner { + Owner::Npm | Owner::Npx => { + ["npm", "npx", "npm-cli.js", "npx-cli.js"] + .map(String::from) + .to_vec() + } + Owner::Uv => vec!["uv".into(), "uvx".into()], + Owner::Pip => vec!["pip".into(), "pip3".into(), "pip3.12".into()], + _ => vec![owner.executable().into()], + } + }; + for seed in seeds(400) { + let rng = &mut Rng::new(seed); + let owner = *pick(rng, &OWNERS); + let names = launchers(owner); + let executable = rng + .percent(50) + .then(|| PathBuf::from("/install/bin").join(pick(rng, &names))); + let launcher = rng.percent(60); + let base = if launcher { + pick(rng, &names).clone() + } else { + (*pick(rng, &OTHERS)).to_owned() + }; + let argument = format!("{}{base}", pick(rng, &DIRECTORIES)); + let expected = launcher + || executable + .as_ref() + .is_some_and(|executable| executable.ends_with(&base)); + assert_eq!( + process::owner_named(owner, executable.as_deref(), &argument), + expected, + "seed {seed}: {owner:?} with executable {executable:?} \ + launched as {argument:?}" + ); + } +} + +/// A generated set of marked paths, owner commands and decisions, over +/// real directories so the removal guards see a real tree. +struct Cleanup { + _fixture: Fixture, + nodes: Vec, + prepared: Prepared, + decisions: Vec, + files: Action, +} + +fn generate(rng: &mut Rng) -> Cleanup { + let fixture = Fixture::new(); + let root = fixture.env.home.join("scan"); + let mut nodes = vec![root.clone()]; + for index in 0..count(rng, 4, 12) { + let parent = pick(rng, &nodes).clone(); + nodes.push(parent.join(format!("d{index}"))); + } + for node in &nodes { + std::fs::create_dir_all(node).expect("tree"); + } + let candidates = &nodes[1..]; + let mut scopes: Vec = vec![]; + for _ in 0..count(rng, 0, 3) { + let scope = pick(rng, candidates).clone(); + if !scopes.contains(&scope) { + scopes.push(scope); + } + } + let operations = scopes + .iter() + .map(|scope| Operation { + owner: Owner::Uv, + version: "uv 0.11.0".into(), + selected: vec![], + cache_root: scope.clone(), + scope: scope.clone(), + command: Command { + executable: "/fixture/uv".into(), + arguments: vec!["cache".into(), "clean".into()], + environment: BTreeMap::new(), + working_directory: fixture.env.home.clone(), + }, + effects: String::new(), + limitations: String::new(), + }) + .collect::>(); + let mut selected = candidates.to_vec(); + rng.shuffle(&mut selected); + selected.truncate(count(rng, 1, 5)); + let proposals: Vec = selected + .iter() + .map(|path| Proposal { + selected: path.clone(), + bytes: 1, + is_dir: true, + hint: None, + owner: None, + // An owner's scope contains the marked path, or, for a wrapper + // such as npm's, lies inside it. + operations: scopes + .iter() + .enumerate() + .filter(|(_, scope)| { + (path.starts_with(scope) || scope.starts_with(path)) + && rng.percent(70) + }) + .map(|(index, _)| index) + .collect(), + issue: None, + delete: rng.percent(60).then(|| Disclosure { + path: path.clone(), + contains: vec![], + warning: String::new(), + }), + delete_issue: None, + }) + .collect(); + let decisions = proposals + .iter() + .map(|proposal| { + let offered: Vec<_> = + [Decision::Skip, Decision::Owner, Decision::DeleteFiles] + .into_iter() + .filter(|decision| proposal.allows(*decision)) + .collect(); + *pick(rng, &offered) + }) + .collect(); + let files = *pick( + rng, + &[ + Action::Trash, + Action::Permanent, + Action::Trash, + Action::Skip, + ], + ); + let prepared = Prepared { + proposals, + scope_bytes: vec![0; operations.len()], + operations, + root, + environment: fixture.env.clone(), + identities: vec![], + }; + Cleanup { + _fixture: fixture, + nodes, + prepared, + decisions, + files, + } +} + +/// What a decision acts on when it runs. +fn reached(prepared: &Prepared, step: Step) -> &Path { + match step { + Step::Owner(index) => &prepared.operations[index].scope, + Step::Files { proposal, .. } => &prepared.proposals[proposal].selected, + } +} + +/// Approval turns decisions into steps that keep each one: +/// +/// * Skip means nothing happens to the path: no step acts inside it or +/// on anything around it. +/// * No step acts inside another, so nothing is acted on twice. +/// * A path chosen for its owner command is reached only by owner +/// commands, and one chosen for Delete files only by Delete files. +/// * The steps are exactly the chosen commands, and the deletions cover +/// exactly the paths chosen for Delete files. +/// * The confirmation names exactly the intents present. +/// +/// Decisions that keep all of those are approved. The oracle is the set +/// of directories each step reaches, compared node by node. +#[test] +fn approval_keeps_every_decision_and_skip_means_nothing_happens() { + for seed in seeds(300) { + let rng = &mut Rng::new(seed); + let cleanup = generate(rng); + let prepared = &cleanup.prepared; + let decisions = &cleanup.decisions; + let under = |path: &Path| -> BTreeSet<&PathBuf> { + cleanup + .nodes + .iter() + .filter(|node| node.starts_with(path)) + .collect() + }; + let chosen = |wanted: Decision| { + prepared + .proposals + .iter() + .zip(decisions) + .filter(move |(_, decision)| **decision == wanted) + .map(|(proposal, _)| proposal) + }; + let commands: BTreeSet = chosen(Decision::Owner) + .flat_map(|proposal| proposal.operations.iter().copied()) + .collect(); + // Every path some decision acts on, with the decision. + let actions: Vec<(&Path, Decision)> = commands + .iter() + .map(|index| { + (prepared.operations[*index].scope.as_path(), Decision::Owner) + }) + .chain(chosen(Decision::DeleteFiles).map(|proposal| { + (proposal.selected.as_path(), Decision::DeleteFiles) + })) + .collect(); + let consistent = prepared.proposals.iter().zip(decisions).all( + |(proposal, decision)| { + actions.iter().all(|(path, action)| { + action == decision + || under(path).is_disjoint(&under(&proposal.selected)) + }) + }, + ) && commands.iter().all(|left| { + commands.iter().all(|right| { + left == right + || under(&prepared.operations[*left].scope) + .is_disjoint(&under(&prepared.operations[*right].scope)) + }) + }); + let deletes = chosen(Decision::DeleteFiles).count() > 0; + let acceptable = consistent + && !actions.is_empty() + && (!deletes + || matches!(cleanup.files, Action::Trash | Action::Permanent)); + let case = format!( + "seed {seed}: {:#?} decided {decisions:?} with {:?}", + prepared.proposals, cleanup.files + ); + let approved = match prepared.approve(decisions, cleanup.files) { + Ok(approved) => approved, + Err(error) => { + assert!(!acceptable, "{case}: refused: {error}"); + continue; + } + }; + assert!(acceptable, "{case}: approved {:?}", approved.steps); + let reach: Vec<_> = approved + .steps + .iter() + .map(|step| (*step, under(reached(prepared, *step)))) + .collect(); + for (index, (step, nodes)) in reach.iter().enumerate() { + for (other, other_nodes) in &reach[index + 1..] { + assert!( + nodes.is_disjoint(other_nodes), + "{case}: {step:?} and {other:?} overlap" + ); + } + } + for (proposal, decision) in prepared.proposals.iter().zip(decisions) { + let own = under(&proposal.selected); + for (step, nodes) in &reach { + let action = match step { + Step::Owner(_) => Decision::Owner, + Step::Files { .. } => Decision::DeleteFiles, + }; + assert!( + action == *decision || own.is_disjoint(nodes), + "{case}: {step:?} reaches {:?}, decided {decision:?}", + proposal.selected + ); + } + } + let owners: BTreeSet = approved + .steps + .iter() + .filter_map(|step| match step { + Step::Owner(index) => Some(*index), + Step::Files { .. } => None, + }) + .collect(); + assert_eq!(owners, commands, "{case}"); + let deleted: Vec<&PathBuf> = approved + .steps + .iter() + .filter_map(|step| match step { + Step::Files { proposal, action } => { + assert_eq!(*action, cleanup.files, "{case}"); + Some(&prepared.proposals[*proposal].selected) + } + Step::Owner(_) => None, + }) + .collect(); + for proposal in chosen(Decision::DeleteFiles) { + assert!( + deleted + .iter() + .any(|path| proposal.selected.starts_with(path)), + "{case}: {:?} is not deleted", + proposal.selected + ); + } + for path in &deleted { + assert!( + chosen(Decision::DeleteFiles).any(|p| p.selected == **path), + "{case}: {path:?} was not chosen for Delete files" + ); + } + let skipped: Vec<_> = + approved.skipped.iter().map(|report| &report.path).collect(); + let skips: Vec<_> = chosen(Decision::Skip) + .map(|proposal| &proposal.selected) + .collect(); + assert_eq!(skipped, skips, "{case}"); + let phrase = approved.confirmation(); + assert_eq!( + ( + phrase.contains("RUN OWNER CLEANUP"), + phrase.contains("TRASH"), + phrase.contains("DELETE"), + ), + ( + !owners.is_empty(), + !deleted.is_empty() && cleanup.files == Action::Trash, + !deleted.is_empty() && cleanup.files == Action::Permanent, + ), + "{case}: {phrase}" + ); + } +} diff --git a/crates/disktree-core/src/clone_cache.rs b/crates/disktree-core/src/clone_cache.rs new file mode 100644 index 00000000..ddc83639 --- /dev/null +++ b/crates/disktree-core/src/clone_cache.rs @@ -0,0 +1,279 @@ +//! Per-scan reuse of confirmed full-clone metadata, without a serial consumer. + +use std::hash::{Hash, Hasher as _}; +use std::sync::Mutex; + +use rustc_hash::{FxHashMap, FxHashSet, FxHasher}; + +use crate::sharing::CloneInfo; + +const SHARDS: usize = 64; +const GROUPS_PER_SHARD: usize = 1_000_000 / SHARDS; +const ALIASES_PER_SHARD: usize = GROUPS_PER_SHARD; + +struct Sample { + info: CloneInfo, + remaining: u32, + aliases: FxHashSet, +} + +#[derive(Default)] +struct Shard { + groups: FxHashMap<(u64, u64), Sample>, + aliases: usize, +} + +pub struct Cache { + shards: [Mutex; SHARDS], + group_limit: usize, + alias_limit: usize, +} + +impl Default for Cache { + fn default() -> Self { + Self { + shards: std::array::from_fn(|_| Mutex::new(Shard::default())), + group_limit: GROUPS_PER_SHARD, + alias_limit: ALIASES_PER_SHARD, + } + } +} + +impl Cache { + fn shard(&self, key: (u64, u64)) -> &Mutex { + let mut hash = FxHasher::default(); + key.hash(&mut hash); + let index = usize::try_from(hash.finish() % SHARDS as u64) + .expect("shard index fits"); + &self.shards[index] + } + + /// Whether another file of this group was found to share all its + /// blocks: only such a file is sampled. For a listing that leaves the + /// sharing flags out (`macos::Clones::Ids`), which every file of a + /// group shares. A group past the cache's room is not known here, and + /// its files read their own flags: that costs time, not accuracy. + pub fn shares_all(&self, device: u64, id: u64) -> bool { + let key = (device, id); + device != 0 + && id != 0 + && self + .shard(key) + .lock() + .expect("clone cache") + .groups + .contains_key(&key) + } + + /// A reference count is a reuse budget, not a permanent fact. A later + /// member past that budget is measured again, catching clone growth. + /// Modified clones and unknown physical volumes are never reused. + pub fn get( + &self, + device: u64, + id: u64, + inode: u64, + links: u64, + allocated: u64, + measure: impl FnOnce() -> CloneInfo, + ) -> CloneInfo { + let key = (device, id); + if device != 0 && id != 0 && inode != 0 { + let mut shard = self.shard(key).lock().expect("clone cache"); + let alias_room = shard.aliases < self.alias_limit; + if let Some(sample) = shard + .groups + .get_mut(&key) + .filter(|sample| sample.info.data_bytes == allocated) + { + if sample.aliases.contains(&inode) { + return sample.info; + } + if sample.remaining > 0 && (links == 1 || alias_room) { + sample.remaining -= 1; + let info = sample.info; + if links > 1 && sample.aliases.insert(inode) { + shard.aliases += 1; + } + return info; + } + } + drop(shard); + } + // Filesystem calls never hold a shard lock. Racing first samples + // may duplicate a query; they cannot funnel directory workers into + // one slow reader. Each scan owns its cache, including re-scans. + let info = measure(); + if device == 0 + || inode == 0 + || info.device != device + || info.id != id + || info.references < 2 + || info.private_bytes != Some(0) + { + return info; + } + let mut shard = self.shard(key).lock().expect("clone cache"); + if let Some(old) = shard.groups.remove(&key) { + shard.aliases -= old.aliases.len(); + } + if shard.groups.len() < self.group_limit + && (links == 1 || shard.aliases < self.alias_limit) + { + let mut aliases = FxHashSet::default(); + if links > 1 { + aliases.insert(inode); + shard.aliases += 1; + } + shard.groups.insert( + key, + Sample { + info, + remaining: info.references - 1, + aliases, + }, + ); + } + info + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + fn sample(device: u64, id: u64, references: u32) -> CloneInfo { + CloneInfo { + device, + id, + references, + private_bytes: Some(0), + data_bytes: 4096, + } + } + + #[test] + fn volume_scope_scan_lifetime_and_memory_caps_limit_reuse() { + let cache = Cache { + group_limit: 1, + alias_limit: 1, + ..Cache::default() + }; + let calls = Cell::new(0); + for device in 1..=128 { + for inode in 1..=3 { + let value = cache.get(device, 42, inode, 2, 4096, || { + calls.set(calls.get() + 1); + sample(device, 42, 3) + }); + assert_eq!(value.device, device); + } + } + for shard in &cache.shards { + let shard = shard.lock().expect("cache"); + assert!(shard.groups.len() <= 1); + assert!(shard.aliases <= 1); + drop(shard); + } + assert!(calls.get() > 128, "capped aliases must be measured"); + let fresh = Cache::default(); + let mut measured = false; + fresh.get(1, 42, 1, 1, 4096, || { + measured = true; + sample(1, 42, 3) + }); + assert!(measured, "new scans must not reuse previous observations"); + } + + #[test] + fn only_a_sampled_group_is_known_to_share_all_its_blocks() { + let cache = Cache::default(); + assert!(!cache.shares_all(1, 42)); + cache.get(1, 42, 1, 1, 4096, || sample(1, 42, 2)); + assert!(cache.shares_all(1, 42)); + // A modified member is never a sample, nor is an unknown volume. + cache.get(1, 43, 2, 1, 4096, || { + let mut info = sample(1, 43, 2); + info.private_bytes = Some(4096); + info + }); + assert!(!cache.shares_all(1, 43)); + cache.get(0, 44, 3, 1, 4096, || sample(0, 44, 2)); + assert!(!cache.shares_all(0, 44)); + } + + #[test] + fn different_all_fork_allocation_requires_a_fresh_private_measurement() { + let cache = Cache::default(); + cache.get(1, 42, 1, 1, 4096, || sample(1, 42, 2)); + let mut measured = false; + let info = cache.get(1, 42, 2, 1, 8192, || { + measured = true; + let mut info = sample(1, 42, 2); + info.private_bytes = Some(4096); + info + }); + assert!( + measured, + "a resource fork must not inherit another member's zero private size" + ); + assert_eq!(info.private_bytes, Some(4096)); + } + + #[test] + fn reference_budget_refreshes_and_hardlink_aliases_do_not_spend_it() { + let cache = Cache::default(); + let calls = Cell::new(0); + for (inode, links, refs) in [(1, 2, 2), (1, 2, 2), (2, 1, 2), (3, 1, 3)] + { + let info = cache.get(1, 42, inode, links, 4096, || { + calls.set(calls.get() + 1); + sample(1, 42, refs) + }); + assert_eq!(info.references, refs); + } + assert_eq!(calls.get(), 2); + } + + #[test] + fn unknown_volumes_and_modified_members_are_measured_individually() { + for device in [0, 1] { + let cache = Cache::default(); + let calls = Cell::new(0); + for inode in 1..=8 { + cache.get(device, 42, inode, 1, 4096, || { + calls.set(calls.get() + 1); + let mut info = sample(device, 42, 8); + info.private_bytes = Some(4096); + info + }); + } + assert_eq!(calls.get(), 8); + } + } + + #[test] + fn clone_groups_bound_queries_as_both_groups_and_members_grow() { + for n in [128_u32, 1024] { + let cache = Cache::default(); + let calls = Cell::new(0); + for group in 1..=n { + for inode in 1..=n { + cache.get( + 1, + u64::from(group), + u64::from(inode), + 1, + 4096, + || { + calls.set(calls.get() + 1); + sample(1, u64::from(group), n) + }, + ); + } + } + assert_eq!(calls.get(), n, "one query per confirmed group"); + } + } +} diff --git a/crates/disktree-core/src/export.rs b/crates/disktree-core/src/export.rs index 5fba2cd2..d7fbe13b 100644 --- a/crates/disktree-core/src/export.rs +++ b/crates/disktree-core/src/export.rs @@ -67,7 +67,7 @@ pub fn agent_prompt_for( let mut prompt = String::new(); let _ = writeln!( prompt, - "I need to free up disk space on this {} machine. I used disktree \ + "I need to free up disk space on this {} machine. I used PwrDisk \ to look through {} and picked the directories and files below for \ deletion, {} in all.", platform, @@ -218,7 +218,7 @@ pub fn delete_script_for( let mut script = String::from( r#"#!/bin/sh ( -# Generated by disktree; review every path before running. +# Generated by PwrDisk; review every path before running. # GNU/Linux only. Races, shared blocks and changed sizes are possible. # This is NOT a substitute for checking git work and tool-owned data. set -eu diff --git a/crates/disktree-core/src/filter.rs b/crates/disktree-core/src/filter.rs index 24c1a7a9..fb1a1cc6 100644 --- a/crates/disktree-core/src/filter.rs +++ b/crates/disktree-core/src/filter.rs @@ -1,13 +1,19 @@ -//! Typeahead filtering: which parts of a tree match a name. +//! Filtering: which parts of a tree match a name, or a [`Rule`] on what +//! the files are. //! //! A node whose name contains the needle (ignoring ASCII case) matches, and //! is kept whole: everything under a matching directory goes with it. Its //! ancestors are kept only partly, and sized by what matched beneath them, //! so a filtered treemap shows exactly the matches, at their true relative //! sizes, in the places they live. +//! +//! A rule is judged per file, from its own kind, age and reclaimability, +//! and summed up the tree the same way: a directory is whole when every +//! file beneath it passes, partial when some do, and gone when none do. use rustc_hash::FxHashMap; +use crate::classify::Category; use crate::tree::{Metric, Node}; /// How a node takes part in a filtered view. @@ -29,10 +35,149 @@ pub struct Matches { /// Keyed by absolute crumbs. Only matches and their ancestors appear; /// a match's own descendants are implied. pub keep: FxHashMap, Keep>, - /// Topmost matches: a match inside a match is not counted again. + /// Topmost matches: a match inside a match is not counted again. Only + /// names are counted; a filter by [`Rule`] alone counts nothing. pub count: usize, pub bytes: u64, pub files: u64, + /// What a file must be to be kept, besides matching the needle. + pub rule: Option, +} + +/// What a filtered view keeps of each file, from its own facts: its kind, +/// whether its space is reclaimable, and how long ago it was written. The +/// legend sets it, one chip per kind and age. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Rule { + /// Kinds to keep, one bit per [`Category`] (see [`Self::bit`]); none + /// set keeps every kind. + pub only: u16, + /// Kinds to leave out, whatever `only` says. + pub hidden: u16, + /// `Some(true)` keeps only reclaimable space, `Some(false)` leaves it + /// out. Reclaimable is a property, not a kind, so it narrows `only` + /// rather than adding to it. + pub reclaimable: Option, + /// Age buckets to keep, one bit per entry of `age_limits`; none set + /// keeps every age. + pub ages_only: u8, + /// Age buckets to leave out. + pub ages_hidden: u8, + /// Each bucket's upper bound in days, ascending; a file belongs to the + /// first one its age is within, or the last. + pub age_limits: Vec, + /// The moment ages are measured from, in Unix seconds. + pub now: i64, +} + +impl Rule { + /// The bit for `category` in [`Self::only`] and [`Self::hidden`]. + pub const fn bit(category: Category) -> u16 { + 1 << category as u16 + } + + /// Whether the rule keeps everything. + pub const fn is_empty(&self) -> bool { + self.only == 0 + && self.hidden == 0 + && self.reclaimable.is_none() + && self.ages_only == 0 + && self.ages_hidden == 0 + } + + /// Whether the rule keeps `node`, judged by its own facts. Meant for + /// files: a directory's facts are its own or inherited, not a summary + /// of what it holds. + pub fn passes(&self, node: Node<'_>) -> bool { + let kind = Self::bit(node.category); + if self.hidden & kind != 0 || (self.only != 0 && self.only & kind == 0) + { + return false; + } + if self + .reclaimable + .is_some_and(|wanted| node.reclaim.is_some() != wanted) + { + return false; + } + if self.ages_only == 0 && self.ages_hidden == 0 { + return true; + } + // An unknown write time is in no bucket: kept unless the rule + // keeps only some ages. + if node.modified <= 0 { + return self.ages_only == 0; + } + let bit = 1 << self.age_bucket(node.modified); + self.ages_hidden & bit == 0 + && (self.ages_only == 0 || self.ages_only & bit != 0) + } + + fn age_bucket(&self, modified: i64) -> usize { + age_bucket(self.now, &self.age_limits, modified) + } +} + +/// Which age chip a write time falls in: the first limit, in days, it is +/// within, or the last chip when it is older than them all. +fn age_bucket(now: i64, limits: &[i64], modified: i64) -> usize { + let days = (now - modified) / 86_400; + limits + .iter() + .position(|limit| days <= *limit) + .unwrap_or_else(|| limits.len().saturating_sub(1)) +} + +/// What each legend chip would keep of a whole tree. +/// +/// In the tree's own metric: the bytes a chip set to only would show. +/// Judged per file by the facts [`Rule::passes`] reads, so a chip's total +/// is the "Showing" figure a click on it gives. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Shares { + /// By kind, indexed by `Category as usize` (a kind is a bit of a + /// `u16`, so there are at most sixteen). + pub kinds: [u64; 16], + /// Files with a cleanup suggestion. + pub suggested: u64, + /// By age chip, one per limit given; a file with no write time is in + /// none. + pub ages: Vec, +} + +impl Shares { + pub const fn kind(&self, category: Category) -> u64 { + self.kinds[category as usize] + } +} + +/// Sum every file beneath `root` into [`Shares`], with ages measured from +/// `now` against `age_limits` in days, as a [`Rule`] measures them. +pub fn shares(root: Node<'_>, now: i64, age_limits: &[i64]) -> Shares { + let mut shares = Shares { + ages: vec![0; age_limits.len()], + ..Shares::default() + }; + // A stack, not recursion: a scan can be deeper than a thread's stack + // is comfortable with. The root's children, as a filter starts there: + // a scan of one file holds nothing to filter. + let mut stack: Vec> = root.children().iter().collect(); + while let Some(node) = stack.pop() { + let children = node.children(); + if !children.is_empty() { + stack.extend(children.iter()); + continue; + } + shares.kinds[node.category as usize] += node.bytes; + if node.reclaim.is_some() { + shares.suggested += node.bytes; + } + if node.modified > 0 && !age_limits.is_empty() { + shares.ages[age_bucket(now, age_limits, node.modified)] += + node.bytes; + } + } + shares } impl Matches { @@ -62,8 +207,25 @@ impl Matches { }) } + /// [`Self::keep`], for `node` found at `crumbs`. A rule's files are + /// judged as they are asked about, not recorded: a partly kept + /// directory can hold millions of them. + pub fn keep_at(&self, crumbs: &[usize], node: Node<'_>) -> Option { + let keep = self.keep(crumbs); + if keep.is_none() + && self.needle.is_empty() + && node.children().is_empty() + && self.rule.as_ref().is_some_and(|rule| rule.passes(node)) + { + // Only a kept directory holds a passing file, so the parent + // that left this one unrecorded was partial, not absent. + return Some(Keep::Whole); + } + keep + } + /// The value a kept node is laid out by. - pub const fn value(keep: Keep, node: &Node, metric: Metric) -> u64 { + pub const fn value(keep: Keep, node: Node<'_>, metric: Metric) -> u64 { match (keep, metric) { (Keep::Whole, _) => node.value(metric), (Keep::Partial { bytes, .. }, Metric::Bytes) => bytes, @@ -74,7 +236,7 @@ impl Matches { /// Search `node`, found at absolute `base`, for names containing `needle`. /// `None` for an empty needle: nothing is filtered. -pub fn filter(node: &Node, base: &[usize], needle: &str) -> Option { +pub fn filter(node: Node<'_>, base: &[usize], needle: &str) -> Option { let needle = needle.trim().to_ascii_lowercase(); if needle.is_empty() { return None; @@ -91,24 +253,130 @@ pub fn filter(node: &Node, base: &[usize], needle: &str) -> Option { Some(matches) } +/// Search `node`, found at absolute `base`, for what `rule` keeps and, when +/// the needle is not blank, for names containing it. `None` when neither +/// filters anything. +pub fn filter_with( + node: Node<'_>, + base: &[usize], + needle: &str, + rule: Option<&Rule>, +) -> Option { + let Some(rule) = rule.filter(|rule| !rule.is_empty()) else { + return filter(node, base, needle); + }; + let mut matches = Matches { + needle: needle.trim().to_ascii_lowercase(), + base: base.to_vec(), + rule: Some(rule.clone()), + ..Matches::default() + }; + let named = matches.needle.is_empty(); + let mut crumbs = base.to_vec(); + let mut kept = Vec::new(); + let tally = + visit_rule(node, rule, &mut crumbs, &mut matches, &mut kept, named); + matches.keep = kept.into_iter().collect(); + matches.bytes = tally.bytes; + matches.files = tally.files; + Some(matches) +} + +/// What a rule kept beneath a node. +#[derive(Clone, Copy, Default)] +struct Tally { + bytes: u64, + files: u64, + /// Something passed, even if it weighs nothing. + any: bool, + /// Everything passed. + all: bool, +} + +/// [`visit`] under a rule. Entries go on `kept` in depth-first order, so a +/// directory that turns out whole drops its descendants' entries by +/// truncating: they are a run at the end. `named` is set when the needle is +/// blank or an ancestor matched it. +fn visit_rule( + node: Node<'_>, + rule: &Rule, + crumbs: &mut Vec, + matches: &mut Matches, + kept: &mut Vec<(Vec, Keep)>, + named: bool, +) -> Tally { + let mut total = Tally { + all: true, + ..Tally::default() + }; + for (index, child) in node.children().iter().enumerate() { + crumbs.push(index); + let hit = !matches.needle.is_empty() + && contains_ignoring_case(child.name(), &matches.needle); + let child_named = named || hit; + let tally = if child.children().is_empty() { + let passes = child_named && rule.passes(child); + // Without a needle a passing file is judged again when asked + // (`Matches::keep_at`); with one it must be recorded. + if passes && !matches.needle.is_empty() { + kept.push((crumbs.clone(), Keep::Whole)); + } + Tally { + bytes: if passes { child.bytes } else { 0 }, + files: if passes { child.files } else { 0 }, + any: passes, + all: passes, + } + } else { + let start = kept.len(); + let tally = + visit_rule(child, rule, crumbs, matches, kept, child_named); + if tally.all { + kept.truncate(start); + kept.push((crumbs.clone(), Keep::Whole)); + } else if tally.any { + kept.push(( + crumbs.clone(), + Keep::Partial { + bytes: tally.bytes, + files: tally.files, + }, + )); + } + tally + }; + if hit && !named && tally.any { + matches.count += 1; + } + total.bytes += tally.bytes; + total.files += tally.files; + total.any |= tally.any; + total.all &= tally.all; + crumbs.pop(); + } + total +} + /// Returns the bytes and files that matched at or beneath `node`'s /// children, recording what to keep. fn visit( - node: &Node, + node: Node<'_>, crumbs: &mut Vec, matches: &mut Matches, ) -> (u64, u64) { let mut total = (0, 0); - for (index, child) in node.children.iter().enumerate() { + for (index, child) in node.children().iter().enumerate() { crumbs.push(index); - if contains_ignoring_case(&child.name, &matches.needle) { + if contains_ignoring_case(child.name(), &matches.needle) { matches.keep.insert(crumbs.clone(), Keep::Whole); matches.count += 1; total.0 += child.bytes; total.1 += child.files; - } else if !child.children.is_empty() { + } else if !child.children().is_empty() { + let count_before = matches.count; let (bytes, files) = visit(child, crumbs, matches); - if bytes > 0 || files > 0 { + // An empty matching directory still needs a reachable ancestor. + if matches.count > count_before { matches .keep .insert(crumbs.clone(), Keep::Partial { bytes, files }); @@ -124,38 +392,55 @@ fn visit( /// Substring search ignoring ASCII case, without allocating: a filter runs /// over every name in view on every keystroke. fn contains_ignoring_case(haystack: &str, lower_needle: &str) -> bool { + find_ignoring_case(haystack, lower_needle).is_some() +} + +/// Where `lower_needle` first occurs in `haystack`, ignoring ASCII case, as +/// a byte range. The same rule [`filter`] matches by, so a label can mark +/// the part of a name that matched. +/// +/// The range always falls on character boundaries: only ASCII bytes are +/// folded, and a needle that is itself valid UTF-8 cannot start or end +/// inside another character's bytes. +pub fn find_ignoring_case( + haystack: &str, + lower_needle: &str, +) -> Option> { let (hay, needle) = (haystack.as_bytes(), lower_needle.as_bytes()); if needle.is_empty() { - return true; + return Some(0..0); } if needle.len() > hay.len() { - return false; + return None; } - hay.windows(needle.len()).any(|window| { - window - .iter() - .zip(needle) - .all(|(left, right)| left.to_ascii_lowercase() == *right) - }) + hay.windows(needle.len()) + .position(|window| { + window + .iter() + .zip(needle) + .all(|(left, right)| left.to_ascii_lowercase() == *right) + }) + .map(|start| start..start + needle.len()) } #[cfg(test)] mod tests { use super::*; + use crate::tree::{Draft, Tree}; use crate::tree::{NodeKind, aggregate}; - fn file(name: &str, bytes: u64) -> Node { - Node::entry(name, NodeKind::File, bytes) + fn file(name: &str, bytes: u64) -> Draft { + Draft::entry(name, NodeKind::File, bytes) } - fn dir(name: &str, children: Vec) -> Node { - let mut node = Node::directory(name); + fn dir(name: &str, children: Vec) -> Draft { + let mut node = Draft::directory(name); node.children = children; node } - fn tree() -> Node { - let mut root = dir( + fn tree() -> Tree { + let root = dir( "root", vec![ dir( @@ -172,21 +457,22 @@ mod tests { file("readme", 1), ], ); + let mut root = Tree::from(root); aggregate(&mut root, Metric::Bytes); root } - fn crumbs_of(root: &Node, names: &[&str]) -> Vec { + fn crumbs_of(root: Node<'_>, names: &[&str]) -> Vec { let mut node = root; names .iter() .map(|name| { let index = node - .children + .children() .iter() - .position(|child| &*child.name == *name) + .position(|child| child.name() == *name) .expect("present"); - node = &node.children[index]; + node = node.children().at(index); index }) .collect() @@ -194,35 +480,37 @@ mod tests { #[test] fn matches_are_kept_whole_and_their_ancestors_by_what_matched() { - let root = tree(); - let found = filter(&root, &[], "APP").expect("a needle"); + let tree = tree(); + let root = tree.root(); + let found = filter(root, &[], "APP").expect("a needle"); assert_eq!(found.count, 2, "src/App and apps; apple is inside apps"); assert_eq!(found.bytes, 10 + 107); - assert_eq!(found.keep(&crumbs_of(&root, &["apps"])), Some(Keep::Whole)); + assert_eq!(found.keep(&crumbs_of(root, &["apps"])), Some(Keep::Whole)); assert_eq!( - found.keep(&crumbs_of(&root, &["apps", "x"])), + found.keep(&crumbs_of(root, &["apps", "x"])), Some(Keep::Whole), "inside a match" ); assert_eq!( - found.keep(&crumbs_of(&root, &["src"])), + found.keep(&crumbs_of(root, &["src"])), Some(Keep::Partial { bytes: 10, files: 1 }) ); - assert_eq!(found.keep(&crumbs_of(&root, &["src", "notes"])), None); - assert_eq!(found.keep(&crumbs_of(&root, &["readme"])), None); + assert_eq!(found.keep(&crumbs_of(root, &["src", "notes"])), None); + assert_eq!(found.keep(&crumbs_of(root, &["readme"])), None); } #[test] fn a_search_below_the_root_leaves_the_rest_alone() { - let root = tree(); - let src = crumbs_of(&root, &["src"]); + let tree = tree(); + let root = tree.root(); + let src = crumbs_of(root, &["src"]); let found = filter(root.resolve(&src).expect("src"), &src, "main") .expect("needle"); - assert_eq!(found.keep(&crumbs_of(&root, &["apps"])), Some(Keep::Whole)); - assert_eq!(found.keep(&crumbs_of(&root, &["src", "notes"])), None); + assert_eq!(found.keep(&crumbs_of(root, &["apps"])), Some(Keep::Whole)); + assert_eq!(found.keep(&crumbs_of(root, &["src", "notes"])), None); assert_eq!( found.keep(&src), Some(Keep::Partial { @@ -234,16 +522,264 @@ mod tests { #[test] fn an_empty_needle_filters_nothing() { - assert!(filter(&tree(), &[], " ").is_none()); - let found = filter(&tree(), &[], "zzz").expect("needle"); + assert!(filter(tree().root(), &[], " ").is_none()); + let found = filter(tree().root(), &[], "zzz").expect("needle"); assert_eq!(found.count, 0); assert!(found.keep.is_empty()); } + #[test] + fn a_nested_empty_directory_keeps_its_ancestors() { + let root = dir( + "root", + vec![ + dir("parent", vec![dir("empty-match", vec![])]), + file("unrelated", 10), + ], + ); + let mut root = Tree::from(root); + aggregate(&mut root, Metric::Bytes); + let root = root.root(); + let found = filter(root, &[], "empty-match").expect("needle"); + let parent = crumbs_of(root, &["parent"]); + let empty = crumbs_of(root, &["parent", "empty-match"]); + + assert_eq!(found.count, 1); + assert_eq!((found.bytes, found.files), (0, 0)); + assert_eq!( + found.keep(&parent), + Some(Keep::Partial { bytes: 0, files: 0 }) + ); + assert_eq!(found.keep(&empty), Some(Keep::Whole)); + assert_eq!(found.keep(&crumbs_of(root, &["unrelated"])), None); + } + + /// A file of `category`, reclaimable or not, written `days` ago. + fn kind( + name: &str, + bytes: u64, + category: Category, + reclaim: bool, + days: i64, + ) -> Draft { + let mut node = file(name, bytes); + node.category = category; + node.reclaim = reclaim.then_some(crate::classify::Reclaim::BuildOutput); + node.modified = NOW - days * 86_400; + node + } + + const NOW: i64 = 1_800_000_000; + + /// `src` is all code (its `target` reclaimable), `mixed` holds code + /// beside a photo, and `photos` holds only media. + fn kinds() -> Tree { + let root = dir( + "root", + vec![ + dir( + "src", + vec![ + kind("main.rs", 10, Category::Code, false, 1), + dir( + "target", + vec![kind("app", 40, Category::Code, true, 1)], + ), + ], + ), + dir( + "mixed", + vec![ + kind("lib.rs", 5, Category::Code, false, 400), + kind("cat.jpg", 20, Category::Media, false, 400), + ], + ), + dir( + "photos", + vec![kind("dog.jpg", 100, Category::Media, false, 3)], + ), + ], + ); + let mut root = Tree::from(root); + aggregate(&mut root, Metric::Bytes); + root + } + + fn rule() -> Rule { + Rule { + age_limits: vec![7, 30, 182, 365, i64::MAX], + now: NOW, + ..Rule::default() + } + } + + /// Every chip's share is what that chip alone, set to only, would + /// show: the same files, judged by the same facts. + #[test] + fn shares_are_what_each_chip_would_show() { + let tree = kinds(); + let root = tree.root(); + let base = rule(); + let shares = shares(root, NOW, &base.age_limits); + for category in [Category::Code, Category::Media, Category::Cache] { + let only = Rule { + only: Rule::bit(category), + ..base.clone() + }; + let shown = filter_with(root, &[], "", Some(&only)) + .map_or(0, |found| found.bytes); + assert_eq!(shares.kind(category), shown, "{category:?}"); + } + assert_eq!(shares.kind(Category::Code), 55); + assert_eq!(shares.kind(Category::Media), 120); + assert_eq!(shares.suggested, 40); + let suggested = Rule { + reclaimable: Some(true), + ..base + }; + assert_eq!( + filter_with(root, &[], "", Some(&suggested)).map(|f| f.bytes), + Some(shares.suggested) + ); + // This week: main.rs, app and dog.jpg; over a year: the rest. + assert_eq!(shares.ages, vec![150, 0, 0, 0, 25]); + } + + /// How `names` takes part, asked the way a layout asks. + fn kept(found: &Matches, root: Node<'_>, names: &[&str]) -> Option { + let crumbs = crumbs_of(root, names); + found.keep_at(&crumbs, root.resolve(&crumbs).expect("present")) + } + + #[test] + fn a_kind_keeps_its_files_and_sizes_the_folders_that_hold_them() { + let tree = kinds(); + let root = tree.root(); + let code = Rule { + only: Rule::bit(Category::Code), + ..rule() + }; + let found = filter_with(root, &[], "", Some(&code)).expect("a rule"); + assert_eq!((found.bytes, found.files), (55, 3)); + assert_eq!(kept(&found, root, &["src"]), Some(Keep::Whole)); + assert_eq!( + kept(&found, root, &["mixed"]), + Some(Keep::Partial { bytes: 5, files: 1 }) + ); + assert_eq!(kept(&found, root, &["mixed", "lib.rs"]), Some(Keep::Whole)); + assert_eq!(kept(&found, root, &["mixed", "cat.jpg"]), None); + assert_eq!(kept(&found, root, &["photos"]), None); + assert_eq!(found.count, 0, "a rule alone counts no names"); + // Files of a whole folder, and of a partial one, are not recorded. + assert_eq!(found.keep.len(), 2, "{:?}", found.keep); + } + + #[test] + fn a_hidden_kind_leaves_everything_else_whole() { + let tree = kinds(); + let root = tree.root(); + let no_media = Rule { + hidden: Rule::bit(Category::Media), + ..rule() + }; + let found = filter_with(root, &[], "", Some(&no_media)).expect("rule"); + assert_eq!(found.bytes, 55); + assert_eq!(kept(&found, root, &["src"]), Some(Keep::Whole)); + assert_eq!(kept(&found, root, &["src", "target"]), Some(Keep::Whole)); + assert_eq!(kept(&found, root, &["photos"]), None); + } + + #[test] + fn reclaimable_narrows_the_kinds_instead_of_adding_to_them() { + let tree = kinds(); + let root = tree.root(); + let both = Rule { + only: Rule::bit(Category::Code) | Rule::bit(Category::Media), + reclaimable: Some(true), + ..rule() + }; + let found = filter_with(root, &[], "", Some(&both)).expect("rule"); + assert_eq!(found.bytes, 40, "only src/target is reclaimable"); + assert_eq!(kept(&found, root, &["src", "target"]), Some(Keep::Whole)); + assert_eq!(kept(&found, root, &["src", "main.rs"]), None); + assert_eq!(kept(&found, root, &["mixed"]), None); + + let kept_back = Rule { + reclaimable: Some(false), + ..rule() + }; + let found = filter_with(root, &[], "", Some(&kept_back)).expect("rule"); + assert_eq!(found.bytes, 135); + } + + #[test] + fn ages_filter_by_when_each_file_was_written() { + let tree = kinds(); + let root = tree.root(); + let old = Rule { + ages_only: 1 << 4, + ..rule() + }; + let found = filter_with(root, &[], "", Some(&old)).expect("rule"); + assert_eq!(found.bytes, 25, "only mixed's files are over a year old"); + assert_eq!(kept(&found, root, &["mixed"]), Some(Keep::Whole)); + + let not_this_week = Rule { + ages_hidden: 1, + ..rule() + }; + let found = + filter_with(root, &[], "", Some(¬_this_week)).expect("rule"); + assert_eq!(found.bytes, 25); + } + + #[test] + fn a_needle_and_a_rule_keep_only_what_both_allow() { + let tree = kinds(); + let root = tree.root(); + let code = Rule { + only: Rule::bit(Category::Code), + ..rule() + }; + let found = filter_with(root, &[], "i", Some(&code)).expect("both"); + // "mixed" matches the name, but only its code passes the rule; + // "main.rs" matches too. "photos" holds no code. + assert_eq!(found.count, 2); + assert_eq!(found.bytes, 15); + assert_eq!( + kept(&found, root, &["mixed"]), + Some(Keep::Partial { bytes: 5, files: 1 }) + ); + assert_eq!(kept(&found, root, &["mixed", "lib.rs"]), Some(Keep::Whole)); + assert_eq!(kept(&found, root, &["mixed", "cat.jpg"]), None); + assert_eq!(kept(&found, root, &["src", "main.rs"]), Some(Keep::Whole)); + assert_eq!(kept(&found, root, &["src", "target"]), None); + } + + #[test] + fn an_empty_rule_is_the_plain_search() { + let tree = kinds(); + assert!(filter_with(tree.root(), &[], "", Some(&rule())).is_none()); + assert!(filter_with(tree.root(), &[], " ", None).is_none()); + } + #[test] fn case_is_ignored_without_allocating() { assert!(contains_ignoring_case("Cargo.TOML", "toml")); assert!(!contains_ignoring_case("ab", "abc")); assert!(contains_ignoring_case("x", "")); } + + /// A label underlines exactly what matched, so the range has to land on + /// the matched bytes, characters before it included. + #[test] + fn a_match_is_found_where_it_is_in_the_name() { + assert_eq!(find_ignoring_case("build-CACHE", "cache"), Some(6..11)); + // "é" is two bytes: the range counts bytes, and stays on boundaries. + let name = "Résumé cache.txt"; + let range = find_ignoring_case(name, "cache").expect("it matches"); + assert_eq!(&name[range], "cache"); + assert_eq!(find_ignoring_case(name, "é c"), Some(6..10)); + assert_eq!(find_ignoring_case("obj", "cache"), None); + } } diff --git a/crates/disktree-core/src/index.rs b/crates/disktree-core/src/index.rs new file mode 100644 index 00000000..9b1d396f --- /dev/null +++ b/crates/disktree-core/src/index.rs @@ -0,0 +1,1759 @@ +//! How a scanned tree is held: in a handful of buffers, by `u32` index. +//! +//! Every node is a 64-byte record in one vector, each directory's children +//! a contiguous run of it, every name in one string, and the allocation +//! and sharing records, which most nodes lack, in side tables. An +//! allocation keeps only what its node does not already say; see +//! [`records`]. +//! +//! A tree of separately allocated nodes is freed one `free()` at a time, +//! each write reading a page back in, from the compressor if macOS has +//! packed it away: 0.8 to 0.9 s for a 20-million-node tree in a fresh +//! process, 15 s in a window under memory pressure. Here a drop frees eight +//! buffers without reading them, in under a millisecond and with no page +//! faults. Nothing here needs `unsafe`: an index is checked where a pointer +//! would have to be trusted, and a name is a slice of a `String`. +//! +//! The walk builds on many workers at once. Each appends a directory's +//! children as one block when the directory completes, under one lock, so +//! blocks land in whatever order workers finish. [`Tree::build`] then +//! reorders the nodes once so that every subtree is one contiguous run, +//! and from then on a pass can hand separate subtrees to separate workers +//! by splitting the vector, as [`Tree::par_bottom_up`] does. On a tree of +//! 19.9 million nodes that took 2.6 to 3.9 s, and it is what keeps the +//! totals pass at 0.1 to 0.2 s instead of 1.2 to 1.8 s in build order. +//! +//! Reading goes through [`Node`], a cursor that pairs a stored record with +//! the tree it indexes into; writing goes through [`NodeMut`], or a pass +//! over the whole tree. + +use std::fmt; +use std::marker::PhantomData; +use std::num::NonZeroU64; +use std::ops::Deref; +use std::sync::{Mutex, MutexGuard, PoisonError}; + +use rayon::prelude::*; + +use crate::classify::{Category, Reclaim}; +use crate::sharing::{Allocation, Sharing}; +use crate::tree::{Draft, Metric, NodeKind}; + +mod records; +use records::Records; +#[cfg(test)] +pub(crate) use records::kept_whole; + +/// The longest name a tree holds. +/// +/// A local file system allows a few hundred bytes, even decoded lossily; +/// anything read from elsewhere, such as an SSH host's stream, is refused +/// past this before it is built. +pub const MAX_NAME_BYTES: usize = 4096; + +/// Everything about a node that is plain data, and so free to write. +/// +/// `bytes` and `files` are the subtree totals the treemap draws. A disk +/// holds tens of millions of nodes, so every field is paid that many +/// times: the size of a stored node is held by a test. +#[derive(Clone, Copy, Debug)] +pub struct Facts { + pub kind: NodeKind, + /// Subtree total: direct contents plus every descendant. A file's own + /// size, or nothing for a second name of a file already charged. + pub bytes: u64, + /// Files at or beneath this node; `1` for a file. + pub files: u64, + /// Directories at or beneath this node; `1` for a directory. Four + /// billion is more than any volume holds. + pub dirs: u32, + /// `(device, inode)` for files, used to de-duplicate hardlinks. No file + /// has inode zero, which lets `None` cost nothing. + pub inode: Option<(u64, NonZeroU64)>, + /// Some entries here or below could not be read; totals are incomplete. + pub read_error: bool, + /// Newest write time at or beneath this node, in Unix seconds; `0` when + /// unknown. Derived for directories by [`crate::tree::aggregate`]. + pub modified: i64, + /// What kind of data this is, for colour. Set by [`crate::classify`]. + pub category: Category, + /// Why this space can be had back, if it can. Set by + /// [`crate::classify`]; inherited by everything beneath. + pub reclaim: Option, +} + +impl Facts { + /// A directory with nothing counted yet. + pub const fn directory() -> Self { + Self { + kind: NodeKind::Directory, + bytes: 0, + files: 0, + dirs: 1, + inode: None, + read_error: false, + modified: 0, + category: Category::Other, + reclaim: None, + } + } + + /// A leaf entry of `bytes`. + pub fn entry(kind: NodeKind, bytes: u64) -> Self { + Self { + kind, + bytes, + files: u64::from(kind == NodeKind::File), + dirs: 0, + ..Self::directory() + } + } + + /// The value a treemap should weight this node by. + pub const fn value(&self, metric: Metric) -> u64 { + match metric { + Metric::Bytes => self.bytes, + Metric::Files => self.files, + } + } +} + +/// Which side table a node's [`Extra`] points into, in its top three bits. +/// +/// A node carries one index instead of one per table: an allocation is +/// kept for some files and sharing figures for some directories, so two +/// indices would cost every node four bytes for what most never use, and +/// take a stored node from 64 bytes to 72. The tags `1` to `4` are the +/// allocation tables of [`records`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Extra(u32); + +impl Extra { + const NONE: Self = Self(0); + const SHIFT: u32 = 29; + const SHARING: u32 = 5; + const BOTH: u32 = 6; + + fn new(tag: u32, index: usize) -> Self { + // Half a billion records of one kind would sit beside at least as + // many 64-byte nodes: 32 GiB of tree before the first record. + let index = u32::try_from(index) + .ok() + .filter(|index| *index < 1 << Self::SHIFT) + .expect("fewer than half a billion side records"); + Self(tag << Self::SHIFT | index) + } + + const fn tag(self) -> u32 { + self.0 >> Self::SHIFT + } + + const fn index(self) -> usize { + (self.0 & ((1 << Self::SHIFT) - 1)) as usize + } +} + +/// One node as stored: its facts and where its name, children and side +/// records are. +#[derive(Clone, Copy, Debug)] +struct Slot { + facts: Facts, + /// Offset of the name's length prefix in [`Store::names`]. + name: u32, + /// Index of the first child in [`Store::nodes`]; zero when there are + /// none. + first: u32, + len: u32, + extra: Extra, +} + +/// Everything a tree owns. +#[derive(Default)] +struct Store { + nodes: Vec, + /// Every name, each after its length written as one `char`: a `String` + /// can be sliced without checking its bytes again, which `&[u8]` could + /// only skip with `unsafe`, and a length that is a `char` keeps the + /// buffer valid UTF-8. A name is at most a few hundred bytes, well + /// under the surrogate range a `char` cannot hold. + names: String, + allocations: Records, + sharings: Vec, + /// A node with both, which only a followed directory link has. + both: Vec<(Allocation, Sharing)>, + root: u32, +} + +/// A copy made on every worker: copying a large tree is gigabytes of +/// writes to pages touched for the first time, which one thread would +/// fault in one at a time. +impl Clone for Store { + fn clone(&self) -> Self { + let ((nodes, allocations), (names, sharings)) = rayon::join( + || { + rayon::join( + || copied(&self.nodes), + || self.allocations.par_copy(), + ) + }, + || rayon::join(|| self.names.clone(), || copied(&self.sharings)), + ); + Self { + nodes, + names, + allocations, + sharings, + both: self.both.clone(), + root: self.root, + } + } +} + +/// A copy of one buffer, written by every worker: see [`Store`]'s `Clone`. +fn copied(source: &[T]) -> Vec { + let mut copy = Vec::with_capacity(source.len()); + copy.par_extend(source.par_iter().copied()); + copy +} + +fn name_at(names: &str, at: u32) -> &str { + let rest = &names[at as usize..]; + let mut chars = rest.chars(); + let len = chars.next().map_or(0, |len| len as usize); + let start = rest.len() - chars.as_str().len(); + &rest[start..start + len] +} + +impl Store { + fn index(len: usize) -> u32 { + u32::try_from(len).expect("fewer than four billion nodes") + } + + fn name(&self, at: u32) -> &str { + name_at(&self.names, at) + } + + fn push_name(&mut self, name: &str) -> u32 { + let at = u32::try_from(self.names.len()) + .expect("a tree's names fit in four gigabytes"); + // `MAX_NAME_BYTES` is far below the first length that is not a + // `char`, 55,296, where the surrogates begin. + assert!(name.len() <= MAX_NAME_BYTES, "a name of {}", name.len()); + let len = u32::try_from(name.len()) + .ok() + .and_then(char::from_u32) + .expect("a length below the surrogates"); + self.names.push(len); + self.names.push_str(name); + at + } + + /// The allocation of the node of `facts` that holds `extra`. + fn allocation(&self, extra: Extra, facts: &Facts) -> Option { + match extra.tag() { + Extra::BOTH => Some(self.both[extra.index()].0), + tag => self.allocations.get(tag, extra.index(), facts), + } + } + + fn sharing(&self, extra: Extra) -> Option<&Sharing> { + match extra.tag() { + Extra::SHARING => Some(&self.sharings[extra.index()]), + Extra::BOTH => Some(&self.both[extra.index()].1), + _ => None, + } + } + + /// Keep these records for a node of `facts`. + fn extra( + &mut self, + allocation: Option, + sharing: Option, + facts: &Facts, + ) -> Extra { + match (allocation, sharing) { + (None, None) => Extra::NONE, + (Some(allocation), None) => { + let (tag, index) = self.allocations.push(allocation, facts); + Extra::new(tag, index) + } + (None, Some(sharing)) => { + self.sharings.push(sharing); + Extra::new(Extra::SHARING, self.sharings.len() - 1) + } + (Some(allocation), Some(sharing)) => { + self.both.push((allocation, sharing)); + Extra::new(Extra::BOTH, self.both.len() - 1) + } + } + } + + /// Replace a node's sharing figures, in place when it has some, so + /// aggregating again does not grow the tables. A record left behind + /// when a node changes table stays until the tree is dropped; only + /// a change in what is kept does that, which re-ranking never makes. + fn set_sharing( + &mut self, + extra: Extra, + sharing: Option, + facts: &Facts, + ) -> Extra { + let index = extra.index(); + match (extra.tag(), sharing) { + (Extra::SHARING, Some(value)) => { + self.sharings[index] = value; + extra + } + (Extra::BOTH, Some(value)) => { + self.both[index].1 = value; + extra + } + (tag, Some(value)) if records::holds(tag) => { + let allocation = self.allocations.get(tag, index, facts); + self.extra(allocation, Some(value), facts) + } + (Extra::BOTH, None) => { + let allocation = self.both[index].0; + self.extra(Some(allocation), None, facts) + } + (Extra::SHARING, None) => Extra::NONE, + (_, None) => extra, + (_, value) => self.extra(None, value, facts), + } + } + + /// A node for `name` with these facts and records, holding `children`, + /// which become one block of this store. + fn place( + &mut self, + name: &str, + facts: Facts, + allocation: Option, + sharing: Option, + children: impl ExactSizeIterator, + ) -> Slot { + let len = Self::index(children.len()); + let first = if len == 0 { + 0 + } else { + let first = Self::index(self.nodes.len()); + self.nodes.extend(children); + first + }; + Slot { + facts, + name: self.push_name(name), + first, + len, + extra: self.extra(allocation, sharing, &facts), + } + } + + fn children(&self, slot: &Slot) -> &[Slot] { + let first = slot.first as usize; + &self.nodes[first..first + slot.len as usize] + } + + /// A copy of `node` from any tree, and everything beneath it. + fn copy(&mut self, node: Node<'_>, name: &str) -> Slot { + let children: Vec = node + .children() + .iter() + .map(|child| self.copy(child, child.name())) + .collect(); + self.place( + name, + *node.facts(), + node.allocation(), + node.stored_sharing().copied(), + children.into_iter(), + ) + } + + /// A copy of all of `source` under `name`: its buffers appended in + /// order, each index moved past what this store already holds. One + /// sequential pass instead of a walk with a list per directory, which + /// matters because a build copies under the lock every worker needs. + /// `source`'s own root is appended too and left for + /// [`Self::relayout`] to cut, which keeps every index a plain shift. + fn absorb(&mut self, source: &Self, name: &str) -> Slot { + let base = Self::index(self.nodes.len()); + let names = Self::index(self.names.len()); + let allocations = self.allocations.starts(); + let sharings = self.sharings.len(); + let both = self.both.len(); + self.names.push_str(&source.names); + u32::try_from(self.names.len()) + .expect("a tree's names fit in four gigabytes"); + self.allocations.append(&source.allocations); + self.sharings.extend_from_slice(&source.sharings); + self.both.extend_from_slice(&source.both); + let moved = |slot: &Slot| { + let index = slot.extra.index(); + let extra = match slot.extra.tag() { + tag if records::holds(tag) => { + Extra::new(tag, allocations.moved(tag, index)) + } + Extra::SHARING => Extra::new(Extra::SHARING, sharings + index), + Extra::BOTH => Extra::new(Extra::BOTH, both + index), + _ => Extra::NONE, + }; + Slot { + name: names + slot.name, + first: if slot.len == 0 { 0 } else { base + slot.first }, + extra, + ..*slot + } + }; + // Not in parallel: this runs under the builder's lock, and a rayon + // worker waiting on its own jobs can pick up a walk task that asks + // for the same lock. + self.nodes.extend(source.nodes.iter().map(moved)); + Slot { + name: self.push_name(name), + ..moved(&source.nodes[source.root as usize]) + } + } + + fn draft(&mut self, draft: &Draft) -> Slot { + let children: Vec = draft + .children + .iter() + .map(|child| self.draft(child)) + .collect(); + self.place( + &draft.name, + draft.facts, + draft.allocation.as_deref().copied(), + draft.sharing.as_deref().copied(), + children.into_iter(), + ) + } + + /// Reorder the nodes so that every subtree is one contiguous run: the + /// root at index 0, then each directory's block followed by each of its + /// children's runs, in block order. That is what lets a pass hand + /// separate subtrees to separate workers with `split_at_mut`, where a + /// build's order, interleaved by whichever worker finished first, + /// gives no such split. Sorting a block later keeps it true: a child + /// moves within its block and its run stays where it is. + /// + /// In place, by a permutation of four bytes a node, instead of a second + /// copy of the nodes at sixty-four. Nodes no directory reaches are + /// dropped. + fn relayout(&mut self) { + let len = self.nodes.len(); + let mut target = vec![u32::MAX; len]; + target[self.root as usize] = 0; + let mut next: u32 = 1; + // Depth first: a directory's block, then each child's run. + let mut stack: Vec<(u32, u32)> = Vec::new(); + let mut place = + |slot: &Slot, target: &mut [u32], stack: &mut Vec<(u32, u32)>| { + if slot.len > 0 { + for offset in 0..slot.len { + target[(slot.first + offset) as usize] = next + offset; + } + next += slot.len; + stack.push((slot.first, slot.first + slot.len)); + } + }; + place(&self.nodes[self.root as usize], &mut target, &mut stack); + while let Some((child, end)) = stack.pop() { + if child + 1 < end { + stack.push((child + 1, end)); + } + place(&self.nodes[child as usize], &mut target, &mut stack); + } + let reached = next; + // What nothing reaches goes past the end, to be cut off. + for slot in &mut target { + if *slot == u32::MAX { + *slot = next; + next += 1; + } + } + // A block moves whole, so its new start is its first child's. + for slot in &mut self.nodes { + if slot.len > 0 { + slot.first = target[slot.first as usize]; + } + } + for index in 0..len { + while target[index] as usize != index { + let to = target[index] as usize; + self.nodes.swap(index, to); + target.swap(index, to); + } + } + self.nodes.truncate(reached as usize); + self.root = 0; + } + + const fn bytes(&self) -> StorageBytes { + let (allocations, room) = self.allocations.bytes(); + StorageBytes { + used: self.nodes.len() * size_of::() + + self.names.len() + + allocations + + self.sharings.len() * size_of::() + + self.both.len() * size_of::<(Allocation, Sharing)>(), + reserved: self.nodes.capacity() * size_of::() + + self.names.capacity() + + room + + self.sharings.capacity() * size_of::() + + self.both.capacity() * size_of::<(Allocation, Sharing)>(), + } + } +} + +/// What a tree's buffers hold. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct StorageBytes { + /// Bytes holding nodes, names and side records. + pub used: usize, + /// Bytes the buffers have room for, including growth room that is + /// never touched and so never resident. + pub reserved: usize, +} + +/// One entry in a scanned tree, read through the tree that holds it. +/// Its facts read through `Deref`. +#[derive(Clone, Copy)] +pub struct Node<'t> { + store: &'t Store, + slot: &'t Slot, +} + +impl Deref for Node<'_> { + type Target = Facts; + + fn deref(&self) -> &Facts { + &self.slot.facts + } +} + +impl<'t> Node<'t> { + pub const fn facts(self) -> &'t Facts { + &self.slot.facts + } + + pub fn name(self) -> &'t str { + self.store.name(self.slot.name) + } + + /// Children, ordered by [`crate::tree::Metric`] value, descending. + pub fn children(self) -> Children<'t> { + Children { + store: self.store, + slots: self.store.children(self.slot), + } + } + + /// What sharing reads of this file's blocks, made up from the record + /// its tree keeps and the node's own facts, so it is returned by + /// value. An identity is kept only where sharing reads one: for a file + /// with more than one name, reached other than through a followed + /// link. + pub fn allocation(self) -> Option { + self.store.allocation(self.slot.extra, &self.slot.facts) + } + + /// Derived clone figures, sparse: see [`Node::sharing`]. + pub fn stored_sharing(self) -> Option<&'t Sharing> { + self.store.sharing(self.slot.extra) + } + + /// Where this node is in its tree, for [`Tree::set_sharing`]: a pass + /// that only reads can work out figures on every worker, then write + /// them by position. Good until the tree is next changed. + pub(crate) fn id(self) -> u32 { + debug_assert!( + self.store + .nodes + .as_ptr_range() + .contains(&std::ptr::from_ref(self.slot)), + "a node of another tree" + ); + let offset = std::ptr::from_ref(self.slot).addr() + - self.store.nodes.as_ptr().addr(); + Store::index(offset / size_of::()) + } + + /// Whether this is its tree's root, and so the whole tree. + fn is_root(self) -> bool { + self.id() == self.store.root + } +} + +impl fmt::Debug for Node<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Node") + .field("name", &self.name()) + .field("facts", self.facts()) + .field("allocation", &self.allocation()) + .field("sharing", &self.stored_sharing()) + .field("children", &self.children()) + .finish() + } +} + +/// A directory's children: a contiguous run of its tree's nodes. +#[derive(Clone, Copy)] +pub struct Children<'t> { + store: &'t Store, + slots: &'t [Slot], +} + +impl<'t> Children<'t> { + pub const fn len(self) -> usize { + self.slots.len() + } + + pub const fn is_empty(self) -> bool { + self.slots.is_empty() + } + + pub fn get(self, index: usize) -> Option> { + let store = self.store; + self.slots.get(index).map(|slot| Node { store, slot }) + } + + /// The child at `index`, which must exist. + pub fn at(self, index: usize) -> Node<'t> { + Node { + store: self.store, + slot: &self.slots[index], + } + } + + pub fn iter(self) -> Iter<'t> { + Iter { + store: self.store, + slots: self.slots.iter(), + } + } + + pub fn par_iter(self) -> impl IndexedParallelIterator> { + let store = self.store; + self.slots.par_iter().map(move |slot| Node { store, slot }) + } +} + +impl<'t> IntoIterator for Children<'t> { + type Item = Node<'t>; + type IntoIter = Iter<'t>; + + fn into_iter(self) -> Iter<'t> { + self.iter() + } +} + +impl fmt::Debug for Children<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.iter()).finish() + } +} + +/// The children of one directory, in order. +#[derive(Clone)] +pub struct Iter<'t> { + store: &'t Store, + slots: std::slice::Iter<'t, Slot>, +} + +impl fmt::Debug for Iter<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Iter") + .field("remaining", &self.slots.len()) + .finish() + } +} + +impl<'t> Iterator for Iter<'t> { + type Item = Node<'t>; + + fn next(&mut self) -> Option> { + let store = self.store; + self.slots.next().map(|slot| Node { store, slot }) + } + + fn size_hint(&self) -> (usize, Option) { + self.slots.size_hint() + } + + fn nth(&mut self, n: usize) -> Option> { + let store = self.store; + self.slots.nth(n).map(|slot| Node { store, slot }) + } +} + +impl DoubleEndedIterator for Iter<'_> { + fn next_back(&mut self) -> Option { + let store = self.store; + self.slots.next_back().map(|slot| Node { store, slot }) + } +} + +impl ExactSizeIterator for Iter<'_> {} + +impl std::iter::FusedIterator for Iter<'_> {} + +/// What a sort of one directory's children compares. +#[derive(Clone, Copy, Debug)] +pub struct Sibling<'a> { + facts: &'a Facts, + pub name: &'a str, +} + +impl Deref for Sibling<'_> { + type Target = Facts; + + fn deref(&self) -> &Facts { + self.facts + } +} + +/// Write access to one node of a tree, and through it to its subtree. +#[derive(Debug)] +pub struct NodeMut<'t> { + store: &'t mut Store, + id: u32, +} + +impl fmt::Debug for Store { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Store") + .field("nodes", &self.nodes.len()) + .field("names", &self.names.len()) + .finish_non_exhaustive() + } +} + +impl Deref for NodeMut<'_> { + type Target = Facts; + + fn deref(&self) -> &Facts { + &self.store.nodes[self.id as usize].facts + } +} + +impl NodeMut<'_> { + /// This node, to read. + pub fn node(&self) -> Node<'_> { + Node { + store: self.store, + slot: &self.store.nodes[self.id as usize], + } + } + + /// A leaf's `bytes` and `inode` are what its allocation was kept + /// against: a clone with one name and no inode reads its size from + /// the node, which is why de-duplication, the one rewrite of a leaf's + /// `bytes`, touches only leaves with an inode. Change neither here. + pub fn facts_mut(&mut self) -> &mut Facts { + &mut self.store.nodes[self.id as usize].facts + } + + /// This node again, for a shorter borrow. + pub const fn reborrow(&mut self) -> NodeMut<'_> { + NodeMut { + store: self.store, + id: self.id, + } + } + + pub fn child_count(&self) -> usize { + self.store.nodes[self.id as usize].len as usize + } + + pub fn child_mut(&mut self, index: usize) -> Option> { + let slot = &self.store.nodes[self.id as usize]; + let index = u32::try_from(index).ok().filter(|i| *i < slot.len)?; + Some(NodeMut { + id: slot.first + index, + store: self.store, + }) + } + + /// Visit each child in order, one at a time. + pub fn for_each_child_mut(&mut self, mut visit: impl FnMut(NodeMut<'_>)) { + let slot = self.store.nodes[self.id as usize]; + for id in slot.first..slot.first + slot.len { + visit(NodeMut { + store: self.store, + id, + }); + } + } + + /// Reorder the children in place. Each child's own children stay + /// where they are: a child records where its block is, and moves + /// with that record. + pub fn sort_children_by( + &mut self, + mut compare: impl FnMut(Sibling<'_>, Sibling<'_>) -> std::cmp::Ordering, + ) { + let Store { nodes, names, .. } = &mut *self.store; + let slot = nodes[self.id as usize]; + let first = slot.first as usize; + nodes[first..first + slot.len as usize].sort_unstable_by( + |left, right| { + compare( + Sibling { + facts: &left.facts, + name: name_at(names, left.name), + }, + Sibling { + facts: &right.facts, + name: name_at(names, right.name), + }, + ) + }, + ); + } + + pub fn set_sharing(&mut self, sharing: Option) { + let Slot { extra, facts, .. } = self.store.nodes[self.id as usize]; + let extra = self.store.set_sharing(extra, sharing, &facts); + self.store.nodes[self.id as usize].extra = extra; + } +} + +/// One directory's children, as a whole-tree pass sees them: their facts +/// and names to read, and their facts and order to change. +#[derive(Debug)] +pub struct Block<'a> { + slots: &'a mut [Slot], + names: &'a str, + /// Where the block starts in the tree's nodes. + first: u32, +} + +impl Block<'_> { + pub const fn len(&self) -> usize { + self.slots.len() + } + + pub const fn is_empty(&self) -> bool { + self.slots.is_empty() + } + + /// The child at `index`, which must exist. + pub fn at(&self, index: usize) -> Sibling<'_> { + let slot = &self.slots[index]; + Sibling { + facts: &slot.facts, + name: name_at(self.names, slot.name), + } + } + + pub fn iter(&self) -> impl ExactSizeIterator> { + self.slots.iter().map(|slot| Sibling { + facts: &slot.facts, + name: name_at(self.names, slot.name), + }) + } + + /// The facts of the child at `index`, which must exist. + pub fn facts_mut(&mut self, index: usize) -> &mut Facts { + &mut self.slots[index].facts + } + + /// Every child's facts, in order. + pub fn for_each_facts_mut(&mut self, visit: impl FnMut(&mut Facts)) { + self.slots + .iter_mut() + .map(|slot| &mut slot.facts) + .for_each(visit); + } + + /// The [`Node::id`] of the child at `index`: what a pass that read the + /// tree first found out about it can be looked up by. + pub(crate) fn id(&self, index: usize) -> u32 { + debug_assert!(index < self.slots.len(), "a child of this block"); + self.first + Store::index(index) + } + + /// Reorder the children; see [`NodeMut::sort_children_by`]. + pub fn sort_by( + &mut self, + mut compare: impl FnMut(Sibling<'_>, Sibling<'_>) -> std::cmp::Ordering, + ) { + let names = self.names; + self.slots.sort_unstable_by(|left, right| { + compare( + Sibling { + facts: &left.facts, + name: name_at(names, left.name), + }, + Sibling { + facts: &right.facts, + name: name_at(names, right.name), + }, + ) + }); + } +} + +/// `node`, whose descendants are all in `region`, which starts at index +/// `base` of the tree's nodes. In the layout [`Store::relayout`] makes, +/// a directory's block opens its run, and each child's run is the part +/// of what follows that starts at the child's first child. +fn bottom_up( + node: &mut Slot, + region: &mut [Slot], + base: usize, + names: &str, + depth: usize, + visit: &(L, D), +) where + L: Fn(&mut Facts) + Sync, + D: Fn(&mut Facts, Block<'_>) + Sync, +{ + let (leaf, directory) = visit; + if !node.facts.kind.is_dir() { + // De-duplication may zero a leaf with an inode; a clone that reads + // its size from the node must never have one. + debug_assert!( + node.facts.inode.is_none() + || !records::reads_size(node.extra.tag()), + "a clone record whose size could be de-duplicated away" + ); + leaf(&mut node.facts); + return; + } + let len = node.len as usize; + let start = if len == 0 { + 0 + } else { + node.first as usize - base + }; + let (block, rest) = region[start..].split_at_mut(len); + let rest_base = base + start + len; + if depth < crate::tree::PARALLEL_LEVELS && len > 1 { + let parts = runs(block, rest, rest_base); + block + .par_iter_mut() + .zip(parts) + .for_each(|(child, (run, base))| { + bottom_up(child, run, base, names, depth + 1, visit); + }); + } else { + for child in block.iter_mut() { + bottom_up(child, rest, rest_base, names, depth + 1, visit); + } + } + let first = node.first; + directory( + &mut node.facts, + Block { + slots: block, + names, + first, + }, + ); +} + +/// Beneath `block`, whose facts are written: each child directory's own +/// block with `directory`, then beneath that. `rest` holds the runs of +/// all of `block`'s children and starts at index `base`, as in +/// [`bottom_up`]. +fn top_down( + block: &[Slot], + rest: &mut [Slot], + base: usize, + names: &str, + depth: usize, + directory: &D, +) where + D: Fn(&Facts, Block<'_>) + Sync, +{ + // As in `bottom_up`, a node that is not a directory is a leaf, and a + // directory that holds nothing has no block to visit. + let below = |child: &Slot, region: &mut [Slot], base: usize| { + let len = child.len as usize; + if !child.facts.kind.is_dir() || len == 0 { + return; + } + let start = child.first as usize - base; + let (block, rest) = region[start..].split_at_mut(len); + directory( + &child.facts, + Block { + slots: &mut *block, + names, + first: child.first, + }, + ); + top_down(block, rest, base + start + len, names, depth + 1, directory); + }; + if depth < crate::tree::PARALLEL_LEVELS && block.len() > 1 { + block + .par_iter() + .zip(runs(block, rest, base)) + .for_each(|(child, (run, base))| below(child, run, base)); + } else { + for child in block { + below(child, rest, base); + } + } +} + +/// Each child's run of `rest`, which holds the runs of all of `block`'s +/// children and starts at index `base`, with the index it starts at; an +/// empty run for a child with no children. Runs are in the order they +/// were laid out, which sorting the block since has not changed. +fn runs<'r>( + block: &[Slot], + rest: &'r mut [Slot], + base: usize, +) -> Vec<(&'r mut [Slot], usize)> { + let len = block.len(); + let mut runs: Vec = + (0..len).filter(|&index| block[index].len > 0).collect(); + runs.sort_unstable_by_key(|&index| block[index].first); + let mut parts: Vec<(&mut [Slot], usize)> = + (0..len).map(|_| (&mut [][..], base)).collect(); + let mut rest = rest; + let mut at = base; + for (order, &index) in runs.iter().enumerate() { + let begin = block[index].first as usize; + let end = runs + .get(order + 1) + .map_or(at + rest.len(), |&next| block[next].first as usize); + let (_, tail) = std::mem::take(&mut rest).split_at_mut(begin - at); + let (run, tail) = tail.split_at_mut(end - begin); + parts[index] = (run, begin); + rest = tail; + at = end; + } + parts +} + +/// Where a tree is built: nodes are appended under a lock, so any number +/// of workers can build at once. `'h` brands what it builds with the +/// build it belongs to. +#[derive(Debug, Default)] +pub struct Builder { + store: Mutex, +} + +/// A node one build has made, not yet placed in its tree. +#[must_use] +pub struct Built<'h> { + slot: Slot, + /// Invariant: a node of one build cannot be taken for another's. + brand: PhantomData &'h ()>, +} + +impl fmt::Debug for Built<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.slot.fmt(f) + } +} + +impl Deref for Built<'_> { + type Target = Facts; + + fn deref(&self) -> &Facts { + &self.slot.facts + } +} + +impl Built<'_> { + /// A leaf's `bytes` and `inode` are what its allocation was kept + /// against: a clone with one name and no inode reads its size from + /// the node, which is why de-duplication, the one rewrite of a leaf's + /// `bytes`, touches only leaves with an inode. Change neither here. + pub const fn facts_mut(&mut self) -> &mut Facts { + &mut self.slot.facts + } +} + +impl Builder { + fn lock(&self) -> MutexGuard<'_, Store> { + self.store.lock().unwrap_or_else(PoisonError::into_inner) + } + + const fn built<'h>(slot: Slot) -> Built<'h> { + Built { + slot, + brand: PhantomData, + } + } + + /// A leaf, or a directory that holds nothing. + pub fn leaf<'h>( + &'h self, + name: &str, + facts: Facts, + allocation: Option, + ) -> Built<'h> { + let slot = self.lock().place( + name, + facts, + allocation, + None, + std::iter::empty(), + ); + Self::built(slot) + } + + /// Several leaves under one lock: how a listing adds its files. + pub fn leaves<'h, 'a>( + &'h self, + leaves: impl IntoIterator)>, + ) -> Vec> { + let mut store = self.lock(); + leaves + .into_iter() + .map(|(name, facts, allocation)| { + Self::built(store.place( + name, + facts, + allocation, + None, + std::iter::empty(), + )) + }) + .collect() + } + + /// A directory holding `children`, which become one block of the tree + /// in the order given. + pub fn directory<'h>( + &'h self, + name: &str, + facts: Facts, + allocation: Option, + children: Vec>, + ) -> Built<'h> { + let slot = self.lock().place( + name, + facts, + allocation, + None, + children.into_iter().map(|child| child.slot), + ); + Self::built(slot) + } + + /// A deep copy of `node`, from any tree, into this build: how a + /// subtree moves between trees. + pub fn copy<'h>(&'h self, node: Node<'_>) -> Built<'h> { + self.copy_named(node, node.name()) + } + + /// [`Self::copy`], under another name. + pub fn copy_named<'h>(&'h self, node: Node<'_>, name: &str) -> Built<'h> { + let mut store = self.lock(); + // A whole tree, as a wider scan reuses one, goes in as its buffers. + let slot = if node.is_root() { + store.absorb(node.store, name) + } else { + store.copy(node, name) + }; + Self::built(slot) + } + + /// `draft`, with everything beneath it. + pub fn draft<'h>(&'h self, draft: &Draft) -> Built<'h> { + Self::built(self.lock().draft(draft)) + } +} + +/// A scanned tree and the buffers its nodes live in. +#[derive(Clone)] +pub struct Tree { + store: Store, +} + +impl fmt::Debug for Tree { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Tree") + .field("root", &self.root()) + .finish_non_exhaustive() + } +} + +impl From for Tree { + fn from(draft: Draft) -> Self { + Self::from(&draft) + } +} + +impl From<&Draft> for Tree { + fn from(draft: &Draft) -> Self { + Self::build(|builder| builder.draft(draft)) + } +} + +impl Tree { + /// Build a tree: `build` makes nodes with the builder it is given and + /// returns the root. The brand keeps every node it makes in this tree. + /// + /// A node of one build cannot become part of another tree, where its + /// indices would name other nodes: + /// + /// ```compile_fail + /// use disktree_core::tree::{Facts, NodeKind, Tree}; + /// let mut smuggled = None; + /// let _first = Tree::build(|builder| { + /// smuggled = + /// Some(builder.leaf("x", Facts::entry(NodeKind::File, 1), None)); + /// builder.leaf("root", Facts::directory(), None) + /// }); + /// let _second = Tree::build(|_| smuggled.take().unwrap()); + /// ``` + pub fn build(build: impl for<'h> FnOnce(&'h Builder) -> Built<'h>) -> Self { + let builder = Builder::default(); + let root = build(&builder).slot; + Self::finish(builder, root) + } + + /// [`Self::build`], for a build that can fail. + pub fn try_build( + build: impl for<'h> FnOnce(&'h Builder) -> Result, E>, + ) -> Result { + let builder = Builder::default(); + let root = build(&builder)?.slot; + Ok(Self::finish(builder, root)) + } + + fn finish(builder: Builder, root: Slot) -> Self { + let mut store = builder + .store + .into_inner() + .unwrap_or_else(PoisonError::into_inner); + store.root = Store::index(store.nodes.len()); + store.nodes.push(root); + store.relayout(); + store.allocations.seal(); + Self { store } + } + + /// A tree of its own holding a copy of `node` and everything beneath: + /// the whole store at once when `node` is a root. + pub fn copy_of(node: Node<'_>) -> Self { + if node.is_root() { + return Self { + store: node.store.clone(), + }; + } + Self::build(|builder| builder.copy(node)) + } + + pub fn root(&self) -> Node<'_> { + Node { + store: &self.store, + slot: &self.store.nodes[self.store.root as usize], + } + } + + pub const fn root_mut(&mut self) -> NodeMut<'_> { + NodeMut { + id: self.store.root, + store: &mut self.store, + } + } + + pub const fn storage_bytes(&self) -> StorageBytes { + self.store.bytes() + } + + /// Replace the sharing figures of the nodes at these positions, which + /// [`Node::id`] gave on this tree, unchanged since. + pub(crate) fn set_sharing( + &mut self, + figures: impl IntoIterator)>, + ) { + for (id, sharing) in figures { + NodeMut { + store: &mut self.store, + id, + } + .set_sharing(sharing); + } + } + + /// Every leaf with `leaf`, then each directory with `directory` once + /// its children are done; separate subtrees near the top run on + /// separate workers. + pub fn par_bottom_up( + &mut self, + leaf: impl Fn(&mut Facts) + Sync, + directory: impl Fn(&mut Facts, Block<'_>) + Sync, + ) { + let Store { nodes, names, .. } = &mut self.store; + let (root, region) = + nodes.split_first_mut().expect("a tree has a root"); + bottom_up(root, region, 1, names, 0, &(leaf, directory)); + } + + /// The root's children with `root`, which writes the root's facts and + /// theirs, then each directory's children with `directory` once its + /// own facts are written, given those facts; separate subtrees near + /// the top run on separate workers, as in [`Self::par_bottom_up`]. + pub fn par_top_down( + &mut self, + root: impl FnOnce(&mut Facts, Block<'_>), + directory: impl Fn(&Facts, Block<'_>) + Sync, + ) { + let Store { nodes, names, .. } = &mut self.store; + let (node, region) = + nodes.split_first_mut().expect("a tree has a root"); + // The root's block, if it has one, is the first after the root. + debug_assert!(node.len == 0 || node.first == 1, "a laid-out tree"); + let (block, rest) = region.split_at_mut(node.len as usize); + root( + &mut node.facts, + Block { + slots: &mut *block, + names, + first: node.first, + }, + ); + let base = 1 + block.len(); + top_down(block, rest, base, names, 0, &directory); + } + + /// Every node, spread across workers, for a pass that only reads and + /// needs no particular order. The n-th has [`Node::id`] n. + pub(crate) fn par_nodes( + &self, + ) -> impl IndexedParallelIterator> { + let store = &self.store; + store.nodes.par_iter().map(move |slot| Node { store, slot }) + } + + /// Records in each side table, for measuring what they cost. + pub const fn side_records(&self) -> (usize, usize, usize) { + ( + self.store.allocations.len(), + self.store.sharings.len(), + self.store.both.len(), + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn file(bytes: u64) -> Facts { + Facts::entry(NodeKind::File, bytes) + } + + fn names(node: Node<'_>) -> Vec<&str> { + node.children().iter().map(Node::name).collect() + } + + fn sample() -> Tree { + Tree::build(|builder| { + let deep = builder.leaf("deep", file(7), None); + let nested = builder.directory( + "child", + Facts::directory(), + None, + vec![deep], + ); + let direct = builder.leaf( + "direct", + file(5), + Some(Allocation { + bytes: 5, + identity: None, + links: 1, + followed: false, + clone: None, + }), + ); + let empty = builder.leaf("", file(0), None); + builder.directory( + "root", + Facts::directory(), + None, + vec![nested, direct, empty], + ) + }) + } + + /// A home directory is tens of millions of nodes: every byte here is + /// tens of megabytes there. + #[test] + fn a_node_stays_small() { + // Facts, then a name offset, the first child, the child count and + // one side-table index. + assert_eq!(size_of::(), 48); + assert_eq!(size_of::(), 64); + } + + #[test] + fn a_built_tree_reads_back() { + let tree = sample(); + let root = tree.root(); + assert_eq!(root.name(), "root"); + assert_eq!(names(root), ["child", "direct", ""]); + let deep = root.children().at(0).children().at(0); + assert_eq!(deep.name(), "deep"); + assert_eq!(deep.bytes, 7); + assert_eq!( + root.children().at(1).allocation().map(|a| a.bytes), + Some(5) + ); + assert!(root.children().at(2).children().is_empty()); + } + + #[test] + fn a_long_name_and_many_children_survive() { + let long = "é".repeat(300); + let tree = Tree::build(|builder| { + let children = (0..1000) + .map(|index| { + builder.leaf(&format!("{index}"), file(index), None) + }) + .chain(std::iter::once(builder.leaf(&long, file(1), None))) + .collect(); + builder.directory("root", Facts::directory(), None, children) + }); + let children = tree.root().children(); + assert_eq!(children.len(), 1001); + assert_eq!(children.at(999).name(), "999"); + assert_eq!(children.at(999).bytes, 999); + assert_eq!(children.at(1000).name(), long); + } + + #[test] + fn writes_reach_the_tree_and_children_reorder_in_place() { + let mut tree = sample(); + let mut root = tree.root_mut(); + root.facts_mut().bytes = 12; + root.for_each_child_mut(|mut child| { + child.facts_mut().read_error = true; + }); + root.sort_children_by(|left, right| left.name.cmp(right.name)); + root.child_mut(0).expect("a child").facts_mut().modified = 9; + let root = tree.root(); + assert_eq!(root.bytes, 12); + assert_eq!(names(root), ["", "child", "direct"]); + assert_eq!(root.children().at(0).modified, 9); + assert!(root.children().iter().all(|child| child.read_error)); + assert_eq!(root.children().at(1).children().at(0).name(), "deep"); + } + + #[test] + fn sharing_is_rewritten_in_place() { + let mut tree = sample(); + let mut root = tree.root_mut(); + root.set_sharing(Some(Sharing::default())); + let first = root.node().stored_sharing().map(std::ptr::from_ref); + root.set_sharing(Some(Sharing { + files: 3, + ..Sharing::default() + })); + assert_eq!(root.node().stored_sharing().map(std::ptr::from_ref), first); + assert_eq!(tree.root().stored_sharing().map(|s| s.files), Some(3)); + tree.root_mut().set_sharing(None); + assert!(tree.root().stored_sharing().is_none()); + } + + #[test] + fn a_node_can_hold_an_allocation_and_sharing() { + let mut tree = sample(); + let mut root = tree.root_mut(); + let mut direct = root.child_mut(1).expect("direct"); + // What aggregating does to every file: no figures to keep must + // not cost the file its allocation. + direct.set_sharing(None); + assert_eq!(direct.node().allocation().map(|a| a.bytes), Some(5)); + direct.set_sharing(Some(Sharing { + files: 2, + ..Sharing::default() + })); + let node = direct.node(); + assert_eq!(node.allocation().map(|a| a.bytes), Some(5)); + assert_eq!(node.stored_sharing().map(|s| s.files), Some(2)); + direct.set_sharing(None); + assert_eq!(direct.node().allocation().map(|a| a.bytes), Some(5)); + assert!(direct.node().stored_sharing().is_none()); + } + + #[test] + fn a_copy_outlives_its_source() { + let source = sample(); + let copy = source.clone(); + drop(source); + assert_eq!(copy.root().children().len(), 3); + assert_eq!( + copy.root().children().at(0).children().at(0).name(), + "deep" + ); + let subtree = { + let source = sample(); + Tree::copy_of(source.root().children().at(0)) + }; + assert_eq!(subtree.root().name(), "child"); + assert_eq!(subtree.root().children().len(), 1); + } + + /// Everything below two nodes reads the same, names included. + fn assert_same(left: Node<'_>, right: Node<'_>) { + assert_eq!(left.bytes, right.bytes, "{}", left.name()); + assert_eq!(left.kind, right.kind, "{}", left.name()); + assert_eq!(left.allocation(), right.allocation(), "{}", left.name()); + assert_eq!( + left.stored_sharing().map(|s| s.files), + right.stored_sharing().map(|s| s.files), + "{}", + left.name() + ); + assert_eq!(names(left), names(right)); + for (left, right) in left.children().iter().zip(right.children()) { + assert_same(left, right); + } + } + + #[test] + fn a_whole_tree_copied_into_a_build_keeps_its_records() { + let mut source = sample(); + let shared = |files| { + Some(Sharing { + files, + ..Sharing::default() + }) + }; + let mut root = source.root_mut(); + root.set_sharing(shared(1)); + // `direct` already has an allocation: this puts it in `both`. + root.child_mut(1).expect("direct").set_sharing(shared(2)); + root.child_mut(0).expect("child").set_sharing(shared(3)); + let allocation = Allocation { + bytes: 9, + identity: None, + links: 1, + followed: false, + clone: None, + }; + let tree = Tree::build(|builder| { + // Records already in every table, so the copy's must move. + let mut before = builder.leaf("before", file(9), Some(allocation)); + before.slot.extra = builder.lock().set_sharing( + before.slot.extra, + shared(4), + &before.slot.facts, + ); + let other = builder.leaf("other", file(1), None); + let other = builder.directory( + "other-dir", + Facts::directory(), + None, + vec![other], + ); + let reused = builder.copy_named(source.root(), "reused"); + builder.directory( + "top", + Facts::directory(), + None, + vec![before, other, reused], + ) + }); + let reused = tree.root().children().at(2); + assert_eq!(reused.name(), "reused"); + assert_same(reused, source.root()); + let before = tree.root().children().at(0); + assert_eq!(before.allocation().map(|a| a.bytes), Some(9)); + assert_eq!(before.stored_sharing().map(|s| s.files), Some(4)); + // The source's root went in too, and nothing reaches it. + assert_eq!(tree.store.nodes.len(), 1 + 3 + 1 + 3 + 1); + } + + /// A file for each allocation table: a wholly shared clone, a + /// modified one, a second name and one kept whole. + fn every_record(builder: &Builder, salt: u64) -> Vec> { + use crate::sharing::CloneInfo; + let info = |private| CloneInfo { + device: 4, + id: salt, + references: 2, + private_bytes: private, + data_bytes: 10, + }; + let clone = |private| Allocation { + bytes: 10, + identity: None, + links: 1, + followed: false, + clone: Some(info(private)), + }; + let mut tracked = file(10); + tracked.inode = Some((4, NonZeroU64::new(salt).expect("inode"))); + let link = Allocation { + identity: Some((4, salt)), + links: 2, + clone: None, + ..clone(None) + }; + [ + (file(10), clone(Some(0)), records::SHARED), + (file(10), clone(Some(salt)), records::CLONE), + (tracked, link, records::LINK), + (tracked, clone(Some(0)), records::FULL), + ] + .into_iter() + .map(|(facts, allocation, tag)| { + let built = + builder.leaf(&format!("{tag}"), facts, Some(allocation)); + assert_eq!(built.slot.extra.tag(), tag); + built + }) + .collect() + } + + #[test] + fn a_whole_tree_copied_into_a_build_keeps_every_allocation_table() { + let source = Tree::build(|builder| { + let files = every_record(builder, 7); + builder.directory("source", Facts::directory(), None, files) + }); + let tree = Tree::build(|builder| { + // A record in every table first, so each of the copy's moves. + let before = every_record(builder, 3); + let before = + builder.directory("before", Facts::directory(), None, before); + let reused = builder.copy_named(source.root(), "reused"); + builder.directory( + "top", + Facts::directory(), + None, + vec![before, reused], + ) + }); + assert_same(tree.root().children().at(1), source.root()); + let again = Tree::build(|builder| { + let files = every_record(builder, 3); + builder.directory("before", Facts::directory(), None, files) + }); + assert_same(tree.root().children().at(0), again.root()); + // And a copy of the whole store, as the size/files toggle makes. + assert_same(tree.clone().root(), tree.root()); + assert_eq!(tree.side_records().0, 8); + } + + /// A clone that reads its size from its node, given an inode after it + /// was kept: de-duplication could zero the size it reads. + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "could be de-duplicated away")] + fn an_inode_on_a_clone_that_reads_its_size_is_caught() { + let mut tree = Tree::build(|builder| { + let files = every_record(builder, 5); + builder.directory("root", Facts::directory(), None, files) + }); + let mut root = tree.root_mut(); + let mut shared = root.child_mut(0).expect("the shared clone"); + assert!(records::reads_size(shared.node().slot.extra.tag())); + shared.facts_mut().inode = NonZeroU64::new(5).map(|inode| (4, inode)); + crate::tree::aggregate(&mut tree, Metric::Bytes); + } + + #[test] + fn a_tree_moves_to_another_thread() { + let tree = sample(); + let count = std::thread::spawn(move || tree.root().children().len()) + .join() + .expect("joined"); + assert_eq!(count, 3); + } + + /// Deeper than the levels that run in parallel, and with every block + /// re-sorted so blocks no longer list children in the order their runs + /// were laid out. + #[test] + fn top_down_writes_every_node_once_from_its_parent() { + fn draft(name: &str, depth: usize) -> Draft { + let mut node = Draft::directory(name); + if depth < crate::tree::PARALLEL_LEVELS + 3 { + node.children = (0..3) + .map(|index| draft(&format!("{name}/{index}"), depth + 1)) + .collect(); + } + node.children.push(Draft::entry( + format!("{name}/file").as_str(), + NodeKind::File, + 0, + )); + node.children + .push(Draft::directory(format!("{name}/empty").as_str())); + node + } + fn check(node: Node<'_>, depth: i64, nodes: &mut usize) { + *nodes += 1; + assert_eq!(node.bytes, 1, "{} written once", node.name()); + assert_eq!(node.modified, depth, "{} at its depth", node.name()); + for child in node.children() { + check(child, depth + 1, nodes); + } + } + let mut tree = Tree::from(draft("root", 0)); + tree.par_bottom_up( + |_| {}, + |_, mut block| { + block.sort_by(|left, right| right.name.cmp(left.name)); + }, + ); + // Each write counts itself in `bytes` and records its depth in + // `modified`, which only the parent's own facts can give. + tree.par_top_down( + |root, mut block| { + root.bytes += 1; + root.modified = 0; + block.for_each_facts_mut(|child| { + child.bytes += 1; + child.modified = 1; + }); + }, + |parent, mut block| { + block.for_each_facts_mut(|child| { + child.bytes += 1; + child.modified = parent.modified + 1; + }); + }, + ); + let mut nodes = 0; + check(tree.root(), 0, &mut nodes); + assert_eq!(nodes, tree.store.nodes.len()); + } + + #[test] + fn a_tree_built_on_every_worker_holds_every_node() { + let tree = Tree::build(|builder| { + let children = (0..64) + .into_par_iter() + .map(|dir| { + let names: Vec = (0..100) + .map(|index| format!("{dir}-{index}")) + .collect(); + let files = builder.leaves( + names.iter().map(|name| (name.as_str(), file(1), None)), + ); + builder.directory( + &format!("{dir}"), + Facts::directory(), + None, + files, + ) + }) + .collect(); + builder.directory("root", Facts::directory(), None, children) + }); + let root = tree.root(); + assert_eq!(root.children().len(), 64); + assert!(root.children().iter().enumerate().all(|(dir, child)| { + child.children().len() == 100 + && child.children().at(99).name() == format!("{dir}-99") + })); + let bytes = tree.storage_bytes(); + assert!(bytes.used > 0 && bytes.used <= bytes.reserved); + } +} diff --git a/crates/disktree-core/src/index/records.rs b/crates/disktree-core/src/index/records.rs new file mode 100644 index 00000000..2a8babf8 --- /dev/null +++ b/crates/disktree-core/src/index/records.rs @@ -0,0 +1,597 @@ +//! An [`Allocation`] as a tree stores it: in the smallest record that +//! holds what the node does not already say. +//! +//! A scan keeps an allocation for every file that may share blocks, and +//! as a 96-byte struct that was more than the nodes themselves cost. On +//! 16.4 million files of agent worktrees, 14.2 million kept one: 97.7 % +//! were clones with one name whose size is the node's own and whose +//! data fork is all of it, and nearly all of those were wholly shared. +//! Such a clone keeps 16 or 24 bytes here. A file with several names, or +//! one reached through a followed link, keeps 16 when it has no clone +//! facts: its identity is the node's inode. Anything else keeps the whole +//! struct, so no figure is ever approximated to fit. + +use rustc_hash::FxHashMap; + +use super::Facts; +use crate::sharing::{Allocation, CloneInfo}; + +/// The tags of [`super::Extra`] that name one of these tables. +pub(super) const SHARED: u32 = 1; +pub(super) const CLONE: u32 = 2; +pub(super) const LINK: u32 = 3; +pub(super) const FULL: u32 = 4; + +/// Whether `tag` names one of these tables. +pub(super) const fn holds(tag: u32) -> bool { + matches!(tag, SHARED | CLONE | LINK | FULL) +} + +/// Whether the table `tag` names reads a file's size from its node, which +/// holds only while the leaf has no inode for de-duplication to act on. +pub(super) const fn reads_size(tag: u32) -> bool { + matches!(tag, SHARED | CLONE) +} + +/// Where each table of one store starts once it is appended to another: +/// the other's lengths before the append. +#[derive(Clone, Copy, Debug)] +pub(super) struct Starts { + shared: usize, + clones: usize, + links: usize, + full: usize, +} + +impl Starts { + /// Where the record at `index` of the table `tag` names moved to. + pub(super) const fn moved(self, tag: u32, index: usize) -> usize { + index + + match tag { + SHARED => self.shared, + CLONE => self.clones, + LINK => self.links, + FULL => self.full, + _ => 0, + } + } +} + +/// A clone with one name and no private blocks: what nearly every file +/// of a directory of cloned worktrees is. Every file of a clone group +/// reads the same one, which is kept once: see [`Records::reuse`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) struct SharedClone { + id: u64, + /// APFS reports the real device as 32 bits. + device: u32, + references: u32, +} + +/// A clone with one name whose private blocks are some, or unknown. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct PartialClone { + id: u64, + /// [`UNKNOWN`] when the file system did not say. + private: u64, + device: u32, + references: u32, +} + +/// Shared records [`Records::reuse`] remembers while a tree is built: +/// a group a record, so room for this many groups. Past it a record is +/// kept per file again, which costs memory, not accuracy. +const REUSED: usize = 1 << 20; + +/// No file holds `u64::MAX` bytes, so it can stand for an unknown +/// private size without an `Option`'s eight bytes of tag. +const UNKNOWN: u64 = u64::MAX; + +/// A file with more than one name, or one a scan that follows links +/// reached, with no clone facts: its own size, which de-duplication can +/// take from the node, and how many names it has. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Linked { + bytes: u64, + links: u32, + followed: bool, +} + +/// The identity sharing reads: only a file with more than one name is +/// matched to its other names, and never through a followed link. +fn identity(facts: &Facts, links: u64, followed: bool) -> Option<(u64, u64)> { + if links > 1 && !followed { + facts.inode.map(|(device, inode)| (device, inode.get())) + } else { + None + } +} + +/// What the stored record is, before it goes into its table. +enum Packed { + SharedClone(SharedClone), + PartialClone(PartialClone), + Linked(Linked), + Full(Allocation), +} + +impl Packed { + /// The smallest record that gives `allocation` back for `facts`. + /// + /// A clone's size is taken from the node only when nothing can change + /// the node's: a leaf with no inode is never de-duplicated, which is + /// the one thing that rewrites a leaf's `bytes`. + fn of(allocation: Allocation, facts: &Facts) -> Self { + #[cfg(test)] + if WHOLE.get() { + return Self::Full(allocation); + } + let Allocation { + bytes, + links, + followed, + clone, + .. + } = allocation; + let identity_kept = allocation.identity + == identity(facts, links, followed) + || links <= 1 + || followed; + match clone { + Some(info) + if links == 1 + && !followed + && !facts.kind.is_dir() + && facts.inode.is_none() + && bytes == facts.bytes + && info.data_bytes == facts.bytes + && info.private_bytes != Some(UNKNOWN) => + { + let Ok(device) = u32::try_from(info.device) else { + return Self::Full(allocation); + }; + if info.private_bytes == Some(0) { + Self::SharedClone(SharedClone { + id: info.id, + device, + references: info.references, + }) + } else { + Self::PartialClone(PartialClone { + id: info.id, + private: info.private_bytes.unwrap_or(UNKNOWN), + device, + references: info.references, + }) + } + } + None if identity_kept => match u32::try_from(links) { + Ok(links) => Self::Linked(Linked { + bytes, + links, + followed, + }), + Err(_) => Self::Full(allocation), + }, + _ => Self::Full(allocation), + } + } +} + +#[cfg(test)] +thread_local! { + /// Keep every record whole, to compare figures against. + static WHOLE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// `build` with every allocation it keeps on this thread kept whole. +#[cfg(test)] +pub fn kept_whole(build: impl FnOnce() -> R) -> R { + WHOLE.set(true); + let built = build(); + WHOLE.set(false); + built +} + +const fn clone_of(facts: &Facts, info: CloneInfo) -> Allocation { + Allocation { + bytes: facts.bytes, + identity: None, + links: 1, + followed: false, + clone: Some(info), + } +} + +/// Every allocation of a tree, one table for each record. +#[derive(Default)] +pub(super) struct Records { + shared: Vec, + clones: Vec, + links: Vec, + full: Vec, + /// Where each shared record is, while the tree is built: files of a + /// group share a record, as no record is ever changed in place. On + /// 8.9 million files of agent worktrees 8.1 million kept one, in 129 + /// thousand groups; one apiece was 124 MiB of a 1 GiB tree. Dropped + /// when the tree is finished. + reuse: FxHashMap, +} + +impl Records { + /// Keep `allocation` for a node of `facts`: the tag of the table it + /// went into and its index there. + pub(super) fn push( + &mut self, + allocation: Allocation, + facts: &Facts, + ) -> (u32, usize) { + match Packed::of(allocation, facts) { + Packed::SharedClone(record) => { + if let Some(&index) = self.reuse.get(&record) { + return (SHARED, index as usize); + } + let index = self.shared.len(); + self.shared.push(record); + if self.reuse.len() < REUSED + && let Ok(at) = u32::try_from(index) + { + self.reuse.insert(record, at); + } + (SHARED, index) + } + Packed::PartialClone(record) => { + self.clones.push(record); + (CLONE, self.clones.len() - 1) + } + Packed::Linked(record) => { + self.links.push(record); + (LINK, self.links.len() - 1) + } + Packed::Full(record) => { + self.full.push(record); + (FULL, self.full.len() - 1) + } + } + } + + /// The allocation at `index` of the table `tag` names, for the node + /// of `facts` it was kept for. + pub(super) fn get( + &self, + tag: u32, + index: usize, + facts: &Facts, + ) -> Option { + Some(match tag { + SHARED => { + let SharedClone { + id, + device, + references, + } = self.shared[index]; + clone_of( + facts, + CloneInfo { + device: u64::from(device), + id, + references, + private_bytes: Some(0), + data_bytes: facts.bytes, + }, + ) + } + CLONE => { + let PartialClone { + id, + private, + device, + references, + } = self.clones[index]; + clone_of( + facts, + CloneInfo { + device: u64::from(device), + id, + references, + private_bytes: (private != UNKNOWN).then_some(private), + data_bytes: facts.bytes, + }, + ) + } + LINK => { + let Linked { + bytes, + links, + followed, + } = self.links[index]; + let links = u64::from(links); + Allocation { + bytes, + identity: identity(facts, links, followed), + links, + followed, + clone: None, + } + } + FULL => self.full[index], + _ => return None, + }) + } + + /// Forget which records can be shared: the tree is finished. + pub(super) fn seal(&mut self) { + self.reuse = FxHashMap::default(); + } + + /// Where each table of a store appended to this one will start. + pub(super) const fn starts(&self) -> Starts { + Starts { + shared: self.shared.len(), + clones: self.clones.len(), + links: self.links.len(), + full: self.full.len(), + } + } + + pub(super) fn append(&mut self, other: &Self) { + self.shared.extend_from_slice(&other.shared); + self.clones.extend_from_slice(&other.clones); + self.links.extend_from_slice(&other.links); + self.full.extend_from_slice(&other.full); + } + + /// A copy made on every worker, as [`super::Store`]'s is. + pub(super) fn par_copy(&self) -> Self { + use super::copied; + let ((shared, clones), (links, full)) = rayon::join( + || rayon::join(|| copied(&self.shared), || copied(&self.clones)), + || rayon::join(|| copied(&self.links), || copied(&self.full)), + ); + Self { + shared, + clones, + links, + full, + reuse: FxHashMap::default(), + } + } + + /// Records kept, in all tables. + pub(super) const fn len(&self) -> usize { + self.shared.len() + + self.clones.len() + + self.links.len() + + self.full.len() + } + + /// Bytes the records fill, and bytes the tables have room for. + pub(super) const fn bytes(&self) -> (usize, usize) { + ( + self.shared.len() * size_of::() + + self.clones.len() * size_of::() + + self.links.len() * size_of::() + + self.full.len() * size_of::(), + self.shared.capacity() * size_of::() + + self.clones.capacity() * size_of::() + + self.links.capacity() * size_of::() + + self.full.capacity() * size_of::(), + ) + } +} + +#[cfg(test)] +mod tests { + use std::num::NonZeroU64; + + use super::*; + use crate::tree::NodeKind; + + fn inode(device: u64, inode: u64) -> Option<(u64, NonZeroU64)> { + Some((device, NonZeroU64::new(inode)?)) + } + + /// Fourteen million records on one real tree: every byte here is + /// fourteen megabytes there. + #[test] + fn an_allocation_record_stays_small() { + assert_eq!(size_of::(), 16); + assert_eq!(size_of::(), 24); + assert_eq!(size_of::(), 16); + // Kept whole only for what the small records cannot say. + assert_eq!(size_of::(), 96); + } + + fn info(private: Option) -> CloneInfo { + CloneInfo { + device: 16_777_234, + id: 0xC0FF_EE00_0000_0001, + references: 70_000, + private_bytes: private, + data_bytes: 4096, + } + } + + fn clone(private: Option) -> Allocation { + Allocation { + bytes: 4096, + // A listing reports one; sharing never reads it for a file + // with one name, so the record does not keep it. + identity: Some((1, 7)), + links: 1, + followed: false, + clone: Some(info(private)), + } + } + + fn file(bytes: u64) -> Facts { + Facts::entry(NodeKind::File, bytes) + } + + /// Kept, then read back: the table it went into and what it reads as. + fn kept(allocation: Allocation, facts: &Facts) -> (u32, Allocation) { + let mut records = Records::default(); + let (tag, index) = records.push(allocation, facts); + (tag, records.get(tag, index, facts).expect("a record")) + } + + #[test] + fn a_clone_with_one_name_keeps_only_what_its_node_does_not_say() { + let facts = file(4096); + for (private, tag) in [ + (Some(0), SHARED), + (Some(1024), CLONE), + (Some(4096), CLONE), + (None, CLONE), + ] { + let (stored, back) = kept(clone(private), &facts); + assert_eq!(stored, tag, "{private:?}"); + assert_eq!( + back, + Allocation { + identity: None, + ..clone(private) + }, + "{private:?}" + ); + } + } + + #[test] + fn files_of_a_group_share_one_record_until_the_tree_is_sealed() { + let mut records = Records::default(); + let small = file(4096); + let large = file(8192); + let mut larger = clone(Some(0)); + larger.bytes = 8192; + larger.clone.as_mut().expect("clone").data_bytes = 8192; + let (tag, first) = records.push(clone(Some(0)), &small); + assert_eq!(tag, SHARED); + // Another member, another size: the size is the node's own. + assert_eq!(records.push(larger, &large), (SHARED, first)); + assert_eq!( + records.get(SHARED, first, &large), + Some(Allocation { + identity: None, + ..larger + }) + ); + // Another reference count is another record. + let mut counted = clone(Some(0)); + counted.clone.as_mut().expect("clone").references = 3; + assert_ne!(records.push(counted, &small), (SHARED, first)); + assert_eq!(records.len(), 2); + records.seal(); + assert_ne!(records.push(clone(Some(0)), &small), (SHARED, first)); + } + + #[test] + fn hardlinks_and_followed_links_keep_their_own_size_and_names() { + let mut facts = file(0); + facts.inode = inode(1, 7); + // A second name de-duplication has already charged elsewhere. + let hardlink = Allocation { + bytes: 4096, + identity: Some((1, 7)), + links: 3, + followed: false, + clone: None, + }; + assert_eq!(kept(hardlink, &facts), (LINK, hardlink)); + let followed = Allocation { + identity: None, + links: 1, + followed: true, + ..hardlink + }; + assert_eq!(kept(followed, &facts), (LINK, followed)); + let directory = Allocation { + bytes: 0, + ..followed + }; + assert_eq!(kept(directory, &Facts::directory()), (LINK, directory)); + } + + /// Whatever a small record would have to guess at is kept whole, and + /// reads back exactly as it went in. + #[test] + fn what_a_small_record_cannot_say_is_kept_whole() { + let facts = file(4096); + let mut tracked = file(4096); + tracked.inode = inode(1, 7); + let mut cases = vec![ + // De-duplication could zero the node's size. + (clone(Some(0)), tracked), + // A resource fork beside the cloned data fork. + ( + Allocation { + clone: Some(CloneInfo { + data_bytes: 1024, + ..info(Some(0)) + }), + ..clone(Some(0)) + }, + facts, + ), + // A clone with more than one name. + ( + Allocation { + links: 2, + identity: Some((1, 7)), + ..clone(Some(0)) + }, + tracked, + ), + // A device wider than APFS reports. + ( + Allocation { + clone: Some(CloneInfo { + device: 1 << 40, + ..info(Some(0)) + }), + ..clone(Some(0)) + }, + facts, + ), + // A private size the sentinel would misread. + (clone(Some(UNKNOWN)), facts), + // More names than the small record counts. + ( + Allocation { + links: 1 << 33, + identity: Some((1, 7)), + clone: None, + ..clone(None) + }, + tracked, + ), + // An identity that is not the node's inode. + ( + Allocation { + links: 2, + identity: Some((1, 8)), + clone: None, + ..clone(None) + }, + tracked, + ), + ]; + // A clone's size differs from its node's. + cases.push((clone(Some(0)), file(8192))); + // A directory's size is its children's. + cases.push(( + clone(Some(0)), + Facts { + bytes: 4096, + ..Facts::directory() + }, + )); + for (allocation, facts) in cases { + assert_eq!( + kept(allocation, &facts), + (FULL, allocation), + "{allocation:?}" + ); + } + } +} diff --git a/crates/disktree-core/src/insights.rs b/crates/disktree-core/src/insights.rs index 589029c5..61bf47a5 100644 --- a/crates/disktree-core/src/insights.rs +++ b/crates/disktree-core/src/insights.rs @@ -28,6 +28,25 @@ pub enum Finding { StaleExperiments { count: usize }, } +impl Finding { + /// The finding in a few words, as a list reads it after the size. + pub fn describe(&self) -> String { + match self { + Self::Reclaimable(reclaim) => { + format!("cleanup candidate: {}", reclaim.label()) + } + Self::Worktrees { count, oldest_days } => format!( + "{count} agent worktree{}, the oldest {oldest_days} d old", + if *count == 1 { "" } else { "s" } + ), + Self::StaleExperiments { count } => format!( + "{count} experiment{} untouched for a month or more", + if *count == 1 { "" } else { "s" } + ), + } + } +} + /// One line of the list. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Candidate { @@ -40,10 +59,10 @@ pub struct Candidate { /// The `limit` largest findings beneath `root`, largest first. `now` is Unix /// seconds, passed in so the answer is testable. -pub fn worth_a_look(root: &Node, now: i64, limit: usize) -> Vec { +pub fn worth_a_look(root: Node<'_>, now: i64, limit: usize) -> Vec { let mut found = Vec::new(); let mut crumbs = Vec::new(); - for (index, child) in root.children.iter().enumerate() { + for (index, child) in root.children().iter().enumerate() { crumbs.push(index); visit(child, &mut crumbs, now, &mut found); crumbs.pop(); @@ -55,7 +74,7 @@ pub fn worth_a_look(root: &Node, now: i64, limit: usize) -> Vec { } fn visit( - node: &Node, + node: Node<'_>, crumbs: &mut Vec, now: i64, found: &mut Vec, @@ -74,11 +93,11 @@ fn visit( }); return; } - let name = &*node.name; + let name = node.name(); let scratch = node.category == Category::AgentScratch; if scratch && name.eq_ignore_ascii_case("worktrees") { - let trees: Vec<&Node> = node - .children + let trees: Vec> = node + .children() .iter() .filter(|child| child.is_dir()) .collect(); @@ -104,7 +123,7 @@ fn visit( && (name.eq_ignore_ascii_case("tries") || name.eq_ignore_ascii_case("experiments")); let mut stale = (0_usize, 0_u64); - for (index, child) in node.children.iter().enumerate() { + for (index, child) in node.children().iter().enumerate() { let is_stale = experiments && child.is_dir() && child.modified > 0 @@ -132,30 +151,32 @@ fn visit( mod tests { use super::*; use crate::classify::classify; + use crate::tree::{Draft, Tree}; use crate::tree::{Metric, NodeKind, aggregate}; const GIB: u64 = 1024 * 1024 * 1024; const NOW: i64 = 1_800_000_000; - fn file(name: &str, bytes: u64, days_old: i64) -> Node { - let mut node = Node::entry(name, NodeKind::File, bytes); + fn file(name: &str, bytes: u64, days_old: i64) -> Draft { + let mut node = Draft::entry(name, NodeKind::File, bytes); node.modified = NOW - days_old * DAY; node } - fn dir(name: &str, children: Vec) -> Node { - let mut node = Node::directory(name); + fn dir(name: &str, children: Vec) -> Draft { + let mut node = Draft::directory(name); node.children = children; node } - fn scan(mut root: Node) -> Node { + fn scan(root: Draft) -> Tree { + let mut root = Tree::from(root); aggregate(&mut root, Metric::Bytes); classify(&mut root); root } - fn home() -> Node { + fn home() -> Tree { scan(dir( "tobi", vec![ @@ -183,7 +204,16 @@ mod tests { "fresh", vec![ file("Cargo.toml", 1, 1), - dir("target", vec![file("o", GIB, 1)]), + dir( + "target", + vec![dir( + "debug", + vec![dir( + "deps", + vec![file("o", GIB, 1)], + )], + )], + ), ], ), ], @@ -197,7 +227,7 @@ mod tests { #[test] fn ranks_findings_largest_first_and_skips_the_tiny() { - let found = worth_a_look(&home(), NOW, 10); + let found = worth_a_look(home().root(), NOW, 10); let kinds: Vec<&Finding> = found.iter().map(|c| &c.finding).collect(); assert_eq!( kinds, @@ -217,14 +247,15 @@ mod tests { #[test] fn documents_are_never_suggested() { - let found = worth_a_look(&home(), NOW, 10); + let found = worth_a_look(home().root(), NOW, 10); assert!(found.iter().all(|c| c.crumbs != vec![3])); } #[test] fn crumbs_address_the_finding_from_the_root() { - let root = home(); - for candidate in worth_a_look(&root, NOW, 10) { + let tree = home(); + let root = tree.root(); + for candidate in worth_a_look(root, NOW, 10) { let node = root.resolve(&candidate.crumbs).expect("resolves"); assert!(node.is_dir()); } @@ -232,7 +263,7 @@ mod tests { #[test] fn the_limit_keeps_the_largest() { - let found = worth_a_look(&home(), NOW, 2); + let found = worth_a_look(home().root(), NOW, 2); assert_eq!(found.len(), 2); assert_eq!( found[1].finding, diff --git a/crates/disktree-core/src/lib.rs b/crates/disktree-core/src/lib.rs index 0f58c7ba..c57c5bae 100644 --- a/crates/disktree-core/src/lib.rs +++ b/crates/disktree-core/src/lib.rs @@ -6,27 +6,40 @@ //! be built and tested without GPUI, a display, or a GPU. pub mod access; +pub mod artifact; pub mod classify; +pub mod cleanup; +#[cfg(any(target_os = "macos", test))] +mod clone_cache; pub mod deployment; pub mod export; pub mod filter; pub mod identity; +pub mod index; pub mod insights; #[cfg(target_os = "macos")] mod macos; +pub mod macos_services; #[cfg(windows)] mod mft; +pub mod path_style; pub mod payload; +pub mod planning; +pub mod query; pub mod remote; pub mod remote_progress; #[cfg(unix)] mod remote_walk; pub mod removal; +pub mod removal_limit; pub mod scan; pub mod scan_preview; pub mod scan_threads; +pub mod sharing; pub mod size; pub mod space; +#[cfg(test)] +mod test_rng; pub mod tree; pub mod treemap; #[cfg(windows)] diff --git a/crates/disktree-core/src/macos.rs b/crates/disktree-core/src/macos.rs index 6cdac06d..4169c651 100644 --- a/crates/disktree-core/src/macos.rs +++ b/crates/disktree-core/src/macos.rs @@ -8,12 +8,15 @@ #![allow( unsafe_code, - reason = "getattrlistbulk, which neither std nor rustix wraps; each block \ + reason = "Darwin attribute calls, which neither std nor rustix wraps; each block \ says why it is sound" )] use std::cell::RefCell; -use std::ffi::{OsStr, c_int, c_void}; +use std::ffi::{CString, OsStr, c_int, c_void}; +use std::fs::Metadata; +use std::os::unix::fs::MetadataExt as _; + use std::io; use std::os::fd::{AsRawFd as _, OwnedFd}; use std::os::unix::ffi::OsStrExt as _; @@ -21,9 +24,28 @@ use std::path::{Path, PathBuf}; use rustix::fs::{AtFlags, FileType, Mode, OFlags}; +use crate::sharing::CloneInfo; + /// Bytes the kernel fills per call: some hundreds of entries. const BUFFER_BYTES: usize = 64 * 1024; +const REFCNT: u32 = 0x1000; +const FULL_SHARE: u64 = 0x40; +const MAY_SHARE: u64 = 0x1 | FULL_SHARE; +const EXTENDED: u32 = libc::FSOPT_ATTR_CMN_EXTENDED; +const RETURNED: u32 = libc::ATTR_CMN_RETURNED_ATTRS; +const REAL_DEVICE: u32 = 0x40; +/// A file's clone group: cheap to list, since APFS keeps it in the inode. +const IDS: u32 = REAL_DEVICE | libc::ATTR_CMNEXT_CLONEID; +/// The group and whether it shares blocks. The flags are dear to list: +/// for every file that was ever cloned APFS looks up how many files share +/// its data, and listing threads queue for that lookup in the kernel. On +/// 8.9 million files of agent worktrees, 7.8 million of them clones, the +/// flags made an 18-thread walk 16 s slower (27 s without them, 43 s with; +/// the group alone cost about 1 s), and the more threads, the more each +/// lookup cost: 3 us of system time a clone on 4 threads, 20 us on 16. +const HINTS: u32 = IDS | libc::ATTR_CMNEXT_EXT_FLAGS; + // From and , which the libc crate does not cover. const ATTR_BIT_MAP_COUNT: u16 = 5; const ATTR_CMN_NAME: u32 = 0x0000_0001; @@ -116,6 +138,39 @@ pub struct Entry { inode: u64, links: u32, flags: u32, + hints: Option, +} + +/// What a listing says about an entry's clone group. +#[derive(Clone, Copy, Debug)] +struct Hints { + /// `ATTR_CMNEXT_REALDEVID`: zero when the file system did not say. + device: u64, + id: u64, + /// `ATTR_CMNEXT_EXT_FLAGS`, when the listing asked for them. + flags: Option, +} + +/// What a listing asks about clones; see [`IDS`] and [`HINTS`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Clones { + Off, + /// Clone groups only. A file's sharing flags then come from another + /// member of its group met earlier in the scan, or from the file's own + /// metadata read, which most clones pay for anyway. + Ids, + /// Clone groups and every file's sharing flags. + Flags, +} + +impl Clones { + const fn attributes(self) -> u32 { + match self { + Self::Off => 0, + Self::Ids => IDS, + Self::Flags => HINTS, + } + } } impl Entry { @@ -135,7 +190,7 @@ impl Entry { &self.name } - /// The name, moved out: the tree keeps it, so nothing copies it. The + /// The name, moved out: it is copied once, into the tree's names. The /// entry's other accessors keep working; `name`, `file_name` and /// `path` do not. pub fn take_name(&mut self) -> Box { @@ -162,8 +217,17 @@ impl Entry { } /// `(st_dev, st_ino)`: the same for two names of one file. - pub const fn identity(&self) -> (u64, u64) { - (self.device, self.inode) + pub fn identity(&self) -> (u64, u64) { + ( + self.hints.map_or(self.device, |hints| { + if hints.device == 0 { + self.device + } else { + hints.device + } + }), + self.inode, + ) } pub const fn device(&self) -> u64 { @@ -171,6 +235,10 @@ impl Entry { } /// Whether the file has more than one name. + pub const fn links(&self) -> u64 { + self.links as u64 + } + pub const fn shared(&self) -> bool { self.links > 1 } @@ -181,6 +249,46 @@ impl Entry { matches!(self.kind, Kind::Directory) && self.flags & SF_DATALESS != 0 } + /// Only clone candidates pay for private-size reads; ordinary metadata + /// and identity remain the values returned by the bulk listing. + /// + /// A listing without sharing flags takes them from the file's clone + /// group. A clone ID names a data stream, and files with the same one + /// are pure clones of each other (getattrlist(2)); APFS keeps the + /// stream's reference count with the stream, not with each file (the + /// Apple File System Reference, `j_dstream_id_val_t`). So a file whose + /// group shares all its blocks does too: across 2.9 million groups on + /// three trees (worktrees, a home Library and a folder of checkouts) + /// no two files of a group disagreed. A group the scan has not met yet + /// is read from the file itself, in the read that measures its private + /// size. + pub fn clone_info( + &self, + dir: &Path, + cache: &crate::clone_cache::Cache, + ) -> Option { + let hints = self.hints?; + if self.kind != Kind::File { + return None; + } + // The path is joined only for a read: most clones never need one. + resolve( + hints, + self.inode, + u64::from(self.links), + self.allocated, + cache, + || { + private_info( + &self.path(dir), + hints.device, + self.inode, + hints.id, + ) + }, + ) + } + fn named(name: &[u8]) -> (Box, Option>) { match std::str::from_utf8(name) { Ok(text) => (text.into(), None), @@ -210,10 +318,50 @@ impl Entry { inode: stat.st_ino, links: u32::from(stat.st_nlink), flags: stat.st_flags, + hints: None, } } } +/// A regular file's clone facts from what its listing said, `read` +/// being the file's own metadata read: its private size, reference count +/// and, when the read found the file the listing did, its sharing flags. +/// [`Entry::clone_info`] calls it for regular files only, with the read +/// by path; the tests stand in for the read. +fn resolve( + hints: Hints, + inode: u64, + links: u64, + allocated: u64, + cache: &crate::clone_cache::Cache, + read: impl Fn() -> (CloneInfo, Option), +) -> Option { + let Hints { device, id, flags } = hints; + let mut measured = None; + let flags = match flags { + Some(flags) => flags, + None if cache.shares_all(device, id) => MAY_SHARE | FULL_SHARE, + None => { + let (info, flags) = read(); + measured = Some(info); + // A file that could not be read again may be a clone: its + // private size stays unknown, the side that never overstates + // a saving. + flags.unwrap_or(MAY_SHARE) + } + }; + if flags & MAY_SHARE == 0 { + return None; + } + let measure = || measured.unwrap_or_else(|| read().0); + if flags & FULL_SHARE == 0 { + return Some(measure()); + } + // A resource fork can differ even when the data fork is cloned. Reuse + // only when the listing agrees with the cached data allocation. + Some(cache.get(device, id, inode, links, allocated, measure)) +} + /// A directory being listed; like `std::fs::ReadDir`, it leaves out `.` /// and `..`. #[derive(Debug)] @@ -226,11 +374,25 @@ pub struct ReadDir { /// Where the next of them starts. offset: usize, done: bool, + clones: Clones, } +/// Directories listed without sharing flags, so a test can tell that its +/// own scan listed some: tests scan side by side. +#[cfg(test)] +static WITHOUT_FLAGS: std::sync::Mutex> = + std::sync::Mutex::new(Vec::new()); + /// List `dir`, with each entry's size, identity and age. A link at `dir` /// itself is followed, as `std::fs::read_dir` follows it. -pub fn read_dir(dir: &Path) -> io::Result { +pub fn read_dir(dir: &Path, clones: Clones) -> io::Result { + #[cfg(test)] + if clones == Clones::Ids { + WITHOUT_FLAGS + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push(dir.to_path_buf()); + } let fd = rustix::fs::open( dir, OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, @@ -245,6 +407,7 @@ pub fn read_dir(dir: &Path) -> io::Result { remaining: 0, offset: 0, done: false, + clones, }) } @@ -305,7 +468,7 @@ impl ReadDir { volattr: 0, dirattr: 0, fileattr: FILE_ATTRIBUTES, - forkattr: 0, + forkattr: self.clones.attributes(), }; loop { // SAFETY: the descriptor is an open directory owned by `self`; @@ -318,13 +481,29 @@ impl ReadDir { &raw mut request, buffer.as_mut_ptr().cast(), BUFFER_BYTES, - 0, + if self.clones == Clones::Off { + 0 + } else { + u64::from(EXTENDED) + }, ) }; if let Ok(count) = u32::try_from(count) { return Ok(count); } let error = io::Error::last_os_error(); + // Optional clone hints must not disable ordinary enumeration on + // volumes or kernels that reject extended attributes. + if self.clones != Clones::Off + && matches!( + error.raw_os_error(), + Some(libc::EINVAL | libc::ENOTSUP) + ) + { + self.clones = Clones::Off; + request.forkattr = 0; + continue; + } if error.kind() != io::ErrorKind::Interrupted { return Err(error); } @@ -362,7 +541,7 @@ impl ReadDir { let common = cursor.u32()?; cursor.at += 8; let file = cursor.u32()?; - cursor.at += 4; + let extended = cursor.u32()?; let error = if common & ATTR_CMN_ERROR == 0 { 0 } else { @@ -374,7 +553,7 @@ impl ReadDir { return Ok((Err(error), length)); } let entry = if common & MEASURED == MEASURED { - cursor.entry(file, name)? + cursor.entry(file, extended, self.clones, name)? } else { None }; @@ -437,18 +616,29 @@ impl<'a> Cursor<'a> { let offset = isize::try_from(self.u32()?.cast_signed()) .map_err(|_| malformed())?; let length = self.u32()? as usize; - reference + let name = reference .checked_add_signed(offset) .zip(length.checked_sub(1)) .and_then(|(start, length)| { self.record.get(start..start.checked_add(length)?) }) - .ok_or_else(malformed) + .ok_or_else(malformed)?; + if name.is_empty() || name == b"." || name == b".." || name.contains(&0) + { + return Err(malformed()); + } + Ok(name) } /// The attributes after the name, every one of them asked for; `None` /// for a file whose sizes the file system left out. - fn entry(&mut self, file: u32, name: &[u8]) -> io::Result> { + fn entry( + &mut self, + file: u32, + extended: u32, + clones: Clones, + name: &[u8], + ) -> io::Result> { let device = self.u32()?.cast_signed(); let kind = match self.u32()? { VDIR => Kind::Directory, @@ -472,6 +662,30 @@ impl<'a> Cursor<'a> { } else { return Ok(None); }; + let real_device = if extended & REAL_DEVICE != 0 { + u64::from(self.u32()?) + } else { + 0 + }; + let clone_id = if extended & libc::ATTR_CMNEXT_CLONEID != 0 { + Some(self.u64()?) + } else { + None + }; + let clone_flags = if extended & libc::ATTR_CMNEXT_EXT_FLAGS != 0 { + Some(self.u64()?) + } else { + None + }; + // Flags that were asked for and not given mean no clone facts, as + // they always have; flags not asked for come from the group. + let hints = clone_id + .filter(|_| clones == Clones::Ids || clone_flags.is_some()) + .map(|id| Hints { + device: real_device, + id, + flags: clone_flags, + }); let (name, exact) = Entry::named(name); Ok(Some(Entry { name, @@ -484,6 +698,7 @@ impl<'a> Cursor<'a> { inode, links, flags, + hints, })) } } @@ -496,7 +711,7 @@ mod tests { use tempfile::TempDir; fn listed(dir: &Path) -> Vec { - let mut entries: Vec = read_dir(dir) + let mut entries: Vec = read_dir(dir, Clones::Off) .expect("list") .collect::>() .expect("entries"); @@ -578,6 +793,16 @@ mod tests { let listed: Vec = listed(root).iter().map(fields).collect(); let stated: Vec = stated(root).iter().map(fields).collect(); assert_eq!(listed, stated); + // Adding clone hints must preserve ordinary metadata, including + // resource forks and hardlink identity in the same bulk record. + let mut clone_entries: Vec = read_dir(root, Clones::Flags) + .expect("list with clone hints") + .collect::>() + .expect("entries"); + clone_entries.sort_by(|left, right| left.name.cmp(&right.name)); + let clone_fields: Vec = + clone_entries.iter().map(fields).collect(); + assert_eq!(clone_fields, stated); let forked = listed.iter().find(|leaf| leaf.0 == "forked").unwrap(); assert_eq!(forked.2, 4, "the data fork's length"); assert!(forked.3 >= 20_000, "the fork's blocks: {}", forked.3); @@ -617,7 +842,734 @@ mod tests { #[test] fn a_missing_directory_is_an_error() { let temp = TempDir::new().expect("tempdir"); - let error = read_dir(&temp.path().join("gone")).expect_err("missing"); + let error = read_dir(&temp.path().join("gone"), Clones::Off) + .expect_err("missing"); assert_eq!(error.kind(), io::ErrorKind::NotFound); } } + +const fn clone_attrs(common: u32, file: u32, extended: u32) -> libc::attrlist { + libc::attrlist { + bitmapcount: libc::ATTR_BIT_MAP_COUNT, + reserved: 0, + commonattr: RETURNED | common, + volattr: 0, + dirattr: 0, + fileattr: file, + forkattr: extended, + } +} + +/// A clone's private size and reference count, read again by path, and +/// its sharing flags when the read found the file the listing did. +fn private_info( + path: &Path, + device: u64, + inode: u64, + id: u64, +) -> (CloneInfo, Option) { + let mut info = CloneInfo { + device, + id, + ..CloneInfo::default() + }; + let Ok(path) = CString::new(path.as_os_str().as_bytes()) else { + return (info, None); + }; + // Re-read identity alongside private size: a replacement between the + // listing/stat and this call must not receive the old file's estimate. + let mut request = clone_attrs( + libc::ATTR_CMN_FILEID, + libc::ATTR_FILE_DATAALLOCSIZE, + libc::ATTR_CMNEXT_PRIVATESIZE | HINTS | REFCNT, + ); + let mut buffer = [0_u8; 96]; + loop { + // SAFETY: valid NUL-terminated path, initialized ABI request and + // writable buffer. NOFOLLOW never asks a symlink target for data. + let result = unsafe { + libc::getattrlist( + path.as_ptr(), + (&raw mut request).cast(), + buffer.as_mut_ptr().cast(), + buffer.len(), + EXTENDED | libc::FSOPT_NOFOLLOW | libc::FSOPT_PACK_INVAL_ATTRS, + ) + }; + if result == 0 { + break; + } + if io::Error::last_os_error().raw_os_error() == Some(libc::EINVAL) + && request.forkattr & REFCNT != 0 + { + request.forkattr &= !REFCNT; + continue; + } + return (info, None); + } + let Some(length) = clone_read_u32(&buffer, 0) else { + return (info, None); + }; + let Some(buffer) = buffer.get(..length as usize) else { + return (info, None); + }; + let common = clone_read_u32(buffer, 4).unwrap_or(0); + let files = clone_read_u32(buffer, 16).unwrap_or(0); + let extended = clone_read_u32(buffer, 20).unwrap_or(0); + if common & libc::ATTR_CMN_FILEID == 0 + || clone_read_u64(buffer, 24) != Some(inode) + { + return (info, None); + } + // Packed order includes realdevid before cloneid, even when unavailable. + // PACK_INVAL_ATTRS reserves its slot; ordinary st_dev can alias APFS + // System and Data volumes and must never substitute for this identity. + let real_device = if extended & REAL_DEVICE != 0 { + u64::from(clone_read_u32(buffer, 48).unwrap_or(0)) + } else { + 0 + }; + if device != 0 && device != real_device { + return (info, None); + } + info.device = real_device; + if extended & libc::ATTR_CMNEXT_CLONEID == 0 + || clone_read_u64(buffer, 52) != Some(id) + { + return (info, None); + } + if extended & libc::ATTR_CMNEXT_PRIVATESIZE != 0 { + info.private_bytes = clone_read_u64(buffer, 40); + } + if files & libc::ATTR_FILE_DATAALLOCSIZE != 0 { + info.data_bytes = clone_read_u64(buffer, 32).unwrap_or(0); + } + if extended & REFCNT != 0 { + info.references = clone_read_u32(buffer, 68).unwrap_or(0); + } + let flags = if extended & libc::ATTR_CMNEXT_EXT_FLAGS == 0 { + None + } else { + clone_read_u64(buffer, 60) + }; + (info, flags) +} + +fn clone_read_u32(bytes: &[u8], at: usize) -> Option { + Some(u32::from_ne_bytes(bytes.get(at..at + 4)?.try_into().ok()?)) +} +fn clone_read_u64(bytes: &[u8], at: usize) -> Option { + Some(u64::from_ne_bytes(bytes.get(at..at + 8)?.try_into().ok()?)) +} + +/// Exceptional path for followed symlinks; ordinary entries use bulk hints. +pub fn clone_info(path: &Path, meta: &Metadata) -> Option { + let path_c = CString::new(path.as_os_str().as_bytes()).ok()?; + let mut request = clone_attrs(0, 0, HINTS); + let mut buffer = [0_u8; 48]; + // SAFETY: valid path, ABI request and writable buffer of the stated size. + let result = unsafe { + libc::getattrlist( + path_c.as_ptr(), + (&raw mut request).cast(), + buffer.as_mut_ptr().cast(), + buffer.len(), + EXTENDED | libc::FSOPT_NOFOLLOW | libc::FSOPT_PACK_INVAL_ATTRS, + ) + }; + if result != 0 + || clone_read_u32(&buffer, 20)? & HINTS != HINTS + || clone_read_u64(&buffer, 36)? & MAY_SHARE == 0 + { + return None; + } + Some( + private_info( + path, + u64::from(clone_read_u32(&buffer, 24)?), + meta.ino(), + clone_read_u64(&buffer, 28)?, + ) + .0, + ) +} + +#[cfg(test)] +mod clone_tests { + use super::*; + use crate::scan::{ScanOptions, scan}; + use std::fs; + use std::io::{Seek, SeekFrom, Write}; + use std::process::Command; + + fn fixture() -> tempfile::TempDir { + let temp = tempfile::tempdir().expect("tempdir"); + let source = temp.path().join("original"); + fs::write(&source, vec![0x5a; 8 * 1024 * 1024]).expect("write"); + assert!( + Command::new("cp") + .arg("-c") + .arg(&source) + .arg(temp.path().join("clone")) + .status() + .expect("cp -c") + .success() + ); + temp + } + + #[test] + fn ten_apfs_worktrees_with_a_surviving_clone_only_credit_private_files() { + let temp = fixture(); + for index in 0..10 { + let dir = temp.path().join(format!("worktree-{index}")); + fs::create_dir(&dir).expect("worktree"); + assert!( + Command::new("cp") + .arg("-c") + .arg(temp.path().join("original")) + .arg(dir.join("shared")) + .status() + .expect("cp -c") + .success() + ); + fs::write(dir.join("private"), vec![0x31; 64 * 1024]) + .expect("private file"); + } + let tree = scan(temp.path(), ScanOptions::default()).expect("scan"); + let tree = tree.root(); + let selected: Vec<_> = tree + .children() + .iter() + .filter(|node| node.name().starts_with("worktree-")) + .collect(); + assert_eq!(selected.len(), 10); + assert_eq!( + selected.iter().map(|node| node.bytes).sum::(), + 10 * (8 * 1024 * 1024 + 64 * 1024) + ); + let estimate = crate::sharing::estimate(selected); + assert_eq!(estimate.lower, 10 * 64 * 1024); + assert_eq!(estimate.upper, estimate.lower); + assert!(!estimate.partial); + } + + #[test] + fn a_listing_without_flags_finds_what_one_with_them_finds() { + let temp = fixture(); + let dir = temp.path(); + for name in ["second", "modified"] { + assert!( + Command::new("cp") + .arg("-c") + .arg(dir.join("original")) + .arg(dir.join(name)) + .status() + .expect("cp -c") + .success() + ); + } + let mut modified = fs::OpenOptions::new() + .write(true) + .open(dir.join("modified")) + .expect("open"); + modified.write_all(&[1; 4096]).expect("write"); + modified.sync_all().expect("sync"); + fs::write(dir.join("plain"), vec![7; 64 * 1024]).expect("plain"); + fs::hard_link(dir.join("second"), dir.join("linked")).expect("link"); + let infos = |clones| { + let cache = crate::clone_cache::Cache::default(); + let mut entries: Vec = read_dir(dir, clones) + .expect("list") + .collect::>() + .expect("entries"); + entries.sort_by(|left, right| left.name.cmp(&right.name)); + if clones == Clones::Ids { + assert!(entries.iter().all(|entry| { + entry.hints.is_some_and(|hints| hints.flags.is_none()) + })); + } + entries + .iter() + .map(|entry| { + (entry.name.clone(), entry.clone_info(dir, &cache)) + }) + .collect::>() + }; + let flagged = infos(Clones::Flags); + let shared: Vec<&str> = flagged + .iter() + .filter(|(_, info)| info.is_some()) + .map(|(name, _)| &**name) + .collect(); + assert_eq!( + shared, + ["clone", "linked", "modified", "original", "second"] + ); + assert_eq!(infos(Clones::Ids), flagged); + } + + /// Every node's name, size, allocation and sharing figures, children + /// by name: two scans of one tree read the same only if all agree. + fn every_figure(node: crate::tree::Node<'_>, into: &mut Vec) { + into.push(format!( + "{} {} {} {:?} {:?}", + node.name(), + node.bytes, + node.files, + node.allocation(), + node.sharing() + )); + let mut children: Vec<_> = node.children().iter().collect(); + children.sort_by(|left, right| left.name().cmp(right.name())); + for child in children { + every_figure(child, into); + } + } + + /// Worktrees cloned from a source tree, as an agent makes them: some + /// with a modified clone, a file of their own, a hardlink, a resource + /// fork, and clones at the top that put their siblings' listings + /// without flags. Scanned as listings choose and with flags in every + /// listing, every figure agrees. + #[test] + fn worktrees_scan_the_same_with_flags_in_every_listing() { + let temp = tempfile::tempdir().expect("tempdir"); + let root = temp.path(); + let source = root.join("source"); + fs::create_dir_all(source.join("nested/deeper")).expect("source"); + for (name, size) in [ + ("a", 64 * 1024), + ("b", 8 * 1024), + ("nested/c", 16 * 1024), + ("nested/deeper/d", 4096), + ("nested/deeper/e", 12 * 1024), + ] { + fs::write(source.join(name), vec![name.len() as u8; size]) + .expect("source file"); + } + let clone = |from: &Path, to: &Path| { + assert!( + Command::new("cp") + .arg("-c") + .arg("-R") + .arg(from) + .arg(to) + .status() + .expect("cp -c") + .success() + ); + }; + for index in 0..6 { + clone(&source, &root.join(format!("worktree-{index}"))); + } + for name in ["top-a", "top-b"] { + clone(&source.join("a"), &root.join(name)); + } + let mut modified = fs::OpenOptions::new() + .write(true) + .open(root.join("worktree-1/nested/c")) + .expect("open"); + modified.write_all(&[9; 4096]).expect("write"); + modified.sync_all().expect("sync"); + fs::write(root.join("worktree-2/nested/own"), vec![3; 20 * 1024]) + .expect("own file"); + fs::hard_link( + root.join("worktree-3/b"), + root.join("worktree-3/nested/linked"), + ) + .expect("hardlink"); + fs::write( + root.join("worktree-4/nested/deeper/d/..namedfork/rsrc"), + [1; 4096], + ) + .expect("resource fork"); + let scanned = || { + let tree = scan( + root, + ScanOptions { + // Which name of a hardlink is charged depends on the + // order workers meet them. + dedup_hardlinks: false, + ..ScanOptions::default() + }, + ) + .expect("scan"); + let mut figures = Vec::new(); + every_figure(tree.root(), &mut figures); + figures + }; + let chosen = scanned(); + // The walk lists the root as it resolves: /var is /private/var. + let real = fs::canonicalize(root).expect("canonical root"); + assert!( + WITHOUT_FLAGS + .lock() + .expect("listings") + .iter() + .any(|dir| dir.starts_with(root) || dir.starts_with(&real)), + "some listing of this tree left the flags out" + ); + let flagged = { + /// Clears the switch even if the scan panics, so no later test + /// in this process scans with it set. + struct Reset; + impl Drop for Reset { + fn drop(&mut self) { + crate::scan::ALWAYS_FLAGS + .store(false, std::sync::atomic::Ordering::Relaxed); + } + } + crate::scan::ALWAYS_FLAGS + .store(true, std::sync::atomic::Ordering::Relaxed); + let _reset = Reset; + scanned() + }; + assert_eq!(chosen, flagged); + // The clones were seen as clones: the copies repeat bytes. + let root = &chosen[0]; + assert!(!root.contains("duplicate_bytes: 0,"), "{root}"); + } + + #[test] + fn real_clones_keep_listed_bytes_and_report_sharing() { + let temp = fixture(); + let tree = scan(temp.path(), ScanOptions::default()).expect("scan"); + let tree = tree.root(); + assert_eq!(tree.bytes, 16 * 1024 * 1024); + assert_eq!(tree.sharing().files, 2, "{tree:#?}"); + assert_eq!(tree.sharing().bytes, tree.bytes); + assert_eq!(tree.sharing().duplicate_bytes, 8 * 1024 * 1024); + assert_eq!(tree.sharing().private_bytes, 0); + assert_eq!(tree.sharing().unknown_files, 0); + let baseline = scan( + temp.path(), + ScanOptions { + apfs_clone_metadata: false, + ..ScanOptions::default() + }, + ) + .expect("scan without clone metadata"); + let baseline = baseline.root(); + assert_eq!(baseline.bytes, tree.bytes); + assert_eq!(baseline.sharing().files, 0); + let apparent = scan( + temp.path(), + ScanOptions { + apparent_size: true, + ..ScanOptions::default() + }, + ) + .expect("apparent scan"); + assert_eq!(apparent.root().sharing().files, 0); + } + + #[test] + fn real_clone_hardlinks_and_followed_names_have_set_level_savings() { + let temp = fixture(); + let original = temp.path().join("original"); + fs::hard_link(&original, temp.path().join("alias")).expect("hardlink"); + std::os::unix::fs::symlink(&original, temp.path().join("followed")) + .expect("symlink"); + let tree = scan( + temp.path(), + ScanOptions { + follow_links: true, + ..ScanOptions::default() + }, + ) + .expect("scan"); + let tree = tree.root(); + let by_name = |name: &str| { + tree.children() + .iter() + .find(|node| node.name() == name) + .expect("entry") + }; + let original = by_name("original"); + let alias = by_name("alias"); + let clone = by_name("clone"); + let followed = by_name("followed"); + for node in [original, alias, clone, followed] { + assert_eq!(crate::sharing::estimate([node]).lower, 0); + } + assert_eq!(crate::sharing::estimate([original, clone]).lower, 0); + assert_eq!( + crate::sharing::estimate([original, alias, clone]).lower, + 8 * 1024 * 1024 + ); + assert_eq!(tree.sharing().reclaimable(tree.bytes), 8 * 1024 * 1024); + for node in [original, alias, clone] { + assert_ne!( + node.allocation() + .expect("allocation") + .clone + .expect("clone") + .device, + 0 + ); + } + } + + #[test] + fn resource_fork_allocation_remains_in_the_range_for_full_clones() { + let temp = fixture(); + let fork = temp.path().join("clone/..namedfork/rsrc"); + fs::write(fork, vec![0x31; 4096]).expect("resource fork"); + let tree = scan(temp.path(), ScanOptions::default()).expect("scan"); + let tree = tree.root(); + assert_eq!(tree.sharing().private_bytes, 0); + assert_eq!(tree.sharing().reclaimable(tree.bytes), 8 * 1024 * 1024); + assert_eq!(tree.sharing().possible(tree.bytes), 8 * 1024 * 1024 + 4096); + assert_eq!(tree.sharing().duplicate_bytes, 8 * 1024 * 1024); + let clone = tree + .children() + .iter() + .find(|node| node.name() == "clone") + .expect("clone"); + assert_eq!(clone.sharing().reclaimable(clone.bytes), 0); + assert_eq!(clone.sharing().possible(clone.bytes), 4096); + } + + #[test] + fn modified_clones_keep_private_bytes_and_hardlinks_are_not_clones() { + let temp = fixture(); + let clone = temp.path().join("clone"); + let mut file = fs::OpenOptions::new() + .write(true) + .open(&clone) + .expect("open"); + file.seek(SeekFrom::Start(1024 * 1024)).expect("seek"); + file.write_all(&[1; 4096]).expect("write"); + file.sync_all().expect("sync"); + fs::hard_link(&clone, temp.path().join("linked")).expect("hardlink"); + std::os::unix::fs::symlink(&clone, temp.path().join("symlink")) + .expect("symlink"); + for follow_links in [false, true] { + let tree = scan( + temp.path(), + ScanOptions { + follow_links, + ..ScanOptions::default() + }, + ) + .expect("scan"); + let tree = tree.root(); + assert_eq!(tree.sharing().files, 2, "{tree:#?}"); + assert!(tree.sharing().private_bytes >= 4096); + assert!(tree.sharing().private_bytes < tree.sharing().bytes); + assert_eq!(tree.sharing().duplicate_bytes, 0); + } + } + + #[test] + fn unreadable_private_metadata_is_unknown_not_full_allocation() { + let temp = fixture(); + let source = temp.path().join("original"); + let meta = fs::metadata(&source).expect("metadata"); + let (info, flags) = private_info( + &temp.path().join("missing"), + meta.dev(), + meta.ino(), + 42, + ); + assert_eq!(flags, None); + assert_eq!(info.private_bytes, None); + assert_eq!(info.references, 0); + } + + #[test] + fn malformed_bulk_names_and_records_are_rejected() { + assert!( + Cursor { + record: &[], + at: 24 + } + .name() + .is_err() + ); + let mut record = vec![0_u8; 64]; + record[4..8] + .copy_from_slice(&(RETURNED | libc::ATTR_CMN_NAME).to_ne_bytes()); + record[24..28].copy_from_slice(&8_u32.to_ne_bytes()); + record[28..32].copy_from_slice(&3_u32.to_ne_bytes()); + record[32..35].copy_from_slice(b"ok\0"); + assert_eq!( + Cursor { + record: &record, + at: 24 + } + .name() + .expect("name"), + b"ok" + ); + record[32..35].copy_from_slice(b"..\0"); + assert!( + Cursor { + record: &record, + at: 24 + } + .name() + .is_err() + ); + record[24..28].copy_from_slice(&u32::MAX.to_ne_bytes()); + assert!( + Cursor { + record: &record, + at: 24 + } + .name() + .is_err() + ); + } +} + +/// A model of APFS clones checked against [`resolve`]: listing without +/// sharing flags must find what listing with them finds. +#[cfg(test)] +mod resolve_tests { + use super::*; + use crate::clone_cache::Cache; + use crate::test_rng::Rng; + use std::cell::Cell; + + /// One file as the volume knows it. + #[derive(Clone, Copy, Debug)] + struct File { + device: u64, + id: u64, + inode: u64, + links: u64, + /// Every fork's allocation, as the listing reports it. + allocated: u64, + flags: u64, + /// What the file's own metadata read finds; `None` flags for a + /// file gone since it was listed. + read: (CloneInfo, Option), + } + + /// Clone groups as APFS keeps them: files of a group share one data + /// stream, so its reference count and whether it is shared are the + /// group's; whether a file may share is its own, and set on every + /// file whose stream is shared. Some files are hardlinked, some have + /// a resource fork the group does not share, some are gone by the + /// time they are read, and some groups are on a volume of no known + /// identity. + fn world(rng: &mut Rng) -> Vec { + let mut files = Vec::new(); + let mut inode = 100; + for id in 1..=rng.below(12) + 1 { + let device = u64::from(!rng.percent(10)); + let data = 4096 * (rng.below(4) + 1); + let kind = rng.below(3); + let (references, flags, private, members) = match kind { + // A stream shared by files in the scan and maybe outside. + 0 => { + let members = rng.below(5) + 1; + let outside = rng.below(3); + let references = + u32::try_from(members + outside).expect("small"); + (references.max(2), MAY_SHARE | FULL_SHARE, 0, members) + } + // Cloned once, now alone: a modified clone or an original + // whose clones are gone. + 1 => (1, 0x1, rng.below(2) * 4096, 1), + // Never cloned. + _ => (1, 0, data, 1), + }; + for _ in 0..members { + inode += 1; + let fork = if rng.percent(10) { 4096 } else { 0 }; + let links = if rng.percent(15) { 2 } else { 1 }; + let gone = rng.percent(5); + let info = CloneInfo { + device, + id, + references, + private_bytes: (!gone).then_some(private), + data_bytes: data, + }; + let file = File { + device, + id, + inode, + links, + allocated: data + fork, + flags, + read: (info, (!gone).then_some(flags)), + }; + for _ in 0..links { + files.push(file); + } + } + } + rng.shuffle(&mut files); + files + } + + /// Each file resolved in order with one cache, as a scan's listings + /// are: with the listing's flags or without; and the reads made, for + /// files that may share and files that never could. + fn run(files: &[File], flags: bool) -> (Vec>, u64, u64) { + let cache = Cache::default(); + let (mut sharing, mut plain) = (0, 0); + let found = files + .iter() + .map(|file| { + let reads = Cell::new(0); + let hints = Hints { + device: file.device, + id: file.id, + flags: flags.then_some(file.flags), + }; + let found = resolve( + hints, + file.inode, + file.links, + file.allocated, + &cache, + || { + reads.set(reads.get() + 1); + file.read + }, + ); + if file.flags & MAY_SHARE == 0 { + plain += reads.get(); + } else { + sharing += reads.get(); + } + found + }) + .collect(); + (found, sharing, plain) + } + + #[test] + fn a_listing_without_flags_resolves_every_file_as_one_with_them() { + for seed in 0..2000 { + let files = world(&mut Rng::new(seed)); + let (listed, listed_reads, never) = run(&files, true); + let (grouped, grouped_reads, plain_reads) = run(&files, false); + assert_eq!(never, 0, "seed {seed}"); + for ((file, listed), grouped) in + files.iter().zip(&listed).zip(&grouped) + { + if file.flags & MAY_SHARE == 0 && file.read.1.is_none() { + // Gone before it was read, and never a clone: without + // the listing's word for it, it counts as a clone of + // unknown size, which overstates no saving. + assert_eq!(*listed, None, "seed {seed}"); + let grouped = grouped.expect("counted as a clone"); + assert_eq!(grouped.private_bytes, None, "seed {seed}"); + } else { + assert_eq!(grouped, listed, "seed {seed}: {file:?}"); + } + } + // Files that may share are read no more often; a file never + // cloned is read once a name, which the listing policy weighs. + assert_eq!(grouped_reads, listed_reads, "seed {seed}"); + let plain = files.iter().filter(|f| f.flags & MAY_SHARE == 0); + assert_eq!(plain_reads, plain.count() as u64, "seed {seed}"); + } + } +} diff --git a/crates/disktree-core/src/macos_services.rs b/crates/disktree-core/src/macos_services.rs new file mode 100644 index 00000000..7b6e28da --- /dev/null +++ b/crates/disktree-core/src/macos_services.rs @@ -0,0 +1,229 @@ +//! Read-only visibility into macOS's private, on-volume service stores. +//! +//! These figures come from the same tree as the treemap, not another walk or +//! a subtraction from APFS capacity. They therefore share hardlink accounting +//! and never add volume or snapshot usage to file totals. + +use std::path::{Path, PathBuf}; + +use crate::scan::ScanOptions; +use crate::tree::Node; + +/// A service store whose name alone does not explain its contents. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Service { + Fsevents, + Spotlight, +} + +impl Service { + pub const ALL: [Self; 2] = [Self::Fsevents, Self::Spotlight]; + + pub const fn name(self) -> &'static str { + match self { + Self::Fsevents => ".fseventsd", + Self::Spotlight => ".Spotlight-V100", + } + } + + pub const fn label(self) -> &'static str { + match self { + Self::Fsevents => "FSEvents history", + Self::Spotlight => "Spotlight index", + } + } + + pub const fn guidance(self) -> &'static str { + match self { + Self::Fsevents => { + "Filesystem change history used by backup and sync apps. \ + At an administrator's explicit request, Apple's root-only \ + purge API can shorten old history. Other consumers may need \ + a full rescan. PwrDisk does not purge it." + } + Self::Spotlight => { + "Search metadata for this volume. Keep indexing for file \ + search, or choose folders in Spotlight's Search Privacy \ + settings. Turning indexing off reduces search coverage; \ + removing an index alone can cause it to be rebuilt. \ + PwrDisk does not change indexing." + } + } + } + + pub const fn documentation(self) -> &'static str { + match self { + Self::Fsevents => { + "https://developer.apple.com/library/archive/documentation/\ + Darwin/Conceptual/FSEvents_ProgGuide/UsingtheFSEventsFramework/\ + UsingtheFSEventsFramework.html" + } + Self::Spotlight => { + "https://support.apple.com/guide/mac-help/\ + prevent-spotlight-searches-in-files-mchlp2811/mac" + } + } + } +} + +pub fn is_service_name(name: &str) -> bool { + Service::ALL + .iter() + .any(|service| name.eq_ignore_ascii_case(service.name())) +} + +pub fn is_service_path(path: &Path) -> bool { + path.components() + .any(|part| is_service_name(&part.as_os_str().to_string_lossy())) +} + +/// Unknown contents never acquire a zero-byte measurement. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Usage { + Measured(u64), + /// Bytes successfully measured, with some contents still unknown. + Incomplete(u64), + Unavailable, + OutsideScan, +} + +/// Service-store location for whole startup-disk and external-volume scans. +/// A home scan has no service-store figures; it is not evidence of absence. +pub fn stores_volume(root: &Path) -> Option { + let data = Path::new(crate::space::MACOS_DATA_VOLUME); + if data.starts_with(root) || root == data { + return Some(data.to_path_buf()); + } + if let Ok(below) = root.strip_prefix("/Volumes") { + return below + .components() + .next() + .map(|name| Path::new("/Volumes").join(name.as_os_str())); + } + if root + .file_name() + .is_some_and(|name| is_service_name(&name.to_string_lossy())) + { + return root.parent().map(Path::to_path_buf); + } + None +} + +/// Look up an actual path in the scan; no I/O and no invented totals. +pub fn usage( + root_path: &Path, + tree: Node<'_>, + options: &ScanOptions, + path: &Path, +) -> Usage { + let Ok(below) = path.strip_prefix(root_path) else { + return Usage::OutsideScan; + }; + let mut node = tree; + for part in below.components() { + let Some(child) = node.child_named(&part.as_os_str().to_string_lossy()) + else { + // Missing from a walk can mean failed metadata, filtering, or + // no directory. It cannot establish a service's installation. + return Usage::Unavailable; + }; + node = child; + } + if !node.is_dir() { + return Usage::Unavailable; + } + if node.read_error || !options.include_hidden || options.max_depth.is_some() + { + return if node.bytes == 0 { + Usage::Unavailable + } else { + Usage::Incomplete(node.bytes) + }; + } + Usage::Measured(node.bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tree::{Draft, Tree}; + use crate::tree::{Metric, NodeKind, aggregate}; + + #[test] + fn unavailable_is_not_zero_and_descendant_failures_are_incomplete() { + let path = Path::new("/volume/.Spotlight-V100"); + let mut volume = Draft::directory("volume"); + let options = ScanOptions::default(); + assert_eq!( + usage( + Path::new("/volume"), + Tree::from(&volume).root(), + &options, + path + ), + Usage::Unavailable + ); + let mut store = Draft::directory(".Spotlight-V100"); + store.read_error = true; + volume.children.push(store); + let mut tree = Tree::from(&volume); + aggregate(&mut tree, Metric::Bytes); + assert_eq!( + usage(Path::new("/volume"), tree.root(), &options, path), + Usage::Unavailable + ); + let store = &mut volume.children[0]; + store + .children + .push(Draft::entry("index", NodeKind::File, 4096)); + let mut locked = Draft::directory("locked"); + locked.read_error = true; + store.read_error = false; + store.children.push(locked); + let mut tree = Tree::from(&volume); + aggregate(&mut tree, Metric::Bytes); + assert_eq!( + usage(Path::new("/volume"), tree.root(), &options, path), + Usage::Incomplete(4096) + ); + } + + #[test] + fn readable_empty_store_is_measured_but_filtered_contents_are_unknown() { + let tree = Tree::from(Draft::directory(".fseventsd")); + let path = Path::new("/volume/.fseventsd"); + let mut options = ScanOptions::default(); + assert_eq!( + usage(path, tree.root(), &options, path), + Usage::Measured(0) + ); + options.include_hidden = false; + assert_eq!( + usage(path, tree.root(), &options, path), + Usage::Unavailable + ); + options.include_hidden = true; + options.max_depth = Some(0); + assert_eq!( + usage(path, tree.root(), &options, path), + Usage::Unavailable + ); + assert_eq!( + usage(Path::new("/Users/me"), tree.root(), &options, path), + Usage::OutsideScan + ); + } + + #[test] + fn private_stores_belong_to_the_data_volume_and_external_volumes() { + assert_eq!( + stores_volume(Path::new("/")), + Some(PathBuf::from(crate::space::MACOS_DATA_VOLUME)) + ); + assert_eq!( + stores_volume(Path::new("/Volumes/Backup")), + Some(PathBuf::from("/Volumes/Backup")) + ); + assert_eq!(stores_volume(Path::new("/Users/me")), None); + } +} diff --git a/crates/disktree-core/src/mft.rs b/crates/disktree-core/src/mft.rs index 0a200440..f1f78adb 100644 --- a/crates/disktree-core/src/mft.rs +++ b/crates/disktree-core/src/mft.rs @@ -33,7 +33,7 @@ use windows_sys::Win32::Storage::FileSystem::{ }; use crate::scan::{ScanOptions, ScanProgress}; -use crate::tree::{Node, NodeKind}; +use crate::tree::{Builder, Built, Facts, NodeKind, Tree}; use crate::windows::{Aligned, drive_letter}; /// Most bytes read per call: large enough that the disk streams, small @@ -166,7 +166,7 @@ pub fn scan( canonical: &Path, options: &ScanOptions, progress: &ScanProgress, -) -> Option> { +) -> Option> { // A followed link can lead off this volume, or back into it a second // time, and the table describes neither: the walk follows them. if options.follow_links { @@ -212,7 +212,7 @@ pub fn scan( options, progress, }; - let tree = table.directory(ROOT, crate::scan::file_name(root), 0); + let tree = table.tree(&crate::scan::file_name(root)); // Hundreds of megabytes, whose freeing the caller would otherwise // wait out before it can finish the tree. let Table { @@ -1053,13 +1053,19 @@ impl Table<'_> { } } + /// The tree beneath the root directory, named `name`. + fn tree(&self, name: &str) -> Result { + Tree::try_build(|builder| self.directory(builder, ROOT, name, 0)) + } + /// Mirrors what the walk keeps: see `WalkContext::classify`. - fn directory( + fn directory<'h>( &self, + builder: &'h Builder, number: u32, - name: Box, + name: &str, depth: usize, - ) -> Result { + ) -> Result, Stop> { if depth >= MOST_LEVELS || self.progress.is_cancelled() { return Err(Stop); } @@ -1076,36 +1082,48 @@ impl Table<'_> { if Some(entry.parent_sequence) != sequence { return None; } - self.child(entry, depth, descend).transpose() + self.child(builder, entry, depth, descend).transpose() }; let entries = self.entries(number); // See `tree::PARALLEL_LEVELS`: parallel only near the top. - let children = if depth < crate::tree::PARALLEL_LEVELS { + let found: Vec> = if depth < crate::tree::PARALLEL_LEVELS + { entries .par_iter() .filter_map(child) .collect::>()? } else { // Sized up front: nearly every entry becomes a child, and a - // list grown by doubling copies its nodes over and over. - let mut children = Vec::with_capacity(entries.len()); + // list grown by doubling copies its entries over and over. + let mut found = Vec::with_capacity(entries.len()); for node in entries.iter().filter_map(child) { - children.push(node?); + found.push(node?); } - children + found }; - let mut node = Node::directory(name); - node.children = children; - Ok(node) + // A directory's files go into the tree under one lock, as the + // walk's do: every worker adds to the same buffers, and a lock per + // file would have them queue on it. + let mut children = + builder.leaves(found.iter().filter_map(|child| match child { + Child::Leaf(name, facts) => Some((*name, *facts, None)), + Child::Directory(_) => None, + })); + children.extend(found.into_iter().filter_map(|child| match child { + Child::Directory(built) => Some(built), + Child::Leaf(..) => None, + })); + Ok(builder.directory(name, Facts::directory(), None, children)) } /// The node for `entry`; `None` for one the walk would not list. - fn child( + fn child<'h>( &self, + builder: &'h Builder, entry: &Entry, depth: usize, descend: bool, - ) -> Result, Stop> { + ) -> Result>, Stop> { // The root is its own parent. if entry.child == entry.parent || entry.child < FIRST_USER_RECORD { return Ok(None); @@ -1130,8 +1148,8 @@ impl Table<'_> { return Ok(None); } return self - .directory(entry.child, name.into(), depth + 1) - .map(Some); + .directory(builder, entry.child, name, depth + 1) + .map(|built| Some(Child::Directory(built))); } let size = if self.options.apparent_size { info.apparent @@ -1143,16 +1161,23 @@ impl Table<'_> { } else { NodeKind::File }; - let mut node = Node::entry(name, kind, size); - node.modified = info.modified; + let mut facts = Facts::entry(kind, size); + facts.modified = info.modified; if info.names > 1 { - node.inode = NonZeroU64::new(u64::from(entry.child)) + facts.inode = NonZeroU64::new(u64::from(entry.child)) .map(|record| (0, record)); } - Ok(Some(node)) + Ok(Some(Child::Leaf(name, facts))) } } +/// What an entry becomes: a file, still to be added with its siblings, +/// or a directory already built. +enum Child<'t, 'h> { + Leaf(&'t str, Facts), + Directory(Built<'h>), +} + fn u16_at(bytes: &[u8], at: usize) -> Option { Some(u16::from_le_bytes(bytes.get(at..at + 2)?.try_into().ok()?)) } @@ -1569,9 +1594,13 @@ mod tests { } } - fn paths(node: &Node, prefix: &str, out: &mut Vec<(String, NodeKind)>) { - for child in &node.children { - let path = format!("{prefix}{}", child.name); + fn paths( + node: crate::tree::Node<'_>, + prefix: &str, + out: &mut Vec<(String, NodeKind)>, + ) { + for child in node.children() { + let path = format!("{prefix}{}", child.name()); out.push((path.clone(), child.kind)); paths(child, &format!("{path}/"), out); } @@ -1665,15 +1694,13 @@ mod tests { max_depth, ..ScanOptions::default() }; - let Ok(root) = table(&rows, &options, &progress).directory( - ROOT, - "C:\\".into(), - 0, - ) else { + let Ok(root) = table(&rows, &options, &progress).tree("C:\\") + else { panic!("the table is not cut short"); }; + let root = root.root(); let mut found = Vec::new(); - paths(&root, "", &mut found); + paths(root, "", &mut found); found.sort_by(|left, right| left.0.cmp(&right.0)); let kind = |path: &str| match path { "link" => NodeKind::Symlink, @@ -1709,7 +1736,7 @@ mod tests { let options = ScanOptions::default(); let progress = ScanProgress::default(); let table = table(&rows, &options, &progress); - assert!(table.directory(ROOT, "C:\\".into(), 0).is_err()); + assert!(table.tree("C:\\").is_err()); assert!(!progress.is_cancelled()); } } diff --git a/crates/disktree-core/src/path_style.rs b/crates/disktree-core/src/path_style.rs new file mode 100644 index 00000000..c831e8ff --- /dev/null +++ b/crates/disktree-core/src/path_style.rs @@ -0,0 +1,296 @@ +//! How paths on the scanned machine are joined, split and compared. +//! +//! A local scan follows this machine's rules, which is `std::path`. An SSH +//! host is always Unix: the remote command, the embedded scanners and the +//! delete script are POSIX shell and Linux tools. So remote paths follow +//! POSIX rules on every client. On a Windows client `std::path` would join +//! them with `\`, naming a different file on the host, and split a Unix name +//! such as `a\b` or `c:d` into parts the host never had. +//! +//! Remote paths only ever arrive as JSON strings, so the POSIX side works on +//! `str` and treats a path that is not UTF-8 as matching nothing. + +use std::borrow::Cow; +use std::ffi::OsStr; +use std::path::{Path, PathBuf}; + +/// The path rules of the machine a tree was scanned on. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum PathStyle { + /// This machine's own rules. + #[default] + Native, + /// `/`-separated, as on the Unix host an SSH session scans. + Posix, +} + +impl PathStyle { + /// The style for a local scan, or for a scan of an SSH host. + #[must_use] + pub const fn of(remote: bool) -> Self { + if remote { Self::Posix } else { Self::Native } + } + + /// The separator shown between names. + #[must_use] + pub const fn separator(self) -> char { + match self { + Self::Native => std::path::MAIN_SEPARATOR, + Self::Posix => '/', + } + } + + /// Whether two paths identify the same spelling in this namespace. + #[must_use] + pub fn same(self, left: &Path, right: &Path) -> bool { + match self { + Self::Native => left == right, + Self::Posix => left.as_os_str() == right.as_os_str(), + } + } + + /// Whether `path` names a directory from the machine's root. + #[must_use] + pub fn is_absolute(self, path: &Path) -> bool { + match self { + Self::Native => path.is_absolute(), + Self::Posix => path.to_str().is_some_and(|s| s.starts_with('/')), + } + } + + /// `base` with one more name below it. + #[must_use] + pub fn join(self, base: &Path, name: &str) -> PathBuf { + let mut path = base.to_path_buf(); + self.push(&mut path, name); + path + } + + /// Append one name to `path`. + pub fn push(self, path: &mut PathBuf, name: &str) { + match self { + Self::Native => path.push(name), + Self::Posix => { + let mut joined = path.to_string_lossy().into_owned(); + if !joined.is_empty() && !joined.ends_with('/') { + joined.push('/'); + } + joined.push_str(name); + *path = PathBuf::from(joined); + } + } + } + + /// The last name in `path`, or `None` for the root. + #[must_use] + pub fn file_name(self, path: &Path) -> Option<&OsStr> { + match self { + Self::Native => path.file_name(), + Self::Posix => { + let trimmed = path.to_str()?.trim_end_matches('/'); + let name = trimmed.rsplit('/').next()?; + (!name.is_empty() && name != "..").then(|| OsStr::new(name)) + } + } + } + + /// `path` without its last name, or `None` for the root. + #[must_use] + pub fn parent(self, path: &Path) -> Option<&Path> { + match self { + Self::Native => path.parent(), + Self::Posix => { + let trimmed = path.to_str()?.trim_end_matches('/'); + if trimmed.is_empty() { + return None; + } + Some(Path::new(match trimmed.rfind('/') { + None => "", + Some(at) => match trimmed[..at].trim_end_matches('/') { + "" => "/", + head => head, + }, + })) + } + } + } + + /// `path`, its parent, its parent's parent, and so on to the root. + pub fn ancestors(self, path: &Path) -> impl Iterator { + std::iter::successors(Some(path), move |path| self.parent(path)) + } + + /// The names from `base` down to `path`, or `None` when `path` is not + /// `base` or below it. Names are compared whole, so a name containing a + /// separator of some other platform cannot be mistaken for two. + #[must_use] + pub fn relative<'a>( + self, + base: &Path, + path: &'a Path, + ) -> Option>> { + match self { + Self::Native => { + let rest = path.strip_prefix(base).ok()?; + Some( + rest.components() + .map(|part| part.as_os_str().to_string_lossy()) + .collect(), + ) + } + Self::Posix => posix_relative(base.to_str()?, path.to_str()?) + .map(|names| names.map(Cow::Borrowed).collect()), + } + } + + /// Every name in `path` below its root, in order. + #[must_use] + pub fn names(self, path: &Path) -> Vec> { + match self { + Self::Native => path + .components() + .filter(|part| matches!(part, std::path::Component::Normal(_))) + .map(|part| part.as_os_str().to_string_lossy()) + .collect(), + Self::Posix => path.to_str().map_or_else(Vec::new, |path| { + path.split('/') + .filter(|name| !name.is_empty() && *name != ".") + .map(Cow::Borrowed) + .collect() + }), + } + } + + /// Whether `path` is strictly below `base`. + #[must_use] + pub fn is_below(self, path: &Path, base: &Path) -> bool { + match self { + Self::Native => path != base && path.starts_with(base), + Self::Posix => match (base.to_str(), path.to_str()) { + (Some(base), Some(path)) => posix_relative(base, path) + .is_some_and(|mut names| names.next().is_some()), + _ => false, + }, + } + } +} + +fn posix_relative<'a>( + base: &str, + path: &'a str, +) -> Option> { + let rest = path.strip_prefix(base.trim_end_matches('/'))?; + // `/srv` must not claim `/srvx`; an empty base is a relative start. + if !base.is_empty() && !rest.is_empty() && !rest.starts_with('/') { + return None; + } + Some( + rest.split('/') + .filter(|name| !name.is_empty() && *name != "."), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn names(style: PathStyle, base: &str, path: &str) -> Option> { + style + .relative(Path::new(base), Path::new(path)) + .map(|names| names.into_iter().map(Cow::into_owned).collect()) + } + + /// The host's paths are joined with `/` whatever this machine uses. + #[test] + fn posix_paths_join_with_a_slash_on_every_client() { + let posix = PathStyle::Posix; + let joined = posix.join(Path::new("/home/x"), "child"); + assert_eq!(joined.to_str(), Some("/home/x/child")); + let joined = posix.join(Path::new("/"), "srv"); + assert_eq!(joined.to_str(), Some("/srv")); + let joined = posix.join(&joined, r"back\slash"); + assert_eq!(joined.to_str(), Some(r"/srv/back\slash")); + assert_eq!(posix.join(Path::new(""), "a").to_str(), Some("a")); + } + + /// Names a Windows client would split on stay whole on a Unix host. + #[test] + fn posix_names_keep_backslashes_and_colons() { + let posix = PathStyle::Posix; + let path = Path::new(r"/srv/a\b/c:d"); + assert_eq!(posix.file_name(path), Some(OsStr::new("c:d"))); + assert_eq!(posix.parent(path), Some(Path::new(r"/srv/a\b"))); + assert_eq!( + names(posix, "/srv", r"/srv/a\b/c:d"), + Some(vec![r"a\b".into(), "c:d".into()]) + ); + assert!(posix.is_below(path, Path::new(r"/srv/a\b"))); + assert_eq!(posix.names(path), ["srv", r"a\b", "c:d"]); + assert!(!posix.is_below(path, Path::new("/srv/a"))); + } + + #[test] + fn posix_parents_end_at_the_root() { + let posix = PathStyle::Posix; + let chain: Vec<_> = posix + .ancestors(Path::new("/home/x/")) + .map(|path| path.to_str().unwrap()) + .collect(); + assert_eq!(chain, ["/home/x/", "/home", "/"]); + assert_eq!(posix.parent(Path::new("/")), None); + assert_eq!(posix.file_name(Path::new("/")), None); + assert_eq!(posix.parent(Path::new("name")), Some(Path::new(""))); + } + + #[test] + fn posix_relative_names_respect_name_boundaries() { + let posix = PathStyle::Posix; + assert_eq!(names(posix, "/srv", "/srv"), Some(vec![])); + assert_eq!( + names(posix, "/", "/srv/x"), + Some(vec!["srv".into(), "x".into()]) + ); + assert_eq!(names(posix, "/srv/", "/srv/x"), Some(vec!["x".into()])); + assert_eq!(names(posix, "/srv", "/srvx"), None); + assert_eq!(names(posix, "/srv", "/var"), None); + assert!(!posix.is_below(Path::new("/srv"), Path::new("/srv"))); + assert!(posix.is_below(Path::new("/srv"), Path::new("/"))); + } + + /// Only `/`-rooted paths are absolute on a Unix host; `C:\x` and `\x` + /// name nothing there. + #[test] + fn posix_absolute_means_slash_rooted() { + let posix = PathStyle::Posix; + assert!(posix.is_absolute(Path::new("/"))); + assert!(posix.is_absolute(Path::new("/home/someone"))); + assert!(!posix.is_absolute(Path::new("home/someone"))); + assert!(!posix.is_absolute(Path::new(""))); + assert!(!posix.is_absolute(Path::new(r"\home\someone"))); + assert!(!posix.is_absolute(Path::new(r"C:\Users"))); + assert_eq!(posix.separator(), '/'); + } + + #[test] + fn posix_equality_keeps_foreign_separators_literal() { + let literal = Path::new(r"/srv/a\b"); + let nested = Path::new("/srv/a/b"); + assert!(!PathStyle::Posix.same(literal, nested)); + assert!(PathStyle::Posix.same(literal, literal)); + assert_eq!(PathStyle::Native.same(literal, nested), literal == nested); + } + + /// Native is `std::path`, so local scans behave exactly as before. + #[test] + fn native_follows_this_machine() { + let native = PathStyle::Native; + let base = std::env::temp_dir(); + let joined = native.join(&base, "child"); + assert_eq!(joined, base.join("child")); + assert_eq!(native.parent(&joined), Some(base.as_path())); + assert_eq!(native.file_name(&joined), Some(OsStr::new("child"))); + assert!(native.is_below(&joined, &base)); + assert!(!native.is_below(&base, &base)); + assert_eq!(native.separator(), std::path::MAIN_SEPARATOR); + } +} diff --git a/crates/disktree-core/src/payload.rs b/crates/disktree-core/src/payload.rs index 403b77c3..6e2641dc 100644 --- a/crates/disktree-core/src/payload.rs +++ b/crates/disktree-core/src/payload.rs @@ -118,7 +118,7 @@ impl Archive { .find(|entry| entry.arch == arch) .ok_or_else(|| { io::Error::other(format!( - "this disktree build has no embedded Linux {arch} scanner" + "this PwrDisk build has no embedded Linux {arch} scanner" )) })? .clone(); diff --git a/crates/disktree-core/src/planning.rs b/crates/disktree-core/src/planning.rs new file mode 100644 index 00000000..4282738a --- /dev/null +++ b/crates/disktree-core/src/planning.rs @@ -0,0 +1,932 @@ +//! Read-only hypothetical path sets over one completed scan. No cart or intent. + +use std::path::{Path, PathBuf}; + +use rustc_hash::{FxHashMap, FxHashSet}; +use serde::{Deserialize, Serialize}; + +use crate::removal::{self, Target}; +use crate::scan::ScanOptions; +use crate::sharing::{self, Estimate}; +use crate::space::{self, Attribution}; +use crate::tree::{Node, Tree}; + +/// Bound request work and response size independently of the file count. +pub const MAX_PATHS: usize = 200; +pub const MAX_PEERS: usize = 20; +/// Peer discovery is optional and may be incomplete on very large clone trees. +const PEER_VISITS: usize = 2_000_000; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Context { + pub root: PathBuf, + pub scanned_at: i64, + pub apparent_size: bool, + pub clone_metadata: bool, + pub include_hidden: bool, + pub max_depth: Option, + pub one_filesystem: bool, + pub unreadable: u64, +} + +impl Context { + pub fn of( + root: &Path, + options: &ScanOptions, + scanned_at: i64, + unreadable: u64, + ) -> Self { + Self { + root: root.to_path_buf(), + scanned_at, + apparent_size: options.apparent_size, + clone_metadata: cfg!(target_os = "macos") + && options.apfs_clone_metadata + && !options.apparent_size, + include_hidden: options.include_hidden, + max_depth: options.max_depth, + one_filesystem: options.one_filesystem, + unreadable, + } + } + + const fn physical(&self) -> bool { + !self.apparent_size && self.clone_metadata + } + + const fn limited(&self) -> bool { + self.unreadable > 0 || self.max_depth.is_some() || !self.include_hidden + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Refused { + pub path: PathBuf, + pub reason: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Bounds { + pub lower: u64, + pub upper: u64, + pub partial: bool, +} + +impl From for Bounds { + fn from(value: Estimate) -> Self { + Self { + lower: value.lower, + upper: value.upper, + partial: value.partial, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct VolumeAllocation { + pub scanned_volume: u64, + pub other_volumes: u64, + pub unknown_volume: u64, + /// Target-root attribution; nested volumes are not split by directory totals. + pub scanned_volume_reclaim_lower: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Peer { + pub path: PathBuf, + pub listed_bytes: u64, + pub alone: Bounds, + pub with_selection: Bounds, + /// Interval subtraction, not the difference between two lower bounds. + pub additional: Bounds, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Peers { + /// Direct child directories of this scope are the candidate units. + pub scope: PathBuf, + pub candidates: Vec, + pub candidates_found: usize, + pub truncated: bool, + pub nodes_visited: usize, + pub node_budget: usize, + pub selected_groups: usize, + pub known_unselected_clone_files: u64, + /// Only present after examining all relevant metadata in the scan. + /// These are unresolved reference counts, not discovered owner paths. + pub references_not_seen_in_scan: Option, + pub with_all_returned_peers: Option, + pub additional_with_all_returned_peers: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Report { + pub context: Context, + pub accepted: Vec, + pub covered: Vec, + pub refused: Vec, + /// Apparent lengths when `context.apparent_size`; allocation otherwise. + pub listed_bytes: u64, + pub private_allocation: Option, + /// Listed clone allocation not known private, including repeated copies + /// inside this very selection. It is not uniquely owned physical space. + pub shared_allocation: Option, + pub internal_duplicate_allocation: Option, + pub reclaim: Option, + pub volume: VolumeAllocation, + pub peers: Option, + pub metadata_complete: bool, + pub scan_complete: bool, + pub limitations: Vec, +} + +/// A bounded path-list estimate. +/// +/// Every accepted subtree comes from `tree`; +/// filesystem reads only apply the existing removal guards and attribution. +/// This creates no removal preview and does not authorize removal. +pub fn estimate( + tree: &Tree, + context: Context, + paths: &[PathBuf], + peer_scope: Option<&Path>, + peer_limit: usize, +) -> Result { + if paths.is_empty() || paths.len() > MAX_PATHS { + return Err(format!("Supply 1 to {MAX_PATHS} paths.")); + } + let mut refused = Vec::new(); + let mut targets = Vec::new(); + for path in paths { + let path = removal::normalize(path); + if let Some(node) = resolve(tree, &context.root, &path) { + targets.push(Target { + path, + bytes: node.bytes, + is_dir: node.is_dir(), + hidden: false, + }); + } else { + refused.push(Refused { + path, + reason: "Not in this scanned tree (outside root, skipped, new or unreadable).".into(), + }); + } + } + let mut plan = removal::plan(&targets, &context.root); + refused.extend(plan.blocked.iter().map(|blocked| Refused { + path: blocked.path.clone(), + reason: blocked.reason.clone(), + })); + let nodes: Vec<_> = plan + .targets + .iter() + .filter_map(|target| resolve(tree, &context.root, &target.path)) + .collect(); + let accounting = sharing::Selected::new(nodes.iter().copied()); + plan.estimate_selection(|targets| { + let mut value = if targets.len() == nodes.len() { + accounting.estimate() + } else { + sharing::estimate(targets.iter().filter_map(|target| { + resolve(tree, &context.root, &target.path) + })) + }; + value.partial |= context.limited(); + value + }); + let measured = Estimate { + lower: plan.reclaimable_bytes(), + upper: plan.possible_bytes(), + partial: plan.estimate_partial(), + }; + let shared = nodes + .iter() + .map(|node| node.sharing().shared_bytes().min(node.bytes)) + .sum::(); + // Cross-target duplicates need one union summary, not a sum of directory + // summaries. The discovery pass below accounts for clone identities once. + let duplicates = physical_duplicates(&nodes, context.physical()); + let physical = context.physical(); + let unsplit_volumes = space::mount_boundaries_for(&context.root) + .is_some_and(|mounts| { + plan.targets.iter().all(|target| { + !target.is_dir + || !mounts + .iter() + .any(|mount| mount.starts_with(&target.path)) + }) + }); + let mut volume = VolumeAllocation { + scanned_volume: 0, + other_volumes: 0, + unknown_volume: 0, + scanned_volume_reclaim_lower: (physical + && context.one_filesystem + && unsplit_volumes) + .then_some(plan.reclaim()), + }; + for (target, attribution) in plan.attributed_targets() { + match attribution { + Attribution::Scanned => volume.scanned_volume += target.bytes, + Attribution::Other => volume.other_volumes += target.bytes, + Attribution::Unknown => volume.unknown_volume += target.bytes, + } + } + let mut limitations = vec![ + "Scan-derived bounds before snapshots, open files, compression and later changes; actual freed space is not exactly predictable. Trash usually frees space only after it is emptied.".into(), + "Volume attribution uses each accepted path root; directory totals can span nested volumes, so no scanned-volume reclaim is projected with cross-filesystem scans, nested mounts or unknown mount boundaries. Shared allocation includes internal duplicate listings and unknown private allocation; it is not unique physical usage or allocation necessarily retained outside the selection.".into(), + ]; + if !physical { + limitations.push("Physical bounds and private/shared allocation are unavailable: apparent sizes or APFS clone metadata disabled/unsupported. Use an allocated-size scan with clone collection on macOS.".into()); + } + if measured.partial || duplicates.is_none() || context.limited() { + limitations.push("Incomplete scan or allocation metadata: bounds cover observed entries only; omitted entries and unknown sharing can change the result.".into()); + } + let peers = if peer_limit == 0 || !physical { + None + } else { + let scope = peer_scope.map_or_else( + || default_scope(&context.root, &plan.targets), + removal::normalize, + ); + let scope_node = resolve(tree, &context.root, &scope) + .filter(|node| node.is_dir()) + .ok_or_else(|| { + "Peer scope must be a directory in this scan.".to_string() + })?; + Some(peers( + tree, + &context, + &nodes, + &accounting, + &plan.targets, + &scope, + scope_node, + peer_limit.min(MAX_PEERS), + )) + }; + Ok(Report { + listed_bytes: plan.bytes(), + private_allocation: physical + .then_some(plan.bytes().saturating_sub(shared)), + shared_allocation: physical.then_some(shared), + internal_duplicate_allocation: physical.then_some(duplicates).flatten(), + reclaim: physical.then_some(measured.into()), + volume, + metadata_complete: physical + && !measured.partial + && duplicates.is_some(), + scan_complete: !context.limited(), + context, + accepted: plan + .targets + .iter() + .map(|target| target.path.clone()) + .collect(), + covered: plan + .covered + .iter() + .map(|target| target.path.clone()) + .collect(), + refused, + peers, + limitations, + }) +} + +fn resolve<'a>(tree: &'a Tree, root: &Path, path: &Path) -> Option> { + tree.root() + .descend(path.strip_prefix(root).ok()?) + .map(|(_, node)| node) +} + +fn default_scope(root: &Path, targets: &[Target]) -> PathBuf { + let mut scope = targets + .first() + .and_then(|target| target.path.parent()) + .unwrap_or(root); + for target in targets { + while !target.path.starts_with(scope) { + scope = scope.parent().unwrap_or(root); + } + } + scope.to_path_buf() +} + +type Key = (u64, u64); + +/// An iterative walk, pruning ordinary subtrees and never allocating paths +/// per file. The budget also bounds the iterator stack on a very deep tree. +fn visit<'a>( + node: Node<'a>, + remaining: &mut usize, + mut leaf: impl FnMut(Node<'a>), +) -> bool { + if node + .allocation() + .is_some_and(|allocation| allocation.followed) + { + return true; + } + let mut stack = vec![node.children().iter()]; + if !node.is_dir() { + if *remaining == 0 { + return false; + } + *remaining -= 1; + leaf(node); + return true; + } + while let Some(children) = stack.last_mut() { + let Some(child) = children.next() else { + stack.pop(); + continue; + }; + if *remaining == 0 { + return false; + } + *remaining -= 1; + if child.allocation().is_some_and(|info| info.followed) { + continue; + } + if child.is_dir() { + if child.stored_sharing().is_some() { + stack.push(child.children().iter()); + } + } else { + leaf(child); + } + } + true +} + +fn physical_duplicates(nodes: &[Node<'_>], physical: bool) -> Option { + if !physical { + return None; + } + let mut summary = sharing::DuplicateSummary::default(); + let mut remaining = PEER_VISITS; + for node in nodes { + if !visit(*node, &mut remaining, |leaf| summary.add(leaf)) { + return None; + } + } + summary.bytes() +} + +#[derive(Default)] +struct Group { + references: u32, + seen: u64, + selected: u64, +} + +#[allow( + clippy::too_many_arguments, + reason = "All inputs are borrowed from one scan and selection." +)] +fn peers<'a>( + tree: &'a Tree, + context: &Context, + selected: &[Node<'a>], + accounting: &sharing::Selected, + targets: &[Target], + scope: &Path, + scope_node: Node<'a>, + limit: usize, +) -> Peers { + let mut groups: FxHashMap = FxHashMap::default(); + let mut remaining = PEER_VISITS; + let mut complete = true; + let mut selected_links = FxHashSet::default(); + for node in selected { + complete &= visit(*node, &mut remaining, |leaf| { + let Some(allocation) = leaf.allocation() else { + return; + }; + let Some(info) = allocation.clone else { + return; + }; + if info.device == 0 || info.id == 0 || info.references < 2 { + return; + } + if allocation.links > 1 + && allocation + .identity + .is_some_and(|id| !selected_links.insert(id)) + { + return; + } + let group = groups.entry((info.device, info.id)).or_default(); + group.references = group.references.max(info.references); + group.selected += 1; + }); + } + let mut base = accounting.estimate(); + base.partial |= context.limited(); + if groups.is_empty() { + return Peers { + scope: scope.to_path_buf(), + candidates: Vec::new(), + candidates_found: 0, + truncated: !complete, + nodes_visited: PEER_VISITS - remaining, + node_budget: PEER_VISITS, + selected_groups: 0, + known_unselected_clone_files: 0, + references_not_seen_in_scan: (complete + && !context.limited() + && !base.partial) + .then_some(0), + with_all_returned_peers: Some(base.into()), + additional_with_all_returned_peers: Some(delta(base, base)), + }; + } + let mut seen_links = FxHashSet::default(); + complete &= visit(tree.root(), &mut remaining, |leaf| { + let Some(allocation) = leaf.allocation() else { + return; + }; + let Some(info) = allocation.clone else { + return; + }; + let Some(group) = groups.get_mut(&(info.device, info.id)) else { + return; + }; + if allocation.links > 1 + && allocation.identity.is_some_and(|id| !seen_links.insert(id)) + { + return; + } + group.references = group.references.max(info.references); + group.seen += 1; + }); + // Candidate units are direct children of scope. Resolve exclusions once, + // rather than compare every directory against every selected path. + let scope_selected = + targets.iter().any(|target| scope.starts_with(&target.path)); + let excluded: FxHashSet<_> = targets + .iter() + .filter_map(|target| { + target + .path + .strip_prefix(scope) + .ok()? + .components() + .next() + .map(|component| component.as_os_str().to_os_string()) + }) + .collect(); + let mut candidates = Vec::new(); + let mut candidates_found = 0; + for child in scope_node.children() { + if remaining == 0 { + complete = false; + break; + } + remaining -= 1; + if !child.is_dir() || child.stored_sharing().is_none() { + continue; + } + if scope_selected + || excluded.contains(std::ffi::OsStr::new(child.name())) + { + continue; + } + let mut related = false; + complete &= visit(child, &mut remaining, |leaf| { + related |= + leaf.allocation().and_then(|a| a.clone).is_some_and(|info| { + groups.contains_key(&(info.device, info.id)) + }); + }); + if related { + candidates_found += 1; + if candidates.len() < limit { + candidates.push((scope.join(child.name()), child)); + } + } + } + // Only the bounded returned directories are checked by the removal guards. + let candidate_targets: Vec<_> = candidates + .iter() + .map(|(path, node)| Target { + path: path.clone(), + bytes: node.bytes, + is_dir: true, + hidden: false, + }) + .collect(); + let allowed = removal::plan(&candidate_targets, &context.root); + candidates + .retain(|(path, _)| allowed.targets.iter().any(|t| t.path == *path)); + let nodes: Vec<_> = candidates.iter().map(|(_, node)| *node).collect(); + let (answers, mut combined) = accounting.additions(&nodes); + combined.partial |= context.limited(); + let candidates = candidates + .into_iter() + .zip(answers) + .map(|((path, node), (mut alone, mut union))| { + alone.partial |= context.limited(); + union.partial |= context.limited(); + Peer { + path, + listed_bytes: node.bytes, + alone: alone.into(), + with_selection: union.into(), + additional: delta(base, union), + } + }) + .collect::>(); + let truncated = !complete || candidates_found > candidates.len(); + Peers { + scope: scope.to_path_buf(), + candidates, + candidates_found, + truncated, + nodes_visited: PEER_VISITS - remaining, + node_budget: PEER_VISITS, + selected_groups: groups.len(), + known_unselected_clone_files: groups + .values() + .map(|g| g.seen.saturating_sub(g.selected)) + .sum(), + references_not_seen_in_scan: (complete + && !context.limited() + && !base.partial + && groups.values().all(|g| g.seen <= u64::from(g.references))) + .then(|| { + groups + .values() + .map(|g| u64::from(g.references).saturating_sub(g.seen)) + .sum() + }), + with_all_returned_peers: Some(combined.into()), + additional_with_all_returned_peers: Some(delta(base, combined)), + } +} + +const fn delta(base: Estimate, union: Estimate) -> Bounds { + Bounds { + lower: union.lower.saturating_sub(base.upper), + upper: union.upper.saturating_sub(base.lower), + partial: base.partial || union.partial, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sharing::{Allocation, CloneInfo}; + use crate::tree::{Draft, Metric, NodeKind, Seen, aggregate_deduped}; + + const GB: u64 = 1_000_000_000; + const SIZE: u64 = 12 * GB; + + fn clone_file(inode: u64, refs: u32, private: Option) -> Draft { + let mut file = Draft::entry("data", NodeKind::File, SIZE); + file.inode = + Some((1, std::num::NonZeroU64::new(inode).expect("inode"))); + file.allocation = Some(Box::new(Allocation { + bytes: SIZE, + identity: Some((1, inode)), + links: 1, + followed: false, + clone: Some(CloneInfo { + device: 1, + id: 42, + references: refs, + private_bytes: private, + data_bytes: SIZE, + }), + })); + file + } + + fn fixture( + refs: u32, + private: Option, + ) -> (tempfile::TempDir, Tree, Context) { + let temp = tempfile::tempdir().expect("fixture"); + let mut root = Draft::directory("root"); + for index in 1..=4 { + let name = format!("worktree-{index}"); + std::fs::create_dir(temp.path().join(&name)).expect("directory"); + let mut dir = Draft::directory(name); + dir.children.push(clone_file(index, refs, private)); + root.children.push(dir); + } + let mut tree = Tree::from(root); + aggregate_deduped(&mut tree, Metric::Bytes, &Seen::new()); + let context = Context { + clone_metadata: true, + ..Context::of(temp.path(), &ScanOptions::default(), 123, 0) + }; + (temp, tree, context) + } + + fn selected(root: &Path, count: u64) -> Vec { + (1..=count) + .map(|i| root.join(format!("worktree-{i}"))) + .collect() + } + + #[test] + fn three_of_four_12_gb_worktrees_find_the_last_holder_and_unlock_once() { + let (temp, tree, context) = fixture(4, Some(0)); + let report = estimate( + &tree, + context.clone(), + &selected(temp.path(), 3), + None, + 10, + ) + .expect("estimate"); + assert_eq!(report.listed_bytes, 36 * GB); + assert_eq!(report.private_allocation, Some(0)); + assert_eq!(report.shared_allocation, Some(36 * GB)); + assert_eq!(report.internal_duplicate_allocation, Some(24 * GB)); + assert_eq!( + report.reclaim.as_ref().map(|b| (b.lower, b.upper)), + Some((0, 0)) + ); + let peers = report.peers.expect("peers"); + assert_eq!(peers.known_unselected_clone_files, 1); + assert_eq!(peers.references_not_seen_in_scan, Some(0)); + assert_eq!(peers.candidates.len(), 1); + let peer = &peers.candidates[0]; + assert_eq!(peer.path, temp.path().join("worktree-4")); + assert_eq!( + (peer.additional.lower, peer.additional.upper), + (SIZE, SIZE) + ); + assert_eq!(peer.with_selection.lower, SIZE); + let report = + estimate(&tree, context, &selected(temp.path(), 4), None, 10) + .expect("all four"); + assert_eq!(report.listed_bytes, 48 * GB); + assert_eq!(report.internal_duplicate_allocation, Some(36 * GB)); + assert_eq!( + report.reclaim.as_ref().map(|b| (b.lower, b.upper)), + Some((SIZE, SIZE)) + ); + assert!(report.peers.expect("peers").candidates.is_empty()); + } + + #[test] + fn internal_duplicates_overlap_and_refusals_do_not_inflate_union() { + let (temp, tree, context) = fixture(4, Some(0)); + let mut paths = selected(temp.path(), 4); + paths.extend([ + paths[0].clone(), + paths[0].join("data"), + temp.path().to_path_buf(), + temp.path().join("missing"), + temp.path().parent().expect("parent").join("outside"), + ]); + let report = + estimate(&tree, context, &paths, None, 0).expect("estimate"); + assert_eq!(report.accepted.len(), 4); + assert_eq!(report.covered.len(), 2); + assert_eq!(report.refused.len(), 3); + assert_eq!(report.reclaim.expect("bounds").lower, SIZE); + assert_eq!(report.internal_duplicate_allocation, Some(36 * GB)); + } + + #[test] + fn external_references_have_no_invented_owner_paths() { + let (temp, tree, context) = fixture(5, Some(0)); + let report = estimate( + &tree, + context.clone(), + &selected(temp.path(), 3), + None, + 10, + ) + .expect("estimate"); + let peers = report.peers.expect("peers"); + assert_eq!(peers.references_not_seen_in_scan, Some(1)); + assert_eq!(peers.known_unselected_clone_files, 1); + assert_eq!(peers.candidates[0].with_selection.upper, 0); + let limited = Context { + include_hidden: false, + ..context + }; + let report = + estimate(&tree, limited, &selected(temp.path(), 3), None, 10) + .expect("limited"); + assert_eq!( + report.peers.expect("peers").references_not_seen_in_scan, + None + ); + assert!(!report.scan_complete); + } + + #[test] + fn modified_clones_keep_uncertain_bounds_and_interval_deltas() { + let (temp, tree, context) = fixture(4, Some(GB)); + let report = + estimate(&tree, context, &selected(temp.path(), 3), None, 10) + .expect("estimate"); + assert_eq!(report.private_allocation, Some(3 * GB)); + assert_eq!(report.shared_allocation, Some(33 * GB)); + assert_eq!( + report.reclaim.map(|b| (b.lower, b.upper)), + Some((3 * GB, 36 * GB)) + ); + let peers = report.peers.expect("peers"); + assert_eq!(peers.candidates[0].with_selection.lower, 15 * GB); + assert_eq!(peers.candidates[0].with_selection.upper, 48 * GB); + assert_eq!(peers.candidates[0].additional.lower, 0); + assert_eq!(peers.candidates[0].additional.upper, 45 * GB); + } + + #[test] + fn missing_metadata_and_unavailable_collection_are_not_exact_measurements() + { + let (temp, tree, context) = fixture(4, None); + let report = estimate( + &tree, + context.clone(), + &selected(temp.path(), 4), + None, + 10, + ) + .expect("missing private"); + assert!(report.reclaim.expect("wide bounds").partial); + assert!(!report.metadata_complete); + assert_eq!( + report.peers.expect("peers").references_not_seen_in_scan, + None + ); + for context in [ + Context { + clone_metadata: false, + ..context.clone() + }, + Context { + apparent_size: true, + ..context + }, + ] { + let report = + estimate(&tree, context, &selected(temp.path(), 4), None, 10) + .expect("unavailable"); + assert!(report.reclaim.is_none()); + assert!(report.private_allocation.is_none()); + assert!(report.shared_allocation.is_none()); + assert!(report.peers.is_none()); + } + } + + #[test] + fn hardlink_aliases_are_not_extra_clone_members_or_reclaim() { + let (temp, _, context) = fixture(2, Some(0)); + let mut root = Draft::directory("root"); + for (index, inode, links) in [(1, 1, 2), (2, 1, 2), (3, 2, 1)] { + let mut dir = Draft::directory(format!("worktree-{index}")); + let mut file = clone_file(inode, 2, Some(0)); + file.allocation.as_mut().expect("allocation").links = links; + dir.children.push(file); + root.children.push(dir); + } + let mut tree = Tree::from(root); + aggregate_deduped(&mut tree, Metric::Bytes, &Seen::new()); + let report = + estimate(&tree, context, &selected(temp.path(), 2), None, 10) + .expect("aliases"); + assert_eq!(report.listed_bytes, SIZE); + assert_eq!(report.internal_duplicate_allocation, Some(0)); + let peers = report.peers.expect("peers"); + assert_eq!(peers.known_unselected_clone_files, 1); + assert_eq!(peers.references_not_seen_in_scan, Some(0)); + assert_eq!(peers.candidates[0].with_selection.lower, SIZE); + } + + #[test] + fn clone_ids_on_separate_volumes_do_not_complete_each_other() { + let (temp, _, mut context) = fixture(2, Some(0)); + let mut root = Draft::directory("root"); + for device in [1, 2] { + let mut dir = Draft::directory(format!("worktree-{device}")); + let mut file = clone_file(device, 2, Some(0)); + file.allocation + .as_mut() + .expect("allocation") + .clone + .as_mut() + .expect("clone") + .device = device; + dir.children.push(file); + root.children.push(dir); + } + let mut tree = Tree::from(root); + aggregate_deduped(&mut tree, Metric::Bytes, &Seen::new()); + context.one_filesystem = false; + let report = + estimate(&tree, context, &selected(temp.path(), 2), None, 10) + .expect("volumes"); + assert_eq!(report.reclaim.expect("bounds").upper, 0); + assert_eq!(report.internal_duplicate_allocation, Some(0)); + assert!(report.volume.scanned_volume_reclaim_lower.is_none()); + assert_eq!( + report.peers.expect("peers").references_not_seen_in_scan, + Some(2) + ); + } + + #[test] + fn bounded_peers_evaluate_the_returned_union_instead_of_summing_rows() { + let (temp, tree, context) = fixture(4, Some(0)); + let report = estimate( + &tree, + context.clone(), + &selected(temp.path(), 1), + None, + 2, + ) + .expect("bounded"); + let peers = report.peers.expect("peers"); + assert_eq!(peers.candidates.len(), 2); + assert_eq!(peers.candidates_found, 3); + assert!(peers.truncated); + assert_eq!(peers.with_all_returned_peers.expect("union").upper, 0); + let report = + estimate(&tree, context, &selected(temp.path(), 1), None, 3) + .expect("all peers"); + let peers = report.peers.expect("peers"); + assert!(peers.candidates.iter().all(|p| p.additional.upper == 0)); + assert_eq!( + peers + .additional_with_all_returned_peers + .expect("union") + .lower, + SIZE + ); + } + + #[test] + fn peer_scope_can_find_a_known_holder_outside_the_default_parent() { + let temp = tempfile::tempdir().expect("fixture"); + let mut root = Draft::directory("root"); + let mut near = Draft::directory("near"); + for inode in 1..=3 { + let name = format!("worktree-{inode}"); + std::fs::create_dir_all(temp.path().join("near").join(&name)) + .expect("near"); + let mut dir = Draft::directory(name); + dir.children.push(clone_file(inode, 4, Some(0))); + near.children.push(dir); + } + let mut distant = Draft::directory("distant"); + std::fs::create_dir(temp.path().join("distant")).expect("distant"); + distant.children.push(clone_file(4, 4, Some(0))); + root.children.extend([near, distant]); + let mut tree = Tree::from(root); + aggregate_deduped(&mut tree, Metric::Bytes, &Seen::new()); + let context = Context { + clone_metadata: true, + ..Context::of(temp.path(), &ScanOptions::default(), 1, 0) + }; + let paths = selected(&temp.path().join("near"), 3); + let report = estimate(&tree, context.clone(), &paths, None, 10) + .expect("default scope"); + let peers = report.peers.expect("peers"); + assert!(peers.candidates.is_empty()); + assert_eq!(peers.known_unselected_clone_files, 1); + assert_eq!(peers.references_not_seen_in_scan, Some(0)); + let report = estimate(&tree, context, &paths, Some(temp.path()), 10) + .expect("wider scope"); + let peers = report.peers.expect("peers"); + assert_eq!(peers.candidates[0].path, temp.path().join("distant")); + assert_eq!(peers.candidates[0].additional.lower, SIZE); + } + + #[test] + fn peer_walk_is_bounded_and_prunes_large_ordinary_subtrees() { + let mut root = Draft::directory("root"); + let mut ordinary = Draft::directory("ordinary"); + for index in 0..100_000 { + ordinary.children.push(Draft::entry( + index.to_string(), + NodeKind::File, + 1, + )); + } + root.children.push(ordinary); + let mut tree = Tree::from(root); + aggregate_deduped(&mut tree, Metric::Bytes, &Seen::new()); + let mut remaining = 100; + assert!(visit(tree.root(), &mut remaining, |_| panic!( + "ordinary subtree pruned" + ))); + assert_eq!(remaining, 99); + let mut remaining = 3; + let ordinary = tree.root().children().iter().next().expect("ordinary"); + let mut leaves = 0; + assert!(!visit(ordinary, &mut remaining, |_| leaves += 1)); + assert_eq!(leaves, 3); + assert_eq!(remaining, 0); + } +} diff --git a/crates/disktree-core/src/query.rs b/crates/disktree-core/src/query.rs new file mode 100644 index 00000000..622932e2 --- /dev/null +++ b/crates/disktree-core/src/query.rs @@ -0,0 +1,246 @@ +//! Questions an agent asks of a scanned tree: what is in a directory, and +//! the largest things matching a description. +//! +//! The window answers these over its link and `pwrdisk mcp` answers them +//! over its own scans, so the logic lives here, once. + +use std::path::{Path, PathBuf}; + +use crate::classify::Category; +use crate::tree::{Node, NodeKind}; + +/// What kind of entry a [`Filter`] matches. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Kind { + /// Files and directories; a matching directory hides its contents. + #[default] + Any, + File, + Dir, +} + +impl Kind { + pub const fn name(self) -> &'static str { + match self { + Self::Any => "any", + Self::File => "file", + Self::Dir => "dir", + } + } + + pub fn named(name: &str) -> Option { + match name { + "any" => Some(Self::Any), + "file" => Some(Self::File), + "dir" => Some(Self::Dir), + _ => None, + } + } +} + +/// What a search keeps. Every field narrows; the default keeps everything. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Filter { + pub kind: Kind, + /// Only entries of at least this many bytes. + pub min_bytes: u64, + pub category: Option, + /// Cleanup candidates by classification, independent of removal guards. + pub reclaimable: bool, + /// Only names containing this, compared lowercased. + pub name: Option, + /// Only entries last written before this Unix time. For a directory + /// that is the newest write anywhere beneath it. + pub before: Option, +} + +impl Filter { + pub fn matches(&self, node: Node<'_>) -> bool { + let kind_ok = match self.kind { + Kind::Any => true, + Kind::File => !node.is_dir(), + Kind::Dir => node.is_dir(), + }; + kind_ok + && node.bytes >= self.min_bytes + && self + .category + .is_none_or(|category| node.category == category) + && (!self.reclaimable || node.reclaim.is_some()) + && self + .name + .as_deref() + .is_none_or(|name| node.name().to_lowercase().contains(name)) + && self.before.is_none_or(|before| { + node.modified > 0 && node.modified < before + }) + } + + /// Collect matches beneath `node`, topmost only: a matching directory + /// is listed once, without what is inside it. Sizes shrink going down, + /// so a node below the minimum ends the walk there. + pub fn collect<'a>( + &self, + path: &Path, + node: Node<'a>, + found: &mut Vec<(PathBuf, Node<'a>)>, + ) { + if node.bytes < self.min_bytes || node.kind == NodeKind::Other { + return; + } + if self.matches(node) { + found.push((path.to_path_buf(), node)); + return; + } + for child in node.children() { + self.collect(&path.join(child.name()), child, found); + } + } +} + +/// What a search found. +#[derive(Clone, Debug, Default)] +pub struct Found<'a> { + /// The largest matches, largest first, at most the limit asked for. + pub matches: Vec<(PathBuf, Node<'a>)>, + /// How many matched in all. + pub count: usize, + /// Bytes of every match, not only the ones listed. + pub bytes: u64, +} + +/// The largest `limit` entries beneath `root` (at `root_path`) that pass +/// `filter`. The root itself is never a match. +pub fn find<'a>( + root_path: &Path, + root: Node<'a>, + filter: &Filter, + limit: usize, +) -> Found<'a> { + let mut matches = Vec::new(); + for child in root.children() { + filter.collect(&root_path.join(child.name()), child, &mut matches); + } + matches.sort_by_key(|(_, node)| std::cmp::Reverse(node.bytes)); + let count = matches.len(); + let bytes = matches.iter().map(|(_, node)| node.bytes).sum(); + matches.truncate(limit); + Found { + matches, + count, + bytes, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::classify::Reclaim; + use crate::tree::{Draft, Tree}; + use crate::tree::{Metric, aggregate}; + + fn tree() -> Tree { + let mut root = Draft::directory("r"); + let mut cache = Draft::directory(".cache"); + cache.reclaim = Some(Reclaim::Regenerable); + cache.category = Category::Cache; + let mut blob = Draft::entry("blob.bin", NodeKind::File, 400); + blob.modified = 1_000; + cache.children.push(blob); + let mut src = Draft::directory("src"); + let mut target = Draft::directory("target"); + target.reclaim = Some(Reclaim::BuildOutput); + target + .children + .push(Draft::entry("app", NodeKind::File, 300)); + src.children.push(target); + let mut main = Draft::entry("main.rs", NodeKind::File, 20); + main.modified = 5_000; + src.children.push(main); + root.children.push(cache); + root.children.push(src); + root.children + .push(Draft::entry("Movie.iso", NodeKind::File, 250)); + let mut root = Tree::from(root); + aggregate(&mut root, Metric::Bytes); + root + } + + #[test] + fn reclaimable_matches_are_topmost_and_largest_first() { + let tree = tree(); + let root = tree.root(); + let root_path = Path::new("/r"); + let found = find( + root_path, + root, + &Filter { + reclaimable: true, + ..Filter::default() + }, + 10, + ); + let paths: Vec = + found.matches.iter().map(|(path, _)| path.clone()).collect(); + assert_eq!( + paths, + [ + root_path.join(".cache"), + root_path.join("src").join("target") + ] + ); + assert_eq!(found.count, 2); + assert_eq!(found.bytes, 700); + } + + #[test] + fn files_over_a_size_and_names_and_ages_filter() { + let tree = tree(); + let root = tree.root(); + let big = find( + Path::new("/r"), + root, + &Filter { + kind: Kind::File, + min_bytes: 260, + ..Filter::default() + }, + 10, + ); + assert_eq!(big.matches.len(), 2); + assert_eq!(big.matches[0].1.name(), "blob.bin"); + assert_eq!(big.matches[1].1.name(), "app"); + + let named = find( + Path::new("/r"), + root, + &Filter { + name: Some("iso".into()), + ..Filter::default() + }, + 1, + ); + assert_eq!(named.count, 1); + assert_eq!(named.matches[0].1.name(), "Movie.iso"); + + // Older than 2_000: blob.bin (1_000), not main.rs (5_000), and not + // the unknown-age iso. + let old = find( + Path::new("/r"), + root, + &Filter { + kind: Kind::File, + before: Some(2_000), + ..Filter::default() + }, + 10, + ); + assert_eq!(old.count, 1); + assert_eq!(old.matches[0].1.name(), "blob.bin"); + + // The limit trims the list but not the totals. + let one = find(Path::new("/r"), root, &Filter::default(), 1); + assert_eq!(one.matches.len(), 1); + assert_eq!(one.count, 3); + } +} diff --git a/crates/disktree-core/src/remote.rs b/crates/disktree-core/src/remote.rs index 27da007f..1ae7d301 100644 --- a/crates/disktree-core/src/remote.rs +++ b/crates/disktree-core/src/remote.rs @@ -5,24 +5,44 @@ //! and stream without making a second serialized copy of the whole tree. use std::io::{self, BufRead, BufReader, Read as _, Write}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::process::{Child, Command, Stdio}; use std::sync::{Arc, Mutex, mpsc}; use serde::{Deserialize, Serialize}; +use crate::path_style::PathStyle; use crate::remote_progress::{INTERVAL, Progress, Shared, Stage, stage}; use crate::scan::ScanOptions; #[cfg(not(unix))] use crate::scan::scan; use crate::space::{SpaceInfo, space_info, volume_root_for}; -use crate::tree::{Node, NodeKind, aggregate}; +use crate::tree::{Built, Facts, NodeKind, Tree, aggregate}; use std::time::Instant; const VERSION: u32 = 1; const MAX_LINE: u64 = 1 << 20; const MAX_DIAGNOSTICS: usize = 16 << 10; +/// Whether `path` names a directory from the remote host's root. Hosts are +/// Unix, so this is POSIX on every client; see `path_style`. +#[must_use] +pub fn is_remote_absolute(path: &Path) -> bool { + PathStyle::Posix.is_absolute(path) +} + +/// The remote command, the scanners and the delete script are POSIX shell +/// and Linux tools, and remote paths are joined as POSIX paths. A Windows +/// host's `C:\` paths would be joined wrongly, so refuse it by name. +fn check_platform(platform: &str) -> io::Result<()> { + if platform == "windows" { + return Err(io::Error::other( + "SSH hosts must run Unix; Windows hosts are not supported", + )); + } + Ok(()) +} + // Non-interactive shells often omit ~/.local/bin. Do not require users to // edit the server's startup files after the documented user-local install. const REMOTE_COMMAND: &str = r#"if command -v disktree-scan >/dev/null 2>&1; then @@ -31,7 +51,7 @@ elif [ -x "$HOME/.local/bin/disktree-scan" ]; then exec "$HOME/.local/bin/disktree-scan" --stdio-v1 else echo 'disktree-scan is not installed on this server.' >&2 -echo 'On the server, run make install-scan from the disktree checkout.' >&2 +echo 'On the server, run make install-scan from the PwrDisk checkout.' >&2 exit 127 fi"#; @@ -80,12 +100,16 @@ pub struct Roots { pub fn read_roots(input: &mut impl BufRead) -> io::Result { let roots: Roots = receive(input)?; + check_platform(&roots.platform)?; if roots.version != VERSION || roots .volumes .iter() - .any(|volume| !volume.point.is_absolute()) - || roots.home.as_ref().is_some_and(|home| !home.is_absolute()) + .any(|volume| !is_remote_absolute(&volume.point)) + || roots + .home + .as_ref() + .is_some_and(|home| !is_remote_absolute(home)) { return Err(io::Error::other("incompatible remote root discovery")); } @@ -107,7 +131,7 @@ pub struct Header { #[derive(Debug)] pub struct Snapshot { pub header: Header, - pub tree: Node, + pub tree: Tree, } // Children are already on the receiver's stack; counts preserve empty dirs @@ -267,7 +291,7 @@ fn serve_request_with_progress( live_tree, )?; #[cfg(not(unix))] - write_node(out, &scan(&root, request.options)?)?; + write_node(out, scan(&root, request.options)?.root())?; // An explicit terminator distinguishes a complete scan from a severed SSH // connection after any otherwise valid prefix of the postorder stream. send(out, &"done")?; @@ -275,8 +299,11 @@ fn serve_request_with_progress( } #[cfg(not(unix))] -fn write_node(out: &mut impl Write, node: &Node) -> io::Result<()> { - for child in &node.children { +fn write_node( + out: &mut impl Write, + node: crate::tree::Node<'_>, +) -> io::Result<()> { + for child in node.children() { write_node(out, child)?; } let kind = match node.kind { @@ -288,17 +315,17 @@ fn write_node(out: &mut impl Write, node: &Node) -> io::Result<()> { send( out, &Record( - if node.name.contains('/') { + if node.name().contains('/') { "root".into() } else { - node.name.to_string() + node.name().to_string() }, kind, node.own_bytes(), node.own_files(), node.modified, node.read_error, - node.children.len(), + node.children().len(), ), ) } @@ -312,161 +339,193 @@ fn read_snapshot_with_progress( shared: &Shared, ) -> io::Result { let header: Header = receive(input)?; - if header.version != VERSION || !header.root.is_absolute() { + check_platform(&header.platform)?; + if header.version != VERSION + || !is_remote_absolute(&header.root) + || [&header.home, &header.disk_root] + .into_iter() + .flatten() + .any(|path| !is_remote_absolute(path)) + { return Err(io::Error::other("incompatible remote helper protocol")); } let mut progress = Progress { stage: Stage::Indexing, + volume_used: crate::space::scan_volume_used( + &header.root, + header.disk_root.as_deref(), + header.space, + &header.platform, + ), directory: Some(header.root.clone()), updated: Some(Instant::now()), ..Progress::default() }; *shared.lock().expect("remote progress lock") = progress.clone(); let mut published = Instant::now(); - let mut stack = Vec::::new(); - let mut line = String::new(); - let seen = crate::tree::Seen::new(); - let mut preview = crate::scan_preview::Builder::default(); - let mut ancestors = Vec::::new(); - let mut preview_published = Instant::now(); - loop { - receive_line(input, &mut line)?; - let text = line.trim_start(); - // The common path is a typed tuple, not a heap-allocated JSON DOM - // followed by another deserialization. Reuse the line allocation. - let record: Record = if text.starts_with('[') { - serde_json::from_str(text).map_err(json_error)? - } else if text.starts_with('{') { - let control: Control = - serde_json::from_str(text).map_err(json_error)?; - if let Some(name) = control.enter { - if !(name.is_empty() && ancestors.is_empty()) - && (name.is_empty() - || name == "." - || name == ".." - || name.contains(['/', '\0']) - || (cfg!(windows) && name.contains(['\\', ':']))) - { - return Err(io::Error::other("invalid preview directory")); + let mut tree = Tree::try_build(|builder| { + let mut stack = Vec::>::new(); + let mut line = String::new(); + let seen = crate::tree::Seen::new(); + let mut preview = crate::scan_preview::Builder::default(); + let mut ancestors = Vec::::new(); + let mut preview_published = Instant::now(); + loop { + receive_line(input, &mut line)?; + let text = line.trim_start(); + // The common path is a typed tuple, not a heap-allocated JSON DOM + // followed by another deserialization. Reuse the line allocation. + let record: Record = if text.starts_with('[') { + serde_json::from_str(text).map_err(json_error)? + } else if text.starts_with('{') { + let control: Control = + serde_json::from_str(text).map_err(json_error)?; + if let Some(name) = control.enter { + if !(name.is_empty() && ancestors.is_empty()) + && (name.is_empty() + || name == "." + || name == ".." + || name.contains(['/', '\0'])) + { + return Err(io::Error::other( + "invalid preview directory", + )); + } + ancestors.push(name); + continue; + } + if let Some(directory) = control.directory { + progress.directory = Some(directory); + progress.updated = Some(Instant::now()); + *shared.lock().expect("remote progress lock") = + progress.clone(); + published = Instant::now(); + continue; + } + let mut entry = control.entry.ok_or_else(|| { + io::Error::other("invalid remote control record") + })?; + let identity = control.link.ok_or_else(|| { + io::Error::other("missing remote hardlink identity") + })?; + if entry.1 != 1 || entry.6 != 0 { + return Err(io::Error::other( + "invalid remote hardlink entry", + )); + } + if entry.2 > 0 && !seen.insert(identity) { + entry.2 = 0; } - ancestors.push(name); - continue; + entry + } else if serde_json::from_str::(text) + .map_err(json_error)? + == "done" + { + break; + } else { + return Err(io::Error::other("invalid remote stream marker")); + }; + let Record(name, kind, bytes, files, modified, read_error, count) = + record; + // Names must remain single components when joined to marked paths. + // Remote paths are joined as POSIX paths on every client, so `\` and + // `:` are ordinary characters in a name, as they are on the host. + if name.is_empty() + || name == "." + || name == ".." + || name.contains(['/', '\0']) + { + return Err(io::Error::other(format!( + "remote name cannot be represented safely: {name:?}" + ))); } - if let Some(directory) = control.directory { - progress.directory = Some(directory); - progress.updated = Some(Instant::now()); - *shared.lock().expect("remote progress lock") = - progress.clone(); - published = Instant::now(); - continue; + if name.len() > crate::tree::MAX_NAME_BYTES { + return Err(io::Error::other(format!( + "remote name is {} bytes long; no file system allows that", + name.len() + ))); } - let mut entry = control.entry.ok_or_else(|| { - io::Error::other("invalid remote control record") - })?; - let identity = control.link.ok_or_else(|| { - io::Error::other("missing remote hardlink identity") - })?; - if entry.1 != 1 || entry.6 != 0 { - return Err(io::Error::other("invalid remote hardlink entry")); + if count > stack.len() { + return Err(io::Error::other(format!( + "incomplete remote directory {name:?}: \ + expected {count} children, received {}", + stack.len(), + ))); } - if entry.2 > 0 && !seen.insert(identity) { - entry.2 = 0; + let kind = match kind { + 0 => NodeKind::Directory, + 1 => NodeKind::File, + 2 => NodeKind::Symlink, + 3 => NodeKind::Other, + _ => return Err(io::Error::other("invalid remote node kind")), + }; + if !kind.is_dir() && count != 0 { + return Err(io::Error::other("remote leaf has children")); } - entry - } else if serde_json::from_str::(text).map_err(json_error)? - == "done" - { - break; - } else { - return Err(io::Error::other("invalid remote stream marker")); - }; - let Record(name, kind, bytes, files, modified, read_error, count) = - record; - // Names must remain single components when joined to marked paths. - if name.is_empty() - || name == "." - || name == ".." - || name.contains(['/', '\0']) - || (cfg!(windows) && name.contains(['\\', ':'])) - { - return Err(io::Error::other(format!( - "remote name cannot be represented safely: {name:?}" - ))); - } - if count > stack.len() { - return Err(io::Error::other(format!( - "incomplete remote directory {name:?}: \ - expected {count} children, received {}", - stack.len(), - ))); - } - let kind = match kind { - 0 => NodeKind::Directory, - 1 => NodeKind::File, - 2 => NodeKind::Symlink, - 3 => NodeKind::Other, - _ => return Err(io::Error::other("invalid remote node kind")), - }; - if !kind.is_dir() && count != 0 { - return Err(io::Error::other("remote leaf has children")); - } - // The final root often owns every stacked node. Transfer that - // allocation instead of briefly duplicating a wide tree's storage. - let children = if count == stack.len() { - std::mem::take(&mut stack) - } else { - stack.split_off(stack.len() - count) - }; - let mut node = Node::entry(name, kind, bytes); - node.files = files; - node.modified = modified; - node.read_error = read_error; - node.children = children; - stack.push(node); - let mut preview_changed = false; - if !ancestors.is_empty() { - if kind.is_dir() { - ancestors.pop(); + // The final root often owns every stacked node. Take the stack + // whole instead of copying a wide tree's nodes out of it first. + let children = if count == stack.len() { + std::mem::take(&mut stack) } else { - preview.add(ancestors.get(1).map(String::as_str), bytes, files); - if progress.preview.is_none() { + stack.split_off(stack.len() - count) + }; + let facts = Facts { + files, + read_error, + modified, + ..Facts::entry(kind, bytes) + }; + stack.push(builder.directory(&name, facts, None, children)); + let mut preview_changed = false; + if !ancestors.is_empty() { + if kind.is_dir() { + ancestors.pop(); + } else { + preview.add( + ancestors.get(1).map(String::as_str), + bytes, + files, + ); + if progress.preview.is_none() { + progress.preview = Some(Arc::new(preview.snapshot())); + preview_changed = true; + } + } + } + progress.dirs += u64::from(kind.is_dir()); + // Legacy helpers include direct totals in directory records too. + // Count each leaf once, never charge its parent's totals again. + if !kind.is_dir() { + progress.files += files; + progress.bytes += bytes; + } + progress.errors += u64::from(read_error); + if published.elapsed() >= INTERVAL || preview_changed { + if progress.preview.is_some() + && preview_published.elapsed().as_secs() >= 1 + { progress.preview = Some(Arc::new(preview.snapshot())); - preview_changed = true; + preview_published = Instant::now(); } + progress.updated = Some(Instant::now()); + *shared.lock().expect("remote progress lock") = + progress.clone(); + published = Instant::now(); } } - progress.dirs += u64::from(kind.is_dir()); - // Legacy helpers include direct totals in directory records too. - // Count each leaf once, never charge its parent's totals again. - if !kind.is_dir() { - progress.files += files; - progress.bytes += bytes; + if progress.preview.is_some() { + progress.preview = Some(Arc::new(preview.snapshot())); } - progress.errors += u64::from(read_error); - if published.elapsed() >= INTERVAL || preview_changed { - if progress.preview.is_some() - && preview_published.elapsed().as_secs() >= 1 - { - progress.preview = Some(Arc::new(preview.snapshot())); - preview_published = Instant::now(); - } - progress.updated = Some(Instant::now()); - *shared.lock().expect("remote progress lock") = progress.clone(); - published = Instant::now(); + progress.stage = Stage::Finalizing; + progress.updated = Some(Instant::now()); + *shared.lock().expect("remote progress lock") = progress; + if stack.len() != 1 { + return Err(io::Error::other("incomplete remote tree")); } - } - if progress.preview.is_some() { - progress.preview = Some(Arc::new(preview.snapshot())); - } - progress.stage = Stage::Finalizing; - progress.updated = Some(Instant::now()); - *shared.lock().expect("remote progress lock") = progress; - if stack.len() != 1 { - return Err(io::Error::other("incomplete remote tree")); - } - let mut tree = stack.pop().expect("one root checked above"); + Ok(stack.pop().expect("one root checked above")) + })?; aggregate(&mut tree, crate::tree::Metric::Bytes); - crate::classify::classify(&mut tree); + crate::classify::classify_at(&mut tree, &header.root, PathStyle::Posix); Ok(Snapshot { header, tree }) } @@ -514,7 +573,7 @@ fn ssh_error(host: &str, details: &str, fallback: &io::Error) -> io::Error { { format!( "Run ssh {host} in a terminal to verify your credentials. \ - When starting disktree from a terminal, SSH can ask for a \ + When starting PwrDisk from a terminal, SSH can ask for a \ password there; GUI launches need an agent or SSH askpass." ) } else if reason.contains("Host key verification failed") { @@ -577,7 +636,8 @@ impl RemoteScan { Self::spawn_with_archive(command, host, request, archive) } - #[cfg(test)] + // Only the Unix tests run a fake ssh, so Windows has no caller. + #[cfg(all(test, unix))] fn spawn_command( command: Command, host: &str, @@ -601,8 +661,10 @@ impl RemoteScan { move |input, progress| { let mut snapshot = read_snapshot_with_progress(input, progress)?; + // The snapshot is already aggregated by size; another + // metric needs only its children reordered. if metric != crate::tree::Metric::Bytes { - aggregate(&mut snapshot.tree, metric); + crate::tree::reorder(&mut snapshot.tree, metric); } Ok(snapshot) }, @@ -744,6 +806,7 @@ mod tests { } } + #[cfg(unix)] fn wait(scan: &RemoteJob) -> io::Result { wait_for(scan, std::time::Duration::from_secs(10)) } @@ -808,6 +871,8 @@ mod tests { } } + // The helper runs on this machine, which must be a Unix host. + #[cfg(unix)] #[test] fn discovery_is_not_a_legacy_scan_request() { let session = SessionRequest { @@ -831,6 +896,8 @@ mod tests { assert!(roots.identity.is_some()); } + // The helper runs on this machine, which must be a Unix host. + #[cfg(unix)] #[test] fn discovery_never_resolves_a_scan_path_and_rejects_unknown_versions() { let mut output = Vec::new(); @@ -901,8 +968,8 @@ mod tests { let handle = RemoteScan::spawn_command(command, "fixture", &request).unwrap(); let snapshot = wait(&handle).unwrap(); - assert_eq!(snapshot.tree.bytes, 5); - assert_eq!(snapshot.tree.files, 1); + assert_eq!(snapshot.tree.root().bytes, 5); + assert_eq!(snapshot.tree.root().files, 1); assert_eq!(std::fs::read(dir.path().join("keep")).unwrap(), b"hello"); } @@ -996,8 +1063,8 @@ mod tests { ) .unwrap(); let snapshot = wait(&handle).unwrap(); - assert_eq!(snapshot.tree.bytes, 10); - assert_eq!(snapshot.tree.files, 2); + assert_eq!(snapshot.tree.root().bytes, 10); + assert_eq!(snapshot.tree.root().files, 2); assert_eq!(handle.progress().files, 2); assert!(snapshot.header.identity.is_some()); assert_eq!(std::fs::read(&cached).unwrap(), bytes); @@ -1073,19 +1140,95 @@ mod tests { .unwrap(); let snapshot = wait_for(&scan, std::time::Duration::from_mins(3)).unwrap(); - assert!(snapshot.tree.is_dir()); + assert!(snapshot.tree.root().is_dir()); assert!(snapshot.header.root.is_absolute()); println!( "SSH {}: {} — {} bytes, {} files, {} directories; space: {:?}", host, snapshot.header.root.display(), - snapshot.tree.bytes, - snapshot.tree.files, - snapshot.tree.dirs, + snapshot.tree.root().bytes, + snapshot.tree.root().files, + snapshot.tree.root().dirs, snapshot.header.space, ); } + fn unix_stream(platform: &str) -> Vec { + let mut data = Vec::new(); + let header = Header { + version: VERSION, + root: PathBuf::from("/srv"), + home: Some(PathBuf::from("/home/someone")), + disk_root: Some(PathBuf::from("/")), + space: None, + platform: platform.into(), + identity: None, + }; + send(&mut data, &header).unwrap(); + for name in [r"a\b", "c:d"] { + send(&mut data, &Record(name.into(), 1, 5, 1, 0, false, 0)) + .unwrap(); + } + send(&mut data, &Record("root".into(), 0, 0, 0, 0, false, 2)).unwrap(); + send(&mut data, &"done").unwrap(); + data + } + + /// Every client reads a Unix host's names as the host wrote them: `\` + /// and `:` are ordinary characters there, and the joined path uses `/`. + #[test] + fn unix_names_with_backslashes_and_colons_reach_every_client() { + let snapshot = read_snapshot(&mut unix_stream("linux").as_slice()) + .expect("a Unix host's names are accepted"); + assert_eq!(snapshot.tree.root().files, 2); + let style = PathStyle::Posix; + for name in [r"a\b", "c:d"] { + assert!(snapshot.tree.root().child_named(name).is_some()); + let path = style.join(&snapshot.header.root, name); + assert_eq!(path.to_str().unwrap(), format!("/srv/{name}")); + } + } + + /// A name no file system could hold is refused as a broken stream, not + /// taken into the tree. + #[test] + fn an_impossibly_long_remote_name_is_refused() { + let mut data = Vec::new(); + let header: Header = serde_json::from_slice( + unix_stream("linux") + .split(|&byte| byte == b'\n') + .next() + .unwrap(), + ) + .unwrap(); + send(&mut data, &header).unwrap(); + let name = "x".repeat(crate::tree::MAX_NAME_BYTES + 1); + send(&mut data, &Record(name, 1, 5, 1, 0, false, 0)).unwrap(); + send(&mut data, &Record("root".into(), 0, 0, 0, 0, false, 1)).unwrap(); + send(&mut data, &"done").unwrap(); + let error = read_snapshot(&mut data.as_slice()).unwrap_err(); + assert!(error.to_string().contains("bytes long"), "{error}"); + } + + /// Remote paths are joined as POSIX paths, so a Windows host is refused + /// by name rather than half-read with the wrong separator. + #[test] + fn windows_hosts_and_non_posix_roots_are_refused() { + let error = read_snapshot(&mut unix_stream("windows").as_slice()) + .unwrap_err() + .to_string(); + assert!(error.contains("Windows hosts"), "{error}"); + for value in [ + serde_json::json!({"version":1,"home":null,"platform":"windows","identity":null,"volumes":[]}), + serde_json::json!({"version":1,"home":"C:\\Users\\x","platform":"linux","identity":null,"volumes":[]}), + serde_json::json!({"version":1,"home":null,"platform":"linux","identity":null,"volumes":[{"point":"C:\\","device":null,"space":null}]}), + ] { + let mut data = serde_json::to_vec(&value).unwrap(); + data.push(b'\n'); + assert!(read_roots(&mut data.as_slice()).is_err(), "{value}"); + } + } + #[test] fn rejects_ssh_options_and_shell_syntax() { for host in ["-oProxyCommand=oops", "dev; touch x", "dev\nother", ""] { @@ -1114,8 +1257,8 @@ mod tests { let mut data = Vec::new(); serve(&mut input.as_slice(), &mut data).unwrap(); let snapshot = read_snapshot(&mut data.as_slice()).unwrap(); - assert_eq!(snapshot.tree.bytes, 1); - assert!(snapshot.tree.child_named(r"back\slash").is_some()); + assert_eq!(snapshot.tree.root().bytes, 1); + assert!(snapshot.tree.root().child_named(r"back\slash").is_some()); } #[cfg(unix)] @@ -1170,10 +1313,13 @@ mod tests { } output.write_all(&tail).unwrap(); let snapshot = worker.join().unwrap().unwrap(); - assert_eq!(snapshot.tree.bytes, 5); + assert_eq!(snapshot.tree.root().bytes, 5); assert_eq!(shared.lock().unwrap().stage, Stage::Finalizing); } + // The live preview this checks comes from the Unix helper's streaming + // walk; on other systems `serve` sends a finished tree with no preview. + #[cfg(unix)] #[test] fn desktop_dedup_counts_links_once_without_requiring_external_names() { let dir = tempfile::tempdir().unwrap(); @@ -1207,23 +1353,32 @@ mod tests { let snapshot = read_snapshot_with_progress(&mut data.as_slice(), &shared) .unwrap(); - assert_eq!(snapshot.tree.bytes, if dedup { 10 } else { 15 }); - assert_eq!(snapshot.tree.files, 3); - let preview = shared.lock().unwrap().preview.clone().unwrap(); - let nested = preview - .entries - .iter() - .find(|entry| entry.name == "nested") - .unwrap(); - assert_eq!(nested.bytes, 5); - assert_eq!(nested.files, 1); - assert_eq!( - preview.entries.iter().map(|e| e.bytes).sum::(), - snapshot.tree.bytes - ); + assert_eq!(snapshot.tree.root().bytes, if dedup { 10 } else { 15 }); + assert_eq!(snapshot.tree.root().files, 3); + let progress = shared.lock().unwrap(); + assert_eq!(progress.bytes, snapshot.tree.root().bytes); + assert_eq!(progress.files, snapshot.tree.root().files); + // Only the Unix streaming walker emits live-tree records; the + // Windows fallback sends the completed tree without a preview. + assert_eq!(progress.preview.is_some(), cfg!(unix)); + if let Some(preview) = &progress.preview { + let nested = preview + .entries + .iter() + .find(|entry| entry.name == "nested") + .unwrap(); + assert_eq!(nested.bytes, 5); + assert_eq!(nested.files, 1); + assert_eq!( + preview.entries.iter().map(|e| e.bytes).sum::(), + snapshot.tree.root().bytes + ); + } } } + // The helper runs on this machine, which must be a Unix host. + #[cfg(unix)] #[test] fn desktop_dedup_accepts_more_than_the_old_pending_link_limit() { let mut data = Vec::new(); @@ -1267,10 +1422,12 @@ mod tests { .unwrap(); send(&mut data, &"done").unwrap(); let snapshot = read_snapshot(&mut data.as_slice()).unwrap(); - assert_eq!(snapshot.tree.files, count + 1); - assert_eq!(snapshot.tree.bytes, count); + assert_eq!(snapshot.tree.root().files, count + 1); + assert_eq!(snapshot.tree.root().bytes, count); } + // The helper runs on this machine, which must be a Unix host. + #[cfg(unix)] #[test] fn protocol_roundtrip_and_truncation() { let dir = tempfile::tempdir().unwrap(); @@ -1290,9 +1447,9 @@ mod tests { serve(&mut input.as_slice(), &mut data).unwrap(); assert!(!data.windows(11).any(|part| part == b"\"directory\"")); let snapshot = read_snapshot(&mut data.as_slice()).unwrap(); - assert_eq!(snapshot.tree.bytes, 5); - assert_eq!(snapshot.tree.files, 1); - assert!(snapshot.tree.child_named("empty").unwrap().is_dir()); + assert_eq!(snapshot.tree.root().bytes, 5); + assert_eq!(snapshot.tree.root().files, 1); + assert!(snapshot.tree.root().child_named("empty").unwrap().is_dir()); data.truncate(data.len() - 7); assert!(read_snapshot(&mut data.as_slice()).is_err()); assert!(dir.path().join("a ' file").exists()); diff --git a/crates/disktree-core/src/remote_progress.rs b/crates/disktree-core/src/remote_progress.rs index 7389d224..a82229b7 100644 --- a/crates/disktree-core/src/remote_progress.rs +++ b/crates/disktree-core/src/remote_progress.rs @@ -33,6 +33,7 @@ pub struct Progress { pub files: u64, pub dirs: u64, pub bytes: u64, + pub volume_used: Option, pub errors: u64, pub directory: Option, pub updated: Option, diff --git a/crates/disktree-core/src/remote_walk.rs b/crates/disktree-core/src/remote_walk.rs index 8bbe4257..7b7a65c5 100644 --- a/crates/disktree-core/src/remote_walk.rs +++ b/crates/disktree-core/src/remote_walk.rs @@ -1,4 +1,4 @@ -//! Bounded-memory SSH traversal. No Node, arena, child vector or sort: +//! Bounded-memory SSH traversal. No Node, child vector or sort: //! the receiver owns the tree; the helper retains only its open ancestors. use std::fs::{self, ReadDir}; use std::io::{self, Write}; @@ -242,7 +242,7 @@ mod tests { rows.iter().filter(|row| row.1 != 0).map(|row| row.2).sum(); let expected = crate::scan::scan(dir.path(), ScanOptions::default()).unwrap(); - assert_eq!(actual, expected.bytes); + assert_eq!(actual, expected.root().bytes); assert_eq!(rows.iter().map(|row| row.3).sum::(), 3); assert_eq!(rows.iter().filter(|row| row.0 == "leaf").count(), 1); assert_eq!(rows.last().unwrap().6, 4); diff --git a/crates/disktree-core/src/removal.rs b/crates/disktree-core/src/removal.rs index 60277529..56482379 100644 --- a/crates/disktree-core/src/removal.rs +++ b/crates/disktree-core/src/removal.rs @@ -24,6 +24,13 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{self, Receiver}; use std::thread; +#[cfg(test)] +thread_local! { + static NESTING_WORK: std::cell::Cell = const { + std::cell::Cell::new(0) + }; +} + /// One path the user asked to remove. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Target { @@ -42,6 +49,8 @@ pub enum RemovalMode { Permanent, /// Move to the desktop trash so the removal can be undone. Trash, + /// Execute an allowlisted owner command for its explicitly previewed scope. + OwnerCleanup, } impl RemovalMode { @@ -49,6 +58,7 @@ impl RemovalMode { match self { Self::Permanent => "Delete permanently", Self::Trash => "Move to trash", + Self::OwnerCleanup => "Owner cleanup", } } @@ -56,6 +66,7 @@ impl RemovalMode { match self { Self::Permanent => "rm -rf: unrecoverable", Self::Trash => "recoverable until the trash is emptied", + Self::OwnerCleanup => "owner-managed; no Trash recovery", } } } @@ -82,6 +93,13 @@ pub struct Plan { reclaim: u64, /// Bytes the targets free on other volumes; see [`Self::foreign`]. foreign: u64, + /// Attribution from the same mount-table read that judged the guards. + attribution: Vec, + /// Clone estimates are separate from listed allocation and its volumes. + reclaimable_bytes: Option, + reclaim_estimate: Option, + possible_bytes: Option, + estimate_partial: bool, } impl Plan { @@ -97,7 +115,65 @@ impl Plan { /// disk mounted under the root can be marked — gives its space back /// there, so projecting it here would lend one disk another's bytes. pub const fn reclaim(&self) -> u64 { - self.reclaim + match self.reclaim_estimate { + Some(bytes) => bytes, + None => self.reclaim, + } + } + + /// Estimated savings across all targets, independent of the volume meter. + pub fn reclaimable_bytes(&self) -> u64 { + self.reclaimable_bytes.unwrap_or_else(|| self.bytes()) + } + + pub fn possible_bytes(&self) -> u64 { + self.possible_bytes + .unwrap_or_else(|| self.reclaimable_bytes()) + } + + pub const fn estimate_partial(&self) -> bool { + self.estimate_partial + } + + /// Evaluate the accepted set together, preserving the guard's volume + /// attribution. An external volume can never inflate this volume's meter. + pub fn estimate_selection( + &mut self, + mut estimate: impl FnMut(&[&Target]) -> crate::sharing::Estimate, + ) { + let all: Vec<_> = self.targets.iter().collect(); + let total = if all.is_empty() { + crate::sharing::Estimate::default() + } else { + estimate(&all) + }; + let scanned: Vec<_> = self + .targets + .iter() + .zip(&self.attribution) + .filter_map(|(target, attribution)| { + (*attribution == crate::space::Attribution::Scanned) + .then_some(target) + }) + .collect(); + let local = if scanned.is_empty() { + crate::sharing::Estimate::default() + } else if scanned.len() == all.len() { + total + } else { + estimate(&scanned) + }; + self.reclaimable_bytes = Some(total.lower); + self.possible_bytes = Some(total.upper); + self.reclaim_estimate = Some(local.lower); + self.estimate_partial = total.partial || local.partial; + } + + /// Target-root attribution from the same mount read as the guards. + pub fn attributed_targets( + &self, + ) -> impl Iterator { + self.targets.iter().zip(self.attribution.iter().copied()) } /// Bytes the targets free on other volumes, which the meter leaves out. @@ -136,7 +212,7 @@ fn plan_against(targets: &[Target], root: &Path, mounts: &MountTable) -> Plan { root: root.clone(), ..Plan::default() }; - let mut accepted: Vec = Vec::new(); + let mut accepted: Vec<(PathBuf, Target)> = Vec::new(); if targets.is_empty() { return plan; @@ -148,10 +224,7 @@ fn plan_against(targets: &[Target], root: &Path, mounts: &MountTable) -> Plan { for target in targets { let path = normalize(&target.path); let reason = - refuse(&path, &root, home.as_ref(), &mounts.points, &mounts.media) - .or_else(|| { - linked(&path, &root, real_root.as_deref(), home.as_ref()) - }); + judge(&path, &root, real_root.as_deref(), home.as_ref(), mounts); if let Some(reason) = reason { plan.blocked.push(Blocked { path: target.path.clone(), @@ -159,37 +232,57 @@ fn plan_against(targets: &[Target], root: &Path, mounts: &MountTable) -> Plan { }); continue; } - accepted.push(Target { - path, - ..target.clone() - }); + accepted.push(( + guard_key(&path), + Target { + path, + ..target.clone() + }, + )); } - // A path inside another target is removed with it. Keep the outer one and - // report the inner one so the review screen can explain the nesting. - accepted.sort_by(|left, right| left.path.cmp(&right.path)); - let mut outer: Vec = Vec::new(); - for target in accepted { - if outer - .iter() - .any(|candidate| within(&target.path, &candidate.path)) - { + // Descendants are contiguous only when sorted by the same keys the + // guards compare (including case and macOS Data-volume aliases). Once + // sorted, only the last retained outer path can cover the next one. + accepted.sort_by(|left, right| { + #[cfg(test)] + NESTING_WORK.set(NESTING_WORK.get() + 1); + left.0 + .cmp(&right.0) + .then_with(|| left.1.path.cmp(&right.1.path)) + }); + let mut outer: Option = None; + for (key, target) in accepted { + #[cfg(test)] + NESTING_WORK.set(NESTING_WORK.get() + 1); + if outer.as_ref().is_some_and(|parent| key.starts_with(parent)) { plan.covered.push(target); } else { - outer.push(target); + outer = Some(key); + plan.targets.push(target); } } - plan.targets = outer; + // Preserve the review list's original path ordering, independently of + // the guard-key ordering used to establish nesting. + for targets in [&mut plan.targets, &mut plan.covered] { + targets.sort_by(|left, right| { + #[cfg(test)] + NESTING_WORK.set(NESTING_WORK.get() + 1); + left.path.cmp(&right.path) + }); + } // Which volume each target's bytes come back to. Only what comes back to // the scanned volume may be shown against its free space. for target in &plan.targets { let bytes = target.bytes; - match crate::space::attribution( + let attribution = crate::space::attribution( mounts.mounts.as_deref(), &plan.root, &target.path, - ) { + ); + plan.attribution.push(attribution); + match attribution { crate::space::Attribution::Scanned => plan.reclaim += bytes, crate::space::Attribution::Other => plan.foreign += bytes, crate::space::Attribution::Unknown => {} @@ -198,11 +291,42 @@ fn plan_against(targets: &[Target], root: &Path, mounts: &MountTable) -> Plan { plan } +/// Why the guards would keep `path` back from a removal under `root`. +/// +/// `None` when they would let it through. The same judgement [`plan`] +/// makes for each target, for one path, so the window can refuse a mark +/// up front instead of offering one that Review would only keep back. +pub fn refusal(path: &Path, root: &Path) -> Option { + let root = normalize(root); + let home = std::env::home_dir().map(|home| Home::of(&home)); + let real_root = fs::canonicalize(&root).ok(); + judge( + &normalize(path), + &root, + real_root.as_deref(), + home.as_ref(), + &mount_points(), + ) +} + +/// One target against every guard: by spelling, then by where links lead. +fn judge( + path: &Path, + root: &Path, + real_root: Option<&Path>, + home: Option<&Home>, + mounts: &MountTable, +) -> Option { + refuse(path, root, home, &mounts.points, &mounts.media) + .or_else(|| linked(path, root, real_root, home)) +} + /// Trees the operating system owns. A whole-disk scan shows them, because /// they are part of what fills the disk, but files there belong to packages /// and removing them by hand breaks the system; pacman, paccache, /// `journalctl --vacuum` or `brew cleanup` are the right tools. Refused even -/// where permissions would allow it, and even inside them. +/// where permissions would allow it, and even inside them, except for the +/// scratch space in [`SCRATCH_TREES`]. /// /// One list for every platform: a macOS tree never exists on Linux, and the /// other way round, so the extra entries cost nothing. On macOS `/etc`, @@ -240,6 +364,16 @@ const SYSTEM_TREES: [&str; 24] = [ "/Network", ]; +/// Scratch space inside a system tree. On macOS `/tmp` and `/var/tmp` are +/// `/private/tmp` and `/private/var/tmp`, so the `/private` entry above would +/// refuse what any user leaves there, though Linux leaves the same folders +/// removable. What is inside them may be removed; the folders themselves +/// stay refused under `/private`. The sticky bit still keeps one user from +/// removing another's files. `/private/var/folders` stays refused: each +/// user's `$TMPDIR` and caches there hold running apps' live state. +#[cfg(not(windows))] +const SCRATCH_TREES: [&str; 2] = ["/private/tmp", "/private/var/tmp"]; + /// How the guards compare paths: lexically normalized, and where the /// platform has more than one spelling for a place, in one of them. /// @@ -279,12 +413,6 @@ fn windows_key(path: &Path) -> PathBuf { path.to_path_buf() } -/// `path` is `base` or inside it, by whole components, as the guards -/// compare them. -fn within(path: &Path, base: &Path) -> bool { - guard_key(path).starts_with(guard_key(base)) -} - /// The system trees with their guard keys, computed once: the review screen /// plans on every frame, for every mark. fn system_tree_keys() -> &'static [(String, PathBuf)] { @@ -306,6 +434,25 @@ fn system_trees() -> Vec { SYSTEM_TREES.iter().map(PathBuf::from).collect() } +/// [`SCRATCH_TREES`] by guard key, computed once like the system trees. +#[cfg(not(windows))] +fn scratch_tree_keys() -> &'static [PathBuf] { + static KEYS: std::sync::LazyLock> = + std::sync::LazyLock::new(|| { + SCRATCH_TREES + .iter() + .map(|tree| guard_key(Path::new(tree))) + .collect() + }); + &KEYS +} + +/// Windows' system trees have no scratch space inside them. +#[cfg(windows)] +const fn scratch_tree_keys() -> &'static [PathBuf] { + &[] +} + /// [`SYSTEM_TREES`] on Windows: Windows itself, installed programs and /// their machine-wide data, and what Windows keeps at the top of its drive /// for restore points, recovery and booting. Taken from the environment, so @@ -367,11 +514,18 @@ const SYSTEM_TOOLS: &str = "remove it with the tool that installed it"; const SYSTEM_TOOLS: &str = "use Settings, or the program's own uninstaller"; /// The system tree the path keyed `key` is in, if any. The home directory is -/// never system, wherever it lives. +/// never system, wherever it lives, and neither is what is inside the +/// scratch space of [`SCRATCH_TREES`]. fn system_tree(key: &Path, home: Option<&Path>) -> Option<&'static str> { if home.is_some_and(|home| key.starts_with(home)) { return None; } + if scratch_tree_keys() + .iter() + .any(|scratch| key != scratch && key.starts_with(scratch)) + { + return None; + } system_tree_keys() .iter() .find(|(_, tree)| key.starts_with(tree)) @@ -426,6 +580,12 @@ fn refuse( if key == root_key { return Some("the scanned root cannot be removed".into()); } + if crate::macos_services::is_service_path(path) { + return Some( + "macOS manages this history or index; use Apple's service tools" + .into(), + ); + } if cfg!(windows) && let Some(name) = path.components().find_map(|part| match part { Component::Normal(name) => { @@ -446,20 +606,29 @@ fn refuse( { return Some("the home directory cannot be removed".into()); } - // On Linux `/home` is usually a mount point of its own and refused as - // one; on macOS `/Users` is on the same volume as `/`, and removing it + // On Linux `/home` is often a mount point of its own and refused as + // one, though not always; on macOS `/Users` is on the same volume as `/`, and removing it // would empty the home directory before failing on `/Users` itself. if home_key.is_some_and(|home| home.starts_with(&key)) { return Some("it contains the home directory".into()); } + // macOS keeps every account's home in /Users, on the same volume as + // the system, and nothing marks another account's home as special: a + // whole-disk scan shows /Users/guest or /Users/Shared as just a folder. + // So /Users and each folder in it are refused there, as on Windows. + // // Elevated through another account's credentials, home is that admin's, // and the user's own profile is just another folder; elevation opens // every other profile too. So on Windows each directory in the profiles // folder (`C:\Users\tobi`, `Public`, `Default`) is refused, taken from // Windows and not from home, whose parent could be anything. What is // inside a profile stays removable, as under one's own home. - if profiles_key().is_some_and(|profiles| is_profile(path, &key, profiles)) { - return Some("a user profile cannot be removed".into()); + // + // Linux keeps them in /home, which is often a volume of its own and so + // refused as a mount point, but just as often a folder on `/`, where + // another account's home is a folder like any other. + if let Some(reason) = profile_refusal(path, &key, profiles_keys()) { + return Some(reason); } // By spelling too: the Data volume's root keeps its name as a key, while // everything under it is keyed as under `/`. @@ -764,16 +933,85 @@ const fn windows_mount_points() -> Vec { /// The key of the folder every user profile is in, `C:\Users` as /// installed; asked of Windows once, since it does not move while running. #[cfg(windows)] -fn profiles_key() -> Option<&'static Path> { - static PROFILES: std::sync::LazyLock> = +fn profiles_keys() -> &'static [PathBuf] { + static PROFILES: std::sync::LazyLock> = std::sync::LazyLock::new(|| { - crate::windows::user_profiles_dir().map(|dir| guard_key(&dir)) + crate::windows::user_profiles_dir() + .map(|dir| guard_key(&dir)) + .into_iter() + .collect() }); - PROFILES.as_deref() + &PROFILES } -#[cfg(not(windows))] -const fn profiles_key() -> Option<&'static Path> { +/// `/Users`, by key. Fixed on macOS: the system and its installer put +/// every account's home there, and a different home location is still a +/// home only for its own account. +#[cfg(target_os = "macos")] +fn profiles_keys() -> &'static [PathBuf] { + static PROFILES: std::sync::LazyLock<[PathBuf; 1]> = + std::sync::LazyLock::new(|| [guard_key(Path::new("/Users"))]); + PROFILES.as_slice() +} + +/// `/home`, and where it really is when it is a link: Fedora's atomic +/// editions link it to `/var/home`, and a scan from either spelling shows +/// the homes as folders directly in it. Taken from the filesystem layout +/// rather than `/etc/passwd`, which lists service accounts whose homes are +/// `/`, `/var/lib/...` or `/nonexistent`, misses accounts from LDAP or +/// SSSD, and forgets a removed account whose files are still there. +#[cfg(target_os = "linux")] +fn profiles_keys() -> &'static [PathBuf] { + static PROFILES: std::sync::LazyLock> = + std::sync::LazyLock::new(|| linux_profiles_keys(Path::new("/home"))); + &PROFILES +} + +/// The keys of `home` as spelled and, if a link leads elsewhere, as it +/// really is. +#[cfg(any(target_os = "linux", all(test, unix)))] +fn linux_profiles_keys(home: &Path) -> Vec { + let mut keys = vec![guard_key(home)]; + if let Ok(real) = fs::canonicalize(home) { + let real = guard_key(&real); + if !keys.contains(&real) { + keys.push(real); + } + } + keys +} + +#[cfg(not(any(windows, target_os = "macos", target_os = "linux")))] +const fn profiles_keys() -> &'static [PathBuf] { + &[] +} + +/// What one folder in the profiles folder is called where it is refused. +#[cfg(windows)] +const PROFILE: &str = "user profile"; +#[cfg(any(target_os = "macos", target_os = "linux"))] +const PROFILE: &str = "user's home folder"; +/// Nowhere else has a profiles folder; never shown. +#[cfg(not(any(windows, target_os = "macos", target_os = "linux")))] +const PROFILE: &str = ""; + +/// Why `path`, keyed `key`, is refused as a profiles folder or a profile +/// in one, judged against every name the folder has. +fn profile_refusal( + path: &Path, + key: &Path, + profiles: &[PathBuf], +) -> Option { + for profiles in profiles { + // The folder itself holds every account's home, the operator's + // included, wherever this process's own home happens to be. + if key == profiles { + return Some(format!("it holds every {PROFILE}")); + } + if is_profile(path, key, profiles) { + return Some(format!("a {PROFILE} cannot be removed")); + } + } None } @@ -973,6 +1211,7 @@ fn home_trash_dir() -> Option { /// What a running removal reports. #[derive(Clone, Debug)] pub enum RemovalEvent { + Cleanup(crate::cleanup::Report), Start { total: usize, }, @@ -1009,43 +1248,219 @@ impl RemovalHandle { } } +/// App removals use the same limit for UI and MCP, each volume against its +/// own ceiling. Preflight completes before the worker removes any target, +/// so a rejected batch does no work. +pub fn spawn_limited( + plan: Plan, + mode: RemovalMode, + limit: crate::removal_limit::Ceilings, +) -> RemovalHandle { + spawn_checked(plan, mode, Some(limit)) +} + /// Start removing the plan's targets on a worker thread. pub fn spawn(plan: Plan, mode: RemovalMode) -> RemovalHandle { - let (sender, events) = mpsc::channel(); - let cancel = Arc::new(AtomicBool::new(false)); - let worker_cancel = Arc::clone(&cancel); - let backend = if mode == RemovalMode::Trash { + spawn_checked(plan, mode, None) +} + +fn spawn_checked( + plan: Plan, + mode: RemovalMode, + limit: Option, +) -> RemovalHandle { + start(plan, mode, limit, None, |work| { + thread::Builder::new() + .name("disktree-remove".into()) + .spawn(work) + .map(drop) + }) +} + +/// The confirmed cleanup decisions travel intact to the removal worker, +/// which runs each step on its own and reports each one. +pub fn spawn_cleanup( + approved: crate::cleanup::Approved, + limit: crate::removal_limit::Ceilings, +) -> RemovalHandle { + start( + approved.plan.clone(), + RemovalMode::OwnerCleanup, + Some(limit), + Some(approved), + |work| { + thread::Builder::new() + .name("disktree-cleanup".into()) + .spawn(work) + .map(drop) + }, + ) +} + +/// Trash is looked for only when something will go there: a Trash run, or +/// a cache cleanup where the person chose to delete files by Trash. +pub(crate) fn backend_for( + mode: RemovalMode, + cleanup: Option<&crate::cleanup::Approved>, +) -> TrashBackend { + let trash_steps = cleanup.is_some_and(|approved| { + approved.steps.iter().any(|step| { + matches!( + step, + crate::cleanup::Step::Files { + action: crate::cleanup::Action::Trash, + .. + } + ) + }) + }); + if mode == RemovalMode::Trash || trash_steps { detect_trash_backend() } else { TrashBackend::Unavailable - }; + } +} - let worker = thread::Builder::new() - .name("disktree-remove".into()) - .spawn({ - let sender = sender.clone(); - move || run(&plan, mode, backend, &worker_cancel, &sender) - }); +/// The work a removal thread runs, boxed so a test can hand it to a +/// spawner that refuses it. +type Work = Box; + +/// [`spawn_checked`] with the thread's start passed in, so a test can make +/// it fail as a process out of threads would. +fn start( + plan: Plan, + mode: RemovalMode, + limit: Option, + cleanup: Option, + spawn: impl FnOnce(Work) -> io::Result<()>, +) -> RemovalHandle { + let (sender, events) = mpsc::channel(); + let cancel = Arc::new(AtomicBool::new(false)); + let worker_cancel = Arc::clone(&cancel); + let backend = backend_for(mode, cleanup.as_ref()); + // Shared, not moved: a spawn that fails drops the work unrun, and the + // targets are still needed to report that each one failed. + let plan = Arc::new(plan); + + let worker = spawn(Box::new({ + let plan = Arc::clone(&plan); + let sender = sender.clone(); + move || { + // Every path has a result, the skipped ones included. + if let Some(approved) = &cleanup { + for report in &approved.skipped { + let _ = sender.send(RemovalEvent::Cleanup(report.clone())); + } + } + // A cleanup admits each step on its own measurement; only the + // capacity ceiling refuses the whole run. + let checked = if mode == RemovalMode::OwnerCleanup { + cleanup + .as_ref() + .ok_or_else(|| { + "Cache cleanup requires approved decisions".to_string() + }) + .and_then(|approved| { + let default = crate::removal_limit::Ceilings::default(); + approved.admit(limit.as_ref().unwrap_or(&default)) + }) + } else { + crate::cleanup::check_raw(&plan.targets).map(|()| vec![]) + }; + let refusals = match checked { + Ok(refusals) => refusals, + Err(reason) => { + if let Some(approved) = &cleanup { + let issue = crate::cleanup::Issue::new( + crate::cleanup::Problem::OverLimit, + reason.clone(), + ); + for index in 0..plan.targets.len() { + let _ = sender.send(RemovalEvent::Cleanup( + approved.report(index, None, None, Err(&issue)), + )); + } + } + fail_all(&plan.targets, &reason, &sender); + return; + } + }; + if let Some(limit) = + limit.filter(|_| mode != RemovalMode::OwnerCleanup) + { + let fresh = self::plan(&plan.targets, &plan.root); + let checked = if fresh.blocked.is_empty() { + crate::removal_limit::measured(&plan.targets) + .and_then(|targets| limit.check(&targets)) + } else { + Err("Removal guards changed before preflight; nothing was removed".into()) + }; + if let Err(reason) = checked { + fail_all(&plan.targets, &reason, &sender); + return; + } + } + run( + &plan, + mode, + backend, + cleanup + .as_ref() + .map(|approved| (approved, refusals.as_slice())), + &worker_cancel, + &sender, + ); + } + })); + // Without `Done` the app would wait on the Removing screen for good: + // the dropped sender reads the same as a worker with nothing new. if let Err(error) = worker { + fail_all( + &plan.targets, + &format!("could not start the removal worker: {error}"), + &sender, + ); + } + + RemovalHandle { events, cancel } +} + +/// A whole run that removed nothing: every target failed for `reason`, +/// then the end, so the run finishes and reads as failed, item by item. +fn fail_all( + targets: &[Target], + reason: &str, + sender: &mpsc::Sender, +) { + let _ = sender.send(RemovalEvent::Start { + total: targets.len(), + }); + for target in targets { let _ = sender.send(RemovalEvent::Item { - path: PathBuf::new(), + path: target.path.clone(), bytes: 0, - outcome: Err(format!( - "could not start the removal worker: {error}" - )), + outcome: Err(reason.to_owned()), }); } - - RemovalHandle { events, cancel } + let _ = sender.send(RemovalEvent::Done { + removed: 0, + bytes: 0, + failed: targets.len(), + }); } fn run( plan: &Plan, mode: RemovalMode, backend: TrashBackend, + cleanup: Option<( + &crate::cleanup::Approved, + &[Option], + )>, cancel: &AtomicBool, sender: &mpsc::Sender, ) { + use crate::cleanup::{Action, Issue, Problem}; let _ = sender.send(RemovalEvent::Start { total: plan.targets.len(), }); @@ -1062,8 +1477,16 @@ fn run( let home = std::env::home_dir().map(|home| Home::of(&home)); let real_root = fs::canonicalize(&plan.root).ok(); - for target in &plan.targets { + for (index, target) in plan.targets.iter().enumerate() { if cancel.load(Ordering::Relaxed) { + // Stopped: what was not started says so, step by step. + if let Some((approved, _)) = cleanup { + for rest in index..plan.targets.len() { + let _ = sender.send(RemovalEvent::Cleanup( + approved.not_reached(rest), + )); + } + } break; } // The /run/media exception must still hold when removal starts; @@ -1090,6 +1513,16 @@ fn run( home.as_ref(), ) }); + // Sample the scope's own volume, including when it differs from + // the scan's meter. Its parent remains after a cache root is cleared. + let sample = || { + target + .path + .parent() + .and_then(|path| crate::space::space_info(path).ok()) + .map(|space| space.available) + }; + let before = (mode == RemovalMode::OwnerCleanup).then(sample).flatten(); let outcome = if let Some(reason) = reason { Err(io::Error::other(reason)) } else { @@ -1098,8 +1531,53 @@ fn run( remove_permanently(&target.path, &plan.root) } RemovalMode::Trash => move_to_trash(&target.path, backend), + RemovalMode::OwnerCleanup => Ok(()), } }; + // A cleanup step: its own refusal, checks and action, with a typed + // reason. One step's failure never stops or changes the next. + let outcome = if let Some((approved, refusals)) = cleanup { + let step = outcome + .map_err(|error| { + Issue::new(Problem::Refused, error.to_string()) + }) + .and_then(|()| { + refusals.get(index).cloned().flatten().map_or(Ok(()), Err) + }) + .and_then(|()| approved.preflight(index)) + .and_then(|()| match approved.steps.get(index) { + Some(crate::cleanup::Step::Owner(operation)) => { + approved.prepared.execute(*operation, cancel) + } + Some(crate::cleanup::Step::Files { action, .. }) => { + match action { + Action::Trash => { + move_to_trash(&target.path, backend) + } + _ => remove_permanently(&target.path, &plan.root), + } + .map_err(|error| { + Issue::new( + Problem::RemovalFailed, + error.to_string(), + ) + }) + } + None => Err(Issue::new( + Problem::Changed, + "Missing cleanup step", + )), + }); + let _ = sender.send(RemovalEvent::Cleanup(approved.report( + index, + before, + sample(), + step.as_ref().copied(), + ))); + step.map_err(|issue| io::Error::other(issue.description())) + } else { + outcome + }; if outcome.is_ok() { removed += 1; bytes += target.bytes; @@ -1712,13 +2190,14 @@ mod tests { ..crate::scan::ScanOptions::default() }; let tree = crate::scan::scan(scan_root, options.clone()).expect("scan"); + let tree = tree.root(); for name in ["one", "two", "original"] { assert!( - tree.children.iter().any(|child| &*child.name == name), + tree.children().iter().any(|child| child.name() == name), "{name}" ); } - assert!(!tree.children.iter().any(|child| &*child.name == "alias")); + assert!(!tree.children().iter().any(|child| child.name() == "alias")); assert_eq!(tree.files, 3); assert_eq!(tree.bytes, 12); assert!( @@ -1737,18 +2216,91 @@ mod tests { .expect("unique"); let tree = crate::scan::scan(scan_root, options).expect("rescan"); let alias = tree - .children + .root() + .children() .iter() - .find(|child| &*child.name == "alias") + .find(|child| child.name() == "alias") .expect("alias retained"); assert!( alias - .children + .children() .iter() - .any(|child| &*child.name == "nested" && child.files == 1) + .any(|child| child.name() == "nested" && child.files == 1) ); } + #[test] + fn removal_nesting_budget() { + let temp = TempDir::new().expect("tempdir"); + let measure = |count| { + let targets: Vec<_> = (0..count) + .map(|index| (index * 73) % count) + .map(|index| Target { + path: temp.path().join(format!("item-{index:05}")), + bytes: 1, + is_dir: false, + hidden: false, + }) + .collect(); + NESTING_WORK.set(0); + let start = std::time::Instant::now(); + let plan = + plan_against(&targets, temp.path(), &MountTable::default()); + let elapsed = start.elapsed(); + let operations = NESTING_WORK.get(); + assert_eq!(plan.targets.len(), count); + eprintln!("plan M={count} work={operations} wall={elapsed:?}"); + operations + }; + let small = measure(128); + let large = measure(1024); + assert!(large <= small * 16, "8x marks: {small} -> {large}"); + assert!(large <= 1024 * 32, "absolute work cap: {large}"); + } + + #[test] + fn nesting_keeps_component_boundaries_duplicates_and_output_order() { + let temp = TempDir::new().expect("tempdir"); + let targets: Vec<_> = + ["z", "ab", "a/deep", "a", "a", "ab/inner", "a/deeper/file"] + .map(|name| target(&temp.path().join(name), 1)) + .into(); + let result = + plan_against(&targets, temp.path(), &MountTable::default()); + let paths = |targets: &[Target]| -> Vec<_> { + targets + .iter() + .map(|item| { + item.path + .strip_prefix(temp.path()) + .expect("under root") + .to_path_buf() + }) + .collect() + }; + assert_eq!(paths(&result.targets), ["a", "ab", "z"].map(PathBuf::from)); + assert_eq!( + paths(&result.covered), + ["a", "a/deep", "a/deeper/file", "ab/inner"].map(PathBuf::from) + ); + assert!(result.blocked.is_empty()); + } + + #[cfg(any(windows, target_os = "macos"))] + #[test] + fn nesting_uses_guard_case_order_even_when_the_child_sorts_first() { + let temp = TempDir::new().expect("tempdir"); + let parent = target(&temp.path().join("alpha"), 3); + let child = target(&temp.path().join("ALPHA/child"), 1); + let result = plan_against( + &[child.clone(), parent.clone()], + temp.path(), + &MountTable::default(), + ); + assert_eq!(result.targets, [parent]); + assert_eq!(result.covered, [child]); + } + #[test] fn a_plan_keeps_only_the_outermost_targets() { let temp = tree(); @@ -1802,6 +2354,23 @@ mod tests { assert_eq!(plan.reclaim(), 100, "the Btrfs subvolume is this disk"); assert_eq!(plan.foreign(), 600, "another disk, and a snapshot"); assert_eq!(plan.unattributed(), 0); + let mut estimated = plan; + estimated.estimate_selection(|targets| { + let bytes = targets.iter().map(|target| target.bytes / 2).sum(); + crate::sharing::Estimate { + lower: bytes, + upper: bytes, + partial: false, + } + }); + assert_eq!(estimated.reclaimable_bytes(), 350); + assert_eq!(estimated.reclaim(), 50, "only this volume's estimate"); + assert_eq!(estimated.foreign(), 600, "listed foreign allocation"); + assert_eq!( + estimated.unattributed(), + 0, + "sharing is not an unknown volume" + ); // A mark inside another is removed with it, so its bytes are counted // once here as they are in the total. @@ -1829,6 +2398,19 @@ mod tests { assert_eq!(plan.reclaim(), 0); assert_eq!(plan.foreign(), 0); assert_eq!(plan.unattributed(), 50, "no saving may be claimed"); + let mut estimated = plan; + estimated.estimate_selection(|_| crate::sharing::Estimate { + lower: 25, + upper: 50, + partial: false, + }); + assert_eq!(estimated.reclaimable_bytes(), 25); + assert_eq!( + estimated.reclaim(), + 0, + "unplaced estimates stay off the meter" + ); + assert_eq!(estimated.unattributed(), 50); } #[test] @@ -1877,6 +2459,24 @@ mod tests { ); } + #[test] + fn macos_service_stores_and_their_contents_are_never_raw_deleted() { + for volume in ["/", "/System/Volumes/Data", "/Volumes/External"] { + for store in [".fseventsd", ".Spotlight-V100", ".SPOTLIGHT-V100"] { + let path = Path::new(volume).join(store); + for path in [path.clone(), path.join("index/blob")] { + let reason = + refuse(&path, Path::new(volume), None, &[], &[]) + .expect("service-owned contents must be kept"); + assert!( + reason.contains("Apple's service tools"), + "{reason}" + ); + } + } + } + } + #[test] fn paths_outside_the_root_are_refused() { let temp = tree(); @@ -2459,6 +3059,60 @@ mod tests { assert!(root.join("a/one.bin").exists()); } + #[test] + fn a_worker_that_cannot_start_ends_the_run_as_failed() { + let temp = tree(); + let root = temp.path(); + let plan = plan( + &[ + target(&root.join("a/b"), 0), + target(&root.join("a/c.bin"), 20), + ], + root, + ); + let paths: Vec = plan + .targets + .iter() + .map(|target| target.path.clone()) + .collect(); + assert_eq!(paths.len(), 2); + + // The spawner refuses the work as a process out of threads would, + // so every event below was sent before `start` returned. + let handle = start(plan, RemovalMode::Permanent, None, None, |_work| { + Err(io::Error::other("out of threads")) + }); + let events: Vec<_> = std::iter::from_fn(|| handle.poll()).collect(); + + // Start, one failure per listed target, then the end: without + // `Done` the window would wait on the Removing screen for good. + assert_eq!(events.len(), paths.len() + 2, "{events:?}"); + assert!(matches!(events[0], RemovalEvent::Start { total: 2 })); + for (event, expected) in events[1..=paths.len()].iter().zip(&paths) { + match event { + RemovalEvent::Item { + path, + bytes: 0, + outcome: Err(reason), + } => { + assert_eq!(path, expected); + assert!(reason.contains("out of threads"), "{reason}"); + } + other => panic!("expected a failed item, got {other:?}"), + } + } + assert!(matches!( + events.last(), + Some(RemovalEvent::Done { + removed: 0, + bytes: 0, + failed: 2, + }) + )); + assert!(root.join("a/b").exists()); + assert!(root.join("a/c.bin").exists()); + } + #[cfg(unix)] #[test] fn a_trash_tool_is_called_with_the_path_after_a_separator() { @@ -2563,6 +3217,133 @@ mod tests { ); } + #[cfg(target_os = "macos")] + #[test] + fn macos_home_folders_are_refused() { + let root = Path::new("/"); + let refused = |path: &str, root: &Path| { + refuse(Path::new(path), root, None, &[], &[]) + }; + // Whatever this process's home is, /Users holds every account's. + assert!( + refused("/Users", root) + .is_some_and(|reason| reason.contains("every user")) + ); + // Shared ships with macOS, so it is there to be judged as a folder. + for spelling in ["/Users/Shared", "/users/shared"] { + assert!( + refused(spelling, root) + .is_some_and(|reason| reason.contains("home folder")), + "{spelling} is an account's folder" + ); + } + // The Data volume's spelling is judged as the same place. + let data = Path::new(crate::space::MACOS_DATA_VOLUME); + assert!( + refused("/System/Volumes/Data/Users/Shared", data) + .is_some_and(|reason| reason.contains("home folder")) + ); + // Inside a home folder stays removable, as under one's own home. + assert_eq!(refused("/Users/Shared/old-installer.pkg", root), None); + assert_eq!(refused("/Users/nobody-is-here", root), None); + } + + #[cfg(target_os = "linux")] + #[test] + fn linux_home_folders_are_refused() { + let root = Path::new("/"); + let refused = |path: &Path| refuse(path, root, None, &[], &[]); + // Whatever this process's home is, /home holds every account's, + // however it is spelled. + for spelling in ["/home", "/home/", "/home/.", "/usr/../home"] { + assert!( + refused(Path::new(spelling)) + .is_some_and(|reason| reason.contains("every user")), + "{spelling} holds every home" + ); + } + // Each directory there is an account's, whoever's it is; a bare + // container may have none. + let homes = fs::read_dir("/home").into_iter().flatten().flatten(); + let dirs = homes + .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir())); + for entry in dirs { + let home = entry.path(); + assert!( + refused(&home) + .is_some_and(|reason| reason.contains("home folder")), + "{} is an account's folder", + home.display() + ); + // Inside a home folder stays removable, as under one's own. + assert_eq!(refused(&home.join("old-installer.tar")), None); + } + // Nothing there is no home folder. + assert_eq!(refused(Path::new("/home/nobody-is-here")), None); + } + + /// Fedora's atomic editions link /home to /var/home: a scan from + /// either spelling shows the homes as folders directly in it. + #[cfg(unix)] + #[test] + fn a_linked_home_folder_is_judged_by_both_names() { + let temp = tempfile::tempdir().expect("tempdir"); + // Its own real name, so the only link in play is the one made here. + let temp = fs::canonicalize(temp.path()).expect("canonical"); + let real = temp.join("var/home"); + fs::create_dir_all(real.join("guest")).expect("mkdir"); + let link = temp.join("home"); + std::os::unix::fs::symlink(&real, &link).expect("symlink"); + let keys = linux_profiles_keys(&link); + assert_eq!(keys.len(), 2, "{keys:?}"); + let refused = |path: &Path| { + profile_refusal(path, &guard_key(path), &keys).unwrap_or_default() + }; + for folder in [&link, &real] { + assert!(refused(folder).contains("every user")); + let path = folder.join("guest"); + assert!( + refused(&path).contains("home folder"), + "{} is an account's folder", + path.display() + ); + } + // A real folder has one name. + assert_eq!(linux_profiles_keys(&real).len(), 1); + } + + #[test] + fn a_single_path_is_judged_as_a_plan_would() { + let temp = tempfile::tempdir().expect("tempdir"); + let root = temp.path(); + let inside = root.join("cache"); + fs::create_dir(&inside).expect("mkdir"); + assert_eq!(refusal(&inside, root), None); + assert!( + refusal(root, root) + .is_some_and(|reason| reason.contains("scanned root")) + ); + let elsewhere = tempfile::tempdir().expect("tempdir"); + assert!( + refusal(elsewhere.path(), root) + .is_some_and(|reason| reason.contains("outside")) + ); + let planned = plan( + &[Target { + path: root.to_path_buf(), + bytes: 0, + is_dir: true, + hidden: false, + }], + root, + ); + assert_eq!( + Some(planned.blocked[0].reason.clone()), + refusal(root, root), + "one judgement, two callers" + ); + } + #[cfg(windows)] #[test] fn windows_profiles_are_refused() { @@ -2687,4 +3468,121 @@ mod tests { assert_eq!(tree_of(Path::new(path), home), None, "{path}"); } } + + /// `/tmp` on macOS is `/private/tmp`: what a user leaves there is theirs + /// to remove, as on Linux, but the folder itself is the system's. + #[test] + #[cfg(not(windows))] + fn macos_scratch_space_is_removable_but_not_the_folders_themselves() { + let home = Path::new("/Users/tobi"); + let macos = |path: &str| { + system_tree( + &guard_key_for(Path::new(path), true), + Some(&guard_key_for(home, true)), + ) + }; + for path in [ + "/private/tmp/pwrdisk-review.kW8Ry1", + "/private/tmp/build/target/debug", + "/private/var/tmp/cache.bin", + // The same places by the Data volume's spelling, and by case. + "/System/Volumes/Data/private/tmp/pwrdisk-review", + "/PRIVATE/TMP/Build", + ] { + assert_eq!(macos(path), None, "{path}"); + } + for path in [ + "/private/tmp", + "/private/var/tmp", + "/System/Volumes/Data/private/tmp", + // A neighbour that only shares the spelling's start. + "/private/tmpfoo/x", + // Every user's `$TMPDIR` and caches stay refused. + "/private/var/folders/xy/T/item", + "/private/var/db/receipts", + ] { + assert_eq!(macos(path), Some("/private"), "{path}"); + } + } + + /// The whole guard, not only the tree lookup: in a whole-disk scan a + /// folder in `/private/tmp` is accepted and `/private/tmp` refused. + #[test] + #[cfg(target_os = "macos")] + fn a_whole_disk_scan_may_remove_what_is_in_private_tmp() { + let home = Home::of(Path::new("/Users/tobi")); + let root = Path::new("/"); + assert_eq!( + refuse( + Path::new("/private/tmp/pwrdisk-guard-fixture"), + root, + Some(&home), + &[], + &[], + ), + None + ); + let reason = + refuse(Path::new("/private/tmp"), root, Some(&home), &[], &[]); + assert!( + reason + .as_deref() + .is_some_and(|reason| reason + .contains("part of the system under /private")), + "{reason:?}" + ); + } + + /// The whole plan, on a real entry: the link and mount checks pass a + /// folder in `/private/tmp` too, so a whole-disk scan may remove it. + #[test] + #[cfg(target_os = "macos")] + fn a_whole_disk_plan_accepts_a_real_entry_in_private_tmp() { + let temp = + tempfile::tempdir_in("/private/tmp").expect("scratch fixture"); + let planned = plan(&[target(temp.path(), 1)], Path::new("/")); + assert!(planned.blocked.is_empty(), "{:?}", planned.blocked); + assert_eq!(planned.targets.len(), 1); + + let planned = + plan(&[target(Path::new("/private/tmp"), 1)], Path::new("/")); + assert!(planned.targets.is_empty()); + } + + #[test] + fn limited_worker_refuses_the_entire_batch_before_removing_anything() { + let temp = tree(); + let paths = [temp.path().join("a/b"), temp.path().join("a/c.bin")]; + let planned = plan( + &[ + target(&paths[0], u64::MAX / 4), + target(&paths[1], u64::MAX / 4), + ], + temp.path(), + ); + let handle = spawn_limited( + planned, + RemovalMode::Permanent, + crate::removal_limit::Limit::default().into(), + ); + let mut done = None; + for _ in 0..2000 { + while let Some(event) = handle.poll() { + if let RemovalEvent::Done { + removed, failed, .. + } = event + { + done = Some((removed, failed)); + } + } + if done.is_some() { + break; + } + thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(done, Some((0, 2))); + for path in paths { + assert!(path.exists()); + } + } } diff --git a/crates/disktree-core/src/removal_limit.rs b/crates/disktree-core/src/removal_limit.rs new file mode 100644 index 00000000..188e3047 --- /dev/null +++ b/crates/disktree-core/src/removal_limit.rs @@ -0,0 +1,577 @@ +//! A per-operation capacity limit, independent of projected savings. + +use std::collections::BTreeMap; +use std::path::Path; + +use serde::{Deserialize, Serialize}; + +use crate::removal::Target; +use crate::size::human_bytes; + +/// The default applies to both Trash and permanent removal. +pub const DEFAULT_PERCENT: u8 = 5; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Limit(u8); + +impl Default for Limit { + fn default() -> Self { + Self(DEFAULT_PERCENT) + } +} + +/// One volume's contribution to a proposed operation, before clone savings. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Budget { + pub volume: String, + pub bytes: u64, + pub capacity: u64, + pub limit: u64, +} + +impl Limit { + pub fn new(percent: u8) -> Result { + if (1..=100).contains(&percent) { + Ok(Self(percent)) + } else { + Err("Removal limit must be between 1% and 100%".into()) + } + } + + pub const fn percent(self) -> u8 { + self.0 + } + + /// Count every target against its own volume; unknown capacity fails closed. + pub fn check(self, targets: &[Target]) -> Result, String> { + Ceilings::from(self).check(targets) + } + + #[cfg(test)] + fn check_with( + self, + targets: &[Target], + volume: impl FnMut(&Path) -> Result<(String, u64), String>, + ) -> Result, String> { + Ceilings::from(self).check_with(targets, volume) + } +} + +/// The limit a removal is held to, volume by volume. +/// +/// One limit for every volume, with some raised to the share the person +/// confirmed for this removal. Only the window raises one, after its +/// second confirmation; an agent's removal is held to a plain [`Limit`]. +/// +/// A confirmation names one volume's share. Applying its percent to every +/// volume would let a mark on another disk — a disk mounted inside the +/// scan — through at that percent of its own capacity without anyone +/// having confirmed it. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Ceilings { + base: Limit, + raised: BTreeMap, +} + +impl From for Ceilings { + fn from(base: Limit) -> Self { + Self { + base, + raised: BTreeMap::new(), + } + } +} + +impl Ceilings { + /// Allow `volume`, keyed as [`volume_of`] keys it, up to `to`. Never + /// lowers it below the base: a confirmation only ever lets more go. + #[must_use] + pub fn raise(mut self, volume: String, to: Limit) -> Self { + if to.0 > self.base.0 { + self.raised.insert(volume, to); + } + self + } + + /// The limit `volume` is held to. + pub fn of(&self, volume: &str) -> Limit { + self.raised.get(volume).copied().unwrap_or(self.base) + } + + /// Count every target against its own volume, each volume against its + /// own limit; unknown capacity fails closed. + pub fn check(&self, targets: &[Target]) -> Result, String> { + self.check_with(targets, volume_of) + } + + /// [`Self::check`] with the volume of each target given, as `volume` + /// gives it: a key and the volume's capacity. + pub fn check_with( + &self, + targets: &[Target], + volume: impl FnMut(&Path) -> Result<(String, u64), String>, + ) -> Result, String> { + usage(targets, volume)? + .into_iter() + .map( + |Usage { + volume, + bytes, + capacity, + }| { + let percent = self.of(&volume).0; + // u128 keeps the inclusive boundary exact even on a huge + // volume. + let limit = u64::try_from( + u128::from(capacity) * u128::from(percent) / 100, + ) + .map_err(|_| "Removal capacity overflow")?; + if bytes > limit { + return Err(format!( + "Removal blocked: {} on {volume} exceeds the \ + {percent}% per-operation limit ({} of {} capacity). \ + Reduce the selection or change the limit in \ + Settings > Safety; do not split an unapproved \ + removal into batches.", + human_bytes(bytes), + human_bytes(limit), + human_bytes(capacity), + )); + } + Ok(Budget { + volume, + bytes, + capacity, + limit, + }) + }, + ) + .collect() + } +} + +/// One volume's part of a removal: the bytes it gives up and its capacity. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Usage { + pub volume: String, + pub bytes: u64, + pub capacity: u64, +} + +/// The targets summed volume by volume, as every limit counts them. +/// +/// One entry per volume `volume` names, in key order. A volume reported +/// with two capacities keeps the smaller, the stricter reading; an +/// unknown or zero capacity fails closed. +pub fn usage( + targets: &[Target], + mut volume: impl FnMut(&Path) -> Result<(String, u64), String>, +) -> Result, String> { + let mut totals = BTreeMap::::new(); + for target in targets { + let (key, capacity) = volume(&target.path)?; + if capacity == 0 { + return Err("Cannot establish a nonzero volume capacity".into()); + } + let total = totals.entry(key).or_insert((0, capacity)); + total.0 = total + .0 + .checked_add(target.bytes) + .ok_or("Removal size overflow")?; + total.1 = total.1.min(capacity); + } + Ok(totals + .into_iter() + .map(|(volume, (bytes, capacity))| Usage { + volume, + bytes, + capacity, + }) + .collect()) +} + +/// The volume removing `path` gives space back on: its key and capacity. +pub fn volume_of(path: &Path) -> Result<(String, u64), String> { + let path = volume_entry(path)?; + let volume = crate::space::device_for(path) + .ok_or("Cannot identify the removal target's volume")?; + let space = crate::space::space_info(path) + .map_err(|error| format!("Cannot read volume capacity: {error}"))?; + Ok((volume, space.total)) +} + +/// The path whose volume removing `path` frees. +/// +/// That is `path` itself, or its directory for a link: removal unlinks the +/// entry itself, even when its destination is missing or lies on another +/// volume. Windows also requires a directory for `GetDiskFreeSpaceExW`, +/// including regular files. +pub fn volume_entry(path: &Path) -> Result<&Path, String> { + let meta = std::fs::symlink_metadata(path) + .map_err(|error| format!("Cannot inspect removal target: {error}"))?; + if meta.is_symlink() || (cfg!(windows) && meta.is_file()) { + path.parent().ok_or_else(|| { + "A removal entry must have a parent directory".into() + }) + } else { + Ok(path) + } +} + +/// Re-measure on the worker before any target is touched. A scan may have +/// hidden entries skipped, a depth limit, or sizes that have since grown. +pub(crate) fn measured(targets: &[Target]) -> Result, String> { + targets.iter().map(|target| { + let meta = std::fs::symlink_metadata(&target.path) + .map_err(|error| format!("Cannot re-measure {}: {error}", target.path.display()))?; + if meta.is_dir() != target.is_dir { + return Err(format!("Target type changed: {}", target.path.display())); + } + let bytes = if meta.is_dir() { + let tree = crate::scan::scan(&target.path, crate::scan::ScanOptions { + dedup_hardlinks: false, + apfs_clone_metadata: false, + ..crate::scan::ScanOptions::default() + }).map_err(|error| format!("Cannot re-measure removal: {error}"))?; + let mut nodes = vec![tree.root()]; + while let Some(node) = nodes.pop() { + if node.read_error { + return Err("Cannot enforce removal limit: part of the selection is unreadable".into()); + } + nodes.extend(node.children()); + } + tree.root().bytes + } else { + #[cfg(windows)] + let bytes = crate::windows::allocated_size(&target.path) + .map_err(|error| format!("Cannot re-measure {}: {error}", target.path.display()))?; + #[cfg(not(windows))] + let bytes = crate::scan::measure(&meta, false); + bytes + }; + Ok(Target { bytes: bytes.max(target.bytes), ..target.clone() }) + }).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn target(path: &str, bytes: u64) -> Target { + Target { + path: path.into(), + bytes, + is_dir: true, + hidden: false, + } + } + + #[test] + fn boundary_is_inclusive_and_sums_targets_per_volume() { + let limit = Limit::default(); + let targets = [target("a", 20), target("b", 30)]; + assert_eq!( + limit + .check_with(&targets, |_| Ok(("disk".into(), 1000))) + .expect("5% boundary")[0] + .bytes, + 50 + ); + assert!( + limit + .check_with(&[target("a", 51)], |_| Ok(("disk".into(), 1000))) + .is_err() + ); + assert!( + limit + .check_with(&targets, |path| Ok(( + path.display().to_string(), + 600 + ))) + .is_ok() + ); + assert!( + limit + .check_with(&targets, |_| Err("unknown volume".into())) + .is_err() + ); + assert!( + limit + .check_with(&targets, |_| Ok(("disk".into(), 0))) + .is_err() + ); + assert!( + limit + .check_with(&[target("a", u64::MAX), target("b", 1)], |_| Ok(( + "disk".into(), + u64::MAX + ))) + .is_err() + ); + assert!(Limit::new(0).is_err()); + assert!(Limit::new(101).is_err()); + } + + /// Two 1000-byte disks, told apart by the path's first component, as a + /// scan of `/` with a USB disk mounted inside it would see them. + fn two_disks(path: &Path) -> Result<(String, u64), String> { + let disk = path + .components() + .next() + .ok_or("no volume")? + .as_os_str() + .to_string_lossy() + .into_owned(); + Ok((disk, 1000)) + } + + #[test] + fn a_confirmed_share_raises_only_its_own_volume() { + let targets = [target("boot/a", 200), target("usb/b", 190)]; + // One percent for every volume was the gap: 20% confirmed for the + // boot disk let 19% of the USB disk through unasked. + assert!( + Limit::new(20) + .expect("20%") + .check_with(&targets, two_disks) + .is_ok() + ); + let boot = Ceilings::from(Limit::default()) + .raise("boot".into(), Limit::new(20).expect("20%")); + let refused = boot + .check_with(&targets, two_disks) + .expect_err("the USB disk is still held to 5%"); + assert!(refused.contains("on usb"), "{refused}"); + assert!(refused.contains("5% per-operation"), "{refused}"); + + let both = boot.raise("usb".into(), Limit::new(19).expect("19%")); + let budgets = both.check_with(&targets, two_disks).expect("confirmed"); + assert_eq!( + budgets + .iter() + .map(|budget| (budget.volume.as_str(), budget.limit)) + .collect::>(), + [("boot", 200), ("usb", 190)] + ); + // Each volume's ceiling is its own: growth on either is refused. + let grown = [target("boot/a", 200), target("usb/b", 191)]; + assert!(both.check_with(&grown, two_disks).is_err()); + let grown = [target("boot/a", 201), target("usb/b", 190)]; + assert!(both.check_with(&grown, two_disks).is_err()); + } + + #[test] + fn raising_never_lowers_a_volume_below_the_base() { + let ten = Limit::new(10).expect("10%"); + let ceilings = Ceilings::from(ten) + .raise("boot".into(), Limit::new(5).expect("5%")) + .raise("usb".into(), Limit::new(30).expect("30%")); + assert_eq!(ceilings.of("boot"), ten); + assert_eq!(ceilings.of("usb").percent(), 30); + assert_eq!(ceilings.of("elsewhere"), ten); + assert_eq!( + ceilings, + Ceilings::from(ten) + .raise("usb".into(), Limit::new(30).expect("30%")) + ); + } + + #[test] + fn usage_groups_by_volume_as_the_check_does() { + let targets = [ + target("usb/b", 190), + target("boot/a", 150), + target("boot/c", 50), + ]; + assert_eq!( + usage(&targets, two_disks).expect("usage"), + [ + Usage { + volume: "boot".into(), + bytes: 200, + capacity: 1000 + }, + Usage { + volume: "usb".into(), + bytes: 190, + capacity: 1000 + }, + ] + ); + // A volume read with two capacities keeps the smaller. + let mut capacities = [1000, 400].into_iter(); + let shrinking = |path: &Path| { + two_disks(path) + .map(|(disk, _)| (disk, capacities.next().expect("two reads"))) + }; + assert_eq!( + usage(&[target("boot/a", 1), target("boot/b", 1)], shrinking) + .expect("usage")[0] + .capacity, + 400 + ); + assert!(usage(&targets, |_| Ok(("disk".into(), 0))).is_err()); + } + + #[test] + fn preflight_includes_hidden_entries_and_growth_since_marking() { + let temp = tempfile::tempdir().expect("fixture"); + let dir = temp.path().join("selected"); + std::fs::create_dir(&dir).expect("mkdir"); + std::fs::write(dir.join(".hidden"), vec![b'x'; 16_384]).expect("write"); + let measured = measured(&[Target { + path: dir, + bytes: 0, + is_dir: true, + hidden: false, + }]) + .expect("measure"); + assert!(measured[0].bytes >= 16_384); + assert!( + Limit::default() + .check_with(&measured, |_| Ok(("fixture".into(), 100_000))) + .is_err() + ); + assert!(temp.path().join("selected/.hidden").exists()); + } + + #[test] + fn regular_file_capacity_uses_its_containing_volume() { + let temp = tempfile::tempdir().expect("fixture"); + let path = temp.path().join("selected.txt"); + let content = vec![b'x'; 1_000]; + std::fs::write(&path, &content).expect("fixture file"); + let targets = [Target { + path: path.clone(), + bytes: 1_000, + is_dir: false, + hidden: false, + }]; + let budgets = Limit::default() + .check(&targets) + .expect("file capacity preflight"); + assert_eq!(budgets.len(), 1); + assert_eq!( + budgets[0].volume, + crate::space::device_for(temp.path()).expect("parent volume") + ); + assert_eq!( + budgets[0].capacity, + crate::space::space_info(temp.path()) + .expect("parent capacity") + .total + ); + assert_eq!(budgets[0].bytes, 1_000); + assert_eq!(std::fs::read(path).expect("file untouched"), content); + } + + #[cfg(unix)] + #[test] + fn dangling_links_use_the_containing_volume() { + let temp = tempfile::tempdir().expect("fixture"); + let link = temp.path().join("dangling"); + std::os::unix::fs::symlink("missing/destination", &link) + .expect("fixture link"); + let targets = [Target { + path: link.clone(), + bytes: 0, + is_dir: false, + hidden: false, + }]; + let limit = Limit::default(); + let budget = limit.check(&targets).expect("link preview"); + assert_eq!( + budget[0].volume, + crate::space::device_for(temp.path()).expect("parent volume") + ); + assert_eq!( + budget[0].capacity, + crate::space::space_info(temp.path()) + .expect("capacity") + .total + ); + let fresh = measured(&targets).expect("link measurement"); + limit.check(&fresh).expect("link worker preflight"); + assert_eq!( + std::fs::read_link(link).expect("link untouched"), + Path::new("missing/destination") + ); + } + + #[cfg(windows)] + #[test] + fn sparse_file_preflight_uses_allocation() { + let temp = tempfile::tempdir().expect("fixture"); + let path = temp.path().join("sparse.bin"); + let file = std::fs::File::create(&path).expect("fixture file"); + let output = std::process::Command::new("fsutil") + .args(["sparse", "setflag"]) + .arg(&path) + .output() + .expect("set fixture sparse flag"); + assert!(output.status.success(), "{output:?}"); + file.set_len(64 * 1024 * 1024).expect("sparse length"); + drop(file); + assert_file_preflight_uses_allocation(&path); + } + + #[cfg(windows)] + #[test] + fn compressed_file_preflight_uses_allocation() { + let temp = tempfile::tempdir().expect("fixture"); + let path = temp.path().join("compressed.bin"); + std::fs::write(&path, vec![b'x'; 4 * 1024 * 1024]) + .expect("fixture file"); + let output = std::process::Command::new("compact") + .args(["/C", "/I", "/Q"]) + .arg(&path) + .output() + .expect("compress fixture"); + assert!(output.status.success(), "{output:?}"); + assert_file_preflight_uses_allocation(&path); + } + + #[cfg(windows)] + fn assert_file_preflight_uses_allocation(path: &Path) { + let parent = path.parent().expect("fixture parent"); + let tree = + crate::scan::scan(parent, crate::scan::ScanOptions::default()) + .expect("directory measurement"); + let tree = tree.root(); + let length = std::fs::metadata(path).expect("metadata").len(); + let targets = [Target { + path: path.into(), + bytes: tree.bytes, + is_dir: false, + hidden: false, + }]; + let fresh = measured(&targets).expect("individual file preflight"); + assert_eq!(fresh[0].bytes, tree.bytes); + assert!( + fresh[0].bytes < length, + "fixture allocation {} must be below logical length {length}", + fresh[0].bytes + ); + // Compression ratios depend on cluster and compression-unit sizes. + // Place the budget just below logical length so allocation fits + // without requiring a particular ratio from the fixture volume. + let capacity = (length - 1) * 100 / u64::from(DEFAULT_PERCENT); + let limit = Limit::default(); + limit + .check_with(&fresh, |_| Ok(("fixture".into(), capacity))) + .expect("allocated size fits the budget"); + assert!( + limit + .check_with( + &[Target { + bytes: length, + ..targets[0].clone() + }], + |_| Ok(("fixture".into(), capacity)) + ) + .is_err(), + "logical length would incorrectly refuse the file" + ); + assert!(path.exists(), "measurement leaves the fixture intact"); + } +} diff --git a/crates/disktree-core/src/scan.rs b/crates/disktree-core/src/scan.rs index 5ffe81a0..33dc8bd4 100644 --- a/crates/disktree-core/src/scan.rs +++ b/crates/disktree-core/src/scan.rs @@ -7,9 +7,10 @@ //! * every directory is a `PendingDir` with an atomic completion counter and a //! `+1` sentinel, so a directory is only built once its own scan *and* all of //! its subdirectory tasks have finished, -//! * children are handed to the parent as finished `Node`s and sizes are -//! aggregated bottom-up in one pass over the finished tree, which is also -//! where hardlinks are de-duplicated. +//! * children are handed to the parent as finished nodes, appended to the +//! tree's buffers (see [`crate::index`]), and sizes are aggregated +//! bottom-up in one pass over the finished tree, which is also where +//! hardlinks are de-duplicated. //! //! What is added on top of dust's approach: live progress counters the UI can //! poll without locking, and cooperative cancellation so a re-scan can abandon @@ -30,7 +31,9 @@ use rayon::Scope; use rustc_hash::FxHashSet; use crate::scan_threads::{Admission, ControllerGuard, ScanThreads}; -use crate::tree::{Metric, Node, NodeKind, Seen, aggregate, aggregate_deduped}; +use crate::tree::{ + Builder, Built, Metric, NodeKind, Seen, Tree, aggregate, aggregate_deduped, +}; /// Errors kept verbatim before the list is truncated; the count keeps rising. const MAX_ERROR_DETAIL: usize = 50; @@ -42,6 +45,9 @@ pub struct ScanOptions { /// what `ls -l` shows; blocks are what the volume actually spends, which is /// what a disk-space tool normally wants. pub apparent_size: bool, + /// Read APFS clone hints and private sizes on macOS. + #[serde(default = "clone_metadata_default")] + pub apfs_clone_metadata: bool, /// Follow symlinks. Off by default: a home directory is full of links, and /// following them double-counts. pub follow_links: bool, @@ -66,10 +72,16 @@ pub struct ScanOptions { pub threads: ScanThreads, } +// Existing SSH requests predate this optional local-macOS scan hint. +const fn clone_metadata_default() -> bool { + true +} + impl Default for ScanOptions { fn default() -> Self { Self { apparent_size: false, + apfs_clone_metadata: clone_metadata_default(), follow_links: false, include_hidden: true, one_filesystem: true, @@ -92,7 +104,11 @@ pub struct ScanProgress { dirs: AtomicU64, bytes: AtomicU64, errors: AtomicU64, + service_errors: AtomicU64, + service_root: OnceLock, finished: AtomicBool, + finalizing: AtomicBool, + volume_used: OnceLock, cancelled: AtomicBool, messages: Mutex>, preview_root: OnceLock, @@ -111,7 +127,13 @@ pub struct ScanSnapshot { pub dirs: u64, pub bytes: u64, pub errors: u64, + /// Service-store failures remain errors, but do not request disk access. + pub service_errors: u64, pub finished: bool, + /// Enumeration is over; totals, sharing and categories are being built. + pub finalizing: bool, + /// Used space at scan start, only when scanning a whole volume. + pub volume_used: Option, pub cancelled: bool, /// Admitted directory jobs, not a machine-wide thread limit. pub threads: usize, @@ -166,6 +188,12 @@ impl ScanProgress { } fn record_error(&self, path: &Path, error: &io::Error) { + if crate::macos_services::is_service_path(path) + || self.service_root.get().is_some_and(|root| root == path) + { + // These optional measurements must not introduce an access nag. + self.service_errors.fetch_add(1, Ordering::Relaxed); + } self.errors.fetch_add(1, Ordering::Relaxed); // A scan without Full Disk Access can refuse thousands of paths; // only the ones that will be kept are worth formatting. @@ -196,7 +224,10 @@ impl ScanProgress { dirs: self.dirs.load(Ordering::Relaxed), bytes: self.bytes.load(Ordering::Relaxed), errors: self.errors.load(Ordering::Relaxed), + service_errors: self.service_errors.load(Ordering::Relaxed), finished: self.finished.load(Ordering::Relaxed), + finalizing: self.finalizing.load(Ordering::Relaxed), + volume_used: self.volume_used.get().copied(), cancelled: self.is_cancelled(), threads: self.threads.load(Ordering::Relaxed), threads_settled: self.threads_settled.load(Ordering::Relaxed), @@ -214,7 +245,7 @@ impl ScanProgress { #[derive(Debug)] pub struct ScanHandle { pub progress: Arc, - result: Receiver>, + result: Receiver>, } /// A subtree already measured, reused by a wider scan instead of walked @@ -224,7 +255,7 @@ pub struct Known { /// Where it is. Compared with the walk's own paths, so give it in the /// same form as the root (both canonical). pub path: PathBuf, - pub tree: Arc, + pub tree: Arc, } impl ScanHandle { @@ -247,9 +278,12 @@ impl ScanHandle { root_device: Mutex::new(None), foreign_mounts: OnceLock::new(), never_scanned: OnceLock::new(), + data_services: OnceLock::new(), + data_device: OnceLock::new(), visited_dirs: Mutex::new(FxHashSet::default()), - root: Mutex::new(None), volume: OnceLock::new(), + #[cfg(target_os = "macos")] + clone_cache: crate::clone_cache::Cache::default(), }); let (sender, result) = mpsc::channel(); @@ -271,7 +305,7 @@ impl ScanHandle { } /// Take the finished tree, if the walk is done. - pub fn poll(&self) -> Option> { + pub fn poll(&self) -> Option> { match self.result.try_recv() { Ok(outcome) => Some(outcome), Err(TryRecvError::Empty) => None, @@ -288,7 +322,7 @@ impl ScanHandle { } /// Walk `root` and return the aggregated tree. Blocking. -pub fn scan(root: &Path, options: ScanOptions) -> io::Result { +pub fn scan(root: &Path, options: ScanOptions) -> io::Result { let progress = Arc::new(ScanProgress::default()); let context = Arc::new(WalkContext { known: None, @@ -297,9 +331,12 @@ pub fn scan(root: &Path, options: ScanOptions) -> io::Result { root_device: Mutex::new(None), foreign_mounts: OnceLock::new(), never_scanned: OnceLock::new(), + data_services: OnceLock::new(), + data_device: OnceLock::new(), visited_dirs: Mutex::new(FxHashSet::default()), - root: Mutex::new(None), volume: OnceLock::new(), + #[cfg(target_os = "macos")] + clone_cache: crate::clone_cache::Cache::default(), }); let node = scan_blocking(root, &context)?; progress.finish(); @@ -320,14 +357,17 @@ struct WalkContext { /// Directories no scan enters, on any volume setting: see /// [`crate::space::never_scanned`]. never_scanned: OnceLock>, + /// A second Data mount exposes private stores, never firmlink aliases. + data_services: OnceLock, + data_device: OnceLock>, /// Directories already entered, so followed symlinks cannot loop. visited_dirs: Mutex>, - /// Set by the root's `complete`, read after the scope joins. - root: Mutex>, /// Serial number of the root's volume, on Windows, for a walk that /// cannot leave it: every listing takes it instead of asking. See /// [`crate::windows::walk_volume`]. volume: OnceLock, + #[cfg(target_os = "macos")] + clone_cache: crate::clone_cache::Cache, } impl WalkContext { @@ -349,13 +389,13 @@ impl WalkContext { /// /// The entry's path is built only where it is used: most entries are /// files, and a disk has millions of them. The name is moved out of - /// the entry last, so nothing copies it. + /// the entry last, so it is copied only once, into the tree's names. fn classify(&self, dir: &Path, entry: &mut impl Listed) -> Classified { let listing = match entry.listing() { Ok(listing) => listing, Err(error) => { self.progress.record_error(&entry.entry_path(dir), &error); - return Classified::Skipped; + return Classified::Unreadable; } }; @@ -376,11 +416,11 @@ impl WalkContext { } Listing::Leaf(kind) => kind, }; - match entry.facts(self.options.apparent_size) { - Ok(facts) => self.leaf(entry.take_name(), kind, &facts), + match entry.facts(dir, self.options.apparent_size, self) { + Ok(facts) => self.leaf(entry.take_name(), kind, facts), Err(error) => { self.progress.record_error(&entry.entry_path(dir), &error); - Classified::Skipped + Classified::Unreadable } } } @@ -397,6 +437,15 @@ impl WalkContext { { return Classified::Skipped; } + if self.data_services.get() == Some(&path) { + // `/` presents the system volume beside Data. This one mount + // exception is constrained by the whitelist in `walk`. + return Classified::Subdirectory { + path, + name: entry.take_name(), + followed: false, + }; + } if self.options.one_filesystem && let Some(foreign) = self.foreign_mounts.get() { @@ -419,17 +468,26 @@ impl WalkContext { return Classified::Skipped; } // Memoized: the subtree a narrower scan already measured is taken - // whole, before any volume rule, since it was measured under the same - // rules. + // whole after mount boundaries, since a cached subtree cannot make + // crossing a mount allowed. if let Some(known) = &self.known && known.path == path { - let mut tree = (*known.tree).clone(); - tree.name = entry.take_name(); - return Classified::Entry(tree); + return Classified::Known(entry.take_name()); } if self.options.one_filesystem && self.foreign_mounts.get().is_none() { - match (directory(), self.root_device(&path)) { + let device = if let Some(data) = self + .data_services + .get() + .filter(|data| path.starts_with(data)) + { + *self.data_device.get_or_init(|| { + fs::metadata(data).map(|meta| device_of(&meta)).ok() + }) + } else { + self.root_device(&path) + }; + match (directory(), device) { (Ok(directory), Some(root_device)) if directory.device != root_device => { @@ -437,7 +495,7 @@ impl WalkContext { } (Err(error), _) => { self.progress.record_error(&path, error); - return Classified::Skipped; + return Classified::Unreadable; } _ => {} } @@ -445,6 +503,7 @@ impl WalkContext { Classified::Subdirectory { path, name: entry.take_name(), + followed: false, } } @@ -458,13 +517,13 @@ impl WalkContext { Classified::Entry(leaf_node( name, NodeKind::Symlink, - &facts, + facts, facts.shared, )) } Err(error) => { self.progress.record_error(path, &error); - Classified::Skipped + Classified::Unreadable } }; } @@ -475,6 +534,7 @@ impl WalkContext { // A dangling link is normal, not an error worth counting. if error.kind() != io::ErrorKind::NotFound { self.progress.record_error(path, &error); + return Classified::Unreadable; } return Classified::Skipped; } @@ -494,6 +554,7 @@ impl WalkContext { return Classified::Subdirectory { path: path.to_path_buf(), name, + followed: true, }; } @@ -501,15 +562,17 @@ impl WalkContext { // What the link leads to, so a file that is also reached directly is // charged once. facts.identity = identity_of(path, &meta); - self.leaf(name, kind_of(&meta, meta.file_type()), &facts) + #[cfg(target_os = "macos")] + if self.options.apfs_clone_metadata && !self.options.apparent_size { + facts.clone_info = fs::canonicalize(path) + .ok() + .and_then(|target| crate::macos::clone_info(&target, &meta)); + } + facts.followed = true; + self.leaf(name, kind_of(&meta, meta.file_type()), facts) } - fn leaf( - &self, - name: Box, - kind: NodeKind, - facts: &Facts, - ) -> Classified { + fn leaf(&self, name: Box, kind: NodeKind, facts: Facts) -> Classified { // A followed link reaches a file a second way, whatever its link // count says. let track = self.options.follow_links || facts.shared; @@ -536,7 +599,12 @@ trait Listed { fn take_name(&mut self) -> Box; fn listing(&self) -> io::Result; /// Size, identity and age of a leaf. - fn facts(&self, apparent_size: bool) -> io::Result; + fn facts( + &self, + _dir: &Path, + apparent_size: bool, + _context: &WalkContext, + ) -> io::Result; /// What a directory is, read before the walk enters it. fn directory(&self) -> io::Result; /// Hidden by an attribute rather than by a leading dot: on Windows, @@ -572,6 +640,7 @@ enum Listing { } /// What a leaf contributes. +#[derive(Clone, Copy)] struct Facts { size: u64, identity: Option<(u64, u64)>, @@ -579,6 +648,9 @@ struct Facts { /// The file may have another name the walk could meet: its identity is /// worth keeping for hardlink de-duplication. shared: bool, + clone_info: Option, + links: u64, + followed: bool, } impl Facts { @@ -588,10 +660,24 @@ impl Facts { identity: file_identity(meta), modified: modified_seconds(meta), shared: shares_inode(meta), + clone_info: None, + links: link_count(meta), + followed: false, } } } +#[cfg(unix)] +fn link_count(meta: &Metadata) -> u64 { + use std::os::unix::fs::MetadataExt as _; + meta.nlink() +} + +#[cfg(not(unix))] +const fn link_count(_meta: &Metadata) -> u64 { + 1 +} + /// A standard directory entry with its name decoded once, up front. #[cfg(not(any(windows, target_os = "macos")))] struct Named { @@ -626,10 +712,14 @@ impl Listed for Named { }) } - fn facts(&self, apparent_size: bool) -> io::Result { - self.entry - .metadata() - .map(|meta| Facts::of(&meta, apparent_size)) + fn facts( + &self, + _dir: &Path, + apparent_size: bool, + _context: &WalkContext, + ) -> io::Result { + let meta = self.entry.metadata()?; + Ok(Facts::of(&meta, apparent_size)) } fn directory(&self) -> io::Result { @@ -663,7 +753,12 @@ impl Listed for crate::macos::Entry { }) } - fn facts(&self, apparent_size: bool) -> io::Result { + fn facts( + &self, + dir: &Path, + apparent_size: bool, + context: &WalkContext, + ) -> io::Result { Ok(Facts { size: if apparent_size { self.apparent() @@ -673,6 +768,13 @@ impl Listed for crate::macos::Entry { identity: Some(self.identity()), modified: self.modified(), shared: self.shared(), + clone_info: if apparent_size { + None + } else { + self.clone_info(dir, &context.clone_cache) + }, + links: self.links(), + followed: false, }) } @@ -706,7 +808,12 @@ impl Listed for crate::windows::Entry { }) } - fn facts(&self, apparent_size: bool) -> io::Result { + fn facts( + &self, + _dir: &Path, + apparent_size: bool, + _context: &WalkContext, + ) -> io::Result { Ok(Facts { size: if apparent_size { self.apparent() @@ -718,6 +825,9 @@ impl Listed for crate::windows::Entry { // The listing has no link count; a file id is free here, so // every file keeps one. shared: true, + clone_info: None, + links: 1, + followed: false, }) } @@ -741,8 +851,11 @@ impl Listed for crate::windows::Entry { fn list( path: &Path, _volume: Option, + _clones: bool, + _clone_flags: bool, ) -> io::Result>> { - Ok(fs::read_dir(path)?.map(|entry| { + let entries = fs::read_dir(path)?; + Ok(entries.map(|entry| { entry.map(|entry| Named { name: entry.file_name().into_string().map_or_else( |raw| raw.to_string_lossy().into(), @@ -757,14 +870,26 @@ fn list( fn list( path: &Path, _volume: Option, + clones: bool, + clone_flags: bool, ) -> io::Result { - crate::macos::read_dir(path) + use crate::macos::Clones; + crate::macos::read_dir( + path, + match (clones, clone_flags) { + (false, _) => Clones::Off, + (true, false) => Clones::Ids, + (true, true) => Clones::Flags, + }, + ) } #[cfg(windows)] fn list( path: &Path, volume: Option, + _clones: bool, + _clone_flags: bool, ) -> io::Result { crate::windows::read_dir(path, volume) } @@ -772,37 +897,49 @@ fn list( /// What a directory entry turned out to be. enum Classified { /// Descend into this directory on a new task. - Subdirectory { path: PathBuf, name: Box }, + Subdirectory { + path: PathBuf, + name: Box, + followed: bool, + }, /// A leaf that contributes size. - Entry(Node), - /// Filtered out, unreadable, or a symlink we chose not to follow. + Entry(Leaf), + /// The directory [`Known`] holds, copied in under this name. + Known(Box), + /// Filtered out, or a symlink we chose not to follow. Skipped, + /// Collection failed, rather than an intentional filter. + Unreadable, } /// One directory being walked, plus the counter that decides when it is done. #[derive(Debug)] -struct PendingDir { +struct PendingDir<'h> { path: PathBuf, parent: Option>, /// Starts at 1 for the directory itself; one more per subdirectory task. /// When it reaches zero the directory is complete. pending: AtomicUsize, /// The node so far, moved out whole once the directory is complete. - partial: Mutex, + partial: Mutex>, read_error: AtomicBool, depth: usize, + followed: bool, + /// Whether its listing asks for APFS sharing flags; see + /// [`subdirectory_flags`]. + clone_flags: bool, } /// What a directory's node is made of before it is built: the name the /// listing gave it, and the files found directly in it plus the finished /// subdirectories handed back up. #[derive(Debug, Default)] -struct Partial { +struct Partial<'h> { name: Box, - children: Vec, + children: Vec>, } -impl PendingDir { +impl<'h> PendingDir<'h> { const fn new( path: PathBuf, name: Box, @@ -819,6 +956,8 @@ impl PendingDir { }), read_error: AtomicBool::new(false), depth, + followed: false, + clone_flags: true, } } @@ -828,25 +967,32 @@ impl PendingDir { /// `bytes` is left at zero on purpose: the walk cannot know the /// aggregate, and [`crate::tree::aggregate`] derives it from the children /// once every child is present. - fn build(&self) -> Node { + fn build(&self, builder: &'h Builder) -> Built<'h> { let partial = std::mem::take(&mut *lock(&self.partial)); - Node { - name: partial.name, - kind: NodeKind::Directory, - bytes: 0, - files: 0, - dirs: 1, - inode: None, + let facts = crate::tree::Facts { read_error: self.read_error.load(Ordering::Relaxed), - modified: 0, - category: crate::classify::Category::Other, - reclaim: None, - children: partial.children, - } + ..crate::tree::Facts::directory() + }; + let allocation = self.followed.then_some(crate::sharing::Allocation { + bytes: 0, + identity: None, + links: 1, + followed: true, + clone: None, + }); + builder.directory(&partial.name, facts, allocation, partial.children) } } -fn scan_blocking(root: &Path, context: &Arc) -> io::Result { +/// Where the walk's finished nodes go: the tree they are made in, and +/// the root once the last directory completes. +struct Sink<'h> { + builder: &'h Builder, + /// Set by the root's `signal_done`, read after the scope joins. + root: Mutex>>, +} + +fn scan_blocking(root: &Path, context: &Arc) -> io::Result { let _ = context.progress.preview_root.set(root.to_path_buf()); let owned = fixed_pool(context.options.threads)?; let pool = owned.as_ref().unwrap_or_else(|| &WALK_POOL); @@ -873,7 +1019,7 @@ fn scan_on_pool( root: &Path, context: &Arc, pool: &rayon::ThreadPool, -) -> io::Result { +) -> io::Result { let root_meta = fs::metadata(root)?; if !root_meta.is_dir() { return Err(io::Error::new( @@ -883,6 +1029,20 @@ fn scan_on_pool( } let resolved = root.canonicalize().ok(); let canonical = resolved.as_deref().unwrap_or(root); + if let Some(used) = crate::space::scan_volume_used( + canonical, + crate::space::volume_root_for(canonical).as_deref(), + crate::space::space_info(canonical).ok(), + std::env::consts::OS, + ) { + let _ = context.progress.volume_used.set(used); + } + if let Some(data) = crate::space::data_services_only(root, canonical) { + let _ = context.data_services.set(data); + } + if let Some(data) = context.data_services.get() { + let _ = context.progress.service_root.set(data.clone()); + } let mut never = crate::space::never_scanned(root, canonical); // Hidden-entry and depth filters can leave an alias as the only route // to files. Keep every mount view when either filter is active. @@ -915,10 +1075,12 @@ fn scan_on_pool( if progress.is_cancelled() { return Err(crate::mft::cancelled()); } - let node = finish_tree(node, &context.options, pool); + progress.finalizing.store(true, Ordering::Relaxed); + let node = finish_tree(node, canonical, &context.options, pool); // The reader counted every file on the volume; the tree may // hold fewer. - progress.settle(node.files, u64::from(node.dirs), node.bytes); + let root = node.root(); + progress.settle(root.files, u64::from(root.dirs), root.bytes); return Ok(node); } // The reader gave up, or never started: the walk counts from nothing. @@ -940,13 +1102,35 @@ fn scan_on_pool( lock(&context.visited_dirs).insert(key); } + let context: &WalkContext = context; + let tree = Tree::try_build(|builder| { + let sink = Sink { + builder, + root: Mutex::new(None), + }; + walk_tree(root, context, pool, &sink)?; + let node = lock(&sink.root).take(); + node.ok_or_else(|| { + io::Error::other(format!("{} produced no tree", root.display())) + }) + })?; + context.progress.finalizing.store(true, Ordering::Relaxed); + Ok(finish_tree(tree, canonical, &context.options, pool)) +} + +/// Walk from `root` on `pool`, leaving the finished root in `sink`. +fn walk_tree( + root: &Path, + context: &WalkContext, + pool: &rayon::ThreadPool, + sink: &Sink<'_>, +) -> io::Result<()> { let root_dir = Arc::new(PendingDir::new( root.to_path_buf(), file_name(root), None, 0, )); - let context: &WalkContext = context; pool.install(|| { let mut threads = context.options.threads.normalized(); threads.max_threads = @@ -969,30 +1153,34 @@ fn scan_on_pool( // Pool-sized fixed scans need no admission lock or ready queue. Keep // existing core callers on Rayon's direct scheduling path. rayon::scope(|scope| { - dispatch_fixed(scope, &root_dir, context); + dispatch_fixed(scope, &root_dir, context, sink); }); } else { let admission = Arc::new(Admission::new(root_dir, threads.max_threads)); // The controller owns no Rayon worker and is joined before finishing // the tree, where entry throughput no longer describes useful work. - let _controller = ControllerGuard::spawn( - threads, - Arc::clone(&admission), - Arc::clone(&context.progress), - )?; - rayon::scope(|scope| { - dispatch(scope, admission.start(), context, &admission); - }); + thread::scope(|controller| { + let _controller = ControllerGuard::spawn( + controller, + threads, + Arc::clone(&admission), + Arc::clone(&context.progress), + )?; + rayon::scope(|scope| { + dispatch( + scope, + admission.start(), + context, + &admission, + sink, + ); + }); + Ok::<(), io::Error>(()) + })?; } - Ok::<(), io::Error>(()) - })?; - - let node = lock(&context.root).take(); - let node = node.ok_or_else(|| { - io::Error::other(format!("{} produced no tree", root.display())) - })?; - Ok(finish_tree(node, &context.options, pool)) + Ok(()) + }) } /// The walk's workers, and the file table reader's. Listing directories @@ -1031,8 +1219,8 @@ struct Tally { } impl Tally { - const fn add(&mut self, node: &Node) { - if node.is_dir() { + const fn add(&mut self, node: &crate::tree::Facts) { + if node.kind.is_dir() { // A subtree taken whole from an earlier scan. self.files += node.files; self.dirs += node.dirs as u64; @@ -1054,14 +1242,15 @@ impl Tally { /// Read one directory, spawn a task per subdirectory, then report completion. /// /// Flat tasks inside the scope: the worker stack never grows with tree depth. -fn dispatch_fixed<'scope>( +fn dispatch_fixed<'scope, 'h: 'scope>( scope: &Scope<'scope>, - dir: &Arc, + dir: &Arc>, context: &'scope WalkContext, + sink: &'scope Sink<'h>, ) { - for child in walk(dir, context) { + for child in walk(dir, context, sink) { scope.spawn(move |scope| { - dispatch_fixed(scope, &child, context); + dispatch_fixed(scope, &child, context, sink); }); } } @@ -1069,40 +1258,55 @@ fn dispatch_fixed<'scope>( /// Read one directory, spawn a task per subdirectory, then report completion. /// /// Flat tasks inside the scope: the worker stack never grows with tree depth. -fn dispatch<'scope>( +fn dispatch<'scope, 'h: 'scope>( scope: &Scope<'scope>, - jobs: Vec>, + jobs: Vec>>, context: &'scope WalkContext, - admission: &Arc>>, + admission: &Arc>>>, + sink: &'scope Sink<'h>, ) { for dir in jobs { let admission = Arc::clone(admission); scope.spawn(move |scope| { let mut next = Some(dir); while let Some(dir) = next.take() { - let children = walk(&dir, context); + let children = walk(&dir, context, sink); let mut jobs = admission.complete(children); // Continue locally into one ready descendant; only surplus // jobs are offered to other workers. A running directory is // never split, and a retirement returns from this loop. next = jobs.pop(); - dispatch(scope, jobs, context, &admission); + dispatch(scope, jobs, context, &admission, sink); } }); } } -fn walk(dir: &Arc, context: &WalkContext) -> Vec> { +fn walk<'h>( + dir: &Arc>, + context: &WalkContext, + sink: &Sink<'h>, +) -> Vec>> { if context.cancelled() { // Queued jobs still own a pending token even when no I/O is needed. - signal_done(dir, context); + signal_done(dir, sink); return Vec::new(); } - let mut subdirs: Vec> = Vec::new(); - let mut leaves: Vec = Vec::new(); + let mut subdirs: Vec> = Vec::new(); + // Gathered first and added to the tree under one lock: every worker + // appends to the same buffers. + let mut found: Vec = Vec::new(); + let mut leaves: Vec> = Vec::new(); let mut tally = Tally::default(); - match list(&dir.path, context.volume.get().copied()) { + let clones = + context.options.apfs_clone_metadata && !context.options.apparent_size; + match list( + &dir.path, + context.volume.get().copied(), + clones, + dir.clone_flags, + ) { Ok(entries) => { for entry in entries { if context.cancelled() { @@ -1110,21 +1314,48 @@ fn walk(dir: &Arc, context: &WalkContext) -> Vec> { } match entry { Ok(mut entry) => { + if context.data_services.get() == Some(&dir.path) + && !crate::macos_services::is_service_name( + entry.name(), + ) + { + continue; + } match context.classify(&dir.path, &mut entry) { - Classified::Subdirectory { path, name } => { + Classified::Subdirectory { + path, + name, + followed, + } => { tally.dirs += 1; - subdirs.push(Arc::new(PendingDir::new( + let mut child = PendingDir::new( path, name, Some(Arc::clone(dir)), dir.depth + 1, - ))); + ); + child.followed = followed; + subdirs.push(child); + } + Classified::Entry(leaf) => { + tally.add(&leaf.facts); + found.push(leaf); } - Classified::Entry(node) => { + Classified::Known(name) => { + let known = context + .known + .as_ref() + .expect("only a known path is reused"); + let node = sink + .builder + .copy_named(known.tree.root(), &name); tally.add(&node); leaves.push(node); } Classified::Skipped => {} + Classified::Unreadable => { + dir.read_error.store(true, Ordering::Relaxed); + } } if tally.files + tally.dirs >= TALLY_EVERY { tally.flush(&context.progress, &dir.path); @@ -1132,6 +1363,7 @@ fn walk(dir: &Arc, context: &WalkContext) -> Vec> { } Err(error) => { context.progress.record_error(&dir.path, &error); + dir.read_error.store(true, Ordering::Relaxed); } } } @@ -1142,6 +1374,17 @@ fn walk(dir: &Arc, context: &WalkContext) -> Vec> { } } tally.flush(&context.progress, &dir.path); + let clone_flags = !clones + || always_flags() + || subdirectory_flags(dir.clone_flags, &found); + leaves.extend( + sink.builder.leaves( + found + .iter() + .map(|leaf| (&*leaf.name, leaf.facts, leaf.allocation)), + ), + ); + drop(found); // A depth-limited scan still measures what is directly in the directory, // it just does not descend further. @@ -1150,12 +1393,12 @@ fn walk(dir: &Arc, context: &WalkContext) -> Vec> { .max_depth .is_none_or(|max_depth| dir.depth < max_depth); // Sized once for the leaves and every subdirectory to come, before any - // subdirectory task can push its node: otherwise that first push - // doubles a list just sized to the leaves, and the slack stays in the - // finished tree. The leaves are copied, not moved: the list they grew - // in carries up to twice their size in slack, and moving it in whole - // made a home directory walk a second slower (measured, 5 interleaved - // pairs). + // subdirectory task can push its node, so no push grows the list + // again. The leaves are copied, not moved: the list they grew in + // carries up to twice their size in slack, which a pending directory + // would hold until its last subdirectory is done. Moving it in whole + // made a home directory walk a second slower (measured before the + // tree held its own buffers, 5 interleaved pairs). let spawned = if descend { subdirs.len() } else { 0 }; { let mut partial = lock(&dir.partial); @@ -1164,55 +1407,109 @@ fn walk(dir: &Arc, context: &WalkContext) -> Vec> { } let mut children = Vec::new(); if descend { - for subdir in subdirs { + for mut subdir in subdirs { if context.cancelled() { break; } dir.pending.fetch_add(1, Ordering::AcqRel); - children.push(subdir); + subdir.clone_flags = clone_flags; + children.push(Arc::new(subdir)); } } - signal_done(dir, context); + signal_done(dir, sink); children } +/// Every listing asks for sharing flags while this is set, as before +/// listings could leave them out: what tests compare the listing policy +/// against. Only the cost differs, so other tests may run beside it. +#[cfg(test)] +pub(crate) static ALWAYS_FLAGS: AtomicBool = AtomicBool::new(false); + +#[cfg(test)] +fn always_flags() -> bool { + ALWAYS_FLAGS.load(Ordering::Relaxed) +} + +#[cfg(not(test))] +const fn always_flags() -> bool { + false +} + +/// Whether the subdirectories of a directory whose files are `found` +/// list their files' APFS sharing flags. Without them a file whose clone +/// group the scan has not met is read on its own, as most clones are +/// anyway to measure their private size, and a file never cloned is read +/// for nothing; per file that read cost about twice what the flags cost a +/// clone in a listing (on a home Library, a folder of checkouts and agent +/// worktrees). Folders resemble their parents, so a directory whose files +/// are clones two to one or more lists its subdirectories without the +/// flags, and others with. A directory of no files passes its own on. +fn subdirectory_flags(own: bool, found: &[Leaf]) -> bool { + let (mut clones, mut plain) = (0_usize, 0_usize); + for leaf in found + .iter() + .filter(|leaf| leaf.facts.kind == NodeKind::File) + { + if leaf + .allocation + .as_ref() + .is_some_and(|allocation| allocation.clone.is_some()) + { + clones += 1; + } else { + plain += 1; + } + } + if clones + plain == 0 { + own + } else { + 2 * plain >= clones + } +} + /// Report that one task for `dir` is done: either its own scan, or one of its /// children. The last one to report builds the node and bubbles up. /// /// This is the whole reason for the `+1` sentinel: a directory is only built /// once its own scan *and* every subdirectory task has finished, no matter /// which of them lands last. -fn signal_done(dir: &Arc, context: &WalkContext) { +fn signal_done<'h>(dir: &Arc>, sink: &Sink<'h>) { if dir.pending.fetch_sub(1, Ordering::AcqRel) != 1 { return; } - let node = dir.build(); + let node = dir.build(sink.builder); let Some(parent) = &dir.parent else { - *lock(&context.root) = Some(node); + *lock(&sink.root) = Some(node); return; }; lock(&parent.partial).children.push(node); - signal_done(parent, context); + signal_done(parent, sink); } /// Charge a hardlinked file once, derive every aggregate from the result, /// then classify. On the walk's pool: the UI's own work on the global pool /// must not queue behind a scan finishing. fn finish_tree( - mut node: Node, + mut tree: Tree, + root: &Path, options: &ScanOptions, pool: &rayon::ThreadPool, -) -> Node { +) -> Tree { pool.install(|| { if options.dedup_hardlinks { - aggregate_deduped(&mut node, options.metric, &Seen::new()); + aggregate_deduped(&mut tree, options.metric, &Seen::new()); } else { - aggregate(&mut node, options.metric); + aggregate(&mut tree, options.metric); } - crate::classify::classify(&mut node); + crate::classify::classify_at( + &mut tree, + root, + crate::path_style::PathStyle::Native, + ); }); - node + tree } /// A leaf. Its identity is kept only when `track` says the walk could meet @@ -1221,17 +1518,39 @@ fn finish_tree( fn leaf_node( name: Box, kind: NodeKind, - facts: &Facts, + facts: Facts, track: bool, -) -> Node { - let mut node = Node::entry(name, kind, facts.size); +) -> Leaf { + let mut node = crate::tree::Facts::entry(kind, facts.size); if track { node.inode = facts .identity .and_then(|(device, file)| Some((device, NonZeroU64::new(file)?))); } node.modified = facts.modified; - node + let allocation = (facts.clone_info.is_some() + || facts.links > 1 + || facts.followed + || (track && cfg!(unix))) + .then_some(crate::sharing::Allocation { + bytes: facts.size, + identity: facts.identity, + links: facts.links, + followed: facts.followed, + clone: facts.clone_info, + }); + Leaf { + name, + facts: node, + allocation, + } +} + +/// A leaf as the listing found it, before it goes into the tree. +struct Leaf { + name: Box, + facts: crate::tree::Facts, + allocation: Option, } /// Last write time in Unix seconds, from the metadata the walk already has: @@ -1380,10 +1699,64 @@ pub(crate) fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { #[cfg(test)] mod tests { use super::*; - use crate::tree::Metric; + use crate::tree::{Metric, Node}; use std::fs; use tempfile::TempDir; + #[test] + fn subdirectories_list_sharing_flags_unless_clones_outnumber_files() { + let leaf = |kind, clone: bool| Leaf { + name: "leaf".into(), + facts: crate::tree::Facts::entry(kind, 4096), + allocation: clone.then(|| crate::sharing::Allocation { + bytes: 4096, + identity: None, + links: 1, + followed: false, + clone: Some(crate::sharing::CloneInfo::default()), + }), + }; + let files = |clones: usize, plain: usize| { + let mut found: Vec = (0..clones) + .map(|_| leaf(NodeKind::File, true)) + .chain((0..plain).map(|_| leaf(NodeKind::File, false))) + .collect(); + found.push(leaf(NodeKind::Symlink, false)); + found + }; + // No files: as the directory itself was listed. + for own in [false, true] { + assert_eq!(subdirectory_flags(own, &files(0, 0)), own); + } + assert!(subdirectory_flags(false, &files(0, 1))); + assert!(subdirectory_flags(false, &files(2, 1))); + assert!(!subdirectory_flags(true, &files(3, 1))); + assert!(!subdirectory_flags(true, &files(5, 0))); + } + + #[test] + fn optional_service_failures_remain_errors_without_requesting_access() { + let progress = ScanProgress::default(); + let data = PathBuf::from("/System/Volumes/Data"); + progress.service_root.set(data.clone()).unwrap(); + let denied = io::Error::from(io::ErrorKind::PermissionDenied); + for path in [ + data.clone(), + data.join(".fseventsd"), + data.join(".Spotlight-V100/Store-V2/index"), + ] { + progress.record_error(&path, &denied); + } + let snapshot = progress.snapshot(); + assert_eq!(snapshot.errors, 3); + assert_eq!(snapshot.service_errors, 3); + assert_eq!(snapshot.messages.len(), 3); + progress.record_error(Path::new("/Users/me/Library/Mail"), &denied); + let snapshot = progress.snapshot(); + assert_eq!(snapshot.errors, 4); + assert_eq!(snapshot.service_errors, 3); + } + /// Apparent sizes, so the assertions are about the tree rather than about /// how the filesystem rounds a small file up to a block. fn options() -> ScanOptions { @@ -1400,19 +1773,84 @@ mod tests { path } - fn scan_dir(root: &Path, options: &ScanOptions) -> Node { + #[test] + fn scan_options_accept_requests_without_optional_clone_metadata() { + let mut request = serde_json::to_value(ScanOptions::default()) + .expect("scan options JSON"); + let options = request.as_object_mut().expect("options object"); + options.remove("apfs_clone_metadata"); + let decoded: ScanOptions = serde_json::from_value(request.clone()) + .expect("existing SSH request without clone option"); + assert!(decoded.apfs_clone_metadata); + request + .as_object_mut() + .expect("options object") + .insert("apfs_clone_metadata".into(), false.into()); + let disabled: ScanOptions = + serde_json::from_value(request).expect("explicit clone option"); + assert!(!disabled.apfs_clone_metadata); + } + + fn scan_dir(root: &Path, options: &ScanOptions) -> Tree { scan(root, options.clone()).expect("scan") } - fn child<'a>(node: &'a Node, name: &str) -> &'a Node { - node.children + fn child<'a>(node: Node<'a>, name: &str) -> Node<'a> { + node.children() .iter() - .find(|child| &*child.name == name) + .find(|child| child.name() == name) .unwrap_or_else(|| { - panic!("no child named {name} in {:?}", node.name) + panic!("no child named {name} in {:?}", node.name()) }) } + #[cfg(unix)] + #[test] + fn a_second_data_mount_counts_private_stores_without_its_user_aliases() { + let temp = TempDir::new().expect("tempdir"); + let root = temp.path(); + let ordinary = write(root, "Users/me/document", 100); + let data = root.join("Data"); + fs::create_dir_all(data.join("Users/me")).expect("mkdir"); + fs::hard_link(&ordinary, data.join("Users/me/document")) + .expect("an alias for the same file"); + let history = write(root, "Data/.fseventsd/events", 1234); + let index = write(root, "Data/.Spotlight-V100/index", 4567); + let duplicate = data.join(".Spotlight-V100/another-name"); + fs::hard_link(&index, &duplicate).expect("hardlink inside a store"); + write(root, "Data/not-a-private-store/blob", 9999); + let context = Arc::new(WalkContext { + known: None, + options: ScanOptions::default(), + progress: Arc::new(ScanProgress::default()), + root_device: Mutex::new(None), + // The Data mount is an explicit boundary on modern macOS. Only + // its whitelisted private stores may cross it. + foreign_mounts: OnceLock::from(FxHashSet::from_iter( + [data.clone()], + )), + never_scanned: OnceLock::new(), + data_services: OnceLock::from(data), + data_device: OnceLock::new(), + visited_dirs: Mutex::new(FxHashSet::default()), + volume: OnceLock::new(), + #[cfg(target_os = "macos")] + clone_cache: crate::clone_cache::Cache::default(), + }); + let tree = scan_blocking(root, &context).expect("scan"); + let tree = tree.root(); + let size = |path: &Path| { + allocated_bytes(&fs::metadata(path).expect("metadata")) + .expect("Unix allocation") + }; + assert_eq!(tree.bytes, size(&ordinary) + size(&history) + size(&index)); + let data = child(tree, "Data"); + assert_eq!(data.children().len(), 2); + assert_eq!(child(data, ".fseventsd").bytes, size(&history)); + assert_eq!(child(data, ".Spotlight-V100").bytes, size(&index)); + assert_eq!(context.progress.snapshot().errors, 0); + } + #[test] fn fixed_worker_pools_change_size_without_reinitializing_rayon() { let cpus = thread::available_parallelism().map_or(1, usize::from); @@ -1456,6 +1894,7 @@ mod tests { let mut settings = options(); settings.threads.max_threads = threads; let tree = scan_dir(temp.path(), &settings); + let tree = tree.root(); assert_eq!(tree.files, 96); assert_eq!(tree.dirs, 193); assert_eq!(tree.bytes, (1..=96).sum::()); @@ -1476,26 +1915,41 @@ mod tests { root_device: Mutex::new(None), foreign_mounts: OnceLock::new(), never_scanned: OnceLock::new(), + data_services: OnceLock::new(), + data_device: OnceLock::new(), visited_dirs: Mutex::new(FxHashSet::default()), - root: Mutex::new(None), volume: OnceLock::new(), + #[cfg(target_os = "macos")] + clone_cache: crate::clone_cache::Cache::default(), }); - let root = Arc::new(PendingDir::new( - temp.path().to_path_buf(), - file_name(temp.path()), - None, - 0, - )); - let queued = walk(&root, &context); - assert_eq!(queued.len(), 128); - assert!(lock(&context.root).is_none()); - progress.cancel(); - for dir in queued { - assert!(walk(&dir, &context).is_empty()); - } - let tree = lock(&context.root).take().expect("root completed"); - assert_eq!(tree.children.len(), 128); - assert!(tree.children.iter().all(|child| child.children.is_empty())); + let tree = Tree::build(|builder| { + let sink = Sink { + builder, + root: Mutex::new(None), + }; + let root = Arc::new(PendingDir::new( + temp.path().to_path_buf(), + file_name(temp.path()), + None, + 0, + )); + let queued = walk(&root, &context, &sink); + assert_eq!(queued.len(), 128); + assert!(lock(&sink.root).is_none()); + progress.cancel(); + for dir in queued { + assert!(walk(&dir, &context, &sink).is_empty()); + } + let root = lock(&sink.root).take(); + root.expect("root completed") + }); + let tree = tree.root(); + assert_eq!(tree.children().len(), 128); + assert!( + tree.children() + .iter() + .all(|child| child.children().is_empty()) + ); } #[test] @@ -1507,12 +1961,13 @@ mod tests { write(root, "b/three.bin", 500); let tree = scan_dir(root, &options()); + let tree = tree.root(); assert_eq!(tree.bytes, 3500); assert_eq!(tree.files, 3); assert_eq!(tree.dirs, 4, "root, a, a/nested, b"); - assert_eq!(child(&tree, "a").bytes, 3000); - assert_eq!(child(child(&tree, "a"), "nested").bytes, 2000); - assert_eq!(child(&tree, "b").bytes, 500); + assert_eq!(child(tree, "a").bytes, 3000); + assert_eq!(child(child(tree, "a"), "nested").bytes, 2000); + assert_eq!(child(tree, "b").bytes, 500); } #[test] @@ -1524,7 +1979,8 @@ mod tests { write(root, "medium.bin", 100); let tree = scan_dir(root, &options()); - let names: Vec<&str> = tree.children.iter().map(|c| &*c.name).collect(); + let tree = tree.root(); + let names: Vec<&str> = tree.children().iter().map(Node::name).collect(); assert_eq!(names, vec!["large.bin", "medium.bin", "small.bin"]); } @@ -1536,6 +1992,7 @@ mod tests { write(root, "sub/deep.bin", 300); let tree = scan_dir(root, &options()); + let tree = tree.root(); assert_eq!(tree.own_bytes(), 700); assert_eq!(tree.own_files(), 1); assert_eq!(tree.bytes, 1000); @@ -1550,6 +2007,7 @@ mod tests { fs::hard_link(&original, root.join("link.bin")).expect("hard link"); let deduped = scan_dir(root, &options()); + let deduped = deduped.root(); assert_eq!(deduped.bytes, 4096); assert_eq!(deduped.files, 2, "both names still exist"); @@ -1560,7 +2018,7 @@ mod tests { ..options() }, ); - assert_eq!(counted.bytes, 8192); + assert_eq!(counted.root().bytes, 8192); } #[test] @@ -1571,8 +2029,9 @@ mod tests { write(root, "visible.bin", 100); let default = scan_dir(root, &options()); + let default = default.root(); assert_eq!(default.bytes, 1000); - assert_eq!(child(&default, ".cache").bytes, 900); + assert_eq!(child(default, ".cache").bytes, 900); let without = scan_dir( root, @@ -1581,7 +2040,7 @@ mod tests { ..options() }, ); - assert_eq!(without.bytes, 100); + assert_eq!(without.root().bytes, 100); } /// Explorer's hidden attribute counts as hidden, as `AppData` has it. @@ -1606,7 +2065,7 @@ mod tests { ..options() }, ); - assert_eq!(without.bytes, 100); + assert_eq!(without.root().bytes, 100); } /// A link to a directory: a symbolic link on Unix, a junction on @@ -1633,10 +2092,11 @@ mod tests { assert!(link_dir(outside.path(), &root.join("link")), "a link"); let tree = scan_dir(root, &options()); + let tree = tree.root(); // Only the real file's bytes; the link itself holds just its target // string, and its 5000-byte destination is outside this tree. assert!(tree.bytes < 200, "{}", tree.bytes); - let link = child(&tree, "link"); + let link = child(tree, "link"); assert_eq!(link.kind, NodeKind::Symlink); assert!(link.bytes < 100, "a link holds only its target string"); } @@ -1655,7 +2115,7 @@ mod tests { ..options() }, ); - assert_eq!(tree.bytes, 42); + assert_eq!(tree.root().bytes, 42); } /// Disk usage is what the volume allocated, not the length: whole @@ -1673,12 +2133,20 @@ mod tests { state.to_le_bytes()[0] }) .collect(); - fs::write(temp.path().join("data.bin"), noise).expect("write"); + // Flush and sync before scanning: on CoW filesystems with delayed + // allocation (such as OpenZFS), asynchronous writes remain buffered + // in transaction groups and report st_blocks = 1 until synced. + let mut file = + fs::File::create(temp.path().join("data.bin")).expect("create"); + std::io::Write::write_all(&mut file, &noise).expect("write"); + file.sync_all().expect("sync"); + drop(file); let tree = scan_dir(temp.path(), &ScanOptions::default()); + let tree = tree.root(); assert!(tree.bytes >= 100_000, "{}", tree.bytes); assert_eq!(tree.bytes % 512, 0, "{}", tree.bytes); let apparent = scan_dir(temp.path(), &options()); - assert_eq!(apparent.bytes, 100_000); + assert_eq!(apparent.root().bytes, 100_000); } #[test] @@ -1696,14 +2164,15 @@ mod tests { ..options() }, ); + let tree = tree.root(); assert_eq!(tree.own_bytes(), 10); - let a = child(&tree, "a"); + let a = child(tree, "a"); assert_eq!( a.bytes, 20, "direct files at the cut-off depth still count" ); assert!( - a.children.iter().all(|child| !child.is_dir()), + a.children().iter().all(|child| !child.is_dir()), "descending stopped at depth 1" ); assert_eq!(a.files, 1); @@ -1719,8 +2188,9 @@ mod tests { write(root, "one/huge.bin", 100_000); let tree = scan_dir(root, &options()); - assert_eq!(child(&tree, "one").bytes, 100_000); - assert_eq!(tree.children[0].name.as_ref(), "one"); + let tree = tree.root(); + assert_eq!(child(tree, "one").bytes, 100_000); + assert_eq!(tree.children().at(0).name(), "one"); let by_files = scan_dir( root, @@ -1729,8 +2199,9 @@ mod tests { ..options() }, ); - assert_eq!(by_files.children[0].name.as_ref(), "many"); - assert_eq!(by_files.children[0].files, 5); + let by_files = by_files.root().children().at(0); + assert_eq!(by_files.name(), "many"); + assert_eq!(by_files.files, 5); } #[cfg(unix)] @@ -1756,19 +2227,33 @@ mod tests { root_device: Mutex::new(None), foreign_mounts: OnceLock::new(), never_scanned: OnceLock::new(), + data_services: OnceLock::new(), + data_device: OnceLock::new(), visited_dirs: Mutex::new(FxHashSet::default()), - root: Mutex::new(None), volume: OnceLock::new(), + #[cfg(target_os = "macos")] + clone_cache: crate::clone_cache::Cache::default(), }); let tree = scan_blocking(root, &context).expect("scan still succeeds"); + let tree = tree.root(); let _ = fs::set_permissions(&locked, fs::Permissions::from_mode(0o700)); - assert_eq!(tree.bytes, 11); - let node = child(&tree, "locked"); - if matches!(readable, Ok(false)) { + assert_eq!(tree.bytes, if readable.is_err() { 11 } else { 33 }); + let node = child(tree, "locked"); + if readable.is_err() { assert!(node.read_error); + assert!(tree.read_error, "unknown contents affect ancestor totals"); assert!(progress.snapshot().errors >= 1); assert!(!progress.snapshot().messages.is_empty()); + assert_eq!( + crate::macos_services::usage( + root, + tree, + &context.options, + &locked + ), + crate::macos_services::Usage::Unavailable + ); } } @@ -1797,10 +2282,13 @@ mod tests { thread::sleep(std::time::Duration::from_millis(1)); } let tree = outcome.expect("the scan finished").expect("a tree"); + let tree = tree.root(); assert_eq!(tree.bytes, 3072); let snapshot = handle.progress.snapshot(); assert!(snapshot.finished); + assert!(snapshot.finalizing); + assert_eq!(snapshot.volume_used, None, "a folder has no known total"); assert_eq!(snapshot.files, 2); assert_eq!(snapshot.errors, 0); let preview = handle.progress.preview(); @@ -1850,14 +2338,15 @@ mod tests { } thread::sleep(std::time::Duration::from_millis(2)); }; + let tree = tree.root(); let reused = tree.child_named("inner").expect("inner is in the tree"); - assert_eq!(reused.files, known.files, "b.bin was never read"); - assert_eq!(reused.bytes, known.bytes); + assert_eq!(reused.files, known.root().files, "b.bin was never read"); + assert_eq!(reused.bytes, known.root().bytes); assert!( tree.child_named("outside.bin").is_some(), "the rest was walked" ); - assert_eq!(tree.files, known.files + 1); + assert_eq!(tree.files, known.root().files + 1); } /// A real whole-disk scan, run by hand: `cargo test -p disktree-core @@ -1870,17 +2359,18 @@ mod tests { let root = crate::space::volume_root_for(&home).expect("a volume root"); let started = std::time::Instant::now(); let tree = scan(&root, ScanOptions::default()).expect("scan"); + let tree = tree.root(); println!("root {} in {:.1?}", root.display(), started.elapsed()); println!( "total {} files {}", crate::size::human_bytes(tree.bytes), tree.files ); - for child in tree.children.iter().take(14) { + for child in tree.children().iter().take(14) { println!( " {:>10} {}", crate::size::human_bytes(child.bytes), - child.name + child.name() ); } let skipped = @@ -1889,7 +2379,7 @@ mod tests { for needle in ["c", "cache", "node_modules", "zzzz"] { let started = std::time::Instant::now(); let found = - crate::filter::filter(&tree, &[], needle).expect("needle"); + crate::filter::filter(tree, &[], needle).expect("needle"); println!( "filter {needle:?}: {} matches, {} in {:.1?}", found.count, diff --git a/crates/disktree-core/src/scan_threads.rs b/crates/disktree-core/src/scan_threads.rs index 5b0b43a3..92b7c1f8 100644 --- a/crates/disktree-core/src/scan_threads.rs +++ b/crates/disktree-core/src/scan_threads.rs @@ -288,18 +288,22 @@ impl Governor { use std::io; use std::sync::atomic::Ordering; use std::sync::{Arc, Condvar}; -use std::thread::{self, JoinHandle}; +use std::thread; use std::time::{Duration, Instant}; use crate::scan::ScanProgress; -pub(crate) struct ControllerGuard { +/// The admission controller's thread, stopped and joined on drop. Scoped: +/// the queue it samples holds the walk's nodes, which borrow the tree +/// being built. +pub(crate) struct ControllerGuard<'scope> { stop: Arc<(Mutex, Condvar)>, - worker: Option>, + worker: Option>, } -impl ControllerGuard { - pub(crate) fn spawn( +impl<'scope> ControllerGuard<'scope> { + pub(crate) fn spawn<'env, T: Send + 'scope>( + scope: &'scope thread::Scope<'scope, 'env>, options: ScanThreads, admission: Arc>, progress: Arc, @@ -311,7 +315,7 @@ impl ControllerGuard { let wake = Arc::clone(&stop); let worker = thread::Builder::new() .name("disktree-admission".into()) - .spawn(move || { + .spawn_scoped(scope, move || { control(options, &admission, &progress, &wake); })?; Ok(Some(Self { @@ -321,7 +325,7 @@ impl ControllerGuard { } } -impl Drop for ControllerGuard { +impl Drop for ControllerGuard<'_> { fn drop(&mut self) { *self.stop.0.lock().unwrap_or_else(PoisonError::into_inner) = true; self.stop.1.notify_one(); diff --git a/crates/disktree-core/src/sharing.rs b/crates/disktree-core/src/sharing.rs new file mode 100644 index 00000000..f142746a --- /dev/null +++ b/crates/disktree-core/src/sharing.rs @@ -0,0 +1,1087 @@ +//! APFS sharing, reported separately from the treemap's allocated bytes. +//! +//! Harold Hunt's clone accounting, ported from huntharo/disktree#3. He +//! first wrote it for diskhound (huntharo/diskhound#4, contributed as +//! tzarebczan/diskhound#40). Clone IDs describe full data-fork clones, not +//! every shared extent of modified files. + +use rayon::prelude::*; +use rustc_hash::FxHashMap; + +use std::sync::Mutex; + +use crate::tree::{Node, Tree}; + +mod reclaim; +pub(crate) use reclaim::Selected; +pub use reclaim::{Estimate, estimate}; + +/// Sparse allocation facts survive hardlink weight de-duplication. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Allocation { + pub bytes: u64, + pub identity: Option<(u64, u64)>, + pub links: u64, + pub followed: bool, + pub clone: Option, +} + +/// Metadata retained only for files that may share allocation. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct CloneInfo { + pub device: u64, + pub id: u64, + pub references: u32, + /// Private data-fork allocation; other forks can remain unmeasured. + pub private_bytes: Option, + /// Clone identity describes the data fork, not resource forks or xattrs. + pub data_bytes: u64, +} + +/// Derived figures; none changes `Node::bytes` or a tile's weight. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Sharing { + pub files: u64, + pub bytes: u64, + pub private_bytes: u64, + pub duplicate_bytes: u64, + pub unknown_files: u64, + /// More than one million distinct groups: repeated-byte reporting is partial. + pub groups_truncated: bool, + pub estimate: Option, +} + +impl Sharing { + /// Lower bound before snapshots or changes since the scan. + pub fn reclaimable(self, listed: u64) -> u64 { + self.estimate.map_or(listed, |estimate| estimate.lower) + } + + pub fn possible(self, listed: u64) -> u64 { + self.estimate.map_or(listed, |estimate| estimate.upper) + } + + /// Allocation in clone files not known to be private. Other clones, + /// selected or not and inside the scan or not, may hold these blocks, + /// so deleting this alone does not free them. An unknown private size + /// counts as shared: the conservative side for a saving. + pub const fn shared_bytes(self) -> u64 { + self.bytes.saturating_sub(self.private_bytes) + } +} + +/// Leaf metadata is already retained; do not allocate another box per clone. +pub(crate) fn leaf_summary(node: Node<'_>) -> Sharing { + let Some(allocation) = node.allocation() else { + return Sharing::default(); + }; + let mut summary = Sharing { + estimate: Some(allocation.estimate()), + ..Sharing::default() + }; + own(node, &mut summary); + summary +} + +impl Allocation { + fn estimate(self) -> Estimate { + if self.followed || (self.links > 1 && self.identity.is_some()) { + return Estimate::default(); + } + if self.links > 1 { + return Estimate { + upper: self.bytes, + partial: true, + ..Estimate::default() + }; + } + let lower = self.clone.map_or(self.bytes, |info| { + info.private_bytes.unwrap_or(0).min(self.bytes) + }); + let full = self.clone.is_some_and(|info| { + info.device != 0 + && info.id != 0 + && info.references >= 2 + && info.private_bytes == Some(0) + }); + Estimate { + lower, + upper: if full { + self.bytes.saturating_sub( + self.clone.map_or(0, |info| info.data_bytes), + ) + } else { + self.bytes + }, + partial: self.clone.is_some_and(CloneInfo::incomplete), + } + } +} + +impl CloneInfo { + const fn incomplete(self) -> bool { + self.device == 0 + || self.id == 0 + || self.references == 0 + || self.private_bytes.is_none() + } +} + +#[derive(Debug)] +struct Group { + bytes: u64, + count: u64, +} + +impl Group { + const fn duplicates(&self) -> u64 { + self.bytes.saturating_mul(self.count - 1) + } +} + +type Groups = FxHashMap<(u64, u64), Group>; + +/// Union duplicate reporting uses exactly the same grouping as aggregation. +#[derive(Default)] +pub(crate) struct DuplicateSummary { + groups: Groups, + summary: Sharing, + incomplete: bool, +} + +impl DuplicateSummary { + pub(crate) fn add(&mut self, node: Node<'_>) { + self.incomplete |= node + .allocation() + .and_then(|allocation| allocation.clone) + .is_some_and(CloneInfo::incomplete); + if let Some((key, group)) = own(node, &mut self.summary) { + join( + &mut self.groups, + key, + group, + MAX_CLONE_GROUPS, + &mut self.summary, + ); + } + } + + pub(crate) const fn bytes(&self) -> Option { + if self.incomplete || self.summary.groups_truncated { + None + } else { + Some(self.summary.duplicate_bytes) + } + } +} +// Bound temporary grouping memory on volumes with millions of clone IDs. +const MAX_CLONE_GROUPS: usize = 1_000_000; + +/// Small-to-large merging avoids walking every subtree for every ancestor. +/// Hardlink duplicates already have zero weight when this pass runs. +pub(crate) fn refresh(tree: &mut Tree) { + collect(tree, MAX_CLONE_GROUPS); +} + +/// A node's new sharing figures, by its position in the tree. +type Update = (u32, Option); + +/// Where workers leave their updates: one list per run of work, so none +/// is copied into another. +type Sink = Mutex>>; + +/// The pass reads the tree on every worker and writes nothing; the +/// figures it settles go into the tree afterwards, by position, since a +/// write would take the whole tree from every other worker. +fn collect(tree: &mut Tree, limit: usize) -> (Groups, reclaim::Accumulator) { + let sink = Sink::default(); + let mut updates = Vec::new(); + let (groups, allocation, _) = + collect_at(tree.root(), limit, 0, &mut updates, &sink); + let mut lists = sink + .into_inner() + .unwrap_or_else(std::sync::PoisonError::into_inner); + lists.push(updates); + tree.set_sharing(lists.into_iter().flatten()); + (groups, allocation) +} + +/// A file's clone facts in a directory's figures: what [`collect`] of the +/// file would return, merged, without the file's own maps. Most files of +/// a large tree are leaves, and a map apiece was most of this pass's time. +fn fold_leaf( + leaf: Node<'_>, + limit: usize, + part: &mut Part, + updates: &mut Vec, +) { + // Only a directory keeps figures; clear a file's only if it has some, + // so a pass reads its millions of files without writing to them. + if leaf.stored_sharing().is_some() { + updates.push((leaf.id(), None)); + } + part.allocation.add_leaf(leaf); + if let Some((key, group)) = own(leaf, &mut part.summary) { + join(&mut part.groups, key, group, limit, &mut part.summary); + } +} + +/// A node's own clone figures, and its group when it can repeat bytes. +fn own(node: Node<'_>, summary: &mut Sharing) -> Option<((u64, u64), Group)> { + let info = node + .allocation() + .and_then(|allocation| allocation.clone) + .filter(|_| node.bytes > 0)?; + summary.files += 1; + summary.bytes = summary.bytes.saturating_add(node.bytes); + summary.private_bytes = summary + .private_bytes + .saturating_add(info.private_bytes.unwrap_or(0).min(node.bytes)); + summary.unknown_files += u64::from(info.private_bytes.is_none()); + (info.device != 0 && info.id != 0 && info.references >= 2).then(|| { + ( + (info.device, info.id), + Group { + // A modified clone repeats only what it still shares; its + // private blocks are its own. An unknown private size keeps + // the whole data fork, as before. + bytes: info.data_bytes.min( + node.bytes.saturating_sub(info.private_bytes.unwrap_or(0)), + ), + count: 1, + }, + ) + }) +} + +fn join( + groups: &mut Groups, + key: (u64, u64), + group: Group, + limit: usize, + summary: &mut Sharing, +) { + reclaim::work(); + if groups.len() >= limit && !groups.contains_key(&key) { + summary.groups_truncated = true; + return; + } + groups + .entry(key) + .and_modify(|old| { + // A scan is not atomic. Use the smaller observation when a file + // changes while its clone group is being measured. + let before = old.duplicates().saturating_add(group.duplicates()); + old.bytes = old.bytes.min(group.bytes); + old.count += group.count; + summary.duplicate_bytes = summary + .duplicate_bytes + .saturating_sub(before) + .saturating_add(old.duplicates()); + }) + .or_insert(group); +} + +#[cfg(test)] +thread_local! { + /// Calls of `collect_at`, each of which makes a node's maps. + static VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// A directory's figures while its children are added: what [`collect`] +/// returns, with the sums its children contribute. +struct Part { + groups: Groups, + allocation: reclaim::Accumulator, + summary: Sharing, +} + +impl Part { + fn new(limit: usize) -> Self { + Self { + groups: Groups::default(), + allocation: reclaim::Accumulator::new(limit), + summary: Sharing::default(), + } + } + + /// Add one child: a file folded straight into these maps, or a + /// directory collected and then merged. + fn add( + &mut self, + child: Node<'_>, + limit: usize, + depth: usize, + updates: &mut Vec, + sink: &Sink, + ) { + if !child.is_dir() { + fold_leaf(child, limit, self, updates); + return; + } + let (groups, allocation, summary) = + collect_at(child, limit, depth + 1, updates, sink); + self.merge( + Self { + groups, + allocation, + summary, + }, + limit, + ); + } + + /// Merge the figures of children that follow these. + fn merge(&mut self, mut other: Self, limit: usize) { + self.allocation.merge(other.allocation); + let (mine, theirs) = (&mut self.summary, other.summary); + mine.duplicate_bytes = + mine.duplicate_bytes.saturating_add(theirs.duplicate_bytes); + mine.groups_truncated |= theirs.groups_truncated; + mine.files += theirs.files; + mine.bytes = mine.bytes.saturating_add(theirs.bytes); + mine.private_bytes = + mine.private_bytes.saturating_add(theirs.private_bytes); + mine.unknown_files += theirs.unknown_files; + if self.groups.len() < other.groups.len() { + std::mem::swap(&mut self.groups, &mut other.groups); + } + for (key, group) in other.groups { + join(&mut self.groups, key, group, limit, &mut self.summary); + } + } +} + +/// `node`'s clone groups and reclaim figures, and the sharing figures it +/// reads as once its update is written, which goes into `updates`. +fn collect_at( + node: Node<'_>, + limit: usize, + depth: usize, + updates: &mut Vec, + sink: &Sink, +) -> (Groups, reclaim::Accumulator, Sharing) { + #[cfg(test)] + VISITS.set(VISITS.get() + 1); + let mut part = Part::new(limit); + if !node.is_dir() { + fold_leaf(node, limit, &mut part, updates); + return (part.groups, part.allocation, leaf_summary(node)); + } + if let Some((key, group)) = own(node, &mut part.summary) { + part.groups.insert(key, group); + } + if depth < crate::tree::PARALLEL_LEVELS { + // Subdirectories near the top are independent work, as in the + // totals pass. Each is merged into this directory's maps as soon + // as it is done, so the maps held at once are these and those of + // the subdirectories in progress. Folding runs of children into a + // set of maps per worker held a set per worker of nearly every + // group in the tree when the same clones fill every subdirectory: + // 18 sets of 129 thousand groups, 0.4 GiB at the end of a scan of + // 8.9 million files of agent worktrees. Merging is commutative, + // so the figures do not depend on which finishes first, short of + // the group limit, where which groups are kept already depended + // on how the work was split. + for child in node.children() { + if !child.is_dir() { + fold_leaf(child, limit, &mut part, updates); + } + } + let merged = Mutex::new(part); + node.children() + .par_iter() + .filter(|child| child.is_dir()) + .for_each(|dir| { + let mut updates = Vec::new(); + let (groups, allocation, summary) = + collect_at(dir, limit, depth + 1, &mut updates, sink); + if !updates.is_empty() { + crate::scan::lock(sink).push(updates); + } + crate::scan::lock(&merged).merge( + Part { + groups, + allocation, + summary, + }, + limit, + ); + }); + part = merged + .into_inner() + .unwrap_or_else(std::sync::PoisonError::into_inner); + } else { + for child in node.children() { + part.add(child, limit, depth, updates, sink); + } + } + let Part { + groups, + mut allocation, + mut summary, + } = part; + if node.allocation().is_some_and(|info| info.followed) { + allocation = reclaim::Accumulator::new(limit); + } + summary.estimate = Some(allocation.estimate()); + // `set_sharing` rewrites a directory's figures in place, so a second + // pass allocates nothing for a directory that already shares. + let kept = summary.files > 0 + || node.allocation().is_some() + || allocation.needs_selection() + || summary.reclaimable(node.bytes) != node.bytes + || summary.possible(node.bytes) != node.bytes; + // Most directories keep nothing and had nothing: no update to write, + // as `fold_leaf` does for files. + if kept || node.stored_sharing().is_some() { + updates.push((node.id(), kept.then_some(summary))); + } + // What `Node::sharing` reads once the update is written: a directory + // that keeps nothing has no allocation of its own to summarize. + ( + groups, + allocation, + if kept { summary } else { Sharing::default() }, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tree::{Draft, Tree}; + use crate::tree::{Metric, NodeKind, Seen, aggregate, aggregate_deduped}; + + fn clone(name: &str, device: u64, id: u64, private: Option) -> Draft { + let mut node = Draft::entry(name, NodeKind::File, 100); + node.allocation = Some(Box::new(Allocation { + bytes: node.bytes, + identity: None, + links: 1, + followed: false, + clone: Some(CloneInfo { + device, + id, + references: 2, + private_bytes: private, + data_bytes: 80, + }), + })); + node + } + + #[test] + fn selecting_a_complete_clone_group_reclaims_its_data_once() { + let mut root = Draft::directory("root"); + root.children = + vec![clone("a", 1, 1, Some(0)), clone("b", 1, 1, Some(0))]; + let mut tree = Tree::from(root); + aggregate(&mut tree, Metric::Bytes); + let root = tree.root(); + assert_eq!(root.sharing().reclaimable(root.bytes), 80); + } + + #[test] + fn group_limit_marks_the_summary_partial_without_losing_private_bytes() { + let mut root = Draft::directory("root"); + root.children = + vec![clone("a", 1, 1, Some(20)), clone("b", 1, 2, Some(20))]; + let mut tree = Tree::from(root); + aggregate(&mut tree, Metric::Bytes); + collect(&mut tree, 1); + let root = tree.root(); + assert!(root.sharing().groups_truncated); + assert_eq!(root.sharing().private_bytes, 40); + } + + #[test] + fn groups_are_volume_scoped_and_only_data_forks_are_duplicated() { + let mut root = Draft::directory("root"); + root.children = vec![ + clone("a", 1, 42, Some(20)), + clone("b", 1, 42, Some(20)), + clone("c", 2, 42, Some(20)), + ]; + let mut tree = Tree::from(root); + aggregate(&mut tree, Metric::Bytes); + let root = tree.root(); + assert_eq!(root.bytes, 300); + assert_eq!(root.sharing().duplicate_bytes, 80); + assert_eq!(root.sharing().reclaimable(root.bytes), 140); + aggregate(&mut tree, Metric::Files); + assert_eq!(tree.root().sharing().duplicate_bytes, 80); + } + + #[test] + fn modified_clones_repeat_only_what_they_still_share() { + let mut root = Draft::directory("root"); + root.children = + vec![clone("a", 1, 1, Some(60)), clone("b", 1, 1, Some(60))]; + let mut tree = Tree::from(root); + aggregate(&mut tree, Metric::Bytes); + let root = tree.root(); + // Each still shares 40 of its 100 bytes: one copy of that repeats. + assert_eq!(root.sharing().duplicate_bytes, 40); + assert!( + root.sharing().duplicate_bytes <= root.sharing().shared_bytes() + ); + } + + #[test] + fn unknown_and_oversized_private_values_stay_conservative() { + let mut root = Draft::directory("root"); + root.children = vec![ + clone("a", 1, 1, None), + clone("b", 1, 2, Some(200)), + Draft::entry("ordinary", NodeKind::File, 30), + ]; + let mut tree = Tree::from(root); + aggregate(&mut tree, Metric::Bytes); + let root = tree.root(); + assert_eq!(root.sharing().unknown_files, 1); + assert_eq!(root.sharing().reclaimable(root.bytes), 130); + } + + #[test] + fn deduplicated_hardlinks_do_not_inflate_sharing() { + let mut root = Draft::directory("root"); + root.children = + vec![clone("a", 1, 1, Some(0)), clone("b", 1, 1, Some(0))]; + for node in &mut root.children { + node.inode = + Some((1, std::num::NonZeroU64::new(123).expect("inode"))); + } + let mut tree = Tree::from(root); + aggregate_deduped(&mut tree, Metric::Bytes, &Seen::new()); + let root = tree.root(); + assert_eq!(root.sharing().files, 1); + assert_eq!(root.sharing().bytes, 100); + assert_eq!(root.sharing().duplicate_bytes, 0); + } + + /// `copies` worktrees nested six levels deep, below the parallel ones, + /// each holding a clone of the same `files` files, as a directory of + /// agent worktrees does. + fn worktrees(copies: u64, files: u64) -> Tree { + let mut root = Draft::directory("worktrees"); + for copy in 0..copies { + let mut tree = Draft::directory(format!("w{copy}")); + for file in 0..files { + let mut node = clone(&format!("f{file}"), 1, file + 1, Some(0)); + if let Some(info) = node + .allocation + .as_mut() + .and_then(|allocation| allocation.clone.as_mut()) + { + info.references = u32::try_from(copies).expect("copies"); + } + tree.children.push(node); + } + for level in 0..6 { + let mut dir = Draft::directory(format!("w{copy}-{level}")); + dir.children.push(tree); + tree = dir; + } + root.children.push(tree); + } + let mut root = Tree::from(root); + aggregate(&mut root, Metric::Bytes); + root + } + + /// On one thread, so the thread-local counters see all of the pass. + fn refresh_work(tree: &mut Tree) -> (u64, u64) { + rayon::ThreadPoolBuilder::new() + .num_threads(1) + .build() + .expect("pool") + .install(|| { + VISITS.set(0); + reclaim::WORK.set(0); + refresh(tree); + (VISITS.get(), reclaim::WORK.get()) + }) + } + + /// The pass once took 11 s on 20 million nodes, most of it making, + /// merging and freeing two maps for every file. Hold it to maps per + /// directory and to work that grows with the files, not faster. + #[test] + fn refresh_work_grows_with_files_and_makes_no_map_per_file() { + let mut counts = Vec::new(); + for (copies, files) in [(8, 64), (64, 512)] { + let mut tree = worktrees(copies, files); + let duplicates = tree.root().sharing().duplicate_bytes; + assert_eq!(duplicates, 80 * (copies - 1) * files); + let (visits, work) = refresh_work(&mut tree); + assert_eq!(tree.root().sharing().duplicate_bytes, duplicates); + assert_eq!( + visits, + u64::from(tree.root().dirs), + "maps are made per directory, never per file" + ); + // Each file is added to its directory's two maps, and its + // group moves into the root's two maps once per other copy: + // fewer than four steps a file however many there are. + let budget = 4 * copies * files; + assert!(work <= budget, "{copies}x{files}: {work} > {budget}"); + counts.push((work, copies * files)); + } + eprintln!("refresh map steps (work, files): {counts:?}"); + } + + #[test] + fn deep_and_parallel_levels_merge_like_one_directory() { + // Members below the parallel levels, beside them and at the top: + // every path through `collect_at` must reach the same totals. + let mut flat = Draft::directory("root"); + let mut nested = Draft::directory("root"); + for (depth, private) in [(0, Some(0)), (3, Some(0)), (7, Some(20))] { + flat.children + .push(clone(&format!("f{depth}"), 1, 9, private)); + let mut leaf = clone("file", 1, 9, private); + for level in 0..depth { + let mut dir = Draft::directory(format!("d{depth}-{level}")); + dir.children.push(leaf); + leaf = dir; + } + nested.children.push(leaf); + } + flat.children.push(Draft::entry("plain", NodeKind::File, 7)); + nested + .children + .push(Draft::entry("plain", NodeKind::File, 7)); + let mut flat = Tree::from(flat); + let mut nested = Tree::from(nested); + aggregate(&mut flat, Metric::Bytes); + aggregate(&mut nested, Metric::Bytes); + assert_eq!(nested.root().sharing(), flat.root().sharing()); + assert_eq!(nested.root().sharing().duplicate_bytes, 2 * 80); + + // A second pass keeps every figure and grows no side table. + let before = nested.root().sharing(); + let storage = nested.storage_bytes(); + aggregate(&mut nested, Metric::Files); + assert_eq!(nested.root().sharing(), before); + assert_eq!(nested.storage_bytes(), storage); + + // A directory that no longer shares gives its figures up. + let mut draft = nested.root().to_draft(); + let deep = draft + .children + .iter_mut() + .find(|child| child.kind.is_dir()) + .expect("a nested branch"); + let emptied = deep.name.clone(); + deep.children.clear(); + let mut nested = Tree::from(draft); + aggregate(&mut nested, Metric::Bytes); + let emptied = nested + .root() + .children() + .iter() + .find(|child| child.name() == &*emptied) + .expect("the emptied branch"); + assert!(emptied.stored_sharing().is_none()); + assert_eq!(nested.root().sharing().files, 2); + } + + /// A tree with a file for every table an allocation can be kept in: + /// clones with one name, wholly shared, modified and unknown, groups + /// that span directories and leave it, hardlinks, a followed link and + /// a clone with a resource fork. + fn every_kind_of_file() -> Draft { + let mut root = Draft::directory("root"); + // A clone whose data fork is all of it, as nearly every one is. + let sized = |name: &str, id, private, references| { + let mut node = clone(name, 1, id, private); + node.bytes = 80; + let allocation = node.allocation.as_mut().expect("allocation"); + allocation.bytes = 80; + let info = allocation.clone.as_mut().expect("clone"); + info.references = references; + node + }; + for (dir, inode) in [("a", 11), ("b", 12)] { + let mut node = Draft::directory(dir); + node.children = vec![ + // A third member outside the tree: never complete. + sized("whole", 7, Some(0), 3), + sized("complete", 8, Some(0), 2), + sized("modified", 9, Some(30), 2), + sized("unknown", 10, None, 2), + clone("fork", 1, 11, Some(0)), + Draft::entry("plain", NodeKind::File, 5), + ]; + let mut link = Draft::entry("link", NodeKind::File, 64); + link.inode = + Some((1, std::num::NonZeroU64::new(inode / 10).expect("ino"))); + link.allocation = Some(Box::new(Allocation { + bytes: 64, + identity: Some((1, inode / 10)), + links: 2, + followed: false, + clone: None, + })); + node.children.push(link); + let mut followed = sized("followed", 7, Some(0), 3); + let allocation = followed.allocation.as_mut().expect("allocation"); + allocation.followed = true; + allocation.clone = None; + node.children.push(followed); + root.children.push(node); + } + root + } + + /// Each node's figures, the estimate of each node alone and of every + /// pair of nodes neither of which holds the other: what a selection + /// of marks reads. + fn figures(tree: &Tree) -> Vec<(Sharing, Estimate)> { + /// Nodes in preorder, each with the end of its subtree's run. + fn preorder<'t>(node: Node<'t>, nodes: &mut Vec<(Node<'t>, usize)>) { + let at = nodes.len(); + nodes.push((node, 0)); + for child in node.children() { + preorder(child, nodes); + } + nodes[at].1 = nodes.len(); + } + let mut nodes = Vec::new(); + preorder(tree.root(), &mut nodes); + let mut figures = Vec::new(); + for &(node, end) in &nodes { + figures.push((node.sharing(), estimate([node]))); + // What follows a node's subtree in preorder is outside it, and + // cannot hold it. + for &(other, _) in &nodes[end..] { + figures.push((Sharing::default(), estimate([node, other]))); + } + } + figures + } + + #[test] + fn every_figure_is_the_same_however_its_allocation_is_kept() { + let draft = every_kind_of_file(); + let measured = |tree: &mut Tree| { + aggregate_deduped(tree, Metric::Bytes, &Seen::new()); + let bytes = figures(tree); + aggregate(tree, Metric::Files); + (bytes, figures(tree)) + }; + let mut packed = Tree::from(&draft); + let mut whole = crate::index::kept_whole(|| Tree::from(&draft)); + // The small records are what the packed tree keeps, or this + // compares the whole tables with themselves. + assert!(packed.storage_bytes().used < whole.storage_bytes().used); + let expected = crate::index::kept_whole(|| measured(&mut whole)); + assert_eq!(measured(&mut packed), expected); + let root = packed.root(); + assert!(root.sharing().duplicate_bytes > 0); + assert!(root.sharing().unknown_files > 0); + assert_ne!(root.sharing().reclaimable(root.bytes), root.bytes); + } + + #[test] + fn clone_groups_merge_across_directories_and_refresh_after_removal() { + let mut root = Draft::directory("root"); + for name in ["a", "b"] { + let mut dir = Draft::directory(name); + dir.children.push(clone("file", 1, 1, Some(0))); + root.children.push(dir); + } + let mut tree = Tree::from(root); + aggregate(&mut tree, Metric::Bytes); + let root = tree.root(); + assert_eq!(root.sharing().duplicate_bytes, 80); + assert_eq!(root.children().at(0).sharing().duplicate_bytes, 0); + // Removing a directory is a rescan into a new tree. + let mut draft = root.to_draft(); + draft.children.pop(); + let mut tree = Tree::from(draft); + aggregate(&mut tree, Metric::Bytes); + let root = tree.root(); + assert_eq!(root.sharing().duplicate_bytes, 0); + assert_eq!(root.sharing().files, 1); + } + + /// A random tree deeper than the parallel levels: plain files, clones + /// of a few groups spread across directories (wholly shared, modified, + /// unknown, on another volume or none known, with a resource fork), + /// hardlinks across directories and followed links. Every name of a + /// hardlinked file reads as that one file does, and a file has no + /// more names than its link count, as a scan of a tree that holds + /// still finds. With `consistent_links` off, each name has independent + /// facts and names can exceed the link count, as in a changing tree. + fn random_tree( + rng: &mut crate::test_rng::Rng, + consistent_links: bool, + ) -> Draft { + /// Each hardlinked file met so far, and the names it has left. + type Linked = [Option<(Draft, u64)>; 4]; + fn file( + rng: &mut crate::test_rng::Rng, + linked: &mut Linked, + name: String, + consistent_links: bool, + ) -> Draft { + let bytes = 80 * (rng.below(3) + 1); + let mut node = Draft::entry(name, NodeKind::File, bytes); + let kind = rng.below(10); + if kind < 3 { + return node; + } + let device = [1, 1, 1, 2, 0][rng.below(5) as usize]; + let info = CloneInfo { + device, + id: rng.below(5) + 1, + references: u32::try_from(rng.below(4) + 1).expect("small"), + private_bytes: [Some(0), Some(0), Some(40), None] + [rng.below(4) as usize], + // A resource fork the group does not share, now and then. + data_bytes: if rng.percent(15) { bytes - 40 } else { bytes }, + }; + let mut allocation = Allocation { + bytes, + identity: None, + links: 1, + followed: false, + clone: Some(info), + }; + if kind == 8 { + let inode = rng.below(4) + 1; + let slot = + &mut linked[usize::try_from(inode - 1).expect("ino")]; + match slot { + Some((first, left)) if consistent_links && *left > 0 => { + *left -= 1; + let mut name_of = first.clone(); + name_of.name = node.name; + return name_of; + } + // Every name met: another file, of one name. + Some(_) if consistent_links => {} + _ => { + node.inode = Some(( + 1, + std::num::NonZeroU64::new(inode).expect("ino"), + )); + allocation.identity = Some((1, inode)); + allocation.links = rng.below(2) + 2; + if rng.percent(50) { + allocation.clone = None; + } + node.allocation = Some(Box::new(allocation)); + *slot = Some((node.clone(), allocation.links - 1)); + return node; + } + } + } else if kind == 9 { + allocation.followed = true; + } + node.allocation = Some(Box::new(allocation)); + node + } + fn directory( + rng: &mut crate::test_rng::Rng, + linked: &mut Linked, + name: String, + depth: usize, + consistent_links: bool, + ) -> Draft { + let mut dir = Draft::directory(name); + for index in 0..rng.below(4) { + dir.children.push(file( + rng, + linked, + format!("f{index}"), + consistent_links, + )); + } + if depth < 6 { + for index in 0..rng.below(if depth < 2 { 4 } else { 3 }) { + dir.children.push(directory( + rng, + linked, + format!("d{index}"), + depth + 1, + consistent_links, + )); + } + } + // Files and directories in any order, as a listing gives them. + rng.shuffle(&mut dir.children); + dir + } + directory( + rng, + &mut Linked::default(), + "root".into(), + 0, + consistent_links, + ) + } + + /// A pool of `threads` workers, built once per test and shared by its + /// cases. + fn pool(threads: usize) -> rayon::ThreadPool { + rayon::ThreadPoolBuilder::new() + .num_threads(threads) + .build() + .expect("a pool") + } + + /// Every node's figures after a pass on `pool`, ranked by size and + /// then by files. + fn on_workers( + draft: &Draft, + pool: &rayon::ThreadPool, + whole: bool, + ) -> Vec> { + pool.install(|| { + let build = || Tree::from(draft); + let mut tree = if whole { + crate::index::kept_whole(build) + } else { + build() + }; + let mut measured = |metric| { + if whole { + crate::index::kept_whole(|| aggregate(&mut tree, metric)); + } else { + aggregate(&mut tree, metric); + } + figures(&tree) + }; + vec![measured(Metric::Bytes), measured(Metric::Files)] + }) + } + + /// Merging a subdirectory into its parent as it finishes leaves every + /// figure as merging in child order on one worker does. + #[test] + fn random_trees_read_the_same_on_one_worker_and_on_many() { + let one = pool(1); + let many: Vec<_> = [2, 4, 8] + .map(|threads| (threads, pool(threads))) + .into_iter() + .collect(); + for seed in 0..300 { + let draft = random_tree(&mut crate::test_rng::Rng::new(seed), true); + let expected = on_workers(&draft, &one, false); + for (threads, pool) in &many { + assert_eq!( + on_workers(&draft, pool, false), + expected, + "seed {seed} on {threads} workers" + ); + } + } + } + + fn files(node: Node<'_>, into: &mut Vec) { + for child in node.children() { + if child.is_dir() { + files(child, into); + } else { + into.push(child.to_draft()); + } + } + } + + fn check_flat(node: Node<'_>, seed: u64) { + if !node.is_dir() { + return; + } + let mut flat = Draft::directory("flat"); + files(node, &mut flat.children); + let mut flat = Tree::from(flat); + aggregate(&mut flat, Metric::Bytes); + assert_eq!( + node.sharing(), + flat.root().sharing(), + "seed {seed}: {}", + node.name() + ); + assert_eq!( + estimate([node]), + estimate([flat.root()]), + "seed {seed}: selected {}", + node.name() + ); + for child in node.children() { + check_flat(child, seed); + } + } + + /// Every directory reads as one directory holding all of its files + /// would: an answer that does not go through the merging of + /// subdirectories, near the top or below it, at all. + #[test] + fn random_trees_read_as_their_files_would_side_by_side() { + for seed in 0..300 { + let draft = random_tree(&mut crate::test_rng::Rng::new(seed), true); + let mut tree = Tree::from(&draft); + aggregate(&mut tree, Metric::Bytes); + check_flat(tree.root(), seed); + } + } + + /// Live hardlink observations can disagree or outnumber the reported + /// links. Neither nesting nor a worker's finishing order changes the + /// evidence retained in the estimate. + #[test] + fn changing_hardlinks_read_the_same_flat_nested_and_on_any_workers() { + let workers = [1, 2, 4, 8].map(|threads| (threads, pool(threads))); + for seed in 0..300 { + let draft = + random_tree(&mut crate::test_rng::Rng::new(seed), false); + let mut expected = None; + for (threads, pool) in &workers { + let actual = pool.install(|| { + let mut tree = Tree::from(&draft); + [Metric::Bytes, Metric::Files].map(|metric| { + aggregate(&mut tree, metric); + check_flat(tree.root(), seed); + figures(&tree) + }) + }); + if let Some(expected) = &expected { + assert_eq!( + &actual, expected, + "seed {seed} on {threads} workers" + ); + } else { + expected = Some(actual); + } + } + } + } + + /// Files of a group sharing a record read as each keeping its own. + #[test] + fn random_trees_read_the_same_however_their_allocations_are_kept() { + let workers = pool(4); + let mut reused = 0; + for seed in 0..300 { + let draft = random_tree(&mut crate::test_rng::Rng::new(seed), true); + assert_eq!( + on_workers(&draft, &workers, false), + on_workers(&draft, &workers, true), + "seed {seed}" + ); + let tree = Tree::from(&draft); + let (records, _, _) = tree.side_records(); + let kept = allocations(tree.root()); + reused += kept - records; + } + // Or this compares whole records with themselves. + assert!(reused > 100, "{reused}"); + } + + fn allocations(node: Node<'_>) -> usize { + usize::from(node.allocation().is_some()) + + node.children().iter().map(allocations).sum::() + } +} diff --git a/crates/disktree-core/src/sharing/reclaim.rs b/crates/disktree-core/src/sharing/reclaim.rs new file mode 100644 index 00000000..2ba55fd8 --- /dev/null +++ b/crates/disktree-core/src/sharing/reclaim.rs @@ -0,0 +1,881 @@ +//! Composable selected-set accounting. No pairwise mark or group comparisons. + +use rustc_hash::FxHashMap; + +use super::{Allocation, CloneInfo}; +use crate::tree::Node; + +/// Scan-derived bounds before snapshots, open files, compression and changes +/// after the scan. Only the lower bound is projected onto the volume meter. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Estimate { + pub lower: u64, + pub upper: u64, + /// Missing metadata, bounded accounting or inconsistent observations of + /// one file, including more names than its reported link count. + pub partial: bool, +} + +#[derive(Clone, Copy, Default)] +struct Group { + members: u64, + references: u32, + shared: u64, + all_zero_private: bool, +} + +impl Group { + /// One file's membership of its clone group. + fn member(info: CloneInfo, allocated: u64) -> Self { + Self { + members: 1, + references: info.references, + shared: info.data_bytes.min( + allocated + .saturating_sub(info.private_bytes.unwrap_or(allocated)), + ), + all_zero_private: info.private_bytes == Some(0), + } + } + + fn credit(&self) -> Estimate { + let complete = + self.references >= 2 && self.members == u64::from(self.references); + Estimate { + lower: if complete { self.shared } else { 0 }, + upper: if complete && self.all_zero_private { + self.shared + } else { + 0 + }, + partial: false, + } + } +} + +#[derive(Clone)] +struct Links { + allocation: Allocation, + names: u64, +} + +impl Links { + const fn complete(&self) -> bool { + self.names == self.allocation.links + } +} + +#[derive(Clone, Default)] +pub(super) struct Accumulator { + base: Estimate, + credit: Estimate, + groups: FxHashMap<(u64, u64), Group>, + links: FxHashMap<(u64, u64), Links>, + limit: usize, + incomplete: bool, +} + +impl Accumulator { + pub(super) fn new(limit: usize) -> Self { + Self { + limit, + ..Self::default() + } + } + + pub(super) fn needs_selection(&self) -> bool { + !self.groups.is_empty() || !self.links.is_empty() || self.base.partial + } + + pub(super) const fn estimate(&self) -> Estimate { + Estimate { + lower: self.base.lower.saturating_add(if self.base.partial { + 0 + } else { + self.credit.lower + }), + upper: self.base.upper.saturating_add(self.credit.upper), + partial: self.base.partial || self.incomplete, + } + } + + pub(super) fn leaf(node: Node<'_>, limit: usize) -> Self { + work(); + let mut acc = Self::new(limit); + acc.add_leaf(node); + acc + } + + /// Add one file: its private and possible bytes, its clone group, or + /// its name among a hardlink's. This is what merging a file's own + /// accumulator did, without making one: a tree of millions of clones + /// allocated, merged and freed a set of maps for every file. + pub(super) fn add_leaf(&mut self, node: Node<'_>) { + let Some(allocation) = node.allocation() else { + self.base.lower = self.base.lower.saturating_add(node.bytes); + self.base.upper = self.base.upper.saturating_add(node.bytes); + return; + }; + if allocation.followed { + return; + } + if allocation.links > 1 { + if let Some(key) = allocation.identity { + self.join_links( + key, + Links { + allocation, + names: 1, + }, + ); + } else { + self.base.partial = true; + self.base.upper = + self.base.upper.saturating_add(allocation.bytes); + } + return; + } + if let Some(info) = self.bounds(&allocation, true) { + work(); + self.join( + (info.device, info.id), + Group::member(info, allocation.bytes), + ); + } + } + + fn file(&mut self, allocation: &Allocation, add: bool) { + if let Some(info) = self.bounds(allocation, add) { + self.member(info, allocation.bytes, add); + } + } + + /// A file's private and possible bytes; its clone facts when they can + /// join a group. + fn bounds( + &mut self, + allocation: &Allocation, + add: bool, + ) -> Option { + let info = allocation.clone; + // Missing clone facts may widen the bounds but cannot prove group + // completeness. Keep that limitation when crossing the window link. + self.incomplete |= info.is_some_and(CloneInfo::incomplete); + let private = info.map_or(allocation.bytes, |info| { + info.private_bytes.unwrap_or(0).min(allocation.bytes) + }); + let grouped = info.filter(|info| { + info.device != 0 + && info.id != 0 + && info.references >= 2 + && info.private_bytes.is_some() + }); + // A confirmed full clone retains no blocks while an external member + // remains. Modified/unknown sharing only supplies a lower bound. + let upper = if let Some(info) = grouped.filter(|_| private == 0) { + // PRIVATESIZE describes the data fork. Other forks may still + // have allocation even when that fork is fully shared. + allocation.bytes.saturating_sub(info.data_bytes) + } else { + allocation.bytes + }; + adjust(&mut self.base.lower, private, add); + adjust(&mut self.base.upper, upper, add); + grouped + } + + fn member(&mut self, info: CloneInfo, allocated: u64, add: bool) { + work(); + let key = (info.device, info.id); + if !self.groups.contains_key(&key) && self.groups.len() >= self.limit { + self.base.partial = true; + // Group credit cannot be proved, but these blocks may be freed. + if add && info.private_bytes == Some(0) { + self.base.upper = self.base.upper.saturating_add(allocated); + } + return; + } + let group = self.groups.entry(key).or_insert_with(|| Group { + all_zero_private: true, + shared: u64::MAX, + ..Group::default() + }); + let before = group.credit(); + let file = Group::member(info, allocated); + adjust(&mut group.members, file.members, add); + group.references = group.references.max(file.references); + group.shared = group.shared.min(file.shared); + group.all_zero_private &= file.all_zero_private; + replace(&mut self.credit, before, group.credit()); + } + + pub(super) fn merge(&mut self, mut other: Self) { + // Every entry moves only into a map at least as large. This also + // bounds long chains and groups distributed across many directories. + if self.groups.len() + self.links.len() + < other.groups.len() + other.links.len() + { + std::mem::swap(self, &mut other); + } + // Re-evaluate completed hardlinks after names from both sets merge. + // Removing their old contribution first avoids counting a clone + // member twice when its names straddle selected directories. + let other_links = std::mem::take(&mut other.links); + for links in other_links.values().filter(|links| links.complete()) { + other.file(&links.allocation, false); + } + self.base.lower = self.base.lower.saturating_add(other.base.lower); + self.base.upper = self.base.upper.saturating_add(other.base.upper); + self.base.partial |= other.base.partial; + self.incomplete |= other.incomplete; + for (key, group) in other.groups { + work(); + self.join(key, group); + } + for (key, links) in other_links { + work(); + self.join_links(key, links); + } + } + + fn join(&mut self, key: (u64, u64), group: Group) { + if !self.groups.contains_key(&key) && self.groups.len() >= self.limit { + self.base.partial = true; + self.base.upper = self.base.upper.saturating_add(group.shared); + return; + } + let old = self.groups.entry(key).or_insert_with(|| Group { + shared: u64::MAX, + all_zero_private: true, + ..Group::default() + }); + let before = old.credit(); + old.members += group.members; + old.references = old.references.max(group.references); + old.shared = old.shared.min(group.shared); + old.all_zero_private &= group.all_zero_private; + replace(&mut self.credit, before, old.credit()); + } + + fn join_links(&mut self, key: (u64, u64), links: Links) { + if let Some(old) = self.links.remove(&key) { + // Disagreement is permanent evidence even if these names never + // become complete. Otherwise `bounds` would retain it only when + // an intermediate join happened to complete this file. + self.incomplete |= old.allocation != links.allocation; + if old.complete() { + self.file(&old.allocation, false); + } + let mut allocation = old.allocation; + allocation.bytes = allocation.bytes.min(links.allocation.bytes); + allocation.links = allocation.links.max(links.allocation.links); + if allocation.clone != links.allocation.clone { + // Inconsistent live observations cannot authorize saving. + allocation.clone = Some(CloneInfo::default()); + } + let joined = Links { + allocation, + names: old.names + links.names, + }; + // With matching facts, exceeding the link count cannot be + // undone; a later larger count is itself a disagreement. + self.incomplete |= joined.names > joined.allocation.links; + if joined.complete() { + self.file(&joined.allocation, true); + } + self.links.insert(key, joined); + } else if self.links.len() < self.limit { + if links.complete() { + self.file(&links.allocation, true); + } + self.links.insert(key, links); + } else { + self.base.partial = true; + self.base.upper = + self.base.upper.saturating_add(links.allocation.bytes); + } + } +} + +const fn adjust(total: &mut u64, value: u64, add: bool) { + *total = if add { + total.saturating_add(value) + } else { + total.saturating_sub(value) + }; +} + +const fn replace(total: &mut Estimate, before: Estimate, after: Estimate) { + total.lower = total + .lower + .saturating_sub(before.lower) + .saturating_add(after.lower); + total.upper = total + .upper + .saturating_sub(before.upper) + .saturating_add(after.upper); +} + +/// Accepted non-overlapping aggregated subtrees are evaluated together, so complete +/// groups spanning separate marks receive credit once. +/// +/// Callers cache this scan-derived answer; removal authorization must still be checked afresh. +pub fn estimate<'a>(nodes: impl IntoIterator>) -> Estimate { + Selected::new(nodes).estimate() +} + +/// Reuse one gathered selection for its total, attribution and bounded peers. +pub struct Selected(Accumulator); + +impl Selected { + pub fn new<'a>(nodes: impl IntoIterator>) -> Self { + let mut total = Accumulator::new(super::MAX_CLONE_GROUPS); + for node in nodes { + total.merge(gather(node)); + } + Self(total) + } + + pub const fn estimate(&self) -> Estimate { + self.0.estimate() + } + + /// Disjoint alternatives and their combined union use the same engine. + /// Only candidates are gathered here; the selected tree is never re-walked. + pub fn additions( + &self, + candidates: &[Node<'_>], + ) -> (Vec<(Estimate, Estimate)>, Estimate) { + let mut combined = self.0.clone(); + let mut answers = Vec::with_capacity(candidates.len()); + for node in candidates { + let addition = gather(*node); + let alone = addition.estimate(); + let mut union = self.0.clone(); + union.merge(addition.clone()); + combined.merge(addition); + answers.push((alone, union.estimate())); + } + (answers, combined.estimate()) + } +} + +fn gather(node: Node<'_>) -> Accumulator { + if node.allocation().is_some_and(|info| info.followed) { + return Accumulator::new(super::MAX_CLONE_GROUPS); + } + if !node.is_dir() { + return Accumulator::leaf(node, super::MAX_CLONE_GROUPS); + } + work(); + // Aggregation retains a summary on any subtree whose metadata can + // interact with another mark, including zero-weight hardlink aliases. + // Ordinary subtrees need no second walk after a mark changes. + if node.stored_sharing().is_none() { + let mut total = Accumulator::new(super::MAX_CLONE_GROUPS); + total.base = Estimate { + lower: node.bytes, + upper: node.bytes, + partial: false, + }; + return total; + } + let mut total = Accumulator::new(super::MAX_CLONE_GROUPS); + for child in node.children() { + if child.is_dir() { + total.merge(gather(child)); + } else { + total.add_leaf(child); + } + } + total +} + +#[cfg(test)] +thread_local! { + /// Map entries visited, here and by `sharing::refresh`, which tests + /// hold to a budget. + pub(super) static WORK: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +#[cfg(not(test))] +pub(super) const fn work() {} + +#[cfg(test)] +pub(super) fn work() { + WORK.with(|work| work.set(work.get() + 1)); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tree::{Draft, Tree}; + use crate::tree::{Metric, NodeKind, Seen, aggregate_deduped}; + + fn file( + name: &str, + inode: u64, + links: u64, + clone: Option, + ) -> Draft { + let mut node = Draft::entry(name, NodeKind::File, 4096); + node.inode = + Some((1, std::num::NonZeroU64::new(inode).expect("inode"))); + node.allocation = Some(Box::new(Allocation { + bytes: 4096, + identity: Some((1, inode)), + links, + followed: false, + clone, + })); + node + } + + fn clone_info() -> CloneInfo { + CloneInfo { + device: 1, + id: 42, + references: 2, + private_bytes: Some(0), + data_bytes: 4096, + } + } + + #[test] + fn ten_worktrees_with_external_clones_free_only_their_private_files() { + const MIB: u64 = 1024 * 1024; + const LISTED: u64 = 10 * 1024 * MIB; + let mut root = Draft::directory("root"); + for inode in 1..=11 { + let mut dir = Draft::directory(format!("worktree-{inode}")); + let mut shared = file( + "shared", + inode, + 1, + Some(CloneInfo { + references: 11, + data_bytes: LISTED - 50 * MIB, + ..clone_info() + }), + ); + shared.bytes = LISTED - 50 * MIB; + shared.allocation.as_mut().expect("allocation").bytes = + shared.bytes; + dir.children.push(shared); + if inode <= 10 { + dir.children.push(Draft::entry( + "private", + NodeKind::File, + 50 * MIB, + )); + } + root.children.push(dir); + } + let mut tree = Tree::from(root); + aggregate_deduped(&mut tree, Metric::Bytes, &Seen::new()); + let root = tree.root(); + let selected = || root.children().iter().take(10); + assert_eq!(selected().map(|n| n.bytes).sum::(), 100 * 1024 * MIB); + assert_eq!( + estimate(selected()), + Estimate { + lower: 500 * MIB, + upper: 500 * MIB, + partial: false, + } + ); + // Including the surviving member completes the union exactly once. + assert_eq!(estimate(root.children()).lower, LISTED + 450 * MIB); + assert_eq!(estimate(root.children()).upper, LISTED + 450 * MIB); + } + + #[test] + fn clone_reference_counts_use_the_largest_observation_and_volume() { + let a = file("a", 1, 1, Some(clone_info())); + let mut info = clone_info(); + info.references = 3; + let b = file("b", 2, 1, Some(info)); + assert_eq!( + estimate([Tree::from(&a).root(), Tree::from(&b).root()]).lower, + 0 + ); + info.device = 2; + info.references = 2; + let c = file("c", 3, 1, Some(info)); + assert_eq!( + estimate([Tree::from(&a).root(), Tree::from(&c).root()]).lower, + 0 + ); + } + + #[test] + fn selected_aliases_free_nothing_until_the_last_real_name_is_selected() { + let mut root = Draft::directory("root"); + for name in ["a", "b"] { + let mut dir = Draft::directory(name); + dir.children.push(file("file", 1, 2, None)); + root.children.push(dir); + } + let mut tree = Tree::from(root); + aggregate_deduped(&mut tree, Metric::Bytes, &Seen::new()); + let root = tree.root(); + assert_eq!(root.bytes, 4096); + for child in root.children() { + assert_eq!(estimate([child]).lower, 0); + assert_eq!(child.sharing().reclaimable(child.bytes), 0); + } + assert_eq!(estimate(root.children()).lower, 4096); + assert_eq!(root.sharing().reclaimable(root.bytes), 4096); + } + + #[test] + fn hardlinks_are_one_clone_reference_even_across_marked_directories() { + let mut root = Draft::directory("root"); + for (name, inode, links) in [("a", 1, 2), ("b", 1, 2), ("c", 2, 1)] { + let mut dir = Draft::directory(name); + dir.children + .push(file("file", inode, links, Some(clone_info()))); + root.children.push(dir); + } + let mut tree = Tree::from(root); + aggregate_deduped(&mut tree, Metric::Bytes, &Seen::new()); + let root = tree.root(); + assert_eq!(root.bytes, 8192); + assert_eq!(root.sharing().duplicate_bytes, 4096); + assert_eq!(estimate(root.children().iter().take(2)).lower, 0); + assert_eq!(estimate(root.children()).lower, 4096); + assert_eq!(root.sharing().reclaimable(root.bytes), 4096); + assert_eq!(estimate(root.children()).upper, 4096); + } + + #[test] + fn changing_link_counts_are_partial_before_all_names_are_seen() { + // Two observations with link counts 2 and 3 disagree even though + // neither merge order completes the file's final set of names. + let trees = [ + Tree::from(file("a", 1, 2, None)), + Tree::from(file("b", 1, 3, None)), + ]; + assert!(estimate(trees.iter().map(Tree::root)).partial); + assert!(estimate(trees.iter().rev().map(Tree::root)).partial); + } + + #[test] + fn a_third_name_cannot_hide_conflicting_clone_observations() { + // Reduced from the flat-directory oracle's seed 132: the flat + // order completes two conflicting names before the third arrives; + // nesting completes two matching names, then joins the conflict. + let a = file("a", 1, 2, None); + let b = file("b", 1, 2, Some(clone_info())); + let c = file("c", 1, 2, Some(clone_info())); + let mut flat = Draft::directory("flat"); + flat.children = vec![a.clone(), b.clone(), c.clone()]; + let mut pair = Draft::directory("pair"); + pair.children = vec![b, c]; + let mut nested = Draft::directory("nested"); + nested.children = vec![a, pair]; + let mut flat = Tree::from(flat); + let mut nested = Tree::from(nested); + crate::tree::aggregate(&mut flat, Metric::Bytes); + crate::tree::aggregate(&mut nested, Metric::Bytes); + let flat = estimate([flat.root()]); + let nested = estimate([nested.root()]); + assert!(flat.partial); + assert!(nested.partial); + assert_eq!(flat, nested); + } + + #[test] + fn inconsistent_hardlinks_are_partial_without_completing_the_file() { + let mut smaller = file("smaller", 1, 3, None); + smaller.allocation.as_mut().expect("allocation").bytes = 2048; + for names in [ + vec![file("a", 1, 3, None), file("b", 1, 3, Some(clone_info()))], + vec![file("a", 1, 3, None), smaller], + vec![ + file("a", 1, 2, None), + file("b", 1, 2, None), + file("c", 1, 2, None), + ], + ] { + let trees: Vec<_> = names.into_iter().map(Tree::from).collect(); + let expected = Estimate { + partial: true, + ..Estimate::default() + }; + assert_eq!(estimate(trees.iter().map(Tree::root)), expected); + assert_eq!(estimate(trees.iter().rev().map(Tree::root)), expected); + } + // Unselected names alone are not inconsistent evidence. + assert_eq!( + estimate([Tree::from(file("a", 1, 3, None)).root()]), + Estimate::default() + ); + } + + #[test] + fn missing_identity_and_private_metadata_never_prove_a_complete_group() { + for missing in ["device", "id", "private", "references"] { + let mut info = clone_info(); + match missing { + "device" => info.device = 0, + "id" => info.id = 0, + "private" => info.private_bytes = None, + _ => info.references = 0, + } + let a = file("a", 1, 1, Some(info)); + let b = file("b", 2, 1, Some(info)); + let estimate = + estimate([Tree::from(&a).root(), Tree::from(&b).root()]); + assert_eq!(estimate.lower, 0, "{missing}"); + assert_eq!(estimate.upper, 8192, "{missing}"); + assert!(estimate.partial, "{missing}"); + } + } + + #[test] + fn modified_groups_and_unknown_sharing_supply_bounds_not_exact_savings() { + let mut info = clone_info(); + info.private_bytes = Some(1024); + let a = file("a", 1, 1, Some(info)); + let b = file("b", 2, 1, Some(info)); + assert_eq!(estimate([Tree::from(&a).root()]).lower, 1024); + assert_eq!(estimate([Tree::from(&a).root()]).upper, 4096); + assert_eq!( + estimate([Tree::from(&a).root(), Tree::from(&b).root()]).lower, + 5120 + ); + assert_eq!( + estimate([Tree::from(&a).root(), Tree::from(&b).root()]).upper, + 8192 + ); + } + + #[test] + fn followed_links_cannot_credit_the_target_or_complete_a_clone_group() { + let mut link = file("link", 1, 1, Some(clone_info())); + link.allocation.as_mut().expect("allocation").followed = true; + let real = file("real", 2, 1, Some(clone_info())); + let mut directory_link = Draft::directory("directory-link"); + directory_link.allocation = link.allocation.clone(); + directory_link.children.push(real.clone()); + assert_eq!( + estimate([Tree::from(&link).root(), Tree::from(&real).root()]) + .lower, + 0 + ); + assert_eq!(estimate([Tree::from(&directory_link).root()]).lower, 0); + } + + #[test] + fn bounded_grouping_drops_shared_credit_without_losing_private_bytes() { + let mut total = Accumulator::new(1); + for group in [1, 2] { + for inode in [1, 2] { + let mut info = clone_info(); + info.id = group; + info.private_bytes = Some(1024); + total.merge(Accumulator::leaf( + Tree::from(file("f", inode, 1, Some(info))).root(), + 1, + )); + } + } + let estimate = total.estimate(); + assert!(estimate.partial); + assert_eq!(estimate.lower, 4096); + assert!(estimate.upper >= estimate.lower); + assert!(total.groups.len() <= 1); + } + + #[test] + fn selected_set_work_scales_with_members_even_when_groups_and_marks_grow() { + let mut counts = Vec::new(); + for n in [128, 1024] { + let mut nodes = Vec::new(); + for group in 1..=n { + for alias in [0, 1] { + let mut dir = Draft::directory(format!("g{group}-{alias}")); + let mut info = clone_info(); + info.id = group; + for member in [1, 2] { + dir.children.push(file( + "f", + group * 2 + member, + 2, + Some(info), + )); + } + let mut dir = Tree::from(dir); + aggregate_deduped(&mut dir, Metric::Bytes, &Seen::new()); + nodes.push(dir); + } + } + WORK.set(0); + let value = estimate(nodes.iter().map(Tree::root)); + assert_eq!(value.lower, n * 4096); + let work = WORK.get(); + assert!(work < n * 40, "absolute work budget: {n}: {work}"); + counts.push(work); + } + assert!(counts[1] <= counts[0] * 16, "{counts:?}"); + eprintln!( + "selected-set accounting operations 128->1024 groups: {counts:?}" + ); + } +} + +#[cfg(test)] +#[cfg(unix)] +mod observation_tests { + use std::fs; + use std::os::unix::fs::MetadataExt as _; + use std::path::Path; + + use proptest::prelude::*; + + use super::*; + use crate::tree::{Draft, NodeKind, Tree}; + + fn observe(path: &Path) -> Draft { + let metadata = fs::metadata(path).expect("the observed name exists"); + let bytes = metadata.blocks() * 512; + let mut node = Draft::entry("observed", NodeKind::File, bytes); + node.allocation = Some(Box::new(Allocation { + bytes, + identity: Some((metadata.dev(), metadata.ino())), + links: metadata.nlink(), + followed: false, + clone: None, + })); + node + } + + fn check_observations( + extra_names: &[u8], + ) -> Result<(), proptest::test_runner::TestCaseError> { + let temp = tempfile::tempdir().expect("a temporary tree"); + let canonical = temp.path().canonicalize().expect("real root"); + let anchor = temp.path().join("anchor"); + fs::write(&anchor, [0; 4096]).expect("a file to link"); + let mut observations = Vec::new(); + let mut trees = Vec::new(); + for (index, extra) in extra_names.iter().copied().enumerate() { + let name = format!("observed-{index}"); + let path = temp.path().join(&name); + fs::hard_link(&anchor, &path).expect("a name to observe"); + let extras: Vec<_> = (0..extra) + .map(|at| { + let path = temp.path().join(format!("extra-{at}")); + fs::hard_link(&anchor, &path).expect("another name"); + path + }) + .collect(); + let observed = observe(&path); + let real = observe(&canonical.join(name)); + // macOS temp roots can be spelled through /var or /private; + // both spellings must supply the same accounting evidence. + prop_assert_eq!( + observed.allocation.as_deref(), + real.allocation.as_deref() + ); + observations + .push(*observed.allocation.as_deref().expect("retained facts")); + trees.push(Tree::from(observed)); + // A scan retains a name already observed even if it is + // unlinked before the next listing. The anchor keeps the + // inode alive, so later observations are of the same file. + fs::remove_file(path).expect("remove the observed name"); + for path in extras { + fs::remove_file(path).expect("remove an extra name"); + } + + // The final observations, with no intermediate sums: facts + // must agree and cannot describe more names than exist. + let first = observations[0]; + let partial = observations.iter().any(|info| *info != first) + || observations.len() as u64 > first.links; + let forward = estimate(trees.iter().map(Tree::root)); + let reverse = estimate(trees.iter().rev().map(Tree::root)); + prop_assert_eq!(forward.partial, partial); + prop_assert_eq!(reverse.partial, partial); + prop_assert_eq!(forward, reverse); + } + Ok(()) + } + + #[test] + fn two_observations_of_a_changing_link_count_stay_partial() { + // Shrunk from the property on pre-fix main: one inode observed + // with 4 links, then 2, while only two names have been selected. + check_observations(&[2, 0]).expect("partial in either order"); + } + + proptest! { + #![proptest_config(ProptestConfig { + cases: 32, + failure_persistence: None, + ..ProptestConfig::default() + })] + + #[test] + fn live_hardlink_observations_match_the_partial_model( + extra_names in prop::collection::vec(0_u8..4, 1..12), + ) { + check_observations(&extra_names)?; + } + } +} + +#[cfg(test)] +mod addition_tests { + use super::*; + use crate::tree::{Draft, Metric, NodeKind, Tree, aggregate}; + + #[test] + fn bounded_peer_unions_scale_with_metadata_not_pairs_of_files() { + let mut counts = Vec::new(); + for count in [128_u64, 1024] { + let mut root = Draft::directory("root"); + for member in 0..=20 { + let mut dir = Draft::directory(format!("member-{member}")); + for group in 1..=count { + let mut file = + Draft::entry(group.to_string(), NodeKind::File, 4096); + file.allocation = Some(Box::new(Allocation { + bytes: 4096, + identity: None, + links: 1, + followed: false, + clone: Some(CloneInfo { + device: 1, + id: group, + references: 21, + private_bytes: Some(0), + data_bytes: 4096, + }), + })); + dir.children.push(file); + } + root.children.push(dir); + } + let mut tree = Tree::from(root); + aggregate(&mut tree, Metric::Bytes); + let nodes: Vec<_> = tree.root().children().iter().collect(); + WORK.set(0); + let (alternatives, together) = + Selected::new(nodes[..1].iter().copied()) + .additions(&nodes[1..]); + assert!(alternatives.iter().all(|(_, union)| union.upper == 0)); + assert_eq!(together.lower, count * 4096); + let operations = WORK.get(); + assert!(operations < count * 200, "{count}: {operations}"); + counts.push(operations); + } + assert!(counts[1] <= counts[0] * 9, "{counts:?}"); + eprintln!( + "20 peer union accounting operations, 128 -> 1024 groups: {counts:?}" + ); + } +} diff --git a/crates/disktree-core/src/size.rs b/crates/disktree-core/src/size.rs index 69cbe624..59269bf8 100644 --- a/crates/disktree-core/src/size.rs +++ b/crates/disktree-core/src/size.rs @@ -10,6 +10,16 @@ pub fn human_bytes(bytes: u64) -> String { scale(bytes).format(1) } +/// `4.0 KiB` when the bounds meet, else `0 B–12 MiB`: a scan-derived +/// estimate, read the same in the window and by an agent. +pub fn human_bytes_range(lower: u64, upper: u64) -> String { + if lower == upper { + human_bytes(lower) + } else { + format!("{}\u{2013}{}", human_bytes(lower), human_bytes(upper)) + } +} + /// `1.4G`, `523M`, `12B`: for tile labels, where columns are scarce. pub fn human_bytes_short(bytes: u64) -> String { scale(bytes).format(0) diff --git a/crates/disktree-core/src/space.rs b/crates/disktree-core/src/space.rs index 2434c6cc..617d91a4 100644 --- a/crates/disktree-core/src/space.rs +++ b/crates/disktree-core/src/space.rs @@ -57,6 +57,25 @@ impl SpaceInfo { } } +/// A volume's used bytes can estimate a whole-volume walk, but a folder's +/// unknown size cannot use its containing disk as a completion denominator. +pub(crate) fn scan_volume_used( + root: &Path, + disk_root: Option<&Path>, + space: Option, + platform: &str, +) -> Option { + let whole_volume = disk_root == Some(root) + // The Data mount is exposed as `/` by `volume_root_for` on macOS. + || (platform == "macos" + && disk_root == Some(Path::new("/")) + && root == Path::new("/System/Volumes/Data")); + space + .filter(|_| whole_volume) + .map(|space| space.used()) + .filter(|&used| used > 0) +} + /// Read the space on the volume containing `path`. #[cfg(windows)] pub fn space_info(path: &Path) -> io::Result { @@ -105,10 +124,9 @@ pub fn device_in(table: &str, path: &Path) -> Option { .lines() .filter_map(|line| { let mut fields = line.split_whitespace(); - let device = fields.next()?; + let device = unescape_octal(fields.next()?); let mount = unescape_octal(fields.next()?); - path.starts_with(&mount) - .then(|| (mount.len(), device.to_string())) + path.starts_with(&mount).then_some((mount.len(), device)) }) .max_by_key(|(length, _)| *length) .map(|(_, device)| device) @@ -130,7 +148,8 @@ pub fn parse_mounts(table: &str) -> Vec { .lines() .filter_map(|line| { let mut fields = line.split_whitespace(); - let source = fields.next()?.to_string(); + // Escaped as in mountinfo: space, tab, newline and backslash. + let source = unescape_octal(fields.next()?); let point = PathBuf::from(unescape_octal(fields.next()?)); let fstype = fields.next()?.to_string(); let options = fields.next().unwrap_or_default().to_string(); @@ -658,23 +677,35 @@ pub const MACOS_DATA_VOLUME: &str = "/System/Volumes/Data"; /// Directories under `root` a scan must never enter, whatever the volume /// rules say, given where `root` really is (`canonical`). /// -/// On macOS: the Data volume's second mount, which is every firmlinked -/// directory again under another name, so walking it counts the disk twice; -/// and `/Network`, an automount point that would reach for a server. The +/// On macOS: `/Network`, an automount point that would reach for a server. +/// The Data volume is restricted separately to its private service stores, +/// so firmlinked directories are not visited again. The /// paths are returned in `root`'s own spelling, because that is how the walk /// names what it finds. pub fn never_scanned(root: &Path, canonical: &Path) -> Vec { if !cfg!(target_os = "macos") { return Vec::new(); } - [MACOS_DATA_VOLUME, "/Network"] - .iter() + std::iter::once("/Network") .filter_map(|skip| Path::new(skip).strip_prefix(canonical).ok()) .filter(|below| !below.as_os_str().is_empty()) .map(|below| root.join(below)) .collect() } +/// A Data mount below the root must expose only private service stores. +/// Scanning Data directly still walks the entire volume once. +pub fn data_services_only(root: &Path, canonical: &Path) -> Option { + if !cfg!(target_os = "macos") { + return None; + } + Path::new(MACOS_DATA_VOLUME) + .strip_prefix(canonical) + .ok() + .filter(|below| !below.as_os_str().is_empty()) + .map(|below| root.join(below)) +} + /// The top of the disk `path` lives on: its mount point, from `statfs`. /// /// The Data volume answers `/System/Volumes/Data`, but the disk a user @@ -864,15 +895,27 @@ fn is_volume_candidate(mount: &Mount) -> bool { { return false; } + // Sub-mounts under `/proc`, `/sys` and `/dev` (such as + // `/proc/sys/fs/binfmt_misc` or `/sys/fs/bpf`) are kernel and device + // interfaces, not storage volumes to offer for a scan. + if mount.point.starts_with("/proc") + || mount.point.starts_with("/sys") + || mount.point.starts_with("/dev") + { + return false; + } !matches!( mount.fstype.as_str(), "autofs" + | "binfmt_misc" + | "bpf" | "cgroup" | "cgroup2" | "configfs" | "debugfs" | "devpts" | "devtmpfs" + | "efivarfs" | "fuse.portal" | "fusectl" | "hugetlbfs" @@ -881,6 +924,7 @@ fn is_volume_candidate(mount: &Mount) -> bool { | "overlay" | "proc" | "pstore" + | "ramfs" | "securityfs" | "sysfs" | "tmpfs" @@ -944,6 +988,34 @@ pub fn volumes() -> Vec { mod tests { use super::*; + #[test] + fn scan_estimates_require_a_whole_volume_and_known_used_space() { + let space = Some(SpaceInfo { + total: 1000, + free: 100, + available: 80, + }); + let root = Path::new("/"); + let estimate = |path, disk, space, platform| { + scan_volume_used(path, disk, space, platform) + }; + assert_eq!(estimate(root, Some(root), space, "linux"), Some(900)); + assert_eq!(estimate(root, None, space, "linux"), None); + assert_eq!(estimate(root, Some(root), None, "linux"), None); + assert_eq!( + estimate(root, Some(root), Some(SpaceInfo::default()), "linux"), + None + ); + assert_eq!( + estimate(Path::new("/home"), Some(root), space, "linux"), + None + ); + let data = Path::new("/System/Volumes/Data"); + assert_eq!(estimate(data, Some(root), space, "macos"), Some(900)); + assert_eq!(estimate(data, Some(root), space, "linux"), None); + assert_eq!(estimate(data, None, space, "macos"), None); + } + const OMARCHY: &str = "\ sys /sys sysfs rw 0 0 run /run tmpfs rw 0 0 @@ -1082,6 +1154,40 @@ portal /run/user/1000/doc fuse.portal rw 0 0 assert_eq!(mounts[0].fstype, "ext4"); } + #[test] + fn mounts_escapes_are_decoded_once() { + let table = "/dev/sda1 /media/My\\040Disk\\134040 ext4 rw 0 0\n\ + //nas/My\\040Share /mnt/tab\\011name cifs rw 0 0\n"; + let mounts = parse_mounts(table); + assert_eq!(mounts.len(), 2); + assert_eq!(mounts[0].point, Path::new("/media/My Disk\\040")); + assert_eq!(mounts[1].point, Path::new("/mnt/tab\tname")); + assert_eq!(mounts[1].source, "//nas/My Share"); + assert_eq!( + device_in(table, Path::new("/media/My Disk\\040/a")).as_deref(), + Some("/dev/sda1") + ); + assert_eq!( + device_in(table, Path::new("/mnt/tab\tname/a")).as_deref(), + Some("//nas/My Share") + ); + } + + #[test] + fn mount_sources_decode_tabs_newlines_and_literal_escape_text_once() { + let source = "//nas/My Share\ttab\nline\\040"; + let table = "//nas/My\\040Share\\011tab\\012line\\134040 /mnt/share cifs rw 0 0\n"; + let mounts = parse_mounts(table); + assert_eq!(mounts[0].source, source); + assert_eq!( + device_in(table, Path::new("/mnt/share/child")).as_deref(), + Some(source) + ); + assert_eq!(device_in(table, Path::new("/mnt/share-other")), None); + let info = "1 0 0:1 / /mnt/share rw - cifs //nas/My\\040Share\\011tab\\012line\\134040 rw\n"; + assert_eq!(parse_mountinfo(info)[0].source, mounts[0].source); + } + #[test] fn volumes_with_least_space_come_first_and_unknowns_last() { let volume = |name: &str, available: Option| Volume { @@ -1175,6 +1281,60 @@ portal /run/user/1000/doc fuse.portal rw 0 0 assert!(points.contains(&PathBuf::from("/var/log")), "{points:?}"); } + #[test] + fn kernel_pseudo_filesystems_are_excluded_from_volume_candidates() { + let table = "\ +/dev/sda1 / ext4 rw 0 0 +/dev/sdb1 /home ext4 rw 0 0 +proc /proc proc rw 0 0 +binfmt_misc /proc/sys/fs/binfmt_misc binfmt_misc rw 0 0 +sysfs /sys sysfs rw 0 0 +bpf /sys/fs/bpf bpf rw 0 0 +efivarfs /sys/firmware/efi/efivars efivarfs rw 0 0 +devtmpfs /dev devtmpfs rw 0 0 +devpts /dev/pts devpts rw 0 0 +none /mnt/ramdisk ramfs rw 0 0 +"; + let volumes = volume_roots_in(&parse_mounts(table)); + assert!(volumes.iter().all(|volume| volume.space.is_none())); + let points: Vec<_> = volumes + .iter() + .map(|volume| volume.point.as_path()) + .collect(); + assert_eq!( + points, + [Path::new("/"), Path::new("/home")], + "only real storage disks remain as volume candidates" + ); + } + + #[test] + fn discovery_filters_types_and_whole_kernel_path_components() { + let mounts = parse_mounts( + "unknown /proc/unknown unknown rw 0 0\n\ + unknown /sys/unknown unknown rw 0 0\n\ + unknown /dev/unknown unknown rw 0 0\n\ + none /mnt/binfmt binfmt_misc rw 0 0\n\ + none /mnt/bpf bpf rw 0 0\n\ + none /mnt/efi efivarfs rw 0 0\n\ + none /mnt/ram ramfs rw 0 0\n\ + /dev/a /process ext4 rw 0 0\n\ + /dev/b /system btrfs rw 0 0\n\ + nas:/disk /device nfs rw 0 0\n", + ); + let roots = volume_roots_in(&mounts); + let points: Vec<_> = roots.iter().map(|v| v.point.as_path()).collect(); + assert_eq!( + points, + [ + Path::new("/device"), + Path::new("/process"), + Path::new("/system") + ] + ); + assert!(roots.iter().all(|v| v.space.is_none())); + } + #[test] fn separate_home_disk_is_its_own_volume() { let separate = parse_mounts( @@ -1371,7 +1531,7 @@ map auto_home on /System/Volumes/Data/home (autofs, automounted, nobrowse) } #[test] - fn only_macos_skips_the_data_volume_and_in_the_roots_spelling() { + fn macos_restricts_data_aliases_but_direct_data_scans_are_unrestricted() { let skipped = never_scanned(Path::new("/"), Path::new("/")); let below_system = never_scanned(Path::new("/System/"), Path::new("/System")); @@ -1382,19 +1542,34 @@ map auto_home on /System/Volumes/Data/home (autofs, automounted, nobrowse) Path::new(MACOS_DATA_VOLUME), ); if cfg!(target_os = "macos") { + assert_eq!(skipped, vec![PathBuf::from("/Network")]); + assert!(below_system.is_empty()); assert_eq!( - skipped, - vec![PathBuf::from(MACOS_DATA_VOLUME), "/Network".into()] - ); - assert_eq!( - below_system, - vec![PathBuf::from("/System/Volumes/Data")] + data_services_only( + Path::new("/spelling"), + Path::new("/System") + ), + Some(PathBuf::from("/spelling/Volumes/Data")) ); } else { assert!(skipped.is_empty() && below_system.is_empty()); } assert!(inside.is_empty()); assert!(itself.is_empty(), "asking for it by name scans it"); + assert_eq!( + data_services_only( + Path::new(MACOS_DATA_VOLUME), + Path::new(MACOS_DATA_VOLUME) + ), + None + ); + assert_eq!( + data_services_only( + Path::new("/Users/tobi"), + Path::new("/Users/tobi") + ), + None + ); } #[test] diff --git a/crates/disktree-core/src/test_rng.rs b/crates/disktree-core/src/test_rng.rs new file mode 100644 index 00000000..8537a6be --- /dev/null +++ b/crates/disktree-core/src/test_rng.rs @@ -0,0 +1,37 @@ +//! A seeded generator for tests that try many random cases: the same +//! seed gives the same case, so a failure names the seed that made it. + +/// `SplitMix64`: small, fast and good enough to pick test cases. +pub struct Rng(u64); + +impl Rng { + pub const fn new(seed: u64) -> Self { + Self(seed) + } + + pub const fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + /// A number below `n`, which must not be zero. + pub fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + + /// True `percent` times in a hundred. + pub fn percent(&mut self, percent: u64) -> bool { + self.below(100) < percent + } + + pub fn shuffle(&mut self, items: &mut [T]) { + for at in (1..items.len()).rev() { + let other = usize::try_from(self.below(at as u64 + 1)) + .expect("an index fits"); + items.swap(at, other); + } + } +} diff --git a/crates/disktree-core/src/tree.rs b/crates/disktree-core/src/tree.rs index 4bbeda44..e55b6f42 100644 --- a/crates/disktree-core/src/tree.rs +++ b/crates/disktree-core/src/tree.rs @@ -1,14 +1,12 @@ //! The scanned tree. -use std::num::NonZeroU64; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{LazyLock, Mutex, OnceLock}; -use rayon::prelude::*; use rustc_hash::FxHashSet; -use crate::classify::{Category, Reclaim}; +use crate::path_style::PathStyle; /// What a node represents on disk. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -62,62 +60,43 @@ impl Metric { } } -/// One entry in the scanned tree. +pub use crate::index::{ + Block, Builder, Built, Children, Facts, Iter, MAX_NAME_BYTES, Node, + NodeMut, Sibling, StorageBytes, Tree, +}; + +/// A node and everything beneath it, owned and on the heap. /// -/// `bytes` and `files` are the subtree totals the treemap draws; what sits -/// directly in a directory is [`Self::own_bytes`] and [`Self::own_files`], -/// read from its children when the selection line asks. A disk holds tens -/// of millions of nodes, so every field is paid that many times: the size -/// is held by a test. +/// How tests and small trees are written before they become a [`Tree`]; a +/// scan builds its tree in place, through [`Tree::build`]. Its +/// facts read and write through `Deref`, as a node's do. #[derive(Clone, Debug)] -pub struct Node { +pub struct Draft { pub name: Box, - pub kind: NodeKind, - /// Subtree total: direct contents plus every descendant. A file's own - /// size, or nothing for a second name of a file already charged. - pub bytes: u64, - /// Files at or beneath this node; `1` for a file. - pub files: u64, - /// Directories at or beneath this node; `1` for a directory. Four - /// billion is more than any volume holds. - pub dirs: u32, - /// `(device, inode)` for files, used to de-duplicate hardlinks. No file - /// has inode zero, which lets `None` cost nothing. - pub inode: Option<(u64, NonZeroU64)>, - /// The directory could not be read; its contents are unknown. - pub read_error: bool, - /// Newest write time at or beneath this node, in Unix seconds; `0` when - /// unknown. Derived for directories by [`aggregate`]. - pub modified: i64, - /// What kind of data this is, for colour. Set by [`crate::classify`]. - pub category: Category, - /// Why this space can be had back, if it can. Set by - /// [`crate::classify`]; inherited by everything beneath. - pub reclaim: Option, - /// Children, ordered by [`Metric`] value, descending. + pub facts: Facts, + pub allocation: Option>, + pub sharing: Option>, pub children: Vec, } -impl Node { +impl std::ops::Deref for Draft { + type Target = Facts; + + fn deref(&self) -> &Facts { + &self.facts + } +} + +impl std::ops::DerefMut for Draft { + fn deref_mut(&mut self) -> &mut Facts { + &mut self.facts + } +} + +impl Draft { /// A directory with no children yet. - #[allow( - clippy::missing_const_for_fn, - reason = "`impl Into>` cannot be called in a const fn" - )] pub fn directory(name: impl Into>) -> Self { - Self { - name: name.into(), - kind: NodeKind::Directory, - bytes: 0, - files: 0, - dirs: 1, - inode: None, - read_error: false, - modified: 0, - category: Category::Other, - reclaim: None, - children: Vec::new(), - } + Self::of(name, Facts::directory()) } /// A leaf entry. @@ -126,87 +105,119 @@ impl Node { kind: NodeKind, bytes: u64, ) -> Self { + Self::of(name, Facts::entry(kind, bytes)) + } + + fn of(name: impl Into>, facts: Facts) -> Self { Self { name: name.into(), - kind, - bytes, - files: u64::from(kind == NodeKind::File), - dirs: 0, - inode: None, - read_error: false, - modified: 0, - category: Category::Other, - reclaim: None, + facts, + allocation: None, + sharing: None, children: Vec::new(), } } +} + +impl Node<'_> { + /// This node and everything beneath it as a [`Draft`], to change its + /// shape and build again. + pub fn to_draft(self) -> Draft { + let mut draft = Draft::of(self.name(), *self.facts()); + draft.allocation = self.allocation().map(Box::new); + draft.sharing = self.stored_sharing().copied().map(Box::new); + draft.children = self.children().iter().map(Self::to_draft).collect(); + draft + } - pub const fn is_dir(&self) -> bool { - self.kind.is_dir() + /// Sparse: ordinary files do not pay for five additional byte counters. + pub fn sharing(self) -> crate::sharing::Sharing { + self.stored_sharing() + .copied() + .unwrap_or_else(|| crate::sharing::leaf_summary(self)) + } + + pub const fn is_dir(self) -> bool { + self.facts().kind.is_dir() } /// Bytes of the leaf entries directly in this directory, or this file's /// own size. - pub fn own_bytes(&self) -> u64 { + pub fn own_bytes(self) -> u64 { if !self.is_dir() { return self.bytes; } - self.children + self.children() .iter() .filter(|child| !child.is_dir()) .fold(0, |sum, child| child.bytes.saturating_add(sum)) } /// Files directly in this directory; `1` for a file. - pub fn own_files(&self) -> u64 { + pub fn own_files(self) -> u64 { if !self.is_dir() { return self.files; } - self.children + self.children() .iter() .filter(|child| !child.is_dir()) .map(|child| child.files) .sum() } - /// [`Self::inode`] as the plain pair a platform reports. - pub fn identity(&self) -> Option<(u64, u64)> { + /// [`Facts::inode`] as the plain pair a platform reports. + pub fn identity(self) -> Option<(u64, u64)> { self.inode.map(|(device, file)| (device, file.get())) } /// The value a treemap should weight this node by. - pub const fn value(&self, metric: Metric) -> u64 { - match metric { - Metric::Bytes => self.bytes, - Metric::Files => self.files, - } + pub const fn value(self, metric: Metric) -> u64 { + self.facts().value(metric) } /// The child with this name, if there is one. - pub fn child_named(&self, name: &str) -> Option<&Self> { - self.children.iter().find(|child| &*child.name == name) + pub fn child_named(self, name: &str) -> Option { + self.children().iter().find(|child| child.name() == name) } - pub fn child(&self, index: usize) -> Option<&Self> { - self.children.get(index) + pub fn child(self, index: usize) -> Option { + self.children().get(index) + } + + /// The node at `relative`, a path below this one, with the crumbs that + /// lead there. Components are compared one at a time, so a name holding + /// a separator cannot stand for two. + pub fn descend(self, relative: &Path) -> Option<(Vec, Self)> { + let mut node = self; + let mut crumbs = Vec::new(); + for component in relative.components() { + let name = component.as_os_str().to_string_lossy(); + let index = node + .children() + .iter() + .position(|child| child.name() == name)?; + node = node.children().at(index); + crumbs.push(index); + } + Some((crumbs, node)) } /// Follow `crumbs` from this node. Crumbs are child indices, so they stay /// valid across re-sorting only for the tree they were produced from. - pub fn resolve(&self, crumbs: &[usize]) -> Option<&Self> { + pub fn resolve(self, crumbs: &[usize]) -> Option { let mut node = self; for &index in crumbs { - node = node.children.get(index)?; + node = node.children().get(index)?; } Some(node) } /// The chain of nodes ending at `crumbs`, including this node. - pub fn resolve_chain<'a>(&'a self, crumbs: &[usize]) -> Vec<&'a Self> { + pub fn resolve_chain(self, crumbs: &[usize]) -> Vec { let mut chain = vec![self]; let mut node = self; for &index in crumbs { - match node.children.get(index) { + match node.children().get(index) { Some(child) => { chain.push(child); node = child; @@ -218,8 +229,8 @@ impl Node { } /// Index of the largest child, used to pick a useful descent target. - pub const fn largest_child(&self) -> Option { - if self.children.is_empty() { + pub fn largest_child(self) -> Option { + if self.children().is_empty() { None } else { Some(0) @@ -227,8 +238,8 @@ impl Node { } /// Depth of the deepest descendant. - pub fn depth(&self) -> u32 { - self.children + pub fn depth(self) -> u32 { + self.children() .iter() .map(Self::depth) .max() @@ -237,15 +248,15 @@ impl Node { /// Breadth-first search for the first node whose name contains `needle` /// (case-insensitive), returning its crumbs and the node. - pub fn find(&self, needle: &str) -> Option<(Vec, &Self)> { + pub fn find(self, needle: &str) -> Option<(Vec, Self)> { let needle = needle.to_lowercase(); if needle.is_empty() { return None; } let mut queue = vec![(Vec::new(), self)]; while let Some((crumbs, node)) = queue.pop() { - for (index, child) in node.children.iter().enumerate() { - if child.name.to_lowercase().contains(&needle) { + for (index, child) in node.children().iter().enumerate() { + if child.name().to_lowercase().contains(&needle) { let found: Vec = crumbs .iter() .copied() @@ -253,7 +264,7 @@ impl Node { .collect(); return Some((found, child)); } - if child.is_dir() && !child.children.is_empty() { + if child.is_dir() && !child.children().is_empty() { let mut next = crumbs.clone(); next.push(index); queue.push((next, child)); @@ -272,16 +283,58 @@ impl Node { /// and [`Node::own_files`]. Deriving them is what keeps them consistent: /// hardlink de-duplication rewrites a leaf's weight, and every total above /// it follows without a second pass. -pub fn aggregate(node: &mut Node, metric: Metric) { - aggregate_at(node, metric, 0, None); +pub fn aggregate(tree: &mut Tree, metric: Metric) { + aggregate_tree(tree, metric, None); + crate::sharing::refresh(tree); +} + +/// Every directory's totals from its children, then its children in +/// order, with separate subtrees near the top on separate workers. +fn aggregate_tree(tree: &mut Tree, metric: Metric, seen: Option<&Seen>) { + tree.par_bottom_up( + |facts| { + // Every name of a file has the file's size, so one that weighs + // nothing need not be remembered to be charged once. + if facts.bytes > 0 + && let Some(seen) = seen + && let Some((device, file)) = facts.inode + && !seen.insert((device, file.get())) + { + facts.bytes = 0; + } + }, + |facts, mut block| { + let mut bytes = 0; + let mut files = 0; + let mut dirs: u32 = 1; + let mut modified = 0; + let mut read_error = facts.read_error; + for child in block.iter() { + read_error |= child.read_error; + modified = modified.max(child.modified); + // Saturating: a corrupt volume's file table can claim any + // size. + bytes = child.bytes.saturating_add(bytes); + files += child.files; + dirs += child.dirs; + } + facts.read_error = read_error; + facts.bytes = bytes; + facts.files = files; + facts.dirs = dirs; + facts.modified = modified; + order(&mut block, metric); + }, + ); } /// [`aggregate`], charging a hardlinked file once: a leaf whose identity /// `seen` already holds weighs nothing. Which of a file's names is charged /// is whichever a worker reaches first, so two scans of an unchanged tree /// can split it differently between folders; the totals are the same. -pub(crate) fn aggregate_deduped(node: &mut Node, metric: Metric, seen: &Seen) { - aggregate_at(node, metric, 0, Some(seen)); +pub(crate) fn aggregate_deduped(tree: &mut Tree, metric: Metric, seen: &Seen) { + aggregate_tree(tree, metric, Some(seen)); + crate::sharing::refresh(tree); } /// Identities a finish pass has met. @@ -350,76 +403,51 @@ impl Seen { } } -/// Levels whose subtrees are aggregated in parallel. A top level already +/// Levels whose subtrees are built in parallel. A top level already /// splits a disk into enough work for every thread; below it a parallel /// frame per level would only cut the depth that fits in a worker's stack. pub(crate) const PARALLEL_LEVELS: usize = 4; -fn aggregate_at( - node: &mut Node, - metric: Metric, - depth: usize, - seen: Option<&Seen>, -) { - if !node.is_dir() { - // Every name of a file has the file's size, so one that weighs - // nothing need not be remembered to be charged once. - if node.bytes > 0 - && let Some(seen) = seen - && let Some(key) = node.identity() - && !seen.insert(key) - { - node.bytes = 0; - } - return; - } - - let mut bytes = 0; - let mut files = 0; - let mut dirs: u32 = 1; - let mut modified = 0; - if depth < PARALLEL_LEVELS { - node.children - .par_iter_mut() - .for_each(|child| aggregate_at(child, metric, depth + 1, seen)); - } else { - for child in &mut node.children { - aggregate_at(child, metric, depth + 1, seen); - } - } - for child in &node.children { - modified = modified.max(child.modified); - // Saturating: a corrupt volume's file table can claim any size. - bytes = child.bytes.saturating_add(bytes); - files += child.files; - dirs += child.dirs; - } - node.bytes = bytes; - node.files = files; - node.dirs = dirs; - node.modified = modified; +/// Order every directory's children by `metric`, largest first, leaving +/// every total and sharing figure as it is. +/// +/// For a tree [`aggregate`] has already derived, this is all a change of +/// metric needs: totals and sharing are sums and unions over children, so +/// the order they are visited in changes none of them. On a scanned tree +/// of 19 million nodes this took 0.03 to 0.06 s; the sharing pass that +/// `aggregate` adds took 0.5 to 0.8 s. +pub fn reorder(tree: &mut Tree, metric: Metric) { + tree.par_bottom_up(|_| {}, |_, mut block| order(&mut block, metric)); +} +fn order(block: &mut Block<'_>, metric: Metric) { // Largest first: a treemap lays out big tiles best, and the order is what // makes "descend into the largest child" meaningful. Unstable: names in // one directory are distinct, and the only ties are names that decoded // to the same lossy text, whose order does not matter, so the stable // sort's scratch allocation buys nothing. - node.children.sort_unstable_by(|left, right| { + block.sort_by(|left, right| { right .value(metric) .cmp(&left.value(metric)) - .then_with(|| left.name.cmp(&right.name)) + .then_with(|| left.name.cmp(right.name)) }); } -/// Absolute path of the node at `crumbs` beneath a scanned root. -pub fn path_of(root_path: &Path, root: &Node, crumbs: &[usize]) -> PathBuf { +/// Absolute path of the node at `crumbs` beneath a scanned root, joined by +/// the rules of the machine that was scanned. +pub fn path_of( + root_path: &Path, + root: Node<'_>, + crumbs: &[usize], + style: PathStyle, +) -> PathBuf { let mut path = root_path.to_path_buf(); let mut node = root; for &index in crumbs { - match node.children.get(index) { + match node.children().get(index) { Some(child) => { - path.push(&*child.name); + style.push(&mut path, child.name()); node = child; } None => break, @@ -431,17 +459,10 @@ pub fn path_of(root_path: &Path, root: &Node, crumbs: &[usize]) -> PathBuf { #[cfg(test)] mod tests { use super::*; + use std::num::NonZeroU64; - fn leaf(name: &str, bytes: u64) -> Node { - Node::entry(name, NodeKind::File, bytes) - } - - /// A home directory is tens of millions of nodes: every byte here is - /// tens of megabytes there. - #[test] - #[cfg(target_pointer_width = "64")] - fn a_node_stays_small() { - assert_eq!(size_of::(), 88); + fn leaf(name: &str, bytes: u64) -> Draft { + Draft::entry(name, NodeKind::File, bytes) } #[test] @@ -466,7 +487,7 @@ mod tests { // name of the newer one. let older = (7, (1 << 48) | 0x2A); let newer = (7, (2 << 48) | 0x2A); - let mut root = Node::directory("root"); + let mut root = Draft::directory("root"); for (name, bytes, key) in [ ("older", 4096, older), ("newer", 8192, newer), @@ -476,116 +497,171 @@ mod tests { file.inode = Some((key.0, NonZeroU64::new(key.1).unwrap())); root.children.push(file); } - aggregate_deduped(&mut root, Metric::Bytes, &Seen::new()); - assert_eq!(root.bytes, 4096 + 8192); + let mut tree = Tree::from(root); + aggregate_deduped(&mut tree, Metric::Bytes, &Seen::new()); + assert_eq!(tree.root().bytes, 4096 + 8192); } #[test] fn aggregate_derives_totals_and_orders_children() { - let mut root = Node::directory("root"); - let mut nested = Node::directory("child"); + let mut root = Draft::directory("root"); + let mut nested = Draft::directory("child"); nested.children.push(leaf("deep", 7)); root.children.push(nested); root.children.push(leaf("direct", 5)); root.children.push(leaf("small", 9)); - aggregate(&mut root, Metric::Bytes); + let mut tree = Tree::from(root); + aggregate(&mut tree, Metric::Bytes); + let root = tree.root(); assert_eq!(root.own_bytes(), 5 + 9, "direct leaves only"); assert_eq!(root.bytes, 5 + 9 + 7); assert_eq!(root.files, 3); assert_eq!(root.own_files(), 2); assert_eq!(root.dirs, 2); - assert_eq!(child_named(&root, "child").own_bytes(), 7); - assert_eq!(&*root.children[0].name, "small", "9 bytes, largest first"); - assert_eq!(&*root.children[2].name, "direct"); + assert_eq!(child_named(root, "child").own_bytes(), 7); + assert_eq!( + root.children().at(0).name(), + "small", + "9 bytes, largest first" + ); + assert_eq!(root.children().at(2).name(), "direct"); // A file's own size is what it weighs; aggregates never invent more. - let mut single = leaf("solo", 3); + let mut single = Tree::from(leaf("solo", 3)); aggregate(&mut single, Metric::Bytes); + let single = single.root(); assert_eq!(single.bytes, 3); assert_eq!(single.own_bytes(), 3); assert_eq!(single.files, 1); assert_eq!(single.dirs, 0); } - fn child_named<'a>(node: &'a Node, name: &str) -> &'a Node { - node.children + fn child_named<'a>(node: Node<'a>, name: &str) -> Node<'a> { + node.children() .iter() - .find(|child| &*child.name == name) + .find(|child| child.name() == name) .unwrap_or_else(|| panic!("no child named {name}")) } #[test] fn aggregate_can_rank_by_file_count() { - let mut root = Node::directory("root"); - let mut many = Node::directory("many"); + let mut root = Draft::directory("root"); + let mut many = Draft::directory("many"); for index in 0..5 { many.children.push(leaf(&format!("f{index}"), 1)); } root.children.push(many); root.children.push(leaf("huge", 10_000)); + let mut tree = Tree::from(root); + aggregate(&mut tree, Metric::Bytes); + assert_eq!(tree.root().children().at(0).name(), "huge"); + aggregate(&mut tree, Metric::Files); + assert_eq!(tree.root().children().at(0).name(), "many"); + assert_eq!(tree.root().children().at(0).files, 5); + } + + #[test] + fn reorder_matches_aggregate_without_touching_totals() { + let mut root = Draft::directory("root"); + let mut many = Draft::directory("many"); + for index in 0..5 { + many.children.push(leaf(&format!("f{index}"), 1)); + } + many.children.push(leaf("big", 50)); + root.children.push(many); + root.children.push(leaf("huge", 10_000)); + let mut root = Tree::from(root); aggregate(&mut root, Metric::Bytes); - assert_eq!(&*root.children[0].name, "huge"); - aggregate(&mut root, Metric::Files); - assert_eq!(&*root.children[0].name, "many"); - assert_eq!(root.children[0].files, 5); + + for metric in [Metric::Files, Metric::Bytes, Metric::Files] { + let mut reordered = root.clone(); + reorder(&mut reordered, metric); + aggregate(&mut root, metric); + let (reordered, root) = (reordered.root(), root.root()); + assert_eq!(names(reordered), names(root), "{metric:?}"); + assert_eq!(reordered.bytes, root.bytes); + assert_eq!(reordered.files, root.files); + assert_eq!(reordered.dirs, root.dirs); + assert_eq!(reordered.sharing(), root.sharing()); + } + } + + fn names(node: Node<'_>) -> Vec { + std::iter::once(node.name().to_string()) + .chain(node.children().iter().flat_map(names)) + .collect() } #[test] fn resolve_walks_child_indices() { - let mut root = Node::directory("root"); - let mut nested = Node::directory("child"); + let mut root = Draft::directory("root"); + let mut nested = Draft::directory("child"); nested.children.push(leaf("deep", 1)); root.children.push(nested); + let tree = Tree::from(root); + let root = tree.root(); assert!(root.resolve(&[]).is_some()); - assert_eq!(root.resolve(&[0, 0]).map(|n| &*n.name), Some("deep")); + assert_eq!(root.resolve(&[0, 0]).map(Node::name), Some("deep")); assert!(root.resolve(&[0, 1]).is_none()); assert_eq!(root.resolve_chain(&[0, 0]).len(), 3); } #[test] fn path_of_joins_names_beneath_the_root() { - let mut root = Node::directory("root"); - let mut nested = Node::directory("child"); + let mut root = Draft::directory("root"); + let mut nested = Draft::directory("child"); nested.children.push(leaf("deep", 1)); root.children.push(nested); + let tree = Tree::from(root); + let root = tree.root(); - let path = path_of(Path::new("/home/tobi"), &root, &[0, 0]); + let path = + path_of(Path::new("/home/tobi"), root, &[0, 0], PathStyle::Native); assert_eq!(path, PathBuf::from("/home/tobi/child/deep")); + // A Unix host's path is joined with `/` on every client. + let path = + path_of(Path::new("/home/tobi"), root, &[0, 0], PathStyle::Posix); + assert_eq!(path.to_str(), Some("/home/tobi/child/deep")); } #[test] fn largest_child_is_the_first_child_because_children_are_sorted() { - let mut root = Node::directory("root"); + let mut root = Draft::directory("root"); root.children.push(leaf("big", 10)); root.children.push(leaf("small", 1)); - assert_eq!(root.largest_child(), Some(0)); - assert_eq!(Node::directory("empty").largest_child(), None); + assert_eq!(Tree::from(root).root().largest_child(), Some(0)); + assert_eq!( + Tree::from(Draft::directory("empty")).root().largest_child(), + None + ); } #[test] fn find_reports_crumbs_and_is_case_insensitive() { - let mut root = Node::directory("root"); - let mut target = Node::directory("target"); + let mut root = Draft::directory("root"); + let mut target = Draft::directory("target"); target.children.push(leaf("needle-file", 1)); root.children.push(target); + let tree = Tree::from(root); + let root = tree.root(); let (crumbs, found) = root.find("NEEDLE").expect("found"); assert_eq!(crumbs, vec![0, 0]); - assert_eq!(&*found.name, "needle-file"); + assert_eq!(found.name(), "needle-file"); assert!(root.find("").is_none()); assert!(root.find("absent").is_none()); } #[test] fn depth_counts_edges() { - let mut root = Node::directory("root"); - let mut nested = Node::directory("child"); + let mut root = Draft::directory("root"); + let mut nested = Draft::directory("child"); nested.children.push(leaf("deep", 1)); root.children.push(nested); - assert_eq!(root.depth(), 2); - assert_eq!(leaf("x", 0).depth(), 0); + assert_eq!(Tree::from(root).root().depth(), 2); + assert_eq!(Tree::from(leaf("x", 0)).root().depth(), 0); } } diff --git a/crates/disktree-core/src/treemap.rs b/crates/disktree-core/src/treemap.rs index 598b5590..d7e07832 100644 --- a/crates/disktree-core/src/treemap.rs +++ b/crates/disktree-core/src/treemap.rs @@ -145,7 +145,7 @@ impl Default for LayoutOptions { /// being drawn: a caller that resolves a tile from the scanned root gets that /// tile, at any depth. pub fn layout( - root: &Node, + root: Node<'_>, root_crumbs: &[usize], area: Rect, metric: Metric, @@ -157,7 +157,7 @@ pub fn layout( /// [`layout`], showing only what `filter` keeps: its matches, at the size /// of what matched, inside ancestors sized the same way. pub fn layout_filtered( - root: &Node, + root: Node<'_>, root_crumbs: &[usize], area: Rect, metric: Metric, @@ -185,7 +185,7 @@ struct Placement<'a> { } fn place_children( - node: &Node, + node: Node<'_>, area: Rect, place: &Placement<'_>, depth: u32, @@ -193,14 +193,14 @@ fn place_children( out: &mut Vec, ) { let (metric, options) = (place.metric, place.options); - if node.children.is_empty() || area.w <= 0.0 || area.h <= 0.0 { + if node.children().is_empty() || area.w <= 0.0 || area.h <= 0.0 { return; } // Rank by importance ourselves: the tree is already sorted, but a metric // switch or a hand-built tree must not produce a bad layout. let mut ranked: Vec<(usize, f64)> = node - .children + .children() .iter() .enumerate() .filter_map(|(index, child)| { @@ -208,7 +208,7 @@ fn place_children( None => child.value(metric), Some(filter) => { crumbs.push(index); - let keep = filter.keep(crumbs); + let keep = filter.keep_at(crumbs, child); crumbs.pop(); Matches::value(keep?, child, metric) } @@ -257,7 +257,7 @@ fn place_children( continue; }; - let child = &node.children[index]; + let child = node.children().at(index); let subdividable = child.is_dir() && depth + 1 < options.max_depth; // A directory that is about to be subdivided claims a header band for // its own name. When there is no room for one it stays whole: a name @@ -422,16 +422,22 @@ pub fn hit(tiles: &[Tile], x: f32, y: f32) -> Option<&Tile> { mod tests { use super::*; use crate::tree::NodeKind; + use crate::tree::{Draft, Tree}; - fn file(name: &str, bytes: u64) -> Node { - Node::entry(name, NodeKind::File, bytes) + fn file(name: &str, bytes: u64) -> Draft { + Draft::entry(name, NodeKind::File, bytes) } - /// A directory whose direct contents are the given children, so aggregate - /// totals are consistent before layout runs. - fn dir(name: &str, children: Vec) -> Node { - let mut node = Node::directory(name); + fn dir(name: &str, children: Vec) -> Draft { + let mut node = Draft::directory(name); node.children = children; + node + } + + /// A tree whose root holds the given children, aggregated so totals are + /// consistent before layout runs. + fn tree(name: &str, children: Vec) -> Tree { + let mut node = Tree::from(dir(name, children)); crate::tree::aggregate(&mut node, Metric::Bytes); node } @@ -489,7 +495,7 @@ mod tests { fn layout_nests_children_inside_their_parent() { // Depth first, parent before its own children: that order is what lets // the view paint in sequence and hit-test in reverse. - let root = dir( + let root = tree( "root", vec![ dir("big", vec![file("inside", 100), file("also", 50)]), @@ -498,7 +504,7 @@ mod tests { ); let tiles = layout( - &root, + root.root(), &[], area(), Metric::Bytes, @@ -520,25 +526,25 @@ mod tests { #[test] fn layout_depth_one_stops_at_direct_children() { - let root = dir("root", vec![dir("big", vec![file("inside", 100)])]); + let root = tree("root", vec![dir("big", vec![file("inside", 100)])]); let options = LayoutOptions { max_depth: 1, ..LayoutOptions::default() }; - let tiles = layout(&root, &[], area(), Metric::Bytes, &options); + let tiles = layout(root.root(), &[], area(), Metric::Bytes, &options); assert_eq!(tiles.len(), 1); assert_eq!(tiles[0].crumbs(), &[0]); } #[test] fn a_subdivided_directory_keeps_a_header_for_its_own_name() { - let root = dir( + let root = tree( "root", vec![dir("big", vec![file("inside", 100), file("also", 50)])], ); let tiles = layout( - &root, + root.root(), &[], area(), Metric::Bytes, @@ -575,14 +581,14 @@ mod tests { #[test] fn a_tile_without_room_for_a_header_stays_whole() { - let root = dir("root", vec![dir("big", vec![file("inside", 100)])]); + let root = tree("root", vec![dir("big", vec![file("inside", 100)])]); let options = LayoutOptions { // A band this tall leaves no usable body under it. header: 400.0, min_tile: 150.0, ..LayoutOptions::default() }; - let tiles = layout(&root, &[], area(), Metric::Bytes, &options); + let tiles = layout(root.root(), &[], area(), Metric::Bytes, &options); assert_eq!(tiles.len(), 1, "the child was not subdivided"); assert!(tiles[0].header.is_none(), "and it has no band of its own"); } @@ -592,9 +598,9 @@ mod tests { // Draw the node at [3, 1] of some larger tree: its tiles must be // [3, 1, …], or anything resolving them from the scanned root would // find a stranger. - let node = dir("inner", vec![file("a", 10), file("b", 5)]); + let node = tree("inner", vec![file("a", 10), file("b", 5)]); let tiles = layout( - &node, + node.root(), &[3, 1], area(), Metric::Bytes, @@ -609,9 +615,9 @@ mod tests { #[test] fn a_leaf_never_claims_a_header() { - let root = dir("root", vec![file("solo", 10)]); + let root = tree("root", vec![file("solo", 10)]); let tiles = layout( - &root, + root.root(), &[], area(), Metric::Bytes, @@ -622,15 +628,15 @@ mod tests { #[test] fn layout_merges_the_child_tail_into_one_tile() { - let children: Vec = (0..10) + let children: Vec = (0..10) .map(|index| file(&format!("f{index}"), 10 - index)) .collect(); - let root = dir("root", children); + let root = tree("root", children); let options = LayoutOptions { max_children: 4, ..LayoutOptions::default() }; - let tiles = layout(&root, &[], area(), Metric::Bytes, &options); + let tiles = layout(root.root(), &[], area(), Metric::Bytes, &options); let others: Vec<&Tile> = tiles .iter() .filter(|tile| matches!(tile.kind, TileKind::Others { .. })) @@ -641,13 +647,13 @@ mod tests { #[test] fn hit_returns_the_deepest_tile() { - let root = dir( + let root = tree( "root", vec![dir("big", vec![file("inside", 100)]), file("small", 1)], ); let tiles = layout( - &root, + root.root(), &[], area(), Metric::Bytes, @@ -671,15 +677,18 @@ mod tests { use crate::filter::filter; use crate::tree::{NodeKind, aggregate}; - let file = |name: &str, bytes| Node::entry(name, NodeKind::File, bytes); - let mut src = Node::directory("src"); + let file = + |name: &str, bytes| Draft::entry(name, NodeKind::File, bytes); + let mut src = Draft::directory("src"); src.children = vec![file("big_test.rs", 300), file("other.rs", 700)]; - let mut root = Node::directory("root"); + let mut root = Draft::directory("root"); root.children = vec![src, file("unit_test.txt", 100), file("huge.iso", 5000)]; + let mut root = Tree::from(root); aggregate(&mut root, Metric::Bytes); + let root = root.root(); - let matches = filter(&root, &[], "test").expect("needle"); + let matches = filter(root, &[], "test").expect("needle"); let area = Rect::new(0.0, 0.0, 400.0, 400.0); let options = LayoutOptions { padding: 0.0, @@ -687,7 +696,7 @@ mod tests { ..LayoutOptions::default() }; let tiles = layout_filtered( - &root, + root, &[], area, Metric::Bytes, @@ -697,7 +706,7 @@ mod tests { let names: Vec = tiles .iter() .filter_map(|tile| root.resolve(tile.crumbs())) - .map(|node| node.name.to_string()) + .map(|node| node.name().to_string()) .collect(); assert!(names.contains(&"big_test.rs".to_string())); assert!(names.contains(&"unit_test.txt".to_string())); @@ -714,7 +723,7 @@ mod tests { .iter() .find(|tile| { root.resolve(tile.crumbs()) - .is_some_and(|node| &*node.name == name) + .is_some_and(|node| node.name() == name) }) .map(|tile| tile.rect.w * tile.rect.h) .expect("drawn") @@ -722,4 +731,57 @@ mod tests { let ratio = area_of("src") / area_of("unit_test.txt"); assert!((ratio - 3.0).abs() < 0.05, "ratio {ratio}"); } + + /// A rule's files are not recorded in the matches, so the layout must + /// judge them itself: a partly kept folder still shows its passing + /// files, and only those. + #[test] + fn a_rule_lays_out_the_passing_files_of_a_partial_folder() { + use crate::classify::Category; + use crate::filter::{Rule, filter_with}; + use crate::tree::{NodeKind, aggregate}; + + let file = |name: &str, bytes, category| { + let mut node = Draft::entry(name, NodeKind::File, bytes); + node.category = category; + node + }; + let mut mixed = Draft::directory("mixed"); + mixed.children = vec![ + file("lib.rs", 300, Category::Code), + file("cat.jpg", 700, Category::Media), + ]; + let mut root = Draft::directory("root"); + root.children = vec![mixed, file("main.rs", 100, Category::Code)]; + let mut root = Tree::from(root); + aggregate(&mut root, Metric::Bytes); + let root = root.root(); + + let code = Rule { + only: Rule::bit(Category::Code), + ..Rule::default() + }; + let matches = filter_with(root, &[], "", Some(&code)).expect("rule"); + let options = LayoutOptions { + padding: 0.0, + padding_outer: 0.0, + ..LayoutOptions::default() + }; + let tiles = layout_filtered( + root, + &[], + Rect::new(0.0, 0.0, 400.0, 400.0), + Metric::Bytes, + &options, + Some(&matches), + ); + let names: Vec<&str> = tiles + .iter() + .filter_map(|tile| root.resolve(tile.crumbs())) + .map(crate::tree::Node::name) + .collect(); + assert_eq!(names.len(), 3, "{names:?}"); + assert!(names.contains(&"lib.rs") && names.contains(&"main.rs")); + assert!(!names.contains(&"cat.jpg")); + } } diff --git a/crates/disktree-core/src/windows.rs b/crates/disktree-core/src/windows.rs index 53b8564c..5f039f95 100644 --- a/crates/disktree-core/src/windows.rs +++ b/crates/disktree-core/src/windows.rs @@ -108,7 +108,7 @@ impl Entry { &self.name } - /// The name, moved out: the tree keeps it, so nothing copies it. The + /// The name, moved out: it is copied once, into the tree's names. The /// entry's other accessors keep working; `name`, `file_name` and /// `path` do not. pub fn take_name(&mut self) -> Box { @@ -252,6 +252,28 @@ pub fn read_dir(dir: &Path, volume: Option) -> io::Result { Ok(ReadDir { source }) } +/// Measure a single entry with the same allocation source as a directory +/// scan. Metadata length would overcharge sparse and compressed files; +/// listing the parent also avoids opening or following the entry itself. +pub fn allocated_size(path: &Path) -> io::Result { + let parent = path.parent().ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "Entry has no parent") + })?; + let name = path.file_name().ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "Entry has no file name") + })?; + for entry in read_dir(parent, None)? { + let entry = entry?; + if entry.file_name() == name { + return Ok(entry.allocated()); + } + } + Err(io::Error::new( + io::ErrorKind::NotFound, + "Entry disappeared while measuring allocation", + )) +} + impl Iterator for ReadDir { type Item = io::Result; diff --git a/crates/disktree-link/Cargo.toml b/crates/disktree-link/Cargo.toml new file mode 100644 index 00000000..74f4d66f --- /dev/null +++ b/crates/disktree-link/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "disktree-link" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "The line protocol between a running disktree window and an agent" + +[lints] +workspace = true + +[dependencies] +disktree-core = { workspace = true } +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +[target.'cfg(windows)'.dependencies] +tokio = { version = "1.53.1", features = ["rt", "net", "io-util", "sync", "time", "macros"] } +windows-sys = { version = "0.61", features = [ + "Win32_Foundation", + "Win32_Security_Authorization", + "Win32_Storage_FileSystem", + "Win32_System_Threading", + "Win32_System_IO", + "Win32_System_Pipes", +] } + +[dev-dependencies] +tempfile = "3" diff --git a/crates/disktree-link/src/lib.rs b/crates/disktree-link/src/lib.rs new file mode 100644 index 00000000..76724413 --- /dev/null +++ b/crates/disktree-link/src/lib.rs @@ -0,0 +1,1046 @@ +//! The link between a running PwrDisk window and the agent that drives it. +//! +//! `pwrdisk mcp` scans on its own, so an agent needs no window. When one is +//! open, though, the agent's marks should appear in the mosaic and the +//! free-space meter, and its `show` and `review` should move the screen. +//! This crate is the wire between the two: one request per line of JSON +//! over a per-user socket or Windows named pipe, one line back. +//! +//! When a window is open it is the agent's source of truth: the agent lists +//! and searches the tree the person is looking at, and its marks live in the +//! window. The listing and search logic is [`disktree_core::query`], shared +//! with `pwrdisk mcp`'s own scans, so both answer alike. +//! +//! The endpoint is the trust boundary, the same one the shell has: +//! only this user can reach it. There is no token and no approval step, by +//! design. Removal intents are not authentication credentials: the app +//! requires an expiring, single-use preview matching the confirmed paths, +//! mode and policy. The existing guards and capacity limit apply to both +//! human review and confirmed MCP removal. + +use std::path::{Path, PathBuf}; + +use disktree_core::classify::Category; +use disktree_core::query::{Filter, Kind}; +use disktree_core::tree::Node; +use serde::{Deserialize, Serialize}; + +#[cfg(unix)] +mod unix; +#[cfg(unix)] +pub use unix::{Incoming, Link, Listener}; + +#[cfg(windows)] +mod windows; +#[cfg(windows)] +pub use windows::{Incoming, Link, Listener}; + +#[cfg(not(any(unix, windows)))] +mod unsupported; +#[cfg(not(any(unix, windows)))] +pub use unsupported::{Incoming, Link, Listener}; + +#[cfg(all(test, any(unix, windows)))] +mod transport_tests; + +/// Whether a window can be linked on this system at all. +pub const SUPPORTED: bool = cfg!(any(unix, windows)); + +/// Protocol version, bumped when a message changes shape. Both sides are +/// built from one tree, so a mismatch means an old window is still open. +pub const VERSION: u32 = 9; + +/// Updating the GUI does not replace a process hosted by an MCP client. +pub const RECONNECT_MCP: &str = "Updating PwrDisk's GUI does not restart its MCP server. In your MCP client, restart/reconnect the PwrDisk MCP server using `pwrdisk mcp` from the updated installation. If the GUI is outdated, quit and reopen the updated PwrDisk app."; + +pub fn protocol_mismatch(window: u32, server: u32) -> String { + format!( + "Incompatible PwrDisk link protocols (GUI {window}; MCP server {server}). {RECONNECT_MCP}" + ) +} + +/// Environment variable naming the endpoint, for tests and a second copy +/// of PwrDisk that should not meet the first. +pub const SOCKET_ENV: &str = "PWRDISK_LINK"; + +/// Where the window listens: `$PWRDISK_LINK` if set, else a socket in the +/// user's runtime directory, or a Windows pipe named for the user's SID. +#[cfg(not(windows))] +pub fn socket_path() -> PathBuf { + socket_path_in( + std::env::var_os(SOCKET_ENV).map(PathBuf::from), + std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from), + std::env::var_os("TMPDIR").map(PathBuf::from), + std::env::var_os("USER").map(|user| user.to_string_lossy().into()), + ) +} + +#[cfg(windows)] +pub fn socket_path() -> PathBuf { + std::env::var_os(SOCKET_ENV).map_or_else( + // Fail closed if Windows cannot identify this user. An empty path + // is rejected by both ends rather than sharing a fallback name. + || windows::default_path().unwrap_or_default(), + PathBuf::from, + ) +} + +/// [`socket_path`] over given environment values, so the choice is testable. +/// +/// The runtime directory and `$TMPDIR` are already the user's own, so the +/// name needs no uid there; `/tmp` is shared, so the name carries the user. +pub fn socket_path_in( + override_path: Option, + runtime_dir: Option, + tmp_dir: Option, + user: Option, +) -> PathBuf { + if let Some(path) = override_path { + return path; + } + match runtime_dir.or(tmp_dir) { + Some(dir) => dir.join("pwrdisk.sock"), + None => PathBuf::from("/tmp").join(format!( + "pwrdisk-{}.sock", + user.unwrap_or_else(|| "user".into()) + )), + } +} + +/// One path the agent wants marked, with what it measured so the window +/// can show a size before its own scan of that root lands. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct MarkRequest { + pub path: PathBuf, + pub bytes: u64, + pub is_dir: bool, +} + +/// How a scan should measure, for [`Request::Scan`]. `None` keeps what the +/// window has. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ScanOptionsRequest { + pub apparent_size: Option, + pub include_hidden: Option, + pub one_filesystem: Option, + /// `Some(None)` lifts a depth limit; `Some(Some(n))` sets one. + pub max_depth: Option>, +} + +/// A search, as the agent words it; see [`disktree_core::query::Filter`]. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct FindRequest { + /// Where to search; the scanned root when absent. + pub path: Option, + /// `any`, `file` or `dir`. + pub kind: String, + pub min_bytes: u64, + /// A [`Category::name`]. + pub category: Option, + pub reclaimable: bool, + pub name: Option, + pub before: Option, + pub limit: usize, +} + +impl FindRequest { + /// The filter this asks for, or why it cannot be one. + pub fn filter(&self) -> Result { + let kind = Kind::named(&self.kind) + .ok_or_else(|| format!("unknown kind {}", self.kind))?; + let category = match &self.category { + Some(name) => Some( + Category::named(name) + .ok_or_else(|| format!("unknown category {name}"))?, + ), + None => None, + }; + Ok(Filter { + kind, + min_bytes: self.min_bytes, + category, + reclaimable: self.reclaimable, + name: self + .name + .as_deref() + .map(str::to_lowercase) + .filter(|name| !name.is_empty()), + before: self.before, + }) + } +} + +/// Removal modes are explicit; there is no fallback from Trash to deletion. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RemovalChoice { + Trash, + Permanent, + OwnerCleanup, +} + +impl RemovalChoice { + pub const fn mode(self) -> disktree_core::removal::RemovalMode { + match self { + Self::Trash => disktree_core::removal::RemovalMode::Trash, + Self::Permanent => disktree_core::removal::RemovalMode::Permanent, + Self::OwnerCleanup => { + disktree_core::removal::RemovalMode::OwnerCleanup + } + } + } + /// The phrase for raw modes. A cache cleanup's phrase depends on the + /// intents chosen; its preview carries it in `confirmation`. + pub const fn confirmation(self) -> &'static str { + match self { + Self::Trash => "MOVE TO TRASH", + Self::Permanent => "PERMANENTLY DELETE", + Self::OwnerCleanup => disktree_core::cleanup::RUN_OWNER_CLEANUP, + } + } + + /// Whether `text` is a confirmation phrase this mode can have. + pub fn accepts(self, text: &str) -> bool { + match self { + Self::OwnerCleanup => { + disktree_core::cleanup::CONFIRMATIONS.contains(&text) + } + _ => text == self.confirmation(), + } + } + pub const fn warning(self) -> &'static str { + match self { + Self::Trash => { + "Destructive: moves the listed paths to Trash or Recycle Bin. Recovery may be possible until emptied, but is not guaranteed. Space usually returns only when the user empties it." + } + Self::Permanent => { + "Destructive: permanently deletes the listed paths. This cannot be undone through PwrDisk or Trash." + } + Self::OwnerCleanup => { + "Destructive cache cleanup, decided per path: Skip runs nothing; an owner choice invokes only the previewed owner command for its entire stated scope, including unselected siblings, with no Trash recovery; a delete_files choice deletes exactly that selected path directly, without its owner, by the stated Trash or permanent mode. A failed, unsupported or cancelled owner command never falls back to deleting files. Stop the owning tools before approval. Listed allocation is not guaranteed freed space; APFS snapshots, clones and open files can retain blocks." + } + } + } +} + +/// A short-lived app preview of the exact effective targets and mode. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RemovalPreview { + pub preview_id: String, + pub root: PathBuf, + pub mode: RemovalChoice, + pub paths: Vec, + pub bytes: u64, + pub estimate: SelectionEstimate, + pub limit_percent: u8, + pub volumes: Vec, + pub expires_in_seconds: u64, + /// Owner commands this preview would run, by actual scope. Empty for + /// raw removal modes. + pub cleanup: Vec, + /// Cache cleanup: one proposal per marked path, with what each offers. + #[serde(default)] + pub proposals: Vec, + /// Cache cleanup: the decision for each proposal, in its order. Empty + /// until the person has chosen; such a preview cannot be confirmed. + #[serde(default)] + pub decisions: Vec, + /// Cache cleanup: how Delete files removes, when any path uses it. + #[serde(default)] + pub files: Option, + /// The exact text that confirms this preview; empty when it cannot be + /// confirmed. + #[serde(default)] + pub confirmation: String, + /// Everything to show the person before they confirm, in words. + #[serde(default)] + pub consent: String, +} + +/// The person's choice for one marked path in a cache cleanup. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PathDecision { + pub path: PathBuf, + pub action: disktree_core::cleanup::Decision, +} + +/// Supplied only after the agent obtains explicit user confirmation of +/// the preview's exact paths, mode and consequences. Not a bearer credential. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ConfirmedRemoval { + pub preview_id: String, + pub mode: RemovalChoice, + pub paths: Vec, + pub confirmation: String, + /// Rescan once the removal finishes. Without it the window keeps its + /// tree, with the removed paths shown as removed until a scan, which is + /// what an agent removing several batches wants: a rescan can take + /// minutes. + #[serde(default)] + pub rescan: bool, +} + +/// What the agent asks of the window. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "op", rename_all = "snake_case")] +pub enum Request { + /// Introduce the agent by its client's name; answered with [`State`]. + Hello { client: String, version: u32 }, + /// What the window shows now; answered with [`State`]. + State, + /// Scan `root`, rescanning when it is the root already. Answered with + /// [`State`] at once; the scan lands when `scanning` turns false. + Scan { + root: PathBuf, + options: ScanOptionsRequest, + }, + /// What is in a directory of the window's tree; answered with + /// [`Listing`]. + Ls { path: PathBuf, limit: usize }, + /// The largest entries matching a description; answered with + /// [`FoundList`]. + Find(FindRequest), + /// Read-only hypothetical selection, with bounded retained clone peers. + /// Does not change marks, navigation or a pending removal preview. + Estimate { + paths: Vec, + peer_scope: Option, + peer_limit: usize, + }, + /// Show `path` in the mosaic. `root` is the agent's scan root: when the + /// window shows something else, it rescans from there first. + Show { root: PathBuf, path: PathBuf }, + /// Mark these paths, under the agent's scan `root`. The window measures + /// each from its own tree when it can; `bytes` stands in until then. + /// Already marked paths stay marked; answered with [`Response::Marked`]. + Mark { + root: PathBuf, + targets: Vec, + }, + /// Unmark these paths, or everything when the list is empty; answered + /// with [`State`]. + Unmark { paths: Vec }, + /// Open the review screen over what is marked. + Review, + /// Prepare a single-use intent; does not mark, navigate or remove. + PrepareRemoval { + mode: RemovalChoice, + /// Cache cleanup only: one decision per marked path. Without them + /// the preview lists the proposals and cannot be confirmed. + #[serde(default, skip_serializing_if = "Option::is_none")] + decisions: Option>, + /// Cache cleanup only: Trash or Permanent for Delete files. + #[serde(default, skip_serializing_if = "Option::is_none")] + files: Option, + }, + /// A destructive write, only after explicit confirmation of the preview. + Remove(ConfirmedRemoval), +} + +/// One entry of the tree, as the agent reads it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Entry { + pub name: String, + pub is_dir: bool, + pub bytes: u64, + pub files: u64, + /// A [`Category::name`]. + pub category: String, + /// Why its space can be had back, if it can. + pub reclaim: Option, + /// Artifact identity and cleanup assessment are independent. Missing + /// on older peers; neither detection nor suggestion approves removal. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub artifact: Option, + /// Newest write at or beneath it, Unix seconds; `0` when unknown. + pub modified: i64, + pub read_error: bool, + /// APFS clone sharing beneath it; absent when no file there is a clone. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub clones: Option, + /// Removed since the scan, itself or with a directory holding it. The + /// window keeps the scanned tree until a rescan, so `bytes` is still + /// what the scan measured. Only a window sets it. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub removed: bool, + /// Scanned bytes of what was removed beneath it since the scan, when it + /// is not wholly removed; already inside `bytes`. + #[serde(default, skip_serializing_if = "is_zero")] + pub removed_bytes: u64, +} + +#[expect( + clippy::trivially_copy_pass_by_ref, + reason = "serde's skip_serializing_if passes a reference" +)] +const fn is_zero(bytes: &u64) -> bool { + *bytes == 0 +} + +/// How an entry's listed bytes split once APFS clones are accounted for. +/// `bytes` stays the allocated total; this only annotates it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Clones { + /// Listed bytes outside clone files, plus clone files' private data. + pub private: u64, + /// Clone blocks other clones may hold, inside this scan or not. + pub shared: u64, + /// Bytes listed more than once beneath it, clones of one another. + pub repeated: u64, + /// What removing this entry alone frees, before snapshots: a group is + /// credited only when every clone APFS counts is beneath it. + pub lower: u64, + pub upper: u64, + /// Some clone facts are missing, or too many groups to track. + pub partial: bool, +} + +impl Clones { + /// `4.0 KiB private · 12 MiB shared with other APFS clones`, as the + /// window and an agent's rows both read it; `None` without clone + /// blocks. The refcount counts clones outside the scan too, so the + /// wording never says the blocks are shared only within it. + pub fn split(&self) -> Option { + use disktree_core::size::human_bytes; + (self.shared > 0).then(|| { + format!( + "{} private \u{00b7} {} shared with other APFS clones", + human_bytes(self.private), + human_bytes(self.shared) + ) + }) + } + + pub fn of(node: Node<'_>) -> Option { + let sharing = node.sharing(); + // Only clone files carry these facts: off macOS, in an apparent + // size scan or with clone metadata off there are none, and the + // entry reads exactly as it did before clones were reported. + if sharing.files == 0 { + return None; + } + let shared = sharing.shared_bytes().min(node.bytes); + Some(Self { + private: node.bytes - shared, + shared, + repeated: sharing.duplicate_bytes, + lower: sharing.reclaimable(node.bytes), + upper: sharing.possible(node.bytes), + partial: sharing.groups_truncated + || sharing.unknown_files > 0 + || sharing.estimate.is_some_and(|estimate| estimate.partial), + }) + } +} + +impl Entry { + pub fn at(node: Node<'_>, path: &Path) -> Self { + let mut entry = Self::of(node); + entry.artifact = disktree_core::artifact::assess( + path, + disktree_core::path_style::PathStyle::Native, + node, + ); + entry + } + + pub fn of(node: Node<'_>) -> Self { + Self { + name: node.name().to_string(), + is_dir: node.is_dir(), + bytes: node.bytes, + files: node.files, + category: node.category.name().to_string(), + reclaim: node.reclaim.map(|reclaim| reclaim.label().to_string()), + artifact: None, + modified: node.modified, + read_error: node.read_error, + clones: Clones::of(node), + removed: false, + removed_bytes: 0, + } + } +} + +/// A directory and its largest children. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Listing { + pub path: PathBuf, + pub entry: Entry, + /// The scanned root's total, for the directory's share of it. + pub root_bytes: u64, + /// The scanned root, for naming it. + pub root: PathBuf, + /// Largest first, at most the limit asked for. + pub children: Vec, + /// Children past the limit, and their bytes together. + pub more: usize, + pub more_bytes: u64, +} + +impl Listing { + /// List `node`, which sits at `path` in a tree rooted at `root` whose + /// total is `root_bytes`. + pub fn of( + root: &Path, + root_bytes: u64, + path: &Path, + node: Node<'_>, + limit: usize, + ) -> Self { + let children: Vec = node + .children() + .iter() + .take(limit) + .map(|child| Entry::at(child, &path.join(child.name()))) + .collect(); + let more = node.children().len().saturating_sub(limit); + let more_bytes = node + .children() + .iter() + .skip(limit) + .map(|child| child.bytes) + .sum(); + Self { + path: path.to_path_buf(), + entry: Entry::at(node, path), + root_bytes, + root: root.to_path_buf(), + children, + more, + more_bytes, + } + } +} + +/// One search match, with where it is. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Found { + pub path: PathBuf, + pub entry: Entry, +} + +/// What a search found; see [`disktree_core::query::Found`]. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct FoundList { + pub matches: Vec, + pub count: usize, + pub bytes: u64, +} + +impl FoundList { + pub fn of(found: &disktree_core::query::Found<'_>) -> Self { + Self { + matches: found + .matches + .iter() + .map(|(path, node)| Found { + path: path.clone(), + entry: Entry::at(*node, path), + }) + .collect(), + count: found.count, + bytes: found.bytes, + } + } +} + +/// The tree a window has, in totals. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TreeSummary { + pub bytes: u64, + pub files: u64, + pub dirs: u64, + /// Unix seconds when it landed. + pub scanned_at: i64, + pub elapsed_ms: u64, + pub unreadable: u64, + pub apparent_size: bool, + pub include_hidden: bool, +} + +/// One "worth a look" finding. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Insight { + pub path: PathBuf, + pub bytes: u64, + pub what: String, +} + +/// A mark the window would not take, and why. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Refused { + pub path: PathBuf, + pub reason: String, +} + +/// A marked path as the window holds it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Mark { + pub path: PathBuf, + pub bytes: u64, + pub is_dir: bool, +} + +/// Bounds for the whole accepted union, before snapshots and later changes. +/// Per-mark bounds cannot represent groups spanning several marks. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SelectionEstimate { + pub paths: Vec, + pub lower: u64, + /// Unknown when no physical measurement supports a bound (for example, + /// apparent lengths can be smaller than allocated blocks). + pub upper: Option, + /// Only this lower bound belongs on the scanned volume's meter. + pub on_volume: u64, + /// A limited scan, unmeasured allocation or incomplete sharing metadata. + pub partial: bool, + /// Listed bytes of the selection in APFS clone blocks that other clones + /// may hold; [`Sharing::shared_bytes`] summed. Zero off APFS. + /// + /// [`Sharing::shared_bytes`]: disktree_core::sharing::Sharing::shared_bytes + #[serde(default)] + pub shared: u64, +} + +impl SelectionEstimate { + pub fn of(plan: &disktree_core::removal::Plan) -> Self { + Self { + paths: plan.targets.iter().map(|t| t.path.clone()).collect(), + lower: plan.reclaimable_bytes(), + upper: Some(plan.possible_bytes()), + on_volume: plan.reclaim(), + partial: plan.estimate_partial(), + shared: 0, + } + } + + /// Accepted targets never nest, so their shares add up. + #[must_use] + pub fn with_shared<'a>( + mut self, + nodes: impl IntoIterator>, + ) -> Self { + self.shared = nodes + .into_iter() + .map(|node| node.sharing().shared_bytes().min(node.bytes)) + .sum(); + self + } + + pub fn unknown(plan: &disktree_core::removal::Plan) -> Self { + Self { + lower: 0, + upper: None, + on_volume: 0, + partial: true, + ..Self::of(plan) + } + } +} + +/// The volume the window measures. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Space { + pub total: u64, + pub free: u64, + pub available: u64, +} + +/// What the last removal did, kept until the next one. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Removal { + /// `trash` or `permanent`. + pub mode: String, + pub removed: usize, + pub failed: usize, + /// Bytes of the targets removed, as marked. + pub bytes: u64, + /// Free space gained on the volume, measured before and after; `None` + /// when the volume could not be read. + pub freed: Option, + /// Signed available-space delta for this run, including concurrent writes. + #[serde(default)] + pub observed: Option, + /// Unix seconds when it finished. + pub at: i64, + pub cleanup: Vec, +} + +/// Outcome of the exact previewed selection, including native UI removal. +/// Kept after completion and rescans so an outstanding form can reconcile. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RemovalOperation { + pub preview_id: String, + pub mode: RemovalChoice, + pub paths: Vec, + pub finished: bool, + pub removed: usize, + pub failed: usize, + pub pending: usize, +} + +/// One removal since the last scan, three ways. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RemovalCohort { + /// `trash` or `permanent`. + pub mode: String, + pub removed: u64, + pub failed: usize, + /// Listed bytes of what was removed; a clone counts in every place. + pub reported: u64, + /// What the scan saw as only theirs; `None` when it could not say. + pub private: Option, + /// Free space after minus before, which other programs move too. + pub observed: Option, + /// Unix seconds. + pub started: i64, + pub finished: i64, +} + +/// Every removal since the last scan, and their totals: `observed` runs +/// from the first one's start to the last one's finish. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RemovalLedger { + pub cohorts: Vec, + pub reported: u64, + pub private: Option, + pub observed: Option, +} + +/// What the window shows. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct State { + pub version: u32, + /// GUI package version, independent of the MCP server and link protocol. + #[serde(default)] + pub app_version: String, + /// The scanned root. + pub root: PathBuf, + /// The directory on screen. + pub current: PathBuf, + /// `explore`, `review`, `running` or `done`. + pub screen: String, + /// A scan is in progress; the tree may be absent or about to change. + pub scanning: bool, + /// A tree is on screen. + pub scanned: bool, + pub marks: Vec, + /// Absent until a complete local tree can supply the selected union. + #[serde(default)] + pub estimate: Option, + pub space: Option, + pub removal: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub removal_operation: Option, + /// The removals since the scan on screen, which the tree already + /// leaves out. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub removals: Option, + /// The tree on screen, when there is one. + pub tree: Option, + /// The biggest things that could plausibly go, as the panel lists them. + pub insights: Vec, + /// The SSH host the window is showing, if not this computer. The + /// agent's tools measure and mark this computer only, so a window on a + /// host answers nothing but `hello` and `state`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub remote: Option, +} + +/// Why a window on an SSH host does not do what an agent asks. +pub fn remote_refusal(host: &str) -> String { + format!( + "The PwrDisk window is showing the SSH host {host}. The agent's \ + tools measure and mark this computer only, and PwrDisk does not \ + remove files over SSH. Ask the user to choose This computer in the \ + window to bring it along, or to close it; until then the agent \ + works without the window." + ) +} + +/// The window's answer. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "result", rename_all = "snake_case")] +pub enum Response { + State(State), + /// The marks taken, and the ones not. + Marked { + state: State, + refused: Vec, + }, + Listing(Listing), + Found(FoundList), + Estimate(disktree_core::planning::Report), + RemovalPreview(RemovalPreview), + Ok, + Error { + message: String, + }, +} + +impl Response { + pub fn error(message: impl Into) -> Self { + Self::Error { + message: message.into(), + } + } +} + +/// A line longer than this is not a request; it is a mistake or an attack +/// on memory, and the connection is dropped. +#[cfg(any(unix, windows))] +const MAX_LINE: usize = 8 * 1024 * 1024; + +#[cfg(any(unix, windows))] +fn encode(value: &T) -> std::io::Result { + let mut line = + serde_json::to_string(value).map_err(std::io::Error::other)?; + line.push('\n'); + Ok(line) +} + +#[cfg(any(unix, windows))] +fn decode Deserialize<'de>>(line: &str) -> std::io::Result { + serde_json::from_str(line.trim_end()).map_err(std::io::Error::other) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[cfg(any(unix, windows))] + #[test] + fn requests_round_trip_through_json_lines() { + let request = Request::Mark { + root: PathBuf::from("/home/u"), + targets: vec![MarkRequest { + path: PathBuf::from("/home/u/.cache"), + bytes: 42, + is_dir: true, + }], + }; + let line = encode(&request).expect("encode"); + assert!(line.ends_with('\n')); + assert!(line.contains("\"op\":\"mark\"")); + let back: Request = decode(&line).expect("decode"); + assert_eq!(back, request); + } + + /// A directory of `copies` files, each a clone of one group that APFS + /// says has `references` members. + fn clones( + copies: u64, + references: u32, + private: Option, + ) -> disktree_core::tree::Tree { + use disktree_core::sharing::{Allocation, CloneInfo}; + use disktree_core::tree::{Draft, Metric, NodeKind, Tree, aggregate}; + let mut root = Draft::directory("root"); + for index in 0..copies { + let mut dir = Draft::directory(format!("copy-{index}")); + let mut file = Draft::entry("data", NodeKind::File, 1000); + file.allocation = Some(Box::new(Allocation { + bytes: 1000, + identity: None, + links: 1, + followed: false, + clone: Some(CloneInfo { + device: 1, + id: 7, + references, + private_bytes: private, + data_bytes: 1000, + }), + })); + dir.children.push(file); + root.children.push(dir); + } + root.children.push(Draft::entry( + "plain", + disktree_core::tree::NodeKind::File, + 50, + )); + let mut root = Tree::from(root); + aggregate(&mut root, Metric::Bytes); + root + } + + #[test] + fn a_full_clone_is_all_shared_and_frees_nothing_alone() { + let root = clones(3, 3, Some(0)); + let copy = Clones::of(root.root().children().at(0)).expect("a clone"); + assert_eq!( + copy, + Clones { + private: 0, + shared: 1000, + repeated: 0, + lower: 0, + upper: 0, + partial: false, + } + ); + // Every member is beneath the root, so the group is freed once. + let all = Clones::of(root.root()).expect("clones beneath"); + assert_eq!((all.private, all.shared, all.repeated), (50, 3000, 2000)); + assert_eq!((all.lower, all.upper), (1050, 1050)); + } + + #[test] + fn a_member_outside_the_scan_keeps_the_group_from_being_credited() { + let root = clones(3, 4, Some(0)); + let all = Clones::of(root.root()).expect("clones beneath"); + assert_eq!((all.lower, all.upper), (50, 50)); + assert_eq!(all.repeated, 2000); + } + + #[test] + fn a_modified_clone_counts_its_private_bytes_only() { + let root = clones(3, 3, Some(300)); + let copy = Clones::of(root.root().children().at(0)).expect("a clone"); + assert_eq!((copy.private, copy.shared), (300, 700)); + assert_eq!((copy.lower, copy.upper), (300, 1000)); + assert!(!copy.partial); + } + + #[test] + fn missing_clone_facts_are_partial() { + let mut root = clones(2, 0, Some(0)); + assert!( + Clones::of(root.root().children().at(0)) + .expect("a clone") + .partial + ); + root = clones(2, 2, None); + let copy = Clones::of(root.root().children().at(0)).expect("a clone"); + assert!(copy.partial); + // An unknown private size is never claimed as private. + assert_eq!((copy.private, copy.shared, copy.lower), (0, 1000, 0)); + } + + #[test] + fn entries_without_clones_carry_nothing_and_old_payloads_decode() { + let root = clones(1, 2, Some(0)); + let plain = Entry::of(root.root().children().at(1)); + assert_eq!(plain.name, "plain"); + assert_eq!(plain.clones, None); + let line = serde_json::to_string(&plain).expect("encode"); + assert!(!line.contains("clones"), "{line}"); + // A version 4 entry has no `clones` key at all. + let old: Entry = serde_json::from_str( + r#"{"name":"a","is_dir":true,"bytes":1,"files":1, + "category":"other","reclaim":null,"modified":0, + "read_error":false}"#, + ) + .expect("decode"); + assert_eq!(old.clones, None); + let clone = Entry::of(root.root().children().at(0)); + assert!(clone.clones.is_some()); + let back: Entry = + serde_json::from_str(&serde_json::to_string(&clone).expect("enc")) + .expect("dec"); + assert_eq!(back, clone); + let estimate: SelectionEstimate = serde_json::from_str( + r#"{"paths":[],"lower":0,"upper":0,"on_volume":0, + "partial":false}"#, + ) + .expect("decode"); + assert_eq!(estimate.shared, 0); + } + + #[test] + fn listings_keep_vm_detection_separate_from_cleanup_suggestions() { + use disktree_core::artifact::{Artifact, Disposition}; + use disktree_core::classify::classify_at; + use disktree_core::path_style::PathStyle; + use disktree_core::tree::{Draft, NodeKind, Tree}; + let mut root = Draft::directory("project"); + let mut dependencies = Draft::directory("node_modules"); + dependencies.children.push(Draft::entry( + "package.js", + NodeKind::File, + 10, + )); + root.children = + vec![dependencies, Draft::entry("guest.vmss", NodeKind::File, 20)]; + let mut tree = Tree::from(root); + classify_at(&mut tree, Path::new("/project"), PathStyle::Posix); + let listing = Listing::of( + Path::new("/project"), + 30, + Path::new("/project"), + tree.root(), + 10, + ); + let vm = listing + .children + .iter() + .find(|e| e.name == "guest.vmss") + .unwrap(); + assert_eq!(vm.reclaim, None); + let d = vm.artifact.unwrap(); + assert_eq!(d.kind, Artifact::VmSuspend); + assert_eq!(d.disposition, Disposition::Detected); + let dependencies = listing + .children + .iter() + .find(|e| e.name == "node_modules") + .unwrap(); + assert_eq!( + dependencies.artifact.unwrap().disposition, + Disposition::Suggested + ); + let encoded = serde_json::to_string(&listing).unwrap(); + assert!(encoded.contains("\"disposition\":\"detected\"")); + assert_eq!(serde_json::from_str::(&encoded).unwrap(), listing); + } + + #[test] + fn removed_status_round_trips_and_is_absent_when_nothing_went() { + let root = clones(1, 2, Some(0)); + let plain = Entry::of(root.root().children().at(1)); + assert!(!plain.removed && plain.removed_bytes == 0); + let line = serde_json::to_string(&plain).expect("encode"); + assert!(!line.contains("removed"), "older peers see no new keys"); + let old: Entry = serde_json::from_str(&line).expect("decode"); + assert!(!old.removed && old.removed_bytes == 0); + for entry in [ + Entry { + removed: true, + ..plain.clone() + }, + Entry { + removed_bytes: 4096, + ..plain + }, + ] { + let back: Entry = serde_json::from_str( + &serde_json::to_string(&entry).expect("encode"), + ) + .expect("decode"); + assert_eq!(back, entry); + } + } + + #[test] + fn the_socket_is_the_override_else_a_per_user_place() { + let custom = PathBuf::from("/x/custom.sock"); + assert_eq!( + socket_path_in(Some(custom.clone()), None, None, None), + custom + ); + assert_eq!( + socket_path_in(None, Some("/run/user/1000".into()), None, None), + PathBuf::from("/run/user/1000/pwrdisk.sock") + ); + assert_eq!( + socket_path_in(None, None, Some("/var/t".into()), None), + PathBuf::from("/var/t/pwrdisk.sock") + ); + assert_eq!( + socket_path_in(None, None, None, Some("ann".into())), + PathBuf::from("/tmp/pwrdisk-ann.sock") + ); + } +} diff --git a/crates/disktree-link/src/transport_tests.rs b/crates/disktree-link/src/transport_tests.rs new file mode 100644 index 00000000..6c84fd61 --- /dev/null +++ b/crates/disktree-link/src/transport_tests.rs @@ -0,0 +1,227 @@ +use crate::{Incoming, Link, Listener, Request, Response, decode}; +use crate::{Mark, State, VERSION}; +use std::io::{self, BufRead as _, BufReader, Write as _}; +#[cfg(unix)] +use std::os::unix::net::UnixStream; +use std::path::{Path, PathBuf}; +use std::thread; +use std::time::Duration; + +fn socket() -> (tempfile::TempDir, PathBuf) { + let dir = tempfile::TempDir::new().expect("tempdir"); + #[cfg(unix)] + let path = dir.path().join("l.sock"); + #[cfg(windows)] + let path = PathBuf::from(format!( + r"\\.\pipe\pwrdisk-test-{}", + dir.path().file_name().expect("temp name").to_string_lossy() + )); + (dir, path) +} + +#[cfg(unix)] +fn raw(path: &Path) -> UnixStream { + let raw = UnixStream::connect(path).expect("connect"); + raw.set_read_timeout(Some(Duration::from_secs(5))) + .expect("timeout"); + raw +} + +#[cfg(windows)] +fn raw(path: &Path) -> std::fs::File { + use std::os::windows::fs::OpenOptionsExt as _; + use windows_sys::Win32::Storage::FileSystem::{ + SECURITY_IDENTIFICATION, SECURITY_SQOS_PRESENT, + }; + std::fs::OpenOptions::new() + .read(true) + .write(true) + .custom_flags(SECURITY_IDENTIFICATION | SECURITY_SQOS_PRESENT) + .open(path) + .expect("raw pipe") +} + +fn pump(listener: &Listener) -> Incoming { + for _ in 0..200 { + if let Some(incoming) = listener.drain().into_iter().next() { + return incoming; + } + thread::sleep(Duration::from_millis(5)); + } + panic!("nothing arrived"); +} + +#[test] +fn a_request_reaches_the_queue_and_its_reply_reaches_the_client() { + let (_dir, path) = socket(); + let listener = Listener::bind_at(&path).expect("bind"); + let mut link = Link::connect_at(&path).expect("connect"); + let answer = thread::spawn(move || { + link.call(&Request::Hello { + client: "test".into(), + version: VERSION, + }) + }); + let state = State { + version: VERSION, + app_version: "0.13.0".into(), + root: "/r".into(), + current: "/r".into(), + screen: "explore".into(), + scanning: false, + scanned: true, + estimate: None, + marks: vec![Mark { + path: "/r/x".into(), + bytes: 1, + is_dir: false, + }], + space: None, + removal_operation: None, + removal: None, + removals: None, + tree: None, + insights: Vec::new(), + remote: None, + }; + match pump(&listener) { + Incoming::Request { request, reply, .. } => { + assert!(matches!(request, Request::Hello { .. })); + assert_eq!(listener.connections(), 1); + reply.send(Response::State(state.clone())); + } + Incoming::Closed { .. } => panic!("closed first"), + } + assert_eq!( + answer.join().expect("thread").expect("reply"), + Response::State(state) + ); +} + +#[test] +fn a_live_socket_is_not_stolen() { + let (_dir, path) = socket(); + let first = Listener::bind_at(&path).expect("bind"); + let second = Listener::bind_at(&path); + assert_eq!( + second.err().map(|e| e.kind()), + Some(io::ErrorKind::AddrInUse) + ); + drop(first); +} + +#[test] +fn garbage_gets_an_error_line_not_a_hang() { + let (_dir, path) = socket(); + let listener = Listener::bind_at(&path).expect("bind"); + let mut raw = raw(&path); + raw.write_all(b"not json\n").expect("write"); + let mut reader = BufReader::new(raw); + let mut line = String::new(); + reader.read_line(&mut line).expect("read"); + let response: Response = decode(&line).expect("decode"); + assert!(matches!(response, Response::Error { .. })); + drop(listener); +} + +#[test] +fn dropping_a_reply_closes_only_that_client() { + let (_dir, path) = socket(); + let listener = Listener::bind_at(&path).expect("bind"); + let mut link = Link::connect_at(&path).expect("connect"); + let answer = thread::spawn(move || link.call(&Request::State)); + let connection = match pump(&listener) { + Incoming::Request { + connection, reply, .. + } => { + drop(reply); + connection + } + Incoming::Closed { .. } => panic!("closed first"), + }; + assert!(answer.join().expect("client").is_err()); + assert!( + matches!(pump(&listener), Incoming::Closed { connection: id } if id == connection) + ); + assert_eq!(listener.connections(), 0); + assert!(Link::connect_at(&path).is_ok()); +} + +#[test] +fn two_clients_keep_their_replies_and_connection_ids() { + let (_dir, path) = socket(); + let listener = Listener::bind_at(&path).expect("bind"); + let mut first = Link::connect_at(&path).expect("first"); + let mut second = Link::connect_at(&path).expect("second"); + let a = thread::spawn(move || first.call(&Request::State)); + let mut ids = Vec::new(); + if let Incoming::Request { + connection, reply, .. + } = pump(&listener) + { + ids.push(connection); + reply.send(Response::error("first reply")); + } else { + panic!("closed first"); + } + assert_eq!( + a.join().expect("first thread").expect("first reply"), + Response::error("first reply") + ); + // Drain the first client's close before issuing the second request. + assert!(matches!(pump(&listener), Incoming::Closed { .. })); + let b = thread::spawn(move || second.call(&Request::State)); + if let Incoming::Request { + connection, reply, .. + } = pump(&listener) + { + ids.push(connection); + reply.send(Response::Ok); + } else { + panic!("closed second"); + } + assert_eq!( + b.join().expect("second thread").expect("second reply"), + Response::Ok + ); + assert_ne!(ids[0], ids[1]); +} + +#[test] +fn an_oversized_unterminated_request_is_dropped() { + use std::io::Read as _; + let (_dir, path) = socket(); + let listener = Listener::bind_at(&path).expect("bind"); + let mut raw = raw(&path); + raw.write_all(&vec![b'x'; crate::MAX_LINE]) + .expect("write oversized line"); + let mut byte = [0]; + // Windows can report either a broken pipe or PIPE_NOT_CONNECTED after + // the server disconnects it; Unix reports EOF. + match raw.read(&mut byte) { + Ok(0) => {} + Err(error) if error.kind() == io::ErrorKind::BrokenPipe => {} + #[cfg(windows)] + Err(error) + if error.raw_os_error() + == Some( + windows_sys::Win32::Foundation::ERROR_PIPE_NOT_CONNECTED + .cast_signed(), + ) => {} + result => panic!("expected disconnection, got {result:?}"), + } + assert!(matches!(pump(&listener), Incoming::Closed { .. })); +} + +#[test] +fn hanging_up_is_reported_and_the_listener_can_be_rebound() { + let (_dir, path) = socket(); + let listener = Listener::bind_at(&path).expect("bind"); + drop(Link::connect_at(&path).expect("connect")); + assert!(matches!(pump(&listener), Incoming::Closed { .. })); + assert_eq!(listener.connections(), 0); + drop(listener); + let again = Listener::bind_at(&path).expect("rebind"); + assert!(Link::connect_at(&path).is_ok()); + drop(again); +} diff --git a/crates/disktree-link/src/unix.rs b/crates/disktree-link/src/unix.rs new file mode 100644 index 00000000..e21aed84 --- /dev/null +++ b/crates/disktree-link/src/unix.rs @@ -0,0 +1,328 @@ +//! The socket on Unix: a listener the window owns, and the client an agent +//! holds. + +use std::collections::VecDeque; +use std::io::{self, BufRead as _, BufReader, Read as _, Write as _}; +use std::os::unix::fs::PermissionsExt as _; +use std::os::unix::net::{UnixListener, UnixStream}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::mpsc; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; + +use crate::{MAX_LINE, Request, Response, decode, encode, socket_path}; + +/// How often the accept loop looks for a connection or a stop. Also the +/// most a client waits to be heard; the window drains requests on a similar +/// tick, so this is not the slow part. +const ACCEPT_TICK: Duration = Duration::from_millis(40); + +/// Something a connection sent, or the news that it is gone. +#[derive(Debug)] +pub enum Incoming { + Request { + connection: u64, + request: Request, + reply: Reply, + }, + Closed { + connection: u64, + }, +} + +/// Where a request's answer goes. Dropping it unanswered closes the +/// connection, which the client sees as an error rather than a hang. +#[derive(Debug)] +pub struct Reply(mpsc::Sender); + +impl Reply { + pub fn send(self, response: Response) { + // The connection may have hung up while the window was busy; then + // there is nobody to tell. + let _ = self.0.send(response); + } +} + +/// The window's end: accepts connections in the background and queues what +/// they send for the UI thread to answer on its own schedule. +#[derive(Debug)] +pub struct Listener { + path: PathBuf, + queue: Arc>>, + connections: Arc, + stop: Arc, +} + +impl Listener { + /// Listen at [`socket_path`]. + pub fn bind() -> io::Result { + Self::bind_at(&socket_path()) + } + + /// Listen at `path`, replacing a socket file nothing answers on: the + /// usual leftover of a window that did not exit cleanly. A socket + /// something does answer on is another window's, and this one stays + /// unlinked rather than stealing it. + pub fn bind_at(path: &Path) -> io::Result { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let listener = match UnixListener::bind(path) { + Ok(listener) => listener, + Err(error) if error.kind() == io::ErrorKind::AddrInUse => { + if UnixStream::connect(path).is_ok() { + return Err(io::Error::new( + io::ErrorKind::AddrInUse, + "another PwrDisk window is already linked", + )); + } + std::fs::remove_file(path)?; + UnixListener::bind(path)? + } + Err(error) => return Err(error), + }; + // The runtime directory is already the user's, but a socket in + // `$TMPDIR` may not be: no other user gets to drive this window. + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?; + listener.set_nonblocking(true)?; + + let queue = Arc::new(Mutex::new(VecDeque::new())); + let connections = Arc::new(AtomicUsize::new(0)); + let stop = Arc::new(AtomicBool::new(false)); + let accept = Acceptor { + listener, + queue: Arc::clone(&queue), + connections: Arc::clone(&connections), + stop: Arc::clone(&stop), + next_id: AtomicU64::new(1), + }; + thread::Builder::new() + .name("disktree-link".into()) + .spawn(move || accept.run())?; + Ok(Self { + path: path.to_path_buf(), + queue, + connections, + stop, + }) + } + + pub fn path(&self) -> &Path { + &self.path + } + + /// Connections open right now. + pub fn connections(&self) -> usize { + self.connections.load(Ordering::Relaxed) + } + + /// Everything that arrived since the last drain, oldest first. + pub fn drain(&self) -> Vec { + let mut queue = self + .queue + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + queue.drain(..).collect() + } +} + +impl Drop for Listener { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + // The file is this window's; a stale one would only make the next + // window take the slow path. + let _ = std::fs::remove_file(&self.path); + } +} + +struct Acceptor { + listener: UnixListener, + queue: Arc>>, + connections: Arc, + stop: Arc, + next_id: AtomicU64, +} + +impl Acceptor { + fn run(self) { + while !self.stop.load(Ordering::Relaxed) { + match self.listener.accept() { + Ok((stream, _)) => self.serve(stream), + Err(error) if error.kind() == io::ErrorKind::WouldBlock => { + thread::sleep(ACCEPT_TICK); + } + // A transient accept error is not worth stopping for; a + // persistent one would spin, so the tick stays in. + Err(_) => thread::sleep(ACCEPT_TICK), + } + } + } + + fn serve(&self, stream: UnixStream) { + // The listener is non-blocking so the loop above can see a stop; + // a connection reads whole lines and wants to block. + if stream.set_nonblocking(false).is_err() { + return; + } + let id = self.next_id.fetch_add(1, Ordering::Relaxed); + let connection = Connection { + id, + stream, + queue: Arc::clone(&self.queue), + connections: Arc::clone(&self.connections), + }; + self.connections.fetch_add(1, Ordering::Relaxed); + if thread::Builder::new() + .name(format!("disktree-link-{id}")) + .spawn(move || connection.run()) + .is_err() + { + self.connections.fetch_sub(1, Ordering::Relaxed); + } + } +} + +struct Connection { + id: u64, + stream: UnixStream, + queue: Arc>>, + connections: Arc, +} + +impl Connection { + fn run(mut self) { + let _ = self.exchange(); + self.connections.fetch_sub(1, Ordering::Relaxed); + self.push(Incoming::Closed { + connection: self.id, + }); + } + + fn exchange(&mut self) -> io::Result<()> { + let mut reader = BufReader::new(self.stream.try_clone()?); + let mut line = String::new(); + loop { + line.clear(); + let read = + (&mut reader).take(MAX_LINE as u64).read_line(&mut line)?; + if read == 0 { + return Ok(()); + } + if !line.ends_with('\n') { + // Longer than any request: not a client worth keeping. + return Err(io::Error::other("request too long")); + } + let response = match decode::(&line) { + Ok(request) => { + let (sender, receiver) = mpsc::channel(); + self.push(Incoming::Request { + connection: self.id, + request, + reply: Reply(sender), + }); + // The window answers when its UI thread gets to it; a + // dropped sender means it never will. + receiver + .recv() + .map_err(|_| io::Error::other("the window went away"))? + } + Err(error) => Response::error(format!("bad request: {error}")), + }; + self.stream.write_all(encode(&response)?.as_bytes())?; + } + } + + fn push(&self, incoming: Incoming) { + let mut queue = self + .queue + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + queue.push_back(incoming); + } +} + +/// The agent's end: one connection, one request at a time. +#[derive(Debug)] +pub struct Link { + stream: UnixStream, + reader: BufReader, +} + +impl Link { + /// Connect to the window at [`socket_path`]. + pub fn connect() -> io::Result { + Self::connect_at(&socket_path()) + } + + pub fn connect_at(path: &Path) -> io::Result { + let stream = UnixStream::connect(path)?; + // The window answers from its UI thread between frames; seconds + // means it is gone, not busy. + stream.set_read_timeout(Some(Duration::from_secs(20)))?; + stream.set_write_timeout(Some(Duration::from_secs(5)))?; + let reader = BufReader::new(stream.try_clone()?); + Ok(Self { stream, reader }) + } + + /// Send `request` and wait for the answer. + pub fn call(&mut self, request: &Request) -> io::Result { + self.stream.write_all(encode(request)?.as_bytes())?; + let mut line = String::new(); + let read = (&mut self.reader) + .take(MAX_LINE as u64) + .read_line(&mut line)?; + if read == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "the window closed the link", + )); + } + decode(&line) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hanging_up_is_reported_and_a_stale_socket_is_replaced() { + let dir = tempfile::TempDir::new().expect("tempdir"); + let path = dir.path().join("l.sock"); + let listener = Listener::bind_at(&path).expect("bind"); + { + let _link = Link::connect_at(&path).expect("connect"); + for _ in 0..200 { + if listener.connections() == 1 { + break; + } + thread::sleep(Duration::from_millis(5)); + } + assert_eq!(listener.connections(), 1); + } + let mut closed = false; + for _ in 0..200 { + if listener + .drain() + .iter() + .any(|item| matches!(item, Incoming::Closed { .. })) + { + closed = true; + break; + } + thread::sleep(Duration::from_millis(5)); + } + assert!(closed, "hanging up must reach the listener"); + drop(listener); + // The file is gone with the listener; put a dead one back and a new + // listener must take its place. + assert!(!path.exists()); + drop(UnixListener::bind(&path).expect("stale")); + assert!(path.exists()); + let again = Listener::bind_at(&path).expect("rebind over stale"); + assert!(Link::connect_at(&path).is_ok()); + drop(again); + } +} diff --git a/crates/disktree-link/src/unsupported.rs b/crates/disktree-link/src/unsupported.rs new file mode 100644 index 00000000..d88e65ee --- /dev/null +++ b/crates/disktree-link/src/unsupported.rs @@ -0,0 +1,83 @@ +//! Targets without Unix sockets or Windows named pipes work headless; +//! `show` and `review` explain how to hand the plan over manually. + +use std::io; +use std::path::Path; + +use crate::{Request, Response}; + +/// What a connection sent; nothing ever does here. +#[derive(Debug)] +pub enum Incoming { + Request { + connection: u64, + request: Request, + reply: Reply, + }, + Closed { + connection: u64, + }, +} + +/// Where an answer would go. +#[derive(Debug)] +pub struct Reply; + +impl Reply { + #[allow( + clippy::unused_self, + reason = "the Unix reply consumes itself; this one has the same shape" + )] + pub fn send(self, _response: Response) {} +} + +/// A listener that cannot be bound here. +#[derive(Debug)] +pub struct Listener; + +impl Listener { + pub fn bind() -> io::Result { + Err(unsupported()) + } + + pub fn bind_at(_path: &Path) -> io::Result { + Err(unsupported()) + } + + pub fn path(&self) -> &Path { + Path::new("") + } + + pub const fn connections(&self) -> usize { + 0 + } + + pub const fn drain(&self) -> Vec { + Vec::new() + } +} + +/// A client that cannot connect here. +#[derive(Debug)] +pub struct Link; + +impl Link { + pub fn connect() -> io::Result { + Err(unsupported()) + } + + pub fn connect_at(_path: &Path) -> io::Result { + Err(unsupported()) + } + + pub fn call(&mut self, _request: &Request) -> io::Result { + Err(unsupported()) + } +} + +fn unsupported() -> io::Error { + io::Error::new( + io::ErrorKind::Unsupported, + "the window link is not available on this system yet", + ) +} diff --git a/crates/disktree-link/src/windows.rs b/crates/disktree-link/src/windows.rs new file mode 100644 index 00000000..7e8ca1d7 --- /dev/null +++ b/crates/disktree-link/src/windows.rs @@ -0,0 +1,878 @@ +//! Same-user, local-only Windows named pipes. Overlapped I/O keeps reads, +//! writes and listener shutdown cancellable even when a peer stops reading. + +#![allow( + unsafe_code, + reason = "Win32 user identity and pipe ACLs have no std wrapper; blocks document safety" +)] + +use std::collections::VecDeque; +use std::ffi::c_void; +use std::io; +use std::os::windows::ffi::OsStrExt as _; +use std::os::windows::io::{AsRawHandle, FromRawHandle as _, OwnedHandle}; +use std::path::{Path, PathBuf}; +use std::ptr; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, mpsc}; +use std::thread; +use std::time::Duration; + +use tokio::io::{ + AsyncBufReadExt as _, AsyncRead, AsyncReadExt as _, AsyncWriteExt as _, + BufReader, +}; +use tokio::net::windows::named_pipe::{ + ClientOptions, NamedPipeClient, NamedPipeServer, ServerOptions, +}; +use tokio::runtime::{Builder, Runtime}; +use tokio::sync::oneshot; +use tokio::time::{sleep, timeout}; +use windows_sys::Win32::Foundation::{ + ERROR_ACCESS_DENIED, ERROR_PIPE_BUSY, HANDLE, LocalFree, +}; +use windows_sys::Win32::Security::Authorization::{ + ConvertSidToStringSidW, + ConvertStringSecurityDescriptorToSecurityDescriptorW, GetSecurityInfo, + SDDL_REVISION_1, SE_KERNEL_OBJECT, +}; +use windows_sys::Win32::Security::{ + GetTokenInformation, OWNER_SECURITY_INFORMATION, SECURITY_ATTRIBUTES, + TOKEN_QUERY, TOKEN_USER, TokenUser, +}; +use windows_sys::Win32::System::IO::CancelIoEx; +use windows_sys::Win32::System::Pipes::DisconnectNamedPipe; +use windows_sys::Win32::System::Threading::{ + GetCurrentProcess, OpenProcessToken, +}; + +use crate::{MAX_LINE, Request, Response, decode, encode, socket_path}; + +/// Matches the Unix link's deadlines. A stalled window must not leave an +/// MCP tool waiting forever, and a stalled client must not pin a writer. +const READ_WAIT: Duration = Duration::from_secs(20); +const WRITE_WAIT: Duration = Duration::from_secs(5); +const CONNECT_TICK: Duration = Duration::from_millis(10); + +/// Something a connection sent, or the news that it is gone. +#[derive(Debug)] +pub enum Incoming { + Request { + connection: u64, + request: Request, + reply: Reply, + }, + Closed { + connection: u64, + }, +} + +/// Dropping an unanswered reply closes the connection. +#[derive(Debug)] +pub struct Reply(oneshot::Sender); + +impl Reply { + pub fn send(self, response: Response) { + let _ = self.0.send(response); + } +} + +type Queue = Arc>>; + +/// The window's end. Its I/O runtime lives on a dedicated thread so this +/// synchronous API also works inside the MCP server's Tokio runtime. +#[derive(Debug)] +pub struct Listener { + path: PathBuf, + queue: Queue, + connections: Arc, + stop: Option>, + worker: Option>, +} + +impl Listener { + pub fn bind() -> io::Result { + Self::bind_at(&socket_path()) + } + + /// Claim a local pipe name without taking it from another window. + pub fn bind_at(path: &Path) -> io::Result { + validate_path(path)?; + let path = path.to_path_buf(); + let queue = Arc::new(Mutex::new(VecDeque::new())); + let connections = Arc::new(AtomicUsize::new(0)); + let (stop, stopped) = oneshot::channel(); + let (ready, started) = mpsc::sync_channel(1); + let (p, q, c) = + (path.clone(), Arc::clone(&queue), Arc::clone(&connections)); + let worker = thread::Builder::new() + .name("disktree-link".into()) + .spawn(move || { + let setup = (|| { + let runtime = runtime()?; + let security = Security::current_user()?; + let server = { + let _entered = runtime.enter(); + security.create(&p, true)? + }; + Ok::<_, io::Error>((runtime, security, server)) + })(); + match setup { + Ok((runtime, security, server)) => { + if ready.send(Ok(())).is_ok() { + runtime.block_on(accept( + p, q, c, security, server, stopped, + )); + } + } + Err(error) => { + let _ = ready.send(Err(error)); + } + } + })?; + started.recv().map_err(|_| gone())??; + Ok(Self { + path, + queue, + connections, + stop: Some(stop), + worker: Some(worker), + }) + } + + pub fn path(&self) -> &Path { + &self.path + } + + pub fn connections(&self) -> usize { + self.connections.load(Ordering::Relaxed) + } + + pub fn drain(&self) -> Vec { + self.queue + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .drain(..) + .collect() + } +} + +impl Drop for Listener { + fn drop(&mut self) { + if let Some(stop) = self.stop.take() { + let _ = stop.send(()); + } + // Joining relinquishes every instance before a replacement binds. + // Runtime shutdown cancels idle reads and pending replies as well. + if let Some(worker) = self.worker.take() { + let _ = worker.join(); + } + } +} + +#[allow( + clippy::future_not_send, + reason = "the ACL allocation stays on this dedicated current-thread runtime" +)] +async fn accept( + path: PathBuf, + queue: Queue, + connections: Arc, + security: Security, + mut server: NamedPipeServer, + mut stop: oneshot::Receiver<()>, +) { + let mut id = 0; + loop { + tokio::select! { + _ = &mut stop => break, + result = server.connect() => if result.is_err() { break; }, + } + // Keep an instance alive while making the next one: there must + // never be a gap in which another listener can claim this name. + let Ok(next) = security.create(&path, false) else { + break; + }; + let connected = std::mem::replace(&mut server, next); + id += 1; + connections.fetch_add(1, Ordering::Relaxed); + let (q, c) = (Arc::clone(&queue), Arc::clone(&connections)); + tokio::spawn(async move { + let _ = exchange(connected, &q, id).await; + c.fetch_sub(1, Ordering::Relaxed); + push(&q, Incoming::Closed { connection: id }); + }); + } +} + +async fn exchange( + server: NamedPipeServer, + queue: &Queue, + id: u64, +) -> io::Result<()> { + let mut owned = PipeIo { + pipe: server, + server: true, + }; + let mut pipe = BufReader::new(&mut owned.pipe); + loop { + let Some(line) = read_line(&mut pipe).await? else { + return Ok(()); + }; + let response = match decode::(&line) { + Ok(request) => { + let (sender, receiver) = oneshot::channel(); + push( + queue, + Incoming::Request { + connection: id, + request, + reply: Reply(sender), + }, + ); + receiver.await.map_err(|_| gone())? + } + Err(error) => Response::error(format!("bad request: {error}")), + }; + timeout( + WRITE_WAIT, + pipe.get_mut().write_all(encode(&response)?.as_bytes()), + ) + .await??; + } +} + +fn push(queue: &Queue, incoming: Incoming) { + queue + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push_back(incoming); +} + +/// A bounded line on both sides: partial JSON and unterminated oversized +/// input must never be accepted as a complete request or response. +async fn read_line( + reader: &mut BufReader, +) -> io::Result> { + let mut line = String::new(); + let count = reader.take(MAX_LINE as u64).read_line(&mut line).await?; + if count == 0 { + return Ok(None); + } + if !line.ends_with('\n') { + return Err(io::Error::other("unterminated or oversized link message")); + } + Ok(Some(line)) +} + +#[derive(Debug)] +struct Call { + request: Request, + answer: mpsc::SyncSender>, +} + +/// The agent's end: a synchronous facade over cancellable pipe I/O. +#[derive(Debug)] +pub struct Link { + calls: mpsc::Sender, +} + +impl Link { + pub fn connect() -> io::Result { + Self::connect_at(&socket_path()) + } + + pub fn connect_at(path: &Path) -> io::Result { + validate_path(path)?; + let path = path.to_path_buf(); + let (calls, requests) = mpsc::channel::(); + let (ready, started) = mpsc::sync_channel(1); + thread::Builder::new() + .name("disktree-link-client".into()) + .spawn(move || { + let setup = (|| { + let runtime = runtime()?; + let pipe = runtime.block_on(connect(&path))?; + Ok::<_, io::Error>(( + runtime, + PipeIo { + pipe, + server: false, + }, + )) + })(); + match setup { + Ok((runtime, mut owned)) => { + let mut pipe = BufReader::new(&mut owned.pipe); + if ready.send(Ok(())).is_err() { + return; + } + for call in requests { + let result = runtime.block_on(async { + timeout( + WRITE_WAIT, + pipe.get_mut().write_all( + encode(&call.request)?.as_bytes(), + ), + ) + .await??; + let line = + timeout(READ_WAIT, read_line(&mut pipe)) + .await?? + .ok_or_else(gone)?; + decode(&line) + }); + // After a timeout the next line might be the old + // reply: never reuse a desynchronized connection. + let failed = result.is_err(); + let _ = call.answer.send(result); + if failed { + break; + } + } + } + Err(error) => { + let _ = ready.send(Err(error)); + } + } + })?; + started.recv().map_err(|_| gone())??; + Ok(Self { calls }) + } + + pub fn call(&mut self, request: &Request) -> io::Result { + let (answer, response) = mpsc::sync_channel(1); + self.calls + .send(Call { + request: request.clone(), + answer, + }) + .map_err(|_| gone())?; + response.recv().map_err(|_| gone())? + } +} + +async fn connect(path: &Path) -> io::Result { + connect_for_user(path, ¤t_sid()?).await +} + +async fn connect_for_user( + path: &Path, + user: &str, +) -> io::Result { + timeout(WRITE_WAIT, async { + loop { + // Tokio uses SECURITY_IDENTIFICATION: a pipe server cannot + // impersonate an elevated agent that connects to its name. + match ClientOptions::new().open(path) { + Ok(pipe) => { + // The name and a server-supplied DACL prove nothing: + // another account could have claimed this name first. + // Query this connected handle, never the path, before + // sending Hello, marks, or any other protocol data. + if pipe_owner(pipe.as_raw_handle())? != user { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "the PwrDisk pipe belongs to another user", + )); + } + return Ok(pipe); + } + Err(error) + if error.raw_os_error() + == Some(ERROR_PIPE_BUSY.cast_signed()) => + { + sleep(CONNECT_TICK).await; + } + Err(error) => return Err(error), + } + } + }) + .await? +} + +fn pipe_owner(handle: HANDLE) -> io::Result { + let mut owner = ptr::null_mut(); + let mut descriptor = ptr::null_mut(); + // SAFETY: Windows validates the handle; both outputs are valid pointers. + // The client's GENERIC_READ/WRITE rights include READ_CONTROL. + let status = unsafe { + GetSecurityInfo( + handle, + SE_KERNEL_OBJECT, + OWNER_SECURITY_INFORMATION, + &raw mut owner, + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + &raw mut descriptor, + ) + }; + if status != 0 { + return Err(io::Error::from_raw_os_error(status.cast_signed())); + } + let _allocation = LocalAllocation(descriptor); + if owner.is_null() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "the PwrDisk pipe has no verifiable owner", + )); + } + // SAFETY: owner points into the live security descriptor above. + unsafe { sid_text(owner) } +} + +/// Mio deliberately lets pending writes finish after dropping a pipe. +/// Cancel them explicitly: a peer that never reads must not retain this +/// instance after a timeout or prevent a new window from claiming its name. +#[derive(Debug)] +struct PipeIo { + pipe: T, + server: bool, +} + +impl Drop for PipeIo { + fn drop(&mut self) { + // SAFETY: pipe owns a live overlapped handle. Null means every I/O + // operation on it; Mio retains each OVERLAPPED until completion. + unsafe { + CancelIoEx(self.pipe.as_raw_handle(), ptr::null()); + } + if self.server { + // SAFETY: only a server pipe sets this flag. Disconnect also + // invalidates idle client handles before the server closes. + unsafe { + DisconnectNamedPipe(self.pipe.as_raw_handle()); + } + } + } +} + +fn runtime() -> io::Result { + Builder::new_current_thread().enable_all().build() +} + +fn gone() -> io::Error { + io::Error::new(io::ErrorKind::UnexpectedEof, "the window closed the link") +} + +fn validate_path(path: &Path) -> io::Result<()> { + let name = path.to_string_lossy(); + if name + .get(..9) + .is_some_and(|prefix| prefix.eq_ignore_ascii_case(r"\\.\pipe\")) + && name.len() > 9 + && !name[9..].contains(['\\', '/']) + && !name.contains('\0') + { + Ok(()) + } else { + Err(io::Error::new( + io::ErrorKind::InvalidInput, + "expected a local \\\\.\\pipe\\name", + )) + } +} + +pub fn default_path() -> io::Result { + Ok(PathBuf::from(format!( + r"\\.\pipe\pwrdisk-{}", + current_sid()? + ))) +} + +/// Memory Windows allocated with `LocalAlloc`; both SID strings and security +/// descriptors must be released with `LocalFree`, including on error paths. +struct LocalAllocation(*mut c_void); + +impl Drop for LocalAllocation { + fn drop(&mut self) { + // SAFETY: this pointer came from a successful allocating Win32 API. + unsafe { + LocalFree(self.0); + } + } +} + +fn current_sid() -> io::Result { + let mut token = ptr::null_mut(); + // SAFETY: the process pseudo-handle is valid; token is an out pointer. + if unsafe { + OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &raw mut token) + } == 0 + { + return Err(io::Error::last_os_error()); + } + // SAFETY: OpenProcessToken returned a unique owned handle. + let _token = unsafe { OwnedHandle::from_raw_handle(token) }; + let mut bytes = 0; + // SAFETY: null buffer and zero size query the required length only. + unsafe { + GetTokenInformation( + token, + TokenUser, + ptr::null_mut(), + 0, + &raw mut bytes, + ); + } + // TOKEN_USER contains pointers, so allocate aligned storage for it and + // the SID Windows writes after it, rather than casting a byte buffer. + let mut buffer = + vec![0_usize; (bytes as usize).div_ceil(size_of::())]; + // SAFETY: buffer has the queried size and TOKEN_USER's pointer alignment. + if unsafe { + GetTokenInformation( + token, + TokenUser, + buffer.as_mut_ptr().cast(), + bytes, + &raw mut bytes, + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + // SAFETY: a successful TokenUser query filled a TOKEN_USER at this address. + let user = unsafe { &*buffer.as_ptr().cast::() }; + // SAFETY: the SID belongs to buffer and remains alive through conversion. + unsafe { sid_text(user.User.Sid) } +} + +/// `sid` must point to a valid SID for the duration of this call. +unsafe fn sid_text(sid: *mut c_void) -> io::Result { + let mut text = ptr::null_mut(); + // SAFETY: the caller guarantees a valid SID; text is an out pointer. + if unsafe { ConvertSidToStringSidW(sid, &raw mut text) } == 0 { + return Err(io::Error::last_os_error()); + } + let _allocation = LocalAllocation(text.cast()); + let mut len = 0; + // SAFETY: successful conversion returns a null-terminated UTF-16 string. + unsafe { + while *text.add(len) != 0 { + len += 1; + } + } + // SAFETY: len stops at the terminator inside the allocated SID string. + Ok(String::from_utf16_lossy(unsafe { + std::slice::from_raw_parts(text, len) + })) +} + +struct Security(LocalAllocation); + +impl Security { + fn current_user() -> io::Result { + // A protected DACL grants only this SID access. No Everyone, + // authenticated-users or administrators ACE is inherited. + let sid = current_sid()?; + // An elevated token's default owner can be Administrators rather + // than TokenUser. Both sides identify the account by TokenUser. + Self::from_sddl(&format!("O:{sid}D:P(A;;GA;;;{sid})")) + } + + fn from_sddl(sddl: &str) -> io::Result { + let sddl: Vec = std::ffi::OsStr::new(sddl) + .encode_wide() + .chain(Some(0)) + .collect(); + let mut descriptor = ptr::null_mut(); + // SAFETY: SDDL is terminated and descriptor is an out pointer. + if unsafe { + ConvertStringSecurityDescriptorToSecurityDescriptorW( + sddl.as_ptr(), + SDDL_REVISION_1, + &raw mut descriptor, + ptr::null_mut(), + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + Ok(Self(LocalAllocation(descriptor))) + } + + fn create(&self, path: &Path, first: bool) -> io::Result { + let mut attributes = SECURITY_ATTRIBUTES { + nLength: size_of::() as u32, + lpSecurityDescriptor: self.0.0, + bInheritHandle: 0, + }; + // SAFETY: the descriptor and attributes live through CreateNamedPipeW, + // which copies the descriptor; the handle is not inheritable. + let result = unsafe { + ServerOptions::new() + .first_pipe_instance(first) + .reject_remote_clients(true) + .create_with_security_attributes_raw( + path, + (&raw mut attributes).cast(), + ) + }; + match result { + Err(error) + if first + && error.raw_os_error() + == Some(ERROR_ACCESS_DENIED.cast_signed()) => + { + Err(io::Error::new( + io::ErrorKind::AddrInUse, + "another PwrDisk window owns this pipe, or access was denied", + )) + } + result => result, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::Security::{ + ACCESS_ALLOWED_ACE, DACL_SECURITY_INFORMATION, GetAce, + GetSecurityDescriptorControl, SE_DACL_PROTECTED, + }; + + fn endpoint() -> (tempfile::TempDir, PathBuf) { + let dir = tempfile::tempdir().expect("tempdir"); + let path = PathBuf::from(format!( + r"\\.\pipe\pwrdisk-test-{}", + dir.path().file_name().expect("temp name").to_string_lossy() + )); + (dir, path) + } + + #[test] + fn the_default_pipe_is_stable_and_names_the_current_sid() { + let path = default_path().expect("default pipe"); + assert_eq!(path, default_path().expect("same pipe")); + assert_eq!( + path, + PathBuf::from(format!( + r"\\.\pipe\pwrdisk-{}", + current_sid().expect("SID") + )) + ); + validate_path(&path).expect("local pipe"); + } + + #[test] + fn paths_cannot_address_files_or_remote_pipes() { + for path in [ + r"\\server\pipe\pwrdisk", + r"C:\pwrdisk.sock", + r"\\.\pipe\", + r"\\.\pipe\nested\name", + "", + ] { + assert_eq!( + Listener::bind_at(Path::new(path)) + .expect_err("invalid path") + .kind(), + io::ErrorKind::InvalidInput + ); + assert_eq!( + Link::connect_at(Path::new(path)) + .expect_err("invalid path") + .kind(), + io::ErrorKind::InvalidInput + ); + } + } + + #[test] + fn the_kernel_pipe_has_one_protected_allow_ace_for_this_user() { + let (_dir, path) = endpoint(); + let runtime = runtime().expect("runtime"); + let _entered = runtime.enter(); + let pipe = Security::current_user() + .expect("security") + .create(&path, true) + .expect("pipe"); + assert_eq!( + pipe_owner(pipe.as_raw_handle()).expect("pipe owner"), + current_sid().expect("user SID") + ); + let mut descriptor = ptr::null_mut(); + let mut acl = ptr::null_mut(); + // SAFETY: pipe is live, and the requested outputs are valid pointers. + let status = unsafe { + GetSecurityInfo( + pipe.as_raw_handle(), + SE_KERNEL_OBJECT, + DACL_SECURITY_INFORMATION, + ptr::null_mut(), + ptr::null_mut(), + &raw mut acl, + ptr::null_mut(), + &raw mut descriptor, + ) + }; + assert_eq!(status, 0, "GetSecurityInfo"); + let _allocation = LocalAllocation(descriptor); + assert!(!acl.is_null(), "a null DACL allows everyone"); + let mut control = 0; + let mut revision = 0; + // SAFETY: descriptor is the live allocation returned above. + assert_ne!( + unsafe { + GetSecurityDescriptorControl( + descriptor, + &raw mut control, + &raw mut revision, + ) + }, + 0 + ); + assert_ne!(control & SE_DACL_PROTECTED, 0, "no inherited grants"); + // SAFETY: acl points inside descriptor and is not null. + assert_eq!(unsafe { (*acl).AceCount }, 1, "only one identity"); + let mut ace = ptr::null_mut(); + // SAFETY: the queried ACL has one ACE, and ace is an out pointer. + assert_ne!(unsafe { GetAce(acl, 0, &raw mut ace) }, 0); + // SAFETY: the descriptor was constructed with one ACCESS_ALLOWED_ACE. + let ace = unsafe { &*ace.cast::() }; + assert_eq!(ace.Header.AceType, 0, "ACCESS_ALLOWED_ACE_TYPE"); + // SAFETY: SidStart is the start of the variable-length SID in this ACE. + let sid = + unsafe { sid_text((&raw const ace.SidStart).cast_mut().cast()) } + .expect("ACE SID"); + assert_eq!(sid, current_sid().expect("user SID")); + } + + #[test] + fn a_permissive_pipe_owned_by_a_different_sid_is_rejected() { + let (_dir, path) = endpoint(); + let runtime = runtime().expect("runtime"); + let owner = current_sid().expect("server SID"); + // Model the client as a different account without requiring a + // second Windows login or privileges on the CI runner. This pipe + // admits everyone, just like a squatter's pipe, but its real owner + // must still match the client's expected account. + let client = "S-1-5-21-0-0-0-1234"; + assert_ne!(owner, client); + let _server = { + let _entered = runtime.enter(); + Security::from_sddl(&format!("O:{owner}D:P(A;;GA;;;WD)")) + .expect("permissive security") + .create(&path, true) + .expect("squatter's pipe") + }; + let error = runtime + .block_on(connect_for_user(&path, client)) + .expect_err("a matching name and permissive ACL are not identity"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(error.to_string().contains("belongs to another user")); + } + + #[test] + fn an_unreadable_pipe_owner_is_not_trusted() { + assert!(pipe_owner(ptr::null_mut()).is_err()); + } + + #[test] + fn synchronous_calls_work_inside_a_tokio_runtime() { + let (_dir, path) = endpoint(); + runtime().expect("runtime").block_on(async { + let listener = Listener::bind_at(&path).expect("bind"); + let mut link = Link::connect_at(&path).expect("connect"); + let answer = thread::spawn(move || { + loop { + for incoming in listener.drain() { + if let Incoming::Request { reply, .. } = incoming { + reply.send(Response::Ok); + // Keep the listener alive until the response + // has left its background runtime. + for _ in 0..200 { + if listener.connections() == 0 { + return; + } + thread::sleep(CONNECT_TICK); + } + panic!("client did not disconnect"); + } + } + thread::sleep(CONNECT_TICK); + } + }); + assert_eq!( + link.call(&Request::State).expect("response"), + Response::Ok + ); + drop(link); + answer.join().expect("window thread"); + }); + } + + #[test] + fn dropping_a_listener_cancels_idle_reads_and_pending_replies() { + let (_dir, path) = endpoint(); + let listener = Listener::bind_at(&path).expect("bind"); + let _idle = Link::connect_at(&path).expect("idle"); + let mut link = Link::connect_at(&path).expect("pending"); + let request = thread::spawn(move || link.call(&Request::State)); + let pending = (0..200) + .find_map(|_| { + let incoming = listener.drain().into_iter().next(); + if incoming.is_none() { + thread::sleep(CONNECT_TICK); + } + incoming + }) + .expect("request must reach the listener"); + assert!(matches!(pending, Incoming::Request { .. })); + drop(listener); + assert!(request.join().expect("client thread").is_err()); + // Retaining the reply cannot keep a pipe instance alive. + let _replacement = + Listener::bind_at(&path).expect("rebind immediately"); + drop(pending); + } + + #[test] + fn a_client_that_never_reads_cannot_hold_listener_shutdown() { + use std::io::Write as _; + use std::os::windows::fs::OpenOptionsExt as _; + use windows_sys::Win32::Storage::FileSystem::{ + SECURITY_IDENTIFICATION, SECURITY_SQOS_PRESENT, + }; + + let (_dir, path) = endpoint(); + let listener = Listener::bind_at(&path).expect("bind"); + let mut client = std::fs::OpenOptions::new() + .read(true) + .write(true) + .custom_flags(SECURITY_IDENTIFICATION | SECURITY_SQOS_PRESENT) + .open(&path) + .expect("raw client"); + client + .write_all(encode(&Request::State).expect("encode").as_bytes()) + .expect("request"); + let incoming = (0..200) + .find_map(|_| { + let incoming = listener.drain().into_iter().next(); + if incoming.is_none() { + thread::sleep(CONNECT_TICK); + } + incoming + }) + .expect("request"); + let Incoming::Request { reply, .. } = incoming else { + panic!("closed first"); + }; + // Much larger than the pipe buffer: this write cannot complete + // while the client retains its handle without reading. + reply.send(Response::error("x".repeat(MAX_LINE / 2))); + thread::sleep(Duration::from_millis(100)); + let start = std::time::Instant::now(); + drop(listener); + assert!( + start.elapsed() < Duration::from_secs(2), + "shutdown waited for a reader" + ); + drop(client); + let _replacement = + Listener::bind_at(&path).expect("rebind after cancelled write"); + } +} diff --git a/crates/disktree-mcp/Cargo.toml b/crates/disktree-mcp/Cargo.toml new file mode 100644 index 00000000..ec44d30b --- /dev/null +++ b/crates/disktree-mcp/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "disktree-mcp" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "disktree as an MCP server: scan, explore and mark over stdio" + +[lints] +workspace = true + +[dependencies] +disktree-core = { workspace = true } +disktree-link = { workspace = true } +anyhow = { workspace = true } +rmcp = { version = "3.5", default-features = false, features = ["server", "macros", "transport-io", "elicitation"] } +schemars = "1" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha2 = "0.10" +tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "process"] } + +[dev-dependencies] +tempfile = "3" diff --git a/crates/disktree-mcp/examples/session_report.rs b/crates/disktree-mcp/examples/session_report.rs new file mode 100644 index 00000000..fb3a1aca --- /dev/null +++ b/crates/disktree-mcp/examples/session_report.rs @@ -0,0 +1,54 @@ +//! Print what `pwrdisk mcp` answers for a directory, without a window. +//! +//! `cargo run -p disktree-mcp --example session_report -- DIR [MARK...]` +//! scans DIR here (no socket, no window is launched), then prints the +//! scan report, `pwrdisk_ls DIR`, `pwrdisk_find DIR` and, for each MARK +//! argument (a comma-separated list of paths), the mark plan for that +//! set. Useful for checking how a fixture reads to an agent. + +use std::path::PathBuf; + +use disktree_mcp::Session; +use disktree_mcp::session::{ + FindParams, LsParams, PathsParams, ScanParams, ScanPlan, run_scan, +}; + +fn main() -> Result<(), String> { + let mut args = std::env::args_os().skip(1); + let root = PathBuf::from(args.next().ok_or("usage: DIR [MARK,...]")?); + // A socket nobody listens on, and no launcher: the scan runs here. + let socket = std::env::temp_dir().join("pwrdisk-session-report.sock"); + let mut session = Session::detached(socket, None); + let ScanPlan::Local { root, options } = + session.prepare_scan(&ScanParams { + path: Some(root), + ..ScanParams::default() + })? + else { + return Err("a window answered; this example scans here".into()); + }; + let scan = run_scan(root.clone(), options)?; + println!("== pwrdisk_scan\n{}\n", session.store_scan(scan)); + let ls = LsParams { + path: root.clone(), + ..LsParams::default() + }; + println!("== pwrdisk_ls\n{}", session.ls(&ls)?); + let find = FindParams { + path: Some(root), + ..FindParams::default() + }; + println!("== pwrdisk_find\n{}", session.find(&find)?); + for set in args { + let paths: Vec = set + .to_string_lossy() + .split(',') + .map(PathBuf::from) + .collect(); + let names = set.to_string_lossy().into_owned(); + let params = PathsParams { paths }; + println!("== pwrdisk_mark {names}\n{}", session.mark(¶ms)?); + session.unmark(&PathsParams::default())?; + } + Ok(()) +} diff --git a/crates/disktree-mcp/src/confirmation_tests.rs b/crates/disktree-mcp/src/confirmation_tests.rs new file mode 100644 index 00000000..80693529 --- /dev/null +++ b/crates/disktree-mcp/src/confirmation_tests.rs @@ -0,0 +1,341 @@ +//! Exercise the server/client confirmation exchange without removing data. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::Duration; + +use disktree_link::{ + Incoming, Listener, Mark, RemovalChoice, RemovalPreview, Request, Response, + State, VERSION, +}; +use rmcp::ServiceExt as _; +use serde_json::{Value, json}; +use tokio::io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader}; + +use crate::server::Server; +use crate::session::Session; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn only_interactive_user_confirmation_reaches_the_removal_request() { + for mode_name in ["permanent", "owner_cleanup"] { + let mode = if mode_name == "owner_cleanup" { + RemovalChoice::OwnerCleanup + } else { + RemovalChoice::Permanent + }; + for (supports_form, action, confirmed, native, expected) in [ + (false, "accept", true, 0, 0), + (true, "decline", true, 0, 0), + (true, "cancel", true, 0, 0), + (true, "accept", false, 0, 0), + (true, "accept", true, 0, 1), + (true, "cancel", false, 1, 0), // UI still running. + (true, "cancel", false, 2, 0), // UI completed before cancellation. + (true, "decline", false, 3, 0), // Partial failure in native UI. + (true, "accept", true, 2, 0), // UI completed before acceptance. + (true, "cancel", false, 4, 0), // Unrelated preview. + (true, "cancel", false, 5, 0), // Different mode. + (true, "cancel", false, 6, 0), // Different path list. + (true, "error", false, 0, 0), // Proxy/client lifecycle failure. + (true, "error", false, 2, 0), // UI completion before form error. + ] { + let temp = tempfile::tempdir().expect("fixture"); + let file = temp.path().join("candidate"); + std::fs::write(&file, b"fixture").expect("fixture data"); + #[cfg(not(windows))] + let socket = temp.path().join("window.sock"); + #[cfg(windows)] + let socket = std::path::PathBuf::from(format!( + r"\\.\pipe\pwrdisk-confirmation-{}", + temp.path().file_name().expect("name").to_string_lossy() + )); + let listener = + Listener::bind_at(&socket).expect("fixture listener"); + let calls = Arc::new(AtomicUsize::new(0)); + let stopped = Arc::new(AtomicBool::new(false)); + let (count, stop) = (Arc::clone(&calls), Arc::clone(&stopped)); + let native_state = Arc::new(AtomicUsize::new(0)); + let ui_state = Arc::clone(&native_state); + let root = temp.path().to_path_buf(); + let candidate = file.clone(); + let window = std::thread::spawn(move || { + let mut state = State { + version: VERSION, + app_version: "0.13.0".into(), + root: root.clone(), + current: root.clone(), + screen: "explore".into(), + scanning: false, + scanned: true, + estimate: None, + marks: vec![Mark { + path: candidate.clone(), + bytes: 7, + is_dir: false, + }], + space: None, + removal_operation: None, + removal: None, + removals: None, + tree: None, + insights: vec![], + remote: None, + }; + while !stop.load(Ordering::Relaxed) { + for incoming in listener.drain() { + if let Incoming::Request { request, reply, .. } = + incoming + { + let answer = match request { + Request::Hello { .. } | Request::State => { + let native = + ui_state.load(Ordering::SeqCst); + state.removal_operation = (native > 0) + .then(|| { + disktree_link::RemovalOperation { + preview_id: if native == 4 { + "other-preview" + } else { + "fixture-preview" + } + .into(), + mode: if native == 5 { + RemovalChoice::Trash + } else { + mode + }, + paths: if native == 6 { + vec![root.join("other")] + } else { + vec![candidate.clone()] + }, + finished: native != 1, + removed: usize::from( + native != 1 && native != 3, + ), + failed: usize::from( + native == 3, + ), + pending: usize::from( + native == 1, + ), + } + }); + Response::State(state.clone()) + } + Request::PrepareRemoval { mode, .. } => { + Response::RemovalPreview(RemovalPreview { + preview_id: "fixture-preview".into(), + root: root.clone(), + mode, + paths: vec![candidate.clone()], + bytes: 7, + estimate: + disktree_link::SelectionEstimate { + paths: vec![candidate.clone()], + lower: 0, + upper: None, + on_volume: 0, + partial: true, + shared: 0, + }, + limit_percent: 5, + volumes: vec![], + expires_in_seconds: 300, + cleanup: if mode + == RemovalChoice::OwnerCleanup + { + vec![disktree_core::cleanup::Operation { + owner: disktree_core::cleanup::Owner::Uv, + version: "uv 0.11.0".into(), + selected: vec![candidate.clone()], + cache_root: root.clone(), + scope: candidate.clone(), + command: disktree_core::cleanup::Command { + executable: "/fixture/uv".into(), + arguments: vec!["cache".into(), "clean".into()], + environment: std::collections::BTreeMap::new(), + working_directory: root.clone(), + }, + effects: "Entire cache scope including unselected siblings".into(), + limitations: "No raw deletion fallback; APFS snapshots can retain blocks".into(), + }] + } else { + vec![] + }, + proposals: vec![], + decisions: vec![], + files: None, + confirmation: mode + .confirmation() + .into(), + consent: if mode + == RemovalChoice::OwnerCleanup + { + "Run owner commands (1), exactly as shown: uv cache clean, Entire cache scope including unselected siblings".into() + } else { + String::new() + }, + }) + } + Request::Remove(_) => { + count.fetch_add(1, Ordering::Relaxed); + Response::State(state.clone()) + } + _ => Response::error( + "unexpected fixture request", + ), + }; + reply.send(answer); + } + } + std::thread::sleep(Duration::from_millis(1)); + } + }); + let server = Server::new(Session::detached(socket, None)); + let (client_io, server_io) = tokio::io::duplex(65_536); + let task = tokio::spawn(async move { + let service = server.serve(server_io).await.expect("server"); + let _ = service.waiting().await; + }); + let (input, mut output) = tokio::io::split(client_io); + let mut input = BufReader::new(input); + let capabilities = if supports_form { + json!({"elicitation":{"form":{}}}) + } else { + json!({}) + }; + send( + &mut output, + json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{ + "protocolVersion":"2025-06-18","capabilities":capabilities, + "clientInfo":{"name":"fixture-client","version":"1"} + }}), + ) + .await; + assert_eq!(receive(&mut input).await["id"], 1); + send( + &mut output, + json!({"jsonrpc":"2.0","method":"notifications/initialized"}), + ) + .await; + send(&mut output, json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{ + "name":"pwrdisk_removal_preview","arguments":{"mode":mode_name} + }})).await; + let preview = receive(&mut input).await; + assert_ne!(preview["result"]["isError"], true, "{preview}"); + send(&mut output, json!({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{ + "name":"pwrdisk_remove","arguments":{ + "preview_id":"fixture-preview","mode":mode_name,"paths":[file], + "confirmation":mode.confirmation() + } + }})).await; + let mut asked = false; + loop { + let response = receive(&mut input).await; + if response["method"] == "elicitation/create" { + asked = true; + let message = response["params"]["message"] + .as_str() + .expect("confirmation text"); + assert!(message.contains(&file.display().to_string())); + if mode == RemovalChoice::OwnerCleanup { + // The preview's consent text, and the mode's + // warning that owner failure never deletes files. + for expected in [ + "uv cache clean", + "unselected siblings", + "never falls back to deleting files", + "delete_files choice deletes exactly", + "APFS", + ] { + assert!(message.contains(expected), "{message}"); + } + } else { + assert!(message.contains("permanently deletes")); + assert!(message.contains("cannot be undone")); + } + assert!(message.contains("5% of each volume")); + native_state.store(native, Ordering::SeqCst); + if action == "error" { + send(&mut output, json!({"jsonrpc":"2.0","id":response["id"],"error":{ + "code":-32603,"message":"fixture client disconnected" + }})).await; + continue; + } + // This simulates the client's user response, never model input. + send( + &mut output, + json!({"jsonrpc":"2.0","id":response["id"],"result":{ + "action":action,"content":{"confirmed":confirmed} + }}), + ) + .await; + } else if response["id"] == 3 { + assert_eq!( + response["result"]["isError"] == true, + expected == 0 && !(1..=3).contains(&native), + "{response}" + ); + let text = response.to_string(); + if (1..=3).contains(&native) { + if mode == RemovalChoice::OwnerCleanup { + assert!( + text.contains("cleanup steps succeeded"), + "{text}" + ); + } + assert!( + text.contains("exact previewed selection"), + "{text}" + ); + assert!( + text.contains(if native == 1 { + "already running" + } else { + "finished" + }), + "{text}" + ); + assert!(text.contains("Do not retry"), "{text}"); + if native == 3 { + assert!(text.contains("1 failed"), "{text}"); + } + assert!(!text.contains("new preview"), "{text}"); + } else if supports_form && expected == 0 { + assert!( + text.contains("could not be verified"), + "{text}" + ); + } + break; + } + } + assert_eq!(asked, supports_form); + assert_eq!(calls.load(Ordering::Relaxed), expected); + assert_eq!( + std::fs::read(&file).expect("fixture is untouched"), + b"fixture" + ); + task.abort(); + let _ = task.await; + stopped.store(true, Ordering::Relaxed); + window.join().expect("fixture window"); + } + } +} + +async fn send(output: &mut (impl tokio::io::AsyncWrite + Unpin), value: Value) { + let line = format!("{value}\n"); + output.write_all(line.as_bytes()).await.expect("send"); + output.flush().await.expect("flush"); +} + +async fn receive(input: &mut (impl tokio::io::AsyncBufRead + Unpin)) -> Value { + let mut line = String::new(); + tokio::time::timeout(Duration::from_secs(10), input.read_line(&mut line)) + .await + .expect("protocol response in time") + .expect("read"); + serde_json::from_str(&line).expect("JSON-RPC") +} diff --git a/crates/disktree-mcp/src/lib.rs b/crates/disktree-mcp/src/lib.rs new file mode 100644 index 00000000..8c6948ff --- /dev/null +++ b/crates/disktree-mcp/src/lib.rs @@ -0,0 +1,39 @@ +//! `pwrdisk mcp`: PwrDisk as a Model Context Protocol server over stdio. +//! +//! An agent runs `pwrdisk mcp` as a subprocess, the same way it would run +//! any other tool, and talks to it over stdin and stdout. There is no port, +//! no token and no sign-in: the agent already runs as this user, and this +//! process can do no more than the user's shell can. It scans with +//! `disktree-core` itself, so no window is needed; when a window is open it +//! follows along over [`disktree_link`], and a window can be opened for the +//! review screen. +//! +//! Destructive removal requires a single-use preview and user confirmation. +//! [`Session`] holds what one connected agent knows; [`server`] is the +//! protocol around it. + +pub mod report; +mod retention; +pub mod server; +pub mod session; +pub mod skills; + +#[cfg(test)] +mod confirmation_tests; + +pub use session::Session; + +/// Serve MCP on stdin and stdout until the client hangs up. +pub fn serve() -> anyhow::Result<()> { + use rmcp::ServiceExt as _; + + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build()?; + runtime.block_on(async { + let server = server::Server::new(Session::new()); + let running = server.serve(rmcp::transport::stdio()).await?; + running.waiting().await?; + Ok(()) + }) +} diff --git a/crates/disktree-mcp/src/report.rs b/crates/disktree-mcp/src/report.rs new file mode 100644 index 00000000..57548233 --- /dev/null +++ b/crates/disktree-mcp/src/report.rs @@ -0,0 +1,422 @@ +//! How a tree reads as text. +//! +//! An agent reads these answers as tokens, so each is a short, aligned +//! table with the number that matters first, rather than JSON that repeats +//! every key on every row. Sizes are binary units, as in the window. The +//! rows are [`Entry`] values, so a listing reads the same whether it came +//! from the window or from this process's own scan. + +use std::fmt::Write as _; +use std::path::Path; + +use disktree_core::size::{ + human_bytes, human_bytes_range, human_count, share, share_bar, +}; +use disktree_link::{Clones, Entry, Found, Listing}; + +/// Width of the share bar on a row. +const BAR: usize = 8; + +pub fn observed(delta: Option) -> String { + delta.map_or_else( + || "not measured".to_string(), + |delta| { + let sign = if delta < 0 { "-" } else { "+" }; + format!("{sign}{}", human_bytes(delta.unsigned_abs())) + }, + ) +} + +/// `~/x` for a path under the home directory, else the path as it is. +pub fn display(path: &Path, home: Option<&Path>) -> String { + match home { + Some(home) if path == home => "~".to_string(), + Some(home) => path.strip_prefix(home).map_or_else( + |_| path.display().to_string(), + |rest| format!("~/{}", rest.display()), + ), + None => path.display().to_string(), + } +} + +/// The removals since the window's scan, each three ways, then the total: +/// what to report after several batches, since the tree is not rescanned. +pub fn ledger(ledger: &disktree_link::RemovalLedger, now: i64) -> String { + let private = |bytes: Option| { + bytes.map_or_else(|| "unknown".into(), human_bytes) + }; + let mut out = if ledger + .cohorts + .iter() + .any(|cohort| cohort.mode == "owner_cleanup") + { + String::from( + "Cleanup since the scan: owner command counts and scope allocation are separate from raw removals; owner success does not mean the root disappeared. Observed is the measured volume change.\n", + ) + } else { + String::from( + "Removed since the scan (the tree already leaves these out; reported counts a clone in every place, private is what the scan saw as theirs alone, observed is the volume's measured change):\n", + ) + }; + for (index, cohort) in ledger.cohorts.iter().enumerate() { + let _ = writeln!( + out, + " {}. {} \u{00b7} {} {} \u{00b7} {} failed \u{00b7} {} \ + reported \u{00b7} {} private \u{00b7} {} observed \u{00b7} {}", + index + 1, + cohort.mode, + cohort.removed, + if cohort.mode == "owner_cleanup" { + "cleanup steps succeeded" + } else { + "removed" + }, + cohort.failed, + human_bytes(cohort.reported), + private(cohort.private), + observed(cohort.observed), + age(now, cohort.finished), + ); + } + let _ = writeln!( + out, + " Total: {} reported \u{00b7} {} private \u{00b7} {} observed, \ + from the first removal's start to the last one's end", + human_bytes(ledger.reported), + private(ledger.private), + observed(ledger.observed), + ); + out +} + +/// How long ago `then` was, from `now`, in one unit: `3 d`, `2 mo`. +pub fn age(now: i64, then: i64) -> String { + if then <= 0 { + return "age unknown".to_string(); + } + let seconds = (now - then).max(0); + match seconds { + 0..3_600 => "within the hour".to_string(), + 3_600..86_400 => format!("{} h ago", seconds / 3_600), + 86_400..5_184_000 => format!("{} d ago", seconds / 86_400), + 5_184_000..63_072_000 => format!("{} mo ago", seconds / 2_592_000), + _ => format!("{} y ago", seconds / 31_536_000), + } +} + +/// What an entry is, in one phrase after its name. +pub fn describe(entry: &Entry, now: i64) -> String { + let mut parts = Vec::new(); + // First, since it changes what the rest means: the size is the scan's. + if entry.removed { + parts.push("removed since the scan".to_string()); + } else if entry.removed_bytes > 0 { + parts.push(format!( + "{} of it removed since the scan", + human_bytes(entry.removed_bytes) + )); + } + if entry.is_dir { + parts.push(format!("{} files", human_count(entry.files))); + } + if let Some(split) = entry.clones.as_ref().and_then(clone_split) { + parts.push(split); + } + if entry.category != "other" { + parts.push(entry.category.clone()); + } + if let Some(artifact) = entry.artifact { + parts.push(format!( + "{}: {} ({} evidence)", + artifact.status(), + artifact.kind.label(), + artifact.evidence_label() + )); + parts.push(artifact.guidance().to_string()); + } else if let Some(reclaim) = &entry.reclaim { + parts.push(format!("cleanup candidate: {reclaim}")); + } + if entry.read_error { + parts.push("unreadable".to_string()); + } + parts.push(age(now, entry.modified)); + parts.join(" \u{00b7} ") +} + +/// The split, then what removing the entry alone frees; `None` without +/// clone blocks. +fn clone_split(clones: &Clones) -> Option { + let split = clones.split()?; + Some(format!( + "{split} \u{00b7} frees \u{2248} {} alone{}", + human_bytes_range(clones.lower, clones.upper), + if clones.partial { " (partial)" } else { "" }, + )) +} + +/// A line for a header: how much of `entry` is clone blocks, and how much +/// of it is listed twice. `None` without clone blocks, so reports off APFS +/// read as they always have. +pub fn clone_summary(entry: &Entry) -> Option { + let clones = entry.clones.filter(|clones| clones.shared > 0)?; + let mut line = format!( + "APFS clones: {} of this is shared clone blocks", + human_bytes(clones.shared) + ); + if clones.repeated > 0 { + let _ = write!( + line, + "; \u{2248} {} is counted again, so the files here take \ + \u{2248} {} on disk", + human_bytes(clones.repeated), + human_bytes(entry.bytes.saturating_sub(clones.repeated)), + ); + } + let _ = writeln!( + line, + "{}. Rows split private from shared bytes; shared blocks stay while \ + any clone of them remains, inside this scan or outside it.", + if clones.partial { " (partial)" } else { "" }, + ); + Some(line) +} + +/// One row of a listing: share of `total`, size, name and description. +pub fn row(entry: &Entry, name: &str, total: u64, now: i64) -> String { + let mut name = name.to_string(); + if entry.is_dir { + name.push('/'); + } + format!( + "{} {:>3.0}% {:>9} {name} {}", + share_bar(entry.bytes, total, BAR), + share(entry.bytes, total), + human_bytes(entry.bytes), + describe(entry, now), + ) +} + +/// The children of a listing, largest first, with a line for the rest. +pub fn children(listing: &Listing, now: i64) -> String { + let mut out = String::new(); + let total = listing.entry.bytes.max(1); + for child in &listing.children { + let _ = writeln!(out, "{}", row(child, &child.name, total, now)); + } + if listing.more > 0 { + let _ = writeln!( + out, + "{} {:>3.0}% {:>9} \u{2026} {} more", + share_bar(listing.more_bytes, total, BAR), + share(listing.more_bytes, total), + human_bytes(listing.more_bytes), + listing.more, + ); + } + if listing.children.is_empty() { + out.push_str(if listing.entry.is_dir { + "(empty, or not read)\n" + } else { + "(a file)\n" + }); + } + out +} + +/// Search matches, each with its full path, sharing `total`. +pub fn matches( + found: &[Found], + total: u64, + now: i64, + home: Option<&Path>, +) -> String { + let mut out = String::new(); + for item in found { + let _ = writeln!( + out, + "{}", + row(&item.entry, &display(&item.path, home), total, now) + ); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use disktree_core::tree::{Draft, Metric, NodeKind, Tree, aggregate}; + use std::path::PathBuf; + + #[test] + fn paths_under_home_are_shortened() { + let home = PathBuf::from("/home/ann"); + assert_eq!(display(&home, Some(&home)), "~"); + assert_eq!(display(&home.join("src"), Some(&home)), "~/src"); + assert_eq!(display(Path::new("/var"), Some(&home)), "/var"); + assert_eq!(display(Path::new("/var"), None), "/var"); + } + + #[test] + fn ages_pick_one_unit() { + let now = 1_800_000_000; + assert_eq!(age(now, 0), "age unknown"); + assert_eq!(age(now, now - 10), "within the hour"); + assert_eq!(age(now, now - 7_200), "2 h ago"); + assert_eq!(age(now, now - 3 * 86_400), "3 d ago"); + assert_eq!(age(now, now - 70 * 86_400), "2 mo ago"); + assert_eq!(age(now, now - 800 * 86_400), "2 y ago"); + } + + #[test] + fn vm_state_reports_detection_and_its_owner_workflow() { + let mut entry = entry(None); + entry.artifact = disktree_core::artifact::detect( + Path::new("/VM/guest.vmss"), + disktree_core::path_style::PathStyle::Posix, + false, + ); + let report = describe(&entry, 0); + assert!(report.contains("Detected: VM saved memory"), "{report}"); + assert!(report.contains("name convention evidence"), "{report}"); + assert!(report.contains("shut it down normally"), "{report}"); + assert!(!report.contains("cleanup candidate"), "{report}"); + } + + fn entry(clones: Option) -> Entry { + Entry { + name: "w".into(), + is_dir: true, + bytes: 12 * 1024 * 1024, + files: 12, + category: "other".into(), + artifact: None, + reclaim: None, + modified: 0, + read_error: false, + clones, + removed: false, + removed_bytes: 0, + } + } + + #[test] + fn removed_entries_say_so_first() { + let gone = Entry { + removed: true, + ..entry(None) + }; + assert_eq!( + describe(&gone, 0), + "removed since the scan \u{00b7} 12 files \u{00b7} age unknown" + ); + let part = Entry { + removed_bytes: 4 * 1024 * 1024, + ..entry(None) + }; + assert_eq!( + describe(&part, 0), + "4.0 MiB of it removed since the scan \u{00b7} 12 files \u{00b7} \ + age unknown" + ); + } + + #[test] + fn rows_without_clones_read_as_they_always_have() { + let plain = entry(None); + assert_eq!(describe(&plain, 0), "12 files \u{00b7} age unknown"); + assert_eq!( + row(&plain, "w", plain.bytes, 0), + "\u{2593}\u{2593}\u{2593}\u{2593}\u{2593}\u{2593}\u{2593}\ + \u{2593} 100% 12 MiB w/ 12 files \u{00b7} age unknown" + ); + assert_eq!(clone_summary(&plain), None); + // A modified clone that shares nothing any more says nothing new. + let unshared = entry(Some(Clones { + private: plain.bytes, + shared: 0, + repeated: 0, + lower: plain.bytes, + upper: plain.bytes, + partial: false, + })); + assert_eq!(describe(&unshared, 0), describe(&plain, 0)); + assert_eq!(clone_summary(&unshared), None); + } + + #[test] + fn clone_rows_split_private_from_shared_and_say_what_goes_alone() { + let full = entry(Some(Clones { + private: 4096, + shared: 12 * 1024 * 1024 - 4096, + repeated: 0, + lower: 4096, + upper: 4096, + partial: false, + })); + assert_eq!( + describe(&full, 0), + "12 files \u{00b7} 4.0 KiB private \u{00b7} 12 MiB shared with \ + other APFS clones \u{00b7} frees \u{2248} 4.0 KiB alone \u{00b7} \ + age unknown" + ); + let partial = entry(Some(Clones { + lower: 0, + upper: 8 * 1024 * 1024, + partial: true, + ..full.clones.expect("clones") + })); + let text = describe(&partial, 0); + assert!( + text.contains("frees \u{2248} 0 B\u{2013}8.0 MiB alone (partial)"), + "{text}" + ); + } + + #[test] + fn the_header_says_how_much_is_counted_again() { + let mut root = entry(Some(Clones { + private: 0, + shared: 12 * 1024 * 1024, + repeated: 8 * 1024 * 1024, + lower: 4 * 1024 * 1024, + upper: 4 * 1024 * 1024, + partial: false, + })); + let line = clone_summary(&root).expect("a summary"); + assert!(line.starts_with("APFS clones: 12 MiB"), "{line}"); + assert!(line.contains("\u{2248} 8.0 MiB is counted again"), "{line}"); + assert!(line.contains("take \u{2248} 4.0 MiB on disk"), "{line}"); + assert!(line.contains("outside it"), "{line}"); + root.clones = root.clones.map(|clones| Clones { + repeated: 0, + ..clones + }); + let line = clone_summary(&root).expect("a summary"); + assert!(!line.contains("counted again"), "{line}"); + } + + #[test] + fn a_listing_is_largest_first_with_the_tail_summed() { + let mut root = Draft::directory("r"); + for (name, bytes) in [("a", 10), ("b", 60), ("c", 30)] { + root.children + .push(Draft::entry(name, NodeKind::File, bytes)); + } + let mut root = Tree::from(root); + aggregate(&mut root, Metric::Bytes); + let listing = Listing::of( + Path::new("/r"), + root.root().bytes, + Path::new("/r"), + root.root(), + 2, + ); + let text = children(&listing, 0); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!(lines.len(), 3); + assert!(lines[0].contains("60 B b "), "{}", lines[0]); + assert!(lines[1].contains("30 B c "), "{}", lines[1]); + assert!(lines[2].contains("1 more"), "{}", lines[2]); + assert!(lines[2].contains("10 B"), "{}", lines[2]); + } +} diff --git a/crates/disktree-mcp/src/retention.rs b/crates/disktree-mcp/src/retention.rs new file mode 100644 index 00000000..abd30c5b --- /dev/null +++ b/crates/disktree-mcp/src/retention.rs @@ -0,0 +1,113 @@ +//! A read-only retention preflight, deliberately without byte attribution. + +use std::path::Path; + +const LIMITS: &str = "Retained bytes for the selected paths: unknown. Immediate recovered bytes: unknown. Time Machine snapshot presence is a plausible retention mechanism, not proof of attribution. This does not enumerate every APFS snapshot, open file or later volume write. Even no listed Time Machine snapshots cannot guarantee recovery. Do not alter snapshots or retry removal to chase a projection."; + +#[cfg_attr( + not(target_os = "macos"), + expect( + clippy::unused_async, + reason = "The MCP handler uses the same async API as macOS's bounded command" + ) +)] +pub async fn inspect(path: &Path) -> Result { + if !path.is_absolute() { + return Err("Supply an absolute path on the volume to inspect.".into()); + } + #[cfg(target_os = "macos")] + { + use std::time::Duration; + let mount = disktree_core::space::volume_root_for(path) + .ok_or("Cannot identify the path's volume; retention is unknown")?; + let mut command = tokio::process::Command::new("/usr/bin/tmutil"); + command + .arg("listlocalsnapshots") + .arg(&mount) + .env("LC_ALL", "C") + .kill_on_drop(true); + let result = + tokio::time::timeout(Duration::from_secs(3), command.output()) + .await; + let count = match result { + Ok(Ok(output)) if output.status.success() => { + snapshot_count(&output.stdout) + } + _ => None, + }; + Ok(format!("Read-only Time Machine preflight for {}: {}. {LIMITS}", + mount.display(), count.map_or_else( + || "unavailable (command failed, timed out or returned unrecognized output)".into(), + |count| format!("{count} local Time Machine snapshot(s) listed"), + ))) + } + #[cfg(not(target_os = "macos"))] + Ok(format!( + "Automatic retention inspection is unavailable on this system. Read the system skill reference for read-only checks. {LIMITS}" + )) +} + +/// Unknown output must not become a measured zero. +#[cfg(any(target_os = "macos", test))] +fn snapshot_count(output: &[u8]) -> Option { + if output.len() > 65_536 { + return None; + } + let text = std::str::from_utf8(output).ok()?; + let mut lines = text.lines().filter(|line| !line.trim().is_empty()); + let header = lines.next()?; + if !(header.starts_with("Snapshots for disk ") + || header.starts_with("Snapshots for volume ")) + || !header.ends_with(':') + { + return None; + } + let mut count = 0; + for line in lines { + if !line.starts_with("com.apple.TimeMachine.") + || line.chars().any(char::is_whitespace) + { + return None; + } + count += 1; + } + Some(count) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn captured_tmutil_disk_header_accepts_empty_and_populated_listings() { + // Captured during PR review from: + // LC_ALL=C /usr/bin/tmutil listlocalsnapshots / + let header = b"Snapshots for disk /:\n"; + assert_eq!(snapshot_count(header), Some(0)); + + // Keep the captured header, with invented snapshot names. + let mut listing = header.to_vec(); + listing.extend_from_slice( + b"com.apple.TimeMachine.2026-11-03-100000.local\n\ + com.apple.TimeMachine.2026-11-03-110000.local\n", + ); + assert_eq!(snapshot_count(&listing), Some(2)); + } + + #[test] + fn snapshot_presence_absence_and_unavailable_stay_distinct() { + assert_eq!(snapshot_count(b"Snapshots for volume /:\ncom.apple.TimeMachine.2026-11-03-100000.local\ncom.apple.TimeMachine.2026-11-03-110000.local\n"), Some(2)); + assert_eq!(snapshot_count(b"Snapshots for volume /:\n"), Some(0)); + for output in [ + b"".as_slice(), + b"Operation not permitted", + b"Snapshots for disk /:\nerror", + b"Snapshots for volume /:\nerror", + &[0xff], + ] { + assert_eq!(snapshot_count(output), None); + } + assert!(LIMITS.contains("unknown")); + assert!(LIMITS.contains("not proof")); + } +} diff --git a/crates/disktree-mcp/src/server.rs b/crates/disktree-mcp/src/server.rs new file mode 100644 index 00000000..54a97b64 --- /dev/null +++ b/crates/disktree-mcp/src/server.rs @@ -0,0 +1,839 @@ +//! The MCP surface: explicit read and write tools, and the skills that say how to use them, +//! as prompts, resources and the skills extension. +//! +//! Each tool is a thin call into [`Session`]; the words an agent reads come +//! from there. Tools that only look are marked read-only, so a client can +//! run them without asking. Removal is a destructive write requiring a +//! single-use preview and explicit user confirmation of the paths and mode. + +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +use rmcp::handler::server::router::prompt::PromptRouter; +use rmcp::handler::server::router::tool::ToolRouter; +use rmcp::handler::server::wrapper::Parameters; +use rmcp::model::{ + BooleanSchema, CustomRequest, CustomResult, ElicitRequestParams, + ElicitationAction, ElicitationSchema, ErrorCode, GetPromptResult, + Implementation, InitializeRequestParams, InitializeResult, JsonObject, + ListResourcesResult, PrimitiveSchemaDefinition, PromptMessage, + ReadResourceRequestParams, ReadResourceResponse, ReadResourceResult, + Resource, ResourceContents, Role, ServerCapabilities, ServerConfig, +}; +use rmcp::service::{RequestContext, RoleServer}; +use rmcp::{ + ErrorData, ServerHandler, prompt, prompt_handler, prompt_router, tool, + tool_handler, tool_router, +}; + +use crate::session::{ + EstimateParams, FindParams, LsParams, PathsParams, RankParams, + RemovalPreviewParams, RemoveParams, ScanParams, ScanPlan, Session, + ShowParams, run_scan, +}; +use crate::skills::{self, SKILLS}; + +/// How often a scan the window is running is looked in on. +const SCAN_POLL: Duration = Duration::from_millis(500); +/// How long a window scan is followed before the agent is told to come +/// back: a whole disk can take minutes, a tool call should not. +const SCAN_WAIT: Duration = Duration::from_mins(10); + +/// What the client is told at `initialize`: enough to use the tools well, +/// and safely, without reading a skill first. +const INSTRUCTIONS: &str = "\ +Read skill://pwrdisk-free-space/SKILL.md with pwrdisk_read_skill and its \ +OS reference before choosing cleanup candidates. In PwrAgent, resource \ +reads use the exact serverNameInAgent from manage_mcp_connections \ +action=describe_thread, never the client label. Start with pwrdisk_status, then scan and explore with pwrdisk_ls and \ +pwrdisk_find. Compare explicit candidates with pwrdisk_rank; private and \ +reclaim_lower values are before retention, not immediate recovered space. \ +Use pwrdisk_retention on each selected volume before promising recovery; \ +snapshot presence cannot attribute exact selected-path bytes. \ +Use pwrdisk_estimate for a hypothetical path list without \ +changing the cart; bounded clone-holder peers are inspection leads only. \ +Browsing never moves the displayed directory. Call \ +pwrdisk_show only when the user asks to see a path or requests following. \ +pwrdisk_scan explicitly changes the linked window's scan root. \ +Agree the list before pwrdisk_mark unless a standing instruction covers \ +marking. Approval to mark is never approval to remove. pwrdisk_review \ +only opens the marked list; announce it first and let the person approve. \ +NEVER use computer use, clicks, approval keys or accessibility actions to \ +approve a removal, even after the user approved marking or removal. \ +Caches go through owner_cleanup; a cache name or regenerable \ +classification never authorizes deletion. owner_cleanup without decisions \ +lists one proposal per marked path and cannot be confirmed: show every \ +owner, version, executable, argument, environment override, actual \ +whole-cache scope (including unselected siblings), effects, limitations, \ +recoverability and unavailable reason, then let the user choose skip, owner \ +or delete_files for each path. Never choose for them or suggest \ +delete_files; inspect unknown runtime/install caches first. Preview again \ +with decisions for every path (and delete_files_mode when any deletes \ +files); its confirmation text names each intent, and owner approval never \ +approves deleting files. Unavailable, unsupported, failed or cancelled \ +owners never fall back to deleting files. For MCP removal: \ +pwrdisk_removal_preview requires an explicit owner_cleanup, trash or \ +permanent mode and returns a five-minute, single-use preview. Owner \ +resolution may first report preparing; retry only that read-only preview. \ +Show the \ +user ALL paths, mode, measured bytes and capacity limit. Trash moves data \ +to Trash or Recycle Bin; restoration may be possible until emptied but is \ +not guaranteed, and space usually returns only once emptied. Permanent \ +deletion cannot be undone through PwrDisk or Trash. Wait for explicit \ +user confirmation of this exact operation before pwrdisk_remove, a \ +destructive WRITE requiring the preview ID, exact ordered paths, mode and \ +confirmation text. Standing instructions do not replace this confirmation. \ +The server also requires interactive user confirmation from the MCP client; \ +clients without form elicitation must use human review instead. \ +The app rechecks the preview, existing guards, and the configured limit \ +(5% of each volume's capacity by default) and re-measures before removing \ +anything. No fallback from Trash to permanent deletion; no headless or SSH \ +removal. Refusal, changed scan/marks/policy or expiration requires a new \ +preview and user confirmation. Never retry removal automatically, split \ +batches, change the limit, or use shell/UI deletion to bypass protection. \ +A window refuses a mark past the limit, including marks made before it \ +was linked; only the person can mark past it, in the window. \ +pwrdisk_status reports completion, failures and measured freed space. \ +A linked window's tree and marks are the source of truth. Read \ +skill://pwrdisk-free-space/SKILL.md and the matching references/macos.md, \ +references/linux.md or references/windows.md before marking or removal. \ +For read-only audits use skill://pwrdisk-explain-usage/SKILL.md."; + +#[derive(serde::Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +struct SkillParams { + /// An exact skill:// URI from the PwrDisk skill catalog. + uri: String, +} + +#[derive(serde::Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +struct RetentionParams { + /// An absolute path on the selected volume; run for each volume. + path: std::path::PathBuf, +} + +/// The server: one session behind a lock, so the tools can run from any +/// protocol task while scans run off to the side. +#[derive(Clone)] +pub struct Server { + session: Arc>, + tool_router: ToolRouter, + prompt_router: PromptRouter, +} + +impl std::fmt::Debug for Server { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Server").finish_non_exhaustive() + } +} + +impl Server { + pub fn new(session: Session) -> Self { + Self { + session: Arc::new(Mutex::new(session)), + tool_router: Self::tool_router(), + prompt_router: Self::prompt_router(), + } + } + + /// Run `f` with the session. A poisoned lock means a tool panicked; the + /// state is still worth more than nothing. + pub fn with(&self, f: impl FnOnce(&mut Session) -> R) -> R { + let mut session = + self.session.lock().unwrap_or_else(PoisonError::into_inner); + f(&mut session) + } +} + +#[tool_router] +impl Server { + /// What this session knows: scans held, the window if one is open, what + /// is marked, the last removal, and every volume's free space. Start + /// here. Read `skill://pwrdisk-free-space/SKILL.md` with `pwrdisk_read_skill`. + /// Read it and the OS reference via this tool's exact MCP server name, + /// not its product/client label. In PwrAgent, `manage_mcp_connections` + /// `action=describe_thread` supplies `serverNameInAgent`; use that exact + /// value with `list_mcp_resources(server=...)` and `read_mcp_resource`. + #[tool( + name = "pwrdisk_status", + annotations(title = "PwrDisk status", read_only_hint = true) + )] + async fn status(&self) -> String { + self.with(Session::status) + } + + /// Read the required PwrDisk skill or OS reference directly, using its + /// skill URI. Start with `skill://pwrdisk-free-space/SKILL.md` before + /// choosing cleanup candidates, then references/macos.md, linux.md or + /// windows.md. Also exposed as MCP resources: in PwrAgent use + /// `manage_mcp_connections(action="describe_thread").serverNameInAgent` + /// as the exact server for `list_mcp_resources` and `read_mcp_resource`. + #[tool( + name = "pwrdisk_read_skill", + annotations(title = "Read PwrDisk skill", read_only_hint = true) + )] + async fn read_skill( + &self, + Parameters(params): Parameters, + ) -> Result { + skills::read(¶ms.uri) + .map(str::to_owned) + .ok_or_else(|| "Unknown PwrDisk skill resource URI".into()) + } + + /// Read-only retention preflight before proposing recovered space. + /// On macOS lists Time Machine snapshots for the path's volume with a + /// bounded command. Never changes snapshots. Reports presence only: + /// selected-path retention bytes and immediate recovery remain unknown. + /// Not a complete APFS snapshot or open-file inventory. + #[tool( + name = "pwrdisk_retention", + annotations( + title = "Inspect retention uncertainty", + read_only_hint = true + ) + )] + async fn retention( + &self, + Parameters(params): Parameters, + ) -> Result { + crate::retention::inspect(¶ms.path).await + } + + /// Rank explicit candidate paths by private allocation or standalone + /// conservative reclaim lower bound. Read-only, no marking. Unknown + /// values are null and sort last; known zero stays zero. The complete + /// union is estimated once: never add candidate bounds. Ranking does + /// not establish ownership, disposability or immediate recovered space. + #[tool( + name = "pwrdisk_rank", + annotations(title = "Rank cleanup candidates", read_only_hint = true) + )] + async fn rank( + &self, + Parameters(params): Parameters, + ) -> Result { + self.with(|session| session.rank(¶ms)) + } + + /// Scan a directory tree and keep the result for the other tools. With + /// no arguments it scans the home directory, which takes seconds; disk: + /// true scans the whole volume. Returns totals, the volume's free space + /// and how much of its used space this scan explains, the top level + /// largest first, and the biggest things that could plausibly go. + /// Scanning the same root again replaces the earlier scan. When a + /// PwrDisk window is open it does the scanning and shows the result; + /// the window's tree is then what every other tool reads. + #[tool( + name = "pwrdisk_scan", + annotations(title = "Scan a directory", read_only_hint = true) + )] + async fn scan( + &self, + Parameters(params): Parameters, + ) -> Result { + match self.with(|s| s.prepare_scan(¶ms))? { + ScanPlan::Local { root, options } => { + let scan = tokio::task::spawn_blocking(move || { + run_scan(root, options) + }) + .await + .map_err(|error| format!("the scan task failed: {error}"))??; + Ok(self.with(|s| s.store_scan(scan))) + } + ScanPlan::Window { root } => { + // The window walks; the session is unlocked between looks + // so pwrdisk_status still answers meanwhile. + let started = Instant::now(); + loop { + if let Some(report) = self.with(|s| s.window_scan(&root))? { + return Ok(report); + } + if started.elapsed() > SCAN_WAIT { + return Err(format!( + "The window is still scanning {} after {} s. \ + pwrdisk_status says when it is done; then \ + pwrdisk_ls reads the tree.", + root.display(), + started.elapsed().as_secs() + )); + } + tokio::time::sleep(SCAN_POLL).await; + } + } + } + } + + /// List a scanned directory, largest first: each entry's share, size, + /// kind of data, whether its space can be had back and why, and when it + /// was last written. Sorts by listed allocation, not predicted recovery; + /// compare explicit candidates with `pwrdisk_rank`. Never moves the view. + #[tool( + name = "pwrdisk_ls", + annotations(title = "List a directory", read_only_hint = true) + )] + async fn ls( + &self, + Parameters(params): Parameters, + ) -> Result { + self.with(|s| s.ls(¶ms)) + } + + /// The largest entries matching the filters, anywhere beneath a path or + /// every scanned root: files over a size, everything reclaimable + /// (caches, build output, package stores), one kind of data, a name, + /// or what nobody has written to in a while. A matching directory is + /// listed once, without its contents. Sorts by listed allocation; + /// compare explicit candidates with `pwrdisk_rank` before recommending. + #[tool( + name = "pwrdisk_find", + annotations(title = "Find the largest matches", read_only_hint = true) + )] + async fn find( + &self, + Parameters(params): Parameters, + ) -> Result { + self.with(|s| s.find(¶ms)) + } + + /// Estimate removing a supplied path set without changing marks, scan + /// root, navigation or removal intents. Returns accepted/covered/refused + /// paths, allocation, selected-set physical bounds and scan limitations. + /// Bounded directory peers identify retained clones within the scan and + /// quantify union savings; these are inspection leads, not advice to remove. + #[tool( + name = "pwrdisk_estimate", + annotations( + title = "Estimate hypothetical path set", + read_only_hint = true + ) + )] + async fn estimate( + &self, + Parameters(params): Parameters, + ) -> Result { + self.with(|s| s.estimate_paths(¶ms)) + } + + /// Show a path in the PwrDisk window, selected in its directory, so + /// the user sees what you are looking at. Opens a window when none is. + #[tool( + name = "pwrdisk_show", + annotations( + title = "Show in the window", + read_only_hint = false, + destructive_hint = false + ) + )] + async fn show( + &self, + Parameters(params): Parameters, + ) -> Result { + self.with(|s| s.show_path(¶ms)) + } + + /// Mark paths for removal, once the user has agreed the list or a + /// standing instruction of theirs covers it. Nothing is deleted: marks + /// appear in the + /// PwrDisk window when one is open, and the user removes them from the + /// review screen. Returns the plan: what is marked, what the guards + /// keep back and why (the home directory, an account's folder, a mount + /// point, a system tree), what is covered by another mark, and + /// scan-derived reclaim bounds before retention. These are not + /// guaranteed recovered space. A linked window refuses a mark that + /// would take the list past the capacity limit; only the person can + /// mark past it, in the window. + #[tool( + name = "pwrdisk_mark", + annotations( + title = "Mark for removal", + read_only_hint = false, + destructive_hint = false, + idempotent_hint = true + ) + )] + async fn mark( + &self, + Parameters(params): Parameters, + ) -> Result { + self.with(|s| s.mark(¶ms)) + } + + /// Preview exactly the marked paths in an idle local window for a + /// required explicit mode. Does not remove, navigate or change marks. + /// Show the preview and consequences to the user and await confirmation. + #[tool( + name = "pwrdisk_removal_preview", + annotations( + title = "Preview a removal", + read_only_hint = true, + destructive_hint = false + ) + )] + async fn removal_preview( + &self, + Parameters(params): Parameters, + ) -> Result { + self.with(|session| session.removal_preview(¶ms)) + } + + /// DESTRUCTIVE WRITE: remove only after explicit user confirmation of + /// the preview's exact paths, mode, bytes and consequences. Approval to + /// mark is insufficient. Trash may be recoverable until emptied; + /// permanent deletion cannot be undone. Never use computer use to approve. + /// The app validates the single-use preview and configured capacity limit. + /// Returns when started; poll status for completion. Never retry automatically. + #[tool( + name = "pwrdisk_remove", + annotations( + title = "Remove confirmed paths", + read_only_hint = false, + destructive_hint = true, + idempotent_hint = false + ) + )] + async fn remove( + &self, + Parameters(params): Parameters, + context: RequestContext, + ) -> Result { + if let Some(outcome) = self.with(|s| s.removal_outcome(¶ms)) { + return Ok(outcome); + } + let message = + self.with(|session| session.removal_confirmation_message(¶ms))?; + if !context + .peer + .supported_elicitation_modes() + .contains(&rmcp::service::ElicitationMode::Form) + { + return Err("This MCP client does not support interactive form confirmation. No MCP removal request was sent; check pwrdisk_status for any native UI operation. Use human review in PwrDisk; never approve it through computer use.".into()); + } + let requested_schema = ElicitationSchema::builder().required_property( + "confirmed", PrimitiveSchemaDefinition::Boolean(BooleanSchema::new().with_default(false) + .description("I confirm removal of exactly these paths in the stated mode and understand the consequences")), + ).build().map_err(ToString::to_string)?; + let answer = context + .peer + .create_elicitation(ElicitRequestParams::FormElicitationParams { + meta: None, + message, + requested_schema, + }) + .await; + // The person may have approved in the native UI while this form + // was open. Cancellation describes the form, not that operation. + if let Some(outcome) = self.with(|s| s.removal_outcome(¶ms)) { + return Ok(outcome); + } + let answer = answer.map_err(|error| format!("MCP confirmation failed ({error}). No MCP removal request was sent; native UI outcome could not be verified. Check pwrdisk_status. Never retry automatically."))?; + if !confirmed_by_user(&answer) { + return Err("MCP confirmation was declined or cancelled. No MCP removal request was sent; native UI outcome could not be verified. Check pwrdisk_status before considering a new preview. Never retry automatically.".into()); + } + self.with(|session| session.remove(¶ms)) + } + + /// Unmark paths, or everything when no paths are given. Returns the + /// plan that remains. + #[tool( + name = "pwrdisk_unmark", + annotations( + title = "Unmark", + read_only_hint = false, + destructive_hint = false, + idempotent_hint = true + ) + )] + async fn unmark( + &self, + Parameters(params): Parameters, + ) -> Result { + self.with(|s| s.unmark(¶ms)) + } + + /// Open PwrDisk's review screen over the marks, starting a window if + /// none is open; tell the user first, since it comes forward on their + /// screen. The user decides there: Enter moves the marks to the trash, + /// whose space returns once it is emptied; permanent deletion always + /// asks first. Call `pwrdisk_status` afterwards for what was freed. + #[tool( + name = "pwrdisk_review", + annotations( + title = "Open the review screen", + read_only_hint = false, + destructive_hint = false + ) + )] + async fn review(&self) -> Result { + self.with(Session::review) + } +} + +#[prompt_router] +impl Server { + /// How to free space with PwrDisk: measure, scan, walk, propose, mark + /// what the user agrees to, and hand the decision back on the review + /// screen. Carries this system's cautions. + #[prompt(name = "free-space")] + async fn free_space(&self) -> GetPromptResult { + skill_prompt("pwrdisk-free-space") + } + + /// Where the space went, read-only: scan, walk, account for what the + /// files do not explain, and explain. Carries this system's cautions. + #[prompt(name = "explain-usage")] + async fn explain_usage(&self) -> GetPromptResult { + skill_prompt("pwrdisk-explain-usage") + } +} + +/// Only an explicit positive answer from the client counts as approval. +fn confirmed_by_user(answer: &rmcp::model::ElicitResult) -> bool { + answer.action == ElicitationAction::Accept + && answer + .content + .as_ref() + .and_then(|value| value.get("confirmed")) + .and_then(serde_json::Value::as_bool) + == Some(true) +} + +/// A skill as one prompt message, with this system's reference after it. +fn skill_prompt(name: &str) -> GetPromptResult { + let skill = skills::named(name).expect("a skill listed in SKILLS"); + GetPromptResult::new(vec![PromptMessage::new_text( + Role::User, + skills::prompt_text(skill), + )]) + .with_description(skill.description()) +} + +/// A JSON-RPC error for a request the skills extension cannot answer. +fn invalid(message: impl Into) -> ErrorData { + ErrorData::new(ErrorCode::INVALID_PARAMS, message.into(), None) +} + +#[tool_handler(router = self.tool_router)] +#[prompt_handler(router = self.prompt_router)] +impl ServerHandler for Server { + fn get_info(&self) -> ServerConfig { + let mut capabilities = ServerCapabilities::builder() + .enable_tools() + .enable_prompts() + .enable_resources() + .build(); + // Clients that know the skills extension list the skills with + // `skills/list`; the rest find the same files as resources. + capabilities.extensions = Some( + std::iter::once((skills::EXTENSION.to_string(), JsonObject::new())) + .collect(), + ); + ServerConfig::new(capabilities) + .with_server_info( + Implementation::new("pwrdisk", env!("CARGO_PKG_VERSION")) + .with_title("PwrDisk") + .with_website_url("https://github.com/pwrdrvr/PwrDisk"), + ) + .with_instructions(INSTRUCTIONS) + } + + /// Learn the client's name before answering: a client may call a tool + /// as soon as it has the answer, before `initialized` arrives, and the + /// window's header names the agent from the first `hello`. + async fn initialize( + &self, + request: InitializeRequestParams, + context: RequestContext, + ) -> Result { + self.with(|s| s.set_client(&request.client_info.name)); + context.peer.set_peer_info(request.clone()); + self.negotiate_initialize(&request) + } + + async fn list_resources( + &self, + _request: Option, + _context: RequestContext, + ) -> Result { + Ok(ListResourcesResult::with_all_items(resources())) + } + + async fn read_resource( + &self, + request: ReadResourceRequestParams, + _context: RequestContext, + ) -> Result { + let Some(text) = skills::read(&request.uri) else { + return Err(ErrorData::resource_not_found( + format!("no resource at {}", request.uri), + None, + )); + }; + Ok(ReadResourceResult::new(vec![ + ResourceContents::text(text, request.uri) + .with_mime_type("text/markdown"), + ]) + .into()) + } + + /// `skills/list` and `skills/get`, the skills extension's requests. + /// Anything else is not a method this server has. + async fn on_custom_request( + &self, + request: CustomRequest, + _context: RequestContext, + ) -> Result { + custom(&request.method, request.params.as_ref()) + } +} + +/// Every skill file as a resource; a `SKILL.md` carries the skill's name +/// and description. +pub fn resources() -> Vec { + SKILLS + .iter() + .flat_map(|skill| { + skill.files.iter().map(move |file| { + let address = skills::uri(skill.name, file.path); + let size = u64::try_from(file.text.len()).unwrap_or(u64::MAX); + let resource = if file.path == "SKILL.md" { + Resource::new(address, skill.name) + .with_description(skill.description()) + } else { + Resource::new(address, file.path) + }; + resource.with_mime_type("text/markdown").with_size(size) + }) + }) + .collect() +} + +/// Answer a custom request: the skills extension, or not found. +pub fn custom( + method: &str, + params: Option<&serde_json::Value>, +) -> Result { + if params + .and_then(|params| params.get("cursor")) + .is_some_and(|cursor| !cursor.is_null()) + { + return Err(invalid("this server lists everything in one page")); + } + match method { + "skills/list" => { + let skills: Vec = + SKILLS.iter().map(skills::Skill::manifest).collect(); + Ok(CustomResult::new(serde_json::json!({ "skills": skills }))) + } + "skills/get" => { + let address = params + .and_then(|params| params.get("uri")) + .and_then(serde_json::Value::as_str) + .ok_or_else(|| invalid("skills/get needs a uri"))?; + let skill = skills::by_uri(address) + .ok_or_else(|| invalid(format!("no skill at {address}")))?; + Ok(CustomResult::new( + serde_json::json!({ "skill": skill.manifest() }), + )) + } + _ => Err(ErrorData::new( + ErrorCode::METHOD_NOT_FOUND, + method.to_string(), + None, + )), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Every skill `skills/list` names is the one `skills/get` returns, and + /// every file it lists is a resource that reads back with that size + /// and digest. + #[test] + fn skills_list_get_and_resources_agree() { + let listed = custom("skills/list", None).expect("list").0; + let entries = listed["skills"].as_array().expect("skills"); + assert_eq!(entries.len(), SKILLS.len()); + let resources = resources(); + let mut covered = 0; + for entry in entries { + let address = entry["uri"].as_str().expect("uri"); + let got = custom( + "skills/get", + Some(&serde_json::json!({ "uri": address })), + ) + .expect("get") + .0; + assert_eq!(&got["skill"], entry); + for file in entry["resources"].as_array().expect("files") { + let address = file["uri"].as_str().expect("uri"); + let text = skills::read(address).expect("readable"); + assert_eq!(file["size"], text.len()); + assert_eq!(file["digest"], skills::digest(text)); + let resource = resources + .iter() + .find(|resource| resource.uri == address) + .expect("listed as a resource"); + assert_eq!(resource.size, Some(text.len() as u64)); + covered += 1; + } + } + assert_eq!(covered, resources.len(), "no resource outside a skill"); + } + + #[test] + fn bad_skill_requests_are_refused() { + for params in [ + None, + Some(serde_json::json!({})), + Some(serde_json::json!({ "uri": 7 })), + Some(serde_json::json!({ + "uri": "skill://pwrdisk-free-space/references/macos.md" + })), + Some(serde_json::json!({ "uri": "file:///etc/passwd" })), + ] { + let error = + custom("skills/get", params.as_ref()).expect_err("not a skill"); + assert_eq!(error.code, ErrorCode::INVALID_PARAMS, "{params:?}"); + } + let paged = custom( + "skills/list", + Some(&serde_json::json!({ "cursor": "next" })), + ) + .expect_err("one page"); + assert_eq!(paged.code, ErrorCode::INVALID_PARAMS); + let unknown = custom("skills/delete", None).expect_err("no method"); + assert_eq!(unknown.code, ErrorCode::METHOD_NOT_FOUND); + } + + #[test] + fn the_server_declares_the_skills_extension() { + let server = Server::new(Session::detached( + std::env::temp_dir().join("pwrdisk-no-window.sock"), + None, + )); + let info = server.get_info(); + let extensions = + info.capabilities.extensions.expect("extensions declared"); + assert!(extensions.contains_key(skills::EXTENSION)); + assert!(info.capabilities.resources.is_some()); + assert!(info.capabilities.prompts.is_some()); + let instructions = info.instructions.expect("instructions"); + for skill in SKILLS { + assert!(instructions.contains(&skill.uri()), "{}", skill.name); + } + } + + #[tokio::test] + async fn skills_are_readable_directly_from_tool_discovery() { + let server = Server::new(Session::detached( + std::env::temp_dir().join("pwrdisk-no-window.sock"), + None, + )); + for skill in SKILLS { + for file in skill.files { + let text = server + .read_skill(Parameters(SkillParams { + uri: skills::uri(skill.name, file.path), + })) + .await + .expect("tool reads exact resource"); + assert_eq!(text, file.text); + } + } + assert!( + server + .read_skill(Parameters(SkillParams { + uri: "file:///etc/passwd".into() + })) + .await + .is_err() + ); + let tools = Server::tool_router().list_all(); + for name in ["pwrdisk_read_skill", "pwrdisk_retention", "pwrdisk_rank"] + { + let tool = tools + .iter() + .find(|tool| tool.name == name) + .expect("discoverable"); + assert_eq!( + tool.annotations + .as_ref() + .expect("annotations") + .read_only_hint, + Some(true) + ); + } + let status = tools + .iter() + .find(|tool| tool.name == "pwrdisk_status") + .expect("status"); + assert!( + status + .description + .as_ref() + .expect("onboarding") + .contains("serverNameInAgent") + ); + } + #[test] + fn removal_is_a_destructive_non_idempotent_write_and_listing_is_read_only() + { + let tools = Server::tool_router().list_all(); + let remove = tools + .iter() + .find(|tool| tool.name == "pwrdisk_remove") + .expect("remove"); + let flags = remove.annotations.as_ref().expect("write annotations"); + assert_eq!(flags.read_only_hint, Some(false)); + assert_eq!(flags.destructive_hint, Some(true)); + assert_eq!(flags.idempotent_hint, Some(false)); + let estimate = tools + .iter() + .find(|tool| tool.name == "pwrdisk_estimate") + .expect("estimate"); + assert_eq!( + estimate.annotations.as_ref().expect("read").read_only_hint, + Some(true) + ); + let listing = tools + .iter() + .find(|tool| tool.name == "pwrdisk_ls") + .expect("ls"); + assert_eq!( + listing.annotations.as_ref().expect("read").read_only_hint, + Some(true) + ); + assert!( + !listing.input_schema["properties"] + .as_object() + .expect("properties") + .contains_key("show") + ); + } + + #[test] + fn only_explicit_client_acceptance_with_true_confirms_removal() { + use rmcp::model::ElicitResult; + for action in [ + ElicitationAction::Accept, + ElicitationAction::Decline, + ElicitationAction::Cancel, + ] { + for content in [ + None, + Some(serde_json::json!({"confirmed":false})), + Some(serde_json::json!({"confirmed":true})), + ] { + let mut answer = ElicitResult::new(action.clone()); + answer.content.clone_from(&content); + let expected = action == ElicitationAction::Accept + && content == Some(serde_json::json!({"confirmed":true})); + assert_eq!(confirmed_by_user(&answer), expected); + } + } + } +} diff --git a/crates/disktree-mcp/src/session.rs b/crates/disktree-mcp/src/session.rs new file mode 100644 index 00000000..48b83d74 --- /dev/null +++ b/crates/disktree-mcp/src/session.rs @@ -0,0 +1,4919 @@ +//! What one connected agent knows: the window it is driving, or failing +//! that its own scans, and the marks. +//! +//! When a PwrDisk window is linked it is the source of truth: `ls`, `find` +//! and `scan` read the tree the person is looking at, and the marks live +//! there. Without a window this process scans for itself, so an agent in a +//! terminal needs nothing else. Either way the words an agent reads come +//! from here, over `disktree-core` and the link; [`crate::server`] is the +//! thin layer that turns them into MCP tools. + +use std::fmt::Write as _; +use std::io; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::Arc; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use disktree_core::classify::Category; +use disktree_core::insights::{Candidate, worth_a_look}; +use disktree_core::query::{self, Kind}; +use disktree_core::removal::{ + Plan, Target, detect_trash_backend, normalize, plan, +}; +use disktree_core::scan::{ScanHandle, ScanOptions}; +use disktree_core::sharing::{self, Estimate}; +use disktree_core::size::{human_bytes, human_count, share}; +use disktree_core::space::{ + SpaceInfo, device_for, space_info, volume_root_for, volumes, +}; +use disktree_core::tree::{Node, Tree, path_of}; +use disktree_link::{ + ConfirmedRemoval, FindRequest, FoundList, Insight, Link, Listing, + MarkRequest, RemovalChoice, RemovalPreview, Request, Response, + ScanOptionsRequest, SelectionEstimate, Space, State, TreeSummary, VERSION, +}; +use schemars::JsonSchema; +use serde::Deserialize; + +use crate::report::{age, children, clone_summary, describe, display, matches}; + +/// The measurement context survives a window scan being reused by an agent. +fn scan_context(tree: &TreeSummary) -> String { + format!( + "{} sizes \u{00b7} hidden entries {} \u{00b7} {} unreadable", + if tree.apparent_size { + "apparent" + } else { + "allocated" + }, + if tree.include_hidden { + "included" + } else { + "skipped" + }, + tree.unreadable, + ) +} + +/// Listed allocation is additive; APFS physical usage is not. +const fn allocation_caveat() -> &'static str { + if cfg!(target_os = "macos") { + "macOS: summed allocation can exceed volume usage because APFS clones \ + share blocks. Listed bytes are not guaranteed freed space; snapshots \ + can retain deleted blocks.\n" + } else { + "" + } +} + +/// How many findings a scan report lists. +const INSIGHTS: usize = 8; +/// Top-level rows a scan report shows. +const TOP: usize = 12; +/// Rows a listing shows unless asked otherwise. +const DEFAULT_LIMIT: usize = 20; +/// The most rows any listing shows: past this the agent should filter. +const MAX_LIMIT: usize = 200; +/// What `show` and `review` say on remaining unsupported targets: +/// the person takes the list over by hand. +const NO_LINK: &str = "This system has no window link yet, so PwrDisk \ +cannot show these marks in a window or open its review screen for them. \ +Give the user the marked paths and the plan, and ask them to open PwrDisk, \ +scan the same root, mark those paths and review them there. Do not remove \ +them yourself."; +/// How long to wait for a window that was just launched to start listening. +const LAUNCH_WAIT: Duration = Duration::from_secs(20); +/// A window that did not answer is not launched again sooner than this: it +/// may still be coming up, and a second one would only compete for the +/// socket. +const RELAUNCH_AFTER: Duration = Duration::from_mins(1); + +/// The system this server runs on, and the skill reference written for it. +fn system_line() -> String { + let system = match std::env::consts::OS { + "macos" => "macOS", + "windows" => "Windows", + "linux" => "Linux", + other => other, + }; + crate::skills::platform_reference().map_or_else( + || format!("System: {system}.\n"), + |path| { + format!( + "System: {system}. Before marking, read {}: what this \ + system hides from a scan and what never to mark.\n", + crate::skills::uri("pwrdisk-free-space", path) + ) + }, + ) +} + +/// Unix seconds now. +pub fn now() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |since| since.as_secs().cast_signed()) +} + +/// Starts a PwrDisk window on a root, for the review screen when none is +/// open. Swapped out in tests. +pub type Launcher = Box io::Result<()> + Send>; + +/// One finished scan of this process's own, kept for the rest of the +/// session. +#[derive(Debug)] +pub struct Scan { + pub root: PathBuf, + pub tree: Arc, + pub options: ScanOptions, + /// Unix seconds when the tree landed. + pub at: i64, + pub elapsed: Duration, + pub unreadable: u64, + pub space: Option, + pub device: Option, + pub insights: Vec, +} + +/// What a scan request amounts to, decided with the session locked. +#[derive(Debug)] +pub enum ScanPlan { + /// Walk here, off the protocol thread, then [`Session::store_scan`]. + Local { root: PathBuf, options: ScanOptions }, + /// The window is scanning `root`; poll [`Session::window_scan`] until + /// it reports. + Window { root: PathBuf }, +} + +/// What `pwrdisk_scan` takes. +#[derive(Clone, Debug, Default, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ScanParams { + /// Directory to scan. Default: the home directory. + pub path: Option, + /// Scan the whole volume that `path` (or the home directory) is on. + #[serde(default)] + pub disk: bool, + /// Measure apparent length, as `ls -l` shows it, instead of allocated + /// blocks. Blocks are what the disk spends and what deleting frees. + #[serde(default)] + pub apparent_size: bool, + /// Skip dotfiles and dot-directories. Off by default: `~/.cache` is + /// often the largest thing in a home directory. + #[serde(default)] + pub skip_hidden: bool, + /// Also measure other disks, network shares and pseudo filesystems + /// mounted below the root. Off by default: one volume at a time. + #[serde(default)] + pub cross_filesystems: bool, + /// Stop descending past this depth. Totals below it are unknown, which + /// makes a first look at a huge tree cheap. + pub max_depth: Option, +} + +/// What `pwrdisk_ls` takes. +#[derive(Clone, Debug, Default, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct LsParams { + /// The directory to list, under the scanned root. + pub path: PathBuf, + /// How many entries to list, largest first. Default 20, at most 200. + pub limit: Option, + /// Legacy input, accepted without moving the window. Use `pwrdisk_show` + /// only when the user explicitly asks to see a path. + #[serde(default)] + #[schemars(skip)] + pub show: bool, +} + +/// Ranking metric; values remain scan-derived, before retention. +#[derive( + Clone, Copy, Debug, Default, Deserialize, serde::Serialize, JsonSchema, +)] +#[serde(rename_all = "snake_case")] +pub enum RankBy { + #[default] + Private, + ReclaimLower, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct RankParams { + /// Explicit candidates from one completed scan; 1 to 50 paths. + pub paths: Vec, + /// Private allocation (default), or standalone reclaim lower bound. + /// Neither metric predicts immediate free space; null sorts last. + #[serde(default)] + pub by: RankBy, +} + +/// A hypothetical selection; the marked cart is never used or modified. +#[derive(Clone, Debug, Default, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct EstimateParams { + /// 1 to 200 paths from one completed scan. Overlaps are covered once. + pub paths: Vec, + /// Group retained clones by direct child directories of this scanned + /// directory. Default: the selected paths' common parent. Widen this + /// scope to search elsewhere in the scan; no owner discovery outside it. + pub peer_scope: Option, + /// Maximum directory peers, default 10, at most 20. Zero skips peers. + pub peer_limit: Option, +} + +/// What kind of entry `pwrdisk_find` matches; [`Kind`] as a parameter. +#[derive( + Clone, Copy, Debug, Default, Deserialize, JsonSchema, PartialEq, Eq, +)] +#[serde(rename_all = "lowercase")] +pub enum KindName { + /// Files and directories; a matching directory hides its contents. + #[default] + Any, + File, + Dir, +} + +impl From for Kind { + fn from(name: KindName) -> Self { + match name { + KindName::Any => Self::Any, + KindName::File => Self::File, + KindName::Dir => Self::Dir, + } + } +} + +/// A kind of data, as `pwrdisk_find` filters it; [`Category`] as a +/// parameter. +#[derive(Clone, Copy, Debug, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "kebab-case")] +pub enum CategoryName { + Code, + AgentScratch, + Toolchain, + Synced, + Git, + Media, + Documents, + Cache, + VirtualMachines, + Other, +} + +impl From for Category { + fn from(name: CategoryName) -> Self { + match name { + CategoryName::Code => Self::Code, + CategoryName::AgentScratch => Self::AgentScratch, + CategoryName::Toolchain => Self::Toolchain, + CategoryName::Synced => Self::Synced, + CategoryName::Git => Self::Git, + CategoryName::Media => Self::Media, + CategoryName::Documents => Self::Documents, + CategoryName::Cache => Self::Cache, + CategoryName::VirtualMachines => Self::VirtualMachine, + CategoryName::Other => Self::Other, + } + } +} + +/// An explicit removal mode; never inferred from a default or availability. +#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum RemovalModeName { + Trash, + Permanent, + OwnerCleanup, +} + +impl From for RemovalChoice { + fn from(mode: RemovalModeName) -> Self { + match mode { + RemovalModeName::Trash => Self::Trash, + RemovalModeName::Permanent => Self::Permanent, + RemovalModeName::OwnerCleanup => Self::OwnerCleanup, + } + } +} + +/// The person's choice for one marked path in a cache cleanup. +#[derive(Clone, Copy, Debug, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum CleanupActionName { + /// Do nothing to this path. + Skip, + /// Run exactly the owner command the proposal showed. + Owner, + /// Delete exactly this path directly, without its owner. Only when the + /// person chose it for this path; never suggest it on your own. + DeleteFiles, +} + +impl From for disktree_core::cleanup::Decision { + fn from(action: CleanupActionName) -> Self { + match action { + CleanupActionName::Skip => Self::Skip, + CleanupActionName::Owner => Self::Owner, + CleanupActionName::DeleteFiles => Self::DeleteFiles, + } + } +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CleanupDecisionParam { + /// A marked path, exactly as the proposals listed it. + pub path: PathBuf, + pub action: CleanupActionName, +} + +/// How Delete files removes. No default: the person picks. +#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum FilesModeName { + Trash, + Permanent, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct RemovalPreviewParams { + /// Required: `owner_cleanup` for recognized caches, trash or permanent for + /// ordinary paths. Without `decisions`, `owner_cleanup` lists one + /// proposal per marked path and cannot be confirmed. + pub mode: RemovalModeName, + /// `owner_cleanup` only: the person's choice for every marked path, + /// each named exactly once. + #[serde(default)] + pub decisions: Option>, + /// `owner_cleanup` only, and required when any decision is + /// `delete_files`: trash or permanent, as the person chose. + #[serde(default)] + pub delete_files_mode: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct RemoveParams { + /// Single-use ID returned by `pwrdisk_removal_preview`. Expires in 5 minutes. + pub preview_id: String, + /// Must match the mode the user explicitly approved from the preview. + pub mode: RemovalModeName, + /// Exact ordered path list returned by the preview and approved by the user. + pub paths: Vec, + /// Only after explicit user confirmation: the exact confirmation text the + /// preview returned (for example MOVE TO TRASH, PERMANENTLY DELETE, RUN + /// OWNER CLEANUP or RUN OWNER CLEANUP AND DELETE CACHE FILES). Marking + /// is not approval. + pub confirmation: String, + /// Rescan once the removal finishes. Default false, so the next batch + /// can be found and marked at once; a rescan of a large volume takes + /// minutes. Until one, removed paths are still listed, and the window + /// refuses to mark them. + #[serde(default)] + pub rescan: bool, +} + +/// What `pwrdisk_find` takes. +#[derive(Clone, Debug, Default, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct FindParams { + /// Where to search. Default: the whole scanned tree. + pub path: Option, + /// `file`, `dir` or `any` (default). A matching directory is listed + /// once, without what is inside it. + pub kind: Option, + /// Only entries of at least this many bytes. + pub min_bytes: Option, + /// Only this kind of data. + pub category: Option, + /// Cleanup candidates: caches, build output, package stores, installed + /// dependencies, sync history, trash, scratch. This classification is + /// not removal eligibility; results report removal guard refusals. + #[serde(default)] + pub reclaimable: bool, + /// Only names containing this text, case-insensitively. + pub name: Option, + /// Only entries not written to in this many days. For a directory, the + /// newest write anywhere beneath it counts. + pub older_than_days: Option, + /// How many to list, largest first. Default 25, at most 200. + pub limit: Option, +} + +impl FindParams { + /// The same search as the link words it, with `now` fixing what + /// `older_than_days` means. + fn request(&self, path: Option, now: i64) -> FindRequest { + FindRequest { + path, + kind: Kind::from(self.kind.unwrap_or_default()).name().to_string(), + min_bytes: self.min_bytes.unwrap_or(0), + category: self + .category + .map(|name| Category::from(name).name().to_string()), + reclaimable: self.reclaimable, + name: self.name.clone(), + before: self + .older_than_days + .map(|days| now - i64::from(days) * 86_400), + limit: self.limit.unwrap_or(25).clamp(1, MAX_LIMIT), + } + } +} + +/// What `pwrdisk_mark` and `pwrdisk_unmark` take. +#[derive(Clone, Debug, Default, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PathsParams { + /// Absolute paths under the scanned root. For `pwrdisk_unmark`, an + /// empty list unmarks everything. + #[serde(default)] + pub paths: Vec, +} + +/// What `pwrdisk_show` takes. +#[derive(Clone, Debug, Default, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ShowParams { + /// The path to show in the window, under the scanned root. + pub path: PathBuf, +} + +/// One connected agent's state. +pub struct Session { + home: Option, + socket: PathBuf, + launcher: Option, + client: String, + /// This process's own scans, read only while no window is linked. + scans: Vec, + /// Marks as this session knows them: the window's when one is linked, + /// else its own. + marks: Vec, + link: Option, + /// What the window last said about itself. + window: Option, + /// Why an open window is not linked: it shows an SSH host, speaks + /// another link version, or refused the marks made here. Said instead + /// of starting a window that could not link either. + unlinked: Option, + /// When a window was last started from here, so one that is slow to + /// come up is not started twice. + launched: Option, + pending_removal: Option, +} + +impl std::fmt::Debug for Session { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Session") + .field("client", &self.client) + .field("scans", &self.scans.len()) + .field("marks", &self.marks.len()) + .field("linked", &self.link.is_some()) + .finish_non_exhaustive() + } +} + +/// Start a PwrDisk window on `root`, detached from this process so the +/// agent's exit does not take the window with it. +fn launch_window(root: &Path) -> io::Result<()> { + let exe = std::env::current_exe()?; + let mut command = Command::new(exe); + command + .arg(root) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + #[cfg(unix)] + { + use std::os::unix::process::CommandExt as _; + // Its own process group: a signal to the agent's group stops here. + command.process_group(0); + } + command.spawn()?; + Ok(()) +} + +impl Default for Session { + fn default() -> Self { + Self::new() + } +} + +impl Session { + /// A session over the real socket, able to launch a window. + pub fn new() -> Self { + // Where no window can be linked, starting one would only leave a + // window the agent cannot reach, and another on every retry. + let launcher: Option = if disktree_link::SUPPORTED { + Some(Box::new(launch_window)) + } else { + None + }; + Self::detached(disktree_link::socket_path(), launcher) + } + + /// A session over `socket`, launching windows with `launcher` or not at + /// all. Tests use this with a stand-in for the window. + pub fn detached(socket: PathBuf, launcher: Option) -> Self { + Self { + home: std::env::home_dir(), + socket, + launcher, + client: "an agent".to_string(), + scans: Vec::new(), + marks: Vec::new(), + link: None, + window: None, + unlinked: None, + launched: None, + pending_removal: None, + } + } + + /// Remember who is connected, by the name a client gives at + /// `initialize`, in the words the window shows. + pub fn set_client(&mut self, name: &str) { + let lowered = name.to_ascii_lowercase(); + self.client = if lowered.contains("claude-code") + || lowered.contains("claude code") + { + "Claude Code".to_string() + } else if lowered.contains("claude") { + "Claude".to_string() + } else if lowered.contains("codex") { + "Codex".to_string() + } else if name.trim().is_empty() { + "an agent".to_string() + } else { + name.to_string() + }; + } + + pub fn client(&self) -> &str { + &self.client + } + + pub fn scans(&self) -> &[Scan] { + &self.scans + } + + pub fn marks(&self) -> &[Target] { + &self.marks + } + + fn show(&self, path: &Path) -> String { + display(path, self.home.as_deref()) + } + + // ── scanning ──────────────────────────────────────────────────────── + + /// Decide what a scan request means: the root and the options, and + /// whether the window or this process does the walking. With a window + /// linked the scan is asked of it here, and [`Self::window_scan`] + /// follows it; otherwise the walk runs with the session unlocked. + pub fn prepare_scan( + &mut self, + params: &ScanParams, + ) -> Result { + let base = match ¶ms.path { + Some(path) => self.absolute(path)?, + None => self + .home + .clone() + .ok_or("no path given and no home directory")?, + }; + let root = if params.disk { + volume_root_for(&base).unwrap_or_else(|| PathBuf::from("/")) + } else { + base + }; + let metadata = std::fs::metadata(&root).map_err(|error| { + format!("cannot read {}: {error}", root.display()) + })?; + if !metadata.is_dir() { + return Err(format!("{} is not a directory", root.display())); + } + let options = ScanOptions { + apparent_size: params.apparent_size, + include_hidden: !params.skip_hidden, + one_filesystem: !params.cross_filesystems, + max_depth: params.max_depth, + ..ScanOptions::default() + }; + let request = Request::Scan { + root: root.clone(), + options: ScanOptionsRequest { + apparent_size: Some(options.apparent_size), + include_hidden: Some(options.include_hidden), + one_filesystem: Some(options.one_filesystem), + max_depth: Some(options.max_depth), + }, + }; + if self.try_connect_for_request(Some(&request))? { + Ok(ScanPlan::Window { root }) + } else { + Ok(ScanPlan::Local { root, options }) + } + } + + /// Whether the window has finished the scan of `root` it was asked + /// for, and if so what it found. `Ok(None)` is "still scanning". + pub fn window_scan( + &mut self, + root: &Path, + ) -> Result, String> { + let state = match self.call(&Request::State)? { + Response::State(state) => state, + other => return Err(unexpected(&other)), + }; + if state.root != root { + return Err(format!( + "The window moved to {} before the scan of {} finished; \ + the user may have gone elsewhere. Scan again if needed.", + self.show(&state.root), + self.show(root) + )); + } + if state.scanning { + return Ok(None); + } + let Some(tree) = state.tree.clone() else { + return Err(format!( + "The window has no tree for {}: its scan did not finish. \ + The window shows why.", + self.show(root) + )); + }; + let top = match self.call(&Request::Ls { + path: root.to_path_buf(), + limit: TOP, + })? { + Response::Listing(listing) => listing, + Response::Error { message } => return Err(message), + other => return Err(unexpected(&other)), + }; + let facts = ScanFacts { + root: root.to_path_buf(), + tree, + space: state.space, + device: device_for(root), + top, + insights: state.insights, + }; + let mut report = self.scan_report(&facts); + report.push('\n'); + report.push_str(&self.window_line()); + Ok(Some(report)) + } + + /// Keep a finished scan of this process's own, replacing an earlier one + /// of the same root, and say what it found. + pub fn store_scan(&mut self, scan: Scan) -> String { + self.scans.retain(|known| known.root != scan.root); + let report = self.scan_report(&ScanFacts::of_local(&scan)); + self.scans.push(scan); + report + } + + fn scan_report(&self, facts: &ScanFacts) -> String { + let now = now(); + let tree = &facts.tree; + let mut out = String::new(); + let _ = write!( + out, + "Scanned {} in {:.1} s: {} \u{00b7} {} files \u{00b7} {} \ + directories", + self.show(&facts.root), + Duration::from_millis(tree.elapsed_ms).as_secs_f64(), + human_bytes(tree.bytes), + human_count(tree.files), + human_count(tree.dirs), + ); + let _ = writeln!(out, " \u{00b7} {}", scan_context(tree)); + if let Some(space) = facts.space { + let used = space.total.saturating_sub(space.free); + let _ = writeln!( + out, + "Volume {}{}: {} free of {}, {:.0}% used. This scan holds \ + {:.0}% of what is used; the rest is outside {} or is not \ + files (snapshots, other volumes, swap).", + volume_root_for(&facts.root).map_or_else( + || "?".to_string(), + |root| root.display().to_string() + ), + facts + .device + .as_deref() + .map_or_else(String::new, |device| format!(" ({device})")), + human_bytes(space.available), + human_bytes(space.total), + share(used, space.total.max(1)), + share(tree.bytes, used.max(1)), + self.show(&facts.root), + ); + } + out.push_str(allocation_caveat()); + if let Some(line) = clone_summary(&facts.top.entry) { + out.push_str(&line); + } + out.push_str("Top level, largest first:\n"); + out.push_str(&children(&facts.top, now)); + if !facts.insights.is_empty() { + out.push_str( + "Worth a look, the biggest things that could plausibly go:\n", + ); + for insight in &facts.insights { + let _ = writeln!( + out, + " {:>9} {} {}", + human_bytes(insight.bytes), + self.show(&insight.path), + insight.what, + ); + } + } + out.push_str( + "Next: pwrdisk_ls goes into a directory, pwrdisk_find lists \ + the largest files or every cache, pwrdisk_mark marks what \ + should go.", + ); + out + } + + // ── looking ───────────────────────────────────────────────────────── + + /// An absolute, normalized path: `~` expanded, relative to the working + /// directory otherwise. + fn absolute(&self, path: &Path) -> Result { + let expanded = if let Ok(rest) = path.strip_prefix("~") { + let home = self.home.clone().ok_or("no home directory for ~")?; + home.join(rest) + } else if path.is_absolute() { + path.to_path_buf() + } else { + std::env::current_dir() + .map_err(|error| format!("no working directory: {error}"))? + .join(path) + }; + Ok(normalize(&expanded)) + } + + /// The scan of this process's own holding `path`, with the node there. + fn locate(&self, path: &Path) -> Result, String> { + let path = self.absolute(path)?; + if self.scans.is_empty() { + return Err( + "Nothing is scanned yet. Call pwrdisk_scan first; with no \ + arguments it scans the home directory." + .to_string(), + ); + } + let scan = self + .scans + .iter() + .filter(|scan| path.starts_with(&scan.root)) + .max_by_key(|scan| scan.root.as_os_str().len()) + .ok_or_else(|| { + let roots: Vec = self + .scans + .iter() + .map(|scan| self.show(&scan.root)) + .collect(); + format!( + "{} is outside the scanned roots ({}). Scan a directory \ + that contains it.", + self.show(&path), + roots.join(", ") + ) + })?; + let relative = path + .strip_prefix(&scan.root) + .map_err(|_| "unreachable: prefix was checked".to_string())?; + let (crumbs, node) = + scan.tree.root().descend(relative).ok_or_else(|| { + format!( + "{} is not in the scan of {}: it may be new, hidden, below \ + the depth limit, or on another filesystem. Scan again if \ + it should be there.", + self.show(&path), + self.show(&scan.root) + ) + })?; + Ok(Located { + scan, + path, + crumbs, + node, + }) + } + + /// The window's root when it covers `path`; otherwise why the agent + /// should scan from higher up. Only meaningful while linked. + fn window_root_for(&self, path: &Path) -> Result { + let Some(state) = &self.window else { + return Err("the window has not said where it is".to_string()); + }; + // A window still on the source chooser has no root, and an empty + // path is a prefix of every path. + if state.root.as_os_str().is_empty() { + return Err(format!( + "The PwrDisk window has no tree yet: it is waiting for a \ + source. Call pwrdisk_scan on a directory containing {} and \ + the window scans it.", + self.show(path) + )); + } + if path.starts_with(&state.root) { + return Ok(state.root.clone()); + } + Err(format!( + "{} is outside the PwrDisk window's tree, which is rooted at \ + {}. The window is what the user sees, so it is what you read: \ + call pwrdisk_scan on a directory containing it and the window \ + follows.", + self.show(path), + self.show(&state.root) + )) + } + + /// A directory and its largest children, from the window or from a + /// scan of this process's own. + fn listing( + &mut self, + path: &Path, + limit: usize, + ) -> Result { + if self.try_connect() { + self.window_root_for(path)?; + return match self.call(&Request::Ls { + path: path.to_path_buf(), + limit, + })? { + Response::Listing(listing) => Ok(listing), + Response::Error { message } => Err(message), + other => Err(unexpected(&other)), + }; + } + let found = self.locate(path)?; + Ok(Listing::of( + &found.scan.root, + found.scan.tree.root().bytes, + &found.path, + found.node, + limit, + )) + } + + /// Estimate without adopting or handing over marks from either side. + fn estimate_report_for( + &self, + params: &EstimateParams, + ) -> Result { + use disktree_core::planning::{self, Context}; + if params.paths.is_empty() || params.paths.len() > planning::MAX_PATHS { + return Err(format!("Supply 1 to {} paths.", planning::MAX_PATHS)); + } + let paths = params + .paths + .iter() + .map(|p| self.absolute(p)) + .collect::, _>>()?; + let peer_scope = params + .peer_scope + .as_ref() + .map(|p| self.absolute(p)) + .transpose()?; + let peer_limit = + params.peer_limit.unwrap_or(10).min(planning::MAX_PEERS); + // A normal connection hands over marks and Hello clears an intent. + // This independent State/Estimate exchange does neither and never + // adopts window marks or falls back to stale local trees on failure. + let report = if let Ok(mut link) = Link::connect_at(&self.socket) { + let state = + match link.call(&Request::State).map_err(|e| e.to_string())? { + Response::State(state) => state, + Response::Error { message } => return Err(message), + other => return Err(unexpected(&other)), + }; + if state.version != VERSION { + return Err(disktree_link::protocol_mismatch( + state.version, + VERSION, + )); + } + if let Some(host) = state.remote { + return Err(disktree_link::remote_refusal(&host)); + } + match link + .call(&Request::Estimate { + paths, + peer_scope, + peer_limit, + }) + .map_err(|e| e.to_string())? + { + Response::Estimate(report) => report, + Response::Error { message } => return Err(message), + other => return Err(unexpected(&other)), + } + } else { + if self.link.is_some() || self.window.is_some() { + return Err("The linked window is unavailable; reconnect before estimating its tree.".into()); + } + let scan = self + .scans + .iter() + .rev() + .find(|scan| { + paths.iter().all(|path| path.starts_with(&scan.root)) + }) + .or_else(|| { + self.scans + .iter() + .rev() + .find(|scan| paths[0].starts_with(&scan.root)) + }) + .or_else(|| self.scans.last()) + .ok_or_else(|| { + "Nothing is scanned yet. Call pwrdisk_scan first." + .to_string() + })?; + planning::estimate( + &scan.tree, + Context::of( + &scan.root, + &scan.options, + scan.at, + scan.unreadable, + ), + &paths, + peer_scope.as_deref(), + peer_limit, + )? + }; + Ok(report) + } + + pub fn estimate_paths( + &self, + params: &EstimateParams, + ) -> Result { + let report = self.estimate_report_for(params)?; + let json = + serde_json::to_string_pretty(&report).map_err(|e| e.to_string())?; + Ok(format!( + "Read-only hypothetical selection; marks, scan root, navigation and removal intents are unchanged. All byte values are bytes. listed_bytes is apparent logical size only when context.apparent_size=true; otherwise it is reported allocation including repeated clone allocation. private_allocation is scan-derived, and reclaim is the selected union before retention. {}\n{json}\nPeer rows are alternatives, not additive savings. Additional bounds subtract the original selection's opposite bound. with_all_returned_peers evaluates their union once. Peers are clone-holder directories to inspect, not removal recommendations. Clone IDs cannot enumerate all extent owners, particularly after modification. references_not_seen_in_scan counts unresolved references without owner paths, never known peers; filtered or truncated scans cannot establish that count. Peer candidates are direct children of peers.scope; widen peer_scope explicitly to inspect another part of this scan.", + retention_notice() + )) + } + + /// Rank explicit candidates without marks or clone-peer discovery. + pub fn rank(&self, params: &RankParams) -> Result { + if params.paths.is_empty() || params.paths.len() > 50 { + return Err( + "Supply 1 to 50 candidate paths from one complete scan.".into(), + ); + } + let selection = self.estimate_report_for(&EstimateParams { + paths: params.paths.clone(), + peer_scope: None, + peer_limit: Some(0), + })?; + let mut candidates = Vec::new(); + for path in ¶ms.paths { + let report = self.estimate_report_for(&EstimateParams { + paths: vec![path.clone()], + peer_scope: None, + peer_limit: Some(0), + })?; + if report.context != selection.context { + return Err("Scan context changed during ranking; inspect status and rank again.".into()); + } + candidates.push(report); + } + let candidates: Vec<_> = rank_candidates(candidates, params.by) + .into_iter() + .map(|candidate| { + let report = candidate.estimate; + serde_json::json!({ + "value": candidate.value, + "paths": report.accepted, + "refused": report.refused, + "listed_bytes": report.listed_bytes, + "apparent_size": report.context.apparent_size, + "private_allocation": report.private_allocation, + "reclaim": report.reclaim, + "metadata_complete": report.metadata_complete, + "scan_complete": report.scan_complete, + }) + }) + .collect(); + let json = serde_json::to_string_pretty(&serde_json::json!({ + "rank_by": params.by, "candidates": candidates, "selection_union": selection, + })).map_err(|e| e.to_string())?; + Ok(format!( + "Read-only candidate ranking, known values descending; null is unavailable, never zero. Candidate estimates are alternatives, not additive; selection_union evaluates the full set once. Private allocation is not immediate recovered space. Reclaim lower bounds are before retention, not guaranteed savings. Ownership and cleanup method are not established by ranking: inspect classification with pwrdisk_find/ls, prefer the owning tool, and check worktree status before proposing it. Never remove worktrees just to unlock clone groups.\n{json}\n{}", + retention_notice() + )) + } + + /// List a directory, largest first. + pub fn ls(&mut self, params: &LsParams) -> Result { + let limit = params.limit.unwrap_or(DEFAULT_LIMIT).clamp(1, MAX_LIMIT); + let now = now(); + let path = self.absolute(¶ms.path)?; + let listing = self.listing(&path, limit)?; + let mut out = String::new(); + let _ = writeln!( + out, + "{} {}", + self.show(&listing.path), + describe(&listing.entry, now) + ); + if listing.path != listing.root { + let _ = writeln!( + out, + "{:.0}% of {}, which is {}", + share(listing.entry.bytes, listing.root_bytes), + self.show(&listing.root), + human_bytes(listing.root_bytes) + ); + } + if let Some(line) = clone_summary(&listing.entry) { + out.push_str(&line); + } + out.push_str(&children(&listing, now)); + if params.show { + out.push_str("Window: not shown. Listings never move the view; use pwrdisk_show only when the user asks to see a path.\n"); + } + Ok(out) + } + + /// What a search finds, from the window or from the scans here. + fn found(&mut self, request: &FindRequest) -> Result { + if self.try_connect() { + if let Some(path) = &request.path { + self.window_root_for(path)?; + } + return match self.call(&Request::Find(request.clone()))? { + Response::Found(found) => Ok(found), + Response::Error { message } => Err(message), + other => Err(unexpected(&other)), + }; + } + let filter = request.filter()?; + let scope: Vec<(PathBuf, Node<'_>)> = if let Some(path) = &request.path + { + let located = self.locate(path)?; + vec![(located.path, located.node)] + } else { + if self.scans.is_empty() { + return Err("Nothing is scanned yet. Call pwrdisk_scan first." + .to_string()); + } + // A scan inside another one holds the same entries again; the + // outer scan already counts them. + self.scans + .iter() + .filter(|scan| { + !self.scans.iter().any(|outer| { + outer.root != scan.root + && scan.root.starts_with(&outer.root) + }) + }) + .map(|scan| (scan.root.clone(), scan.tree.root())) + .collect() + }; + let mut all = FoundList::default(); + for (path, node) in &scope { + let found = FoundList::of(&query::find( + path, + *node, + &filter, + request.limit, + )); + all.matches.extend(found.matches); + all.count += found.count; + all.bytes += found.bytes; + } + all.matches + .sort_by_key(|found| std::cmp::Reverse(found.entry.bytes)); + all.matches.truncate(request.limit); + Ok(all) + } + + /// The largest entries matching the filters, topmost matches only. + pub fn find(&mut self, params: &FindParams) -> Result { + let now = now(); + let path = match ¶ms.path { + Some(path) => Some(self.absolute(path)?), + None => None, + }; + let request = params.request(path.clone(), now); + let found = self.found(&request)?; + let where_ = match (&path, &self.window) { + (Some(path), _) => self.show(path), + (None, Some(state)) if self.link.is_some() => { + self.show(&state.root) + } + (None, _) => "the scanned roots".to_string(), + }; + let mut out = String::new(); + if found.count == 0 { + let _ = writeln!(out, "Nothing under {where_} matches."); + return Ok(out); + } + let _ = writeln!( + out, + "{} match{} under {where_}, {} in all; the largest {}:", + found.count, + if found.count == 1 { "" } else { "es" }, + human_bytes(found.bytes), + found.matches.len(), + ); + out.push_str(&matches( + &found.matches, + found.bytes, + now, + self.home.as_deref(), + )); + if params.reclaimable + || found + .matches + .iter() + .any(|item| item.entry.reclaim.is_some()) + { + out.push_str( + "Cleanup candidates are classifications, not permission to \ + remove. Totals are measured bytes, not guaranteed freed \ + space. Prefer the owning tool's cleanup command for \ + tool-owned data.\n", + ); + out.push_str(&self.candidate_guards(&found)); + } + Ok(out) + } + + /// Preview the same guards as review, without adding any marks. Keep + /// system caches visible, but explain why they cannot be removed. + fn candidate_guards(&self, found: &FoundList) -> String { + let targets: Vec = found + .matches + .iter() + .filter(|item| item.entry.reclaim.is_some()) + .map(|item| Target { + path: item.path.clone(), + bytes: item.entry.bytes, + is_dir: item.entry.is_dir, + hidden: is_hidden(&item.path), + }) + .collect(); + let mut out = String::new(); + for root in self.roots_of(&targets) { + let mine: Vec = targets + .iter() + .filter(|target| target.path.starts_with(&root)) + .cloned() + .collect(); + for blocked in plan(&mine, &root).blocked { + let _ = writeln!( + out, + "Removal blocked: {} — {}", + self.show(&blocked.path), + blocked.reason + ); + } + } + out.push_str( + "Removal guards were checked for listed candidates only; \ + marking and review recheck eligibility.\n", + ); + out + } + + // ── the window ────────────────────────────────────────────────────── + + /// Whether the window link could be opened without launching anything + /// or changing its root. + /// A new link learns the window's state and is handed the marks made + /// here before it existed; from then on the window's marks are the + /// marks. + fn try_connect(&mut self) -> bool { + self.try_connect_for_request(None).unwrap_or(false) + } + + /// Only an explicit scan may move a newly linked window to cover the + /// marks made here. Check every mark before sending any of them. An + /// explicit unmark reaches the window even if the handover still fails. + fn try_connect_for_request( + &mut self, + request: Option<&Request>, + ) -> Result { + if self.link.is_some() { + if let Some(request) = request { + self.send_state_request(request)?; + } + return Ok(true); + } + let Ok(link) = Link::connect_at(&self.socket) else { + self.unlinked = None; + return Ok(false); + }; + self.link = Some(link); + // `hello` adopts the window's marks, which would lose these. + let mine = std::mem::take(&mut self.marks); + let hello = Request::Hello { + client: self.client.clone(), + version: VERSION, + }; + let mut unmarked = false; + let refused = match self.call(&hello) { + // A window on an SSH host answers, and `adopt` noted why it is + // not followed. + Ok(Response::State(_)) if self.unlinked.is_some() => None, + Ok(Response::State(state)) => match (|| { + // A failed handover can leave accepted marks in the + // window. Clear them before retrying the remaining marks, + // so a refusal cannot resurrect an explicitly unmarked path. + if let Some(request @ Request::Unmark { .. }) = request { + self.send_state_request(request)?; + unmarked = true; + } + let root = match request { + Some(Request::Scan { root, .. }) => root, + _ => &state.root, + }; + Self::check_handover_root(&mine, root)?; + if let Some(request @ Request::Scan { .. }) = request { + self.send_state_request(request)?; + } + self.push_marks(&mine) + })() { + Ok(()) => return Ok(true), + Err(error) => Some(format!( + "The open PwrDisk window did not take the marks made \ + before it was linked ({error}); they are kept here." + )), + }, + // A version mismatch, said in the window's words. + Ok(Response::Error { message }) => { + Some(if message.contains(disktree_link::RECONNECT_MCP) { + message + } else { + format!("{message} {}", disktree_link::RECONNECT_MCP) + }) + } + Ok(other) => Some(unexpected(&other)), + Err(reason) => { + Some(format!("{reason}. {}", disktree_link::RECONNECT_MCP)) + } + }; + let request_refused = + request.is_some() && refused.is_some() && !unmarked; + if refused.is_some() { + self.unlinked = refused; + } + self.link = None; + self.window = None; + self.marks = mine; + if request_refused && let Some(reason) = &self.unlinked { + return Err(reason.clone()); + } + Ok(false) + } + + fn send_state_request(&mut self, request: &Request) -> Result<(), String> { + match self.call(request)? { + Response::State(_) => Ok(()), + Response::Error { message } => Err(message), + other => Err(unexpected(&other)), + } + } + + fn check_handover_root(mine: &[Target], root: &Path) -> Result<(), String> { + if !mine.is_empty() + && (root.as_os_str().is_empty() + || mine.iter().any(|mark| { + mark.path == root || !mark.path.starts_with(root) + })) + { + return Err( + "the window's root does not contain all the marks. Call \ + pwrdisk_scan on a directory containing all marked paths \ + to move the window explicitly and hand them over" + .to_string(), + ); + } + Ok(()) + } + + /// Open the link, launching a window on `root` when none answers. + fn ensure_link(&mut self, root: &Path) -> Result<(), String> { + if self.try_connect() { + return Ok(()); + } + if let Some(reason) = &self.unlinked { + return Err(reason.clone()); + } + if !disktree_link::SUPPORTED { + return Err(NO_LINK.to_string()); + } + let Some(launcher) = &self.launcher else { + return Err(format!( + "No PwrDisk window is open, and this session cannot open \ + one here ({}). Start `pwrdisk {}` yourself, then call \ + again.", + Link::connect_at(&self.socket) + .err() + .map_or_else(String::new, |error| error.to_string()), + root.display() + )); + }; + if let Some(launched) = self.launched + && launched.elapsed() < RELAUNCH_AFTER + { + return Err(format!( + "A PwrDisk window was started {} s ago and has not \ + answered yet. Give it a moment and call again; if none \ + appeared, start `pwrdisk {}` by hand.", + launched.elapsed().as_secs(), + root.display() + )); + } + launcher(root).map_err(|error| { + format!("could not start a PwrDisk window: {error}") + })?; + let started = Instant::now(); + self.launched = Some(started); + while started.elapsed() < LAUNCH_WAIT { + std::thread::sleep(Duration::from_millis(100)); + if self.try_connect() { + self.launched = None; + return Ok(()); + } + } + Err("A PwrDisk window was started but did not answer in time. \ + Call again once it is open." + .to_string()) + } + + /// Send one request. Every answer that carries the window's state is + /// adopted. A failed link is dropped, so the next call tries again + /// from the start. + fn call(&mut self, request: &Request) -> Result { + let Some(link) = &mut self.link else { + return Err("the window is not linked".to_string()); + }; + match link.call(request) { + Ok(response) => { + if let Response::State(state) | Response::Marked { state, .. } = + &response + { + // Validate both ends, even if a stale peer accepted Hello. + // Never adopt its marks or interpret missing savings as + // measured allocation before establishing compatibility. + if state.version != VERSION { + let reason = disktree_link::protocol_mismatch( + state.version, + VERSION, + ); + self.unlinked = Some(reason.clone()); + self.link = None; + self.window = None; + return Ok(Response::error(reason)); + } + self.adopt(state); + } + Ok(response) + } + Err(error) => { + self.link = None; + self.window = None; + Err(format!("the PwrDisk window link failed: {error}")) + } + } + } + + /// The window's marks are the marks: keep ours in step. A window on an + /// SSH host is only noted, and the link to it dropped: its marks are + /// another machine's paths. + fn adopt(&mut self, state: &State) { + if let Some(host) = &state.remote { + self.unlinked = Some(disktree_link::remote_refusal(host)); + self.window = None; + self.link = None; + return; + } + self.unlinked = None; + self.marks = state + .marks + .iter() + .map(|mark| Target { + hidden: is_hidden(&mark.path), + path: mark.path.clone(), + bytes: mark.bytes, + is_dir: mark.is_dir, + }) + .collect(); + self.window = Some(state.clone()); + } + + /// Hand marks made before the window linked over to it. Each answer + /// carries the window's marks, which replace ours. + fn push_marks(&mut self, mine: &[Target]) -> Result<(), String> { + if !mine.is_empty() { + let root = self + .window + .as_ref() + .ok_or("the window has not said where it is")? + .root + .clone(); + Self::check_handover_root(mine, &root)?; + let targets: Vec = mine + .iter() + .map(|target| MarkRequest { + path: target.path.clone(), + bytes: target.bytes, + is_dir: target.is_dir, + }) + .collect(); + match self.call(&Request::Mark { root, targets })? { + Response::Marked { refused, .. } if !refused.is_empty() => { + return Err(refused + .iter() + .map(|item| { + format!( + "{}: {}", + self.show(&item.path), + item.reason + ) + }) + .collect::>() + .join("; ")); + } + Response::Marked { .. } | Response::State(_) => {} + Response::Error { message } => return Err(message), + other => return Err(unexpected(&other)), + } + } + Ok(()) + } + + /// Show `path` in the window, opening one on `root` if needed. + fn show_in_window( + &mut self, + root: &Path, + path: &Path, + ) -> Result { + let path = self.absolute(path)?; + self.ensure_link(root)?; + match self.call(&Request::Show { + root: root.to_path_buf(), + path: path.clone(), + })? { + Response::Error { message } => Err(message), + _ => Ok(format!("Window: showing {}.\n", self.show(&path))), + } + } + + pub fn show_path(&mut self, params: &ShowParams) -> Result { + let path = self.absolute(¶ms.path)?; + let root = if self.try_connect() { + // A path outside the window but inside a scan held here moves + // the window to that scan's root; one in neither is an error. + match self.window_root_for(&path) { + Ok(root) => root, + Err(outside) => self + .locate(&path) + .map(|found| found.scan.root.clone()) + .map_err(|_| outside)?, + } + } else { + self.locate(&path)?.scan.root.clone() + }; + self.show_in_window(&root, &path) + } + + /// What the window is doing, in one line, for the end of a report. + fn window_line(&mut self) -> String { + // A link that was already open may be stale; ask again. + if self.try_connect() { + let _ = self.call(&Request::State); + } + if let Some(reason) = &self.unlinked { + return format!("Window: open, but not followed. {reason}"); + } + match &self.window { + Some(state) => { + let tree = match &state.tree { + Some(tree) => format!( + " ({} \u{00b7} {} files \u{00b7} scanned {} \u{00b7} {})", + human_bytes(tree.bytes), + human_count(tree.files), + age(now(), tree.scanned_at), + scan_context(tree), + ), + None => String::new(), + }; + format!( + "Window: open on {}{tree}, {} screen{}{} (PwrDisk {}). Its tree is \ + what pwrdisk_ls and pwrdisk_find read.\n{}{}", + self.show(&state.root), + state.screen, + if state.scanning { ", scanning" } else { "" }, + match state.marks.len() { + 0 => String::new(), + 1 => ", 1 mark".to_string(), + n => format!(", {n} marks"), + }, + if state.app_version.is_empty() { + "version unknown" + } else { + &state.app_version + }, + version_notice(state), + if state.tree.is_some() { + allocation_caveat() + } else { + "" + }, + ) + } + None if self.launcher.is_some() => { + "Window: none open. pwrdisk_review opens one on the marks \ + for the user to confirm; pwrdisk_show opens one on a path." + .to_string() + } + None if !disktree_link::SUPPORTED => { + "Window: no link on this system yet. The marks stay in this \ + session; pwrdisk_review says how the user takes them over." + .to_string() + } + None => "Window: none open, and none can be opened from here." + .to_string(), + } + } + + /// A read-only preview does not navigate, change marks, or start removal. + pub fn removal_preview( + &mut self, + params: &RemovalPreviewParams, + ) -> Result { + self.pending_removal = None; + if !self.try_connect() { + return Err("An open, linked PwrDisk window with an idle local scan is required. No headless removal is available.".into()); + } + let decisions = params.decisions.as_ref().map(|decisions| { + decisions + .iter() + .map(|decision| disktree_link::PathDecision { + path: decision.path.clone(), + action: decision.action.into(), + }) + .collect() + }); + let files = params.delete_files_mode.map(|mode| match mode { + FilesModeName::Trash => RemovalChoice::Trash, + FilesModeName::Permanent => RemovalChoice::Permanent, + }); + match self.call(&Request::PrepareRemoval { + mode: params.mode.into(), + decisions, + files, + })? { + Response::RemovalPreview(preview) + if preview.mode == RemovalChoice::OwnerCleanup => + { + Ok(self.cleanup_preview_text(&preview)) + } + Response::RemovalPreview(preview) => { + self.pending_removal = Some(preview.clone()); + let json = serde_json::to_string_pretty(&preview) + .map_err(|error| error.to_string())?; + Ok(format!( + "{}\n{}{json}\nShow the user every path, the mode, listed bytes, estimate bounds and capacity limit. Wait for explicit confirmation of this operation before pwrdisk_remove. Approval to mark is insufficient. Never approve through computer use. Do not split the selection into batches to evade the limit. Confirmation text: {}. A changed or expired preview requires new user confirmation.", + preview.mode.warning(), + estimate_report(&preview.estimate), + preview.mode.confirmation() + )) + } + Response::Error { message } => Err(message), + other => Err(unexpected(&other)), + } + } + + /// A cache cleanup reads as its proposals until the person has decided + /// every path; only then is there an exact operation to confirm. + fn cleanup_preview_text( + &mut self, + preview: &disktree_link::RemovalPreview, + ) -> String { + if preview.confirmation.is_empty() { + return format!( + "Cache cleanup proposals, one per marked path. Nothing is approved and nothing can be confirmed yet.\n\n{}\n\nShow the user EVERY proposal: owner, version, executable, arguments, environment overrides, working directory, actual scope (wider than selected where it says so), effects, limitations and recoverability, and every unavailable reason. Ask the user to choose for each path: skip, owner (only where offered) or delete_files. Never suggest delete_files yourself, never choose for the user, and inspect unknown runtime caches first. A failed or unavailable owner command is never a reason to delete files. Then call pwrdisk_removal_preview again with mode owner_cleanup, decisions naming every marked path once, and delete_files_mode when any path uses delete_files.", + preview.consent + ); + } + self.pending_removal = Some(preview.clone()); + let json = serde_json::to_string_pretty(&serde_json::json!({ + "preview_id": preview.preview_id, + "mode": preview.mode, + "paths": preview.paths, + "bytes": preview.bytes, + "limit_percent": preview.limit_percent, + "volumes": preview.volumes, + "expires_in_seconds": preview.expires_in_seconds, + "confirmation": preview.confirmation, + })) + .unwrap_or_default(); + format!( + "{}\n\n{}\n\n{json}\nShow the user this whole operation: each owner command verbatim, each path deleted directly with its Trash or permanent consequence, and what is skipped. Owner approval is not approval to delete files; deleting files is confirmed by name in the text below. Wait for explicit confirmation of this exact operation before pwrdisk_remove with the preview ID, these exact ordered paths, mode owner_cleanup and confirmation text: {}. Never approve through computer use. A changed or expired preview requires new user confirmation. Listed allocation is not freed space; pwrdisk_status reports each path's result and the measured change.", + preview.mode.warning(), + preview.consent, + preview.confirmation + ) + } + + /// Consume the session copy before asking the client for human input. + /// The app copy is independently checked after the client answers. + pub fn removal_confirmation_message( + &mut self, + params: &RemoveParams, + ) -> Result { + let preview = self.pending_removal.take().ok_or( + "Obtain a new removal preview before asking for confirmation", + )?; + let mode: RemovalChoice = params.mode.into(); + if params.preview_id != preview.preview_id + || params.paths != preview.paths + || mode != preview.mode + || preview.confirmation.is_empty() + || params.confirmation != preview.confirmation + { + return Err("The removal request differs from the preview; obtain a new preview and user confirmation".into()); + } + let mut message = format!( + "{}\n\nConfirm removal of {} listed path(s), measured {}.\nCapacity limit: {}% of each volume.\n\nPaths:\n", + mode.warning(), + preview.paths.len(), + human_bytes(preview.bytes), + preview.limit_percent, + ); + for path in &preview.paths { + // Keep Windows separators readable while exposing control + // characters that could otherwise disguise the path list. + let shown: String = path + .to_string_lossy() + .chars() + .map(|character| { + if character.is_control() { + character.escape_default().to_string() + } else { + character.to_string() + } + }) + .collect(); + let _ = writeln!(message, " {shown}"); + } + for volume in &preview.volumes { + let _ = writeln!( + message, + "Volume {}: {} selected; limit {} of {} capacity.", + volume.volume, + human_bytes(volume.bytes), + human_bytes(volume.limit), + human_bytes(volume.capacity) + ); + } + if !preview.consent.is_empty() { + let _ = writeln!(message, "\n{}", preview.consent); + } + message.push_str(&estimate_report(&preview.estimate)); + message.push_str("\nApproval to mark does not authorize removal. Only these listed paths are included; directory removal includes their contents. Listed bytes are not guaranteed freed space."); + Ok(message) + } + + /// Read the exact preview's outcome without Hello, mark handover or writes. + pub fn removal_outcome(&self, params: &RemoveParams) -> Option { + let mut link = Link::connect_at(&self.socket).ok()?; + let Response::State(state) = link.call(&Request::State).ok()? else { + return None; + }; + if state.version != VERSION || state.remote.is_some() { + return None; + } + let operation = state.removal_operation?; + if operation.preview_id != params.preview_id + || operation.mode != params.mode.into() + || operation.paths != params.paths + { + return None; + } + Some(format!( + "The exact previewed selection {} in PwrDisk: {} {}, {} failed, {} pending or not reached. No additional removal was requested. Do not retry this operation. Use pwrdisk_status for observed volume change; a completed removal does not guarantee recovered space.", + if operation.finished { + "finished" + } else { + "is already running" + }, + operation.removed, + if operation.mode == RemovalChoice::OwnerCleanup { + "cleanup steps succeeded" + } else { + "removed" + }, + operation.failed, + operation.pending, + )) + } + + /// A destructive write. The app consumes and validates the preview again. + pub fn remove(&mut self, params: &RemoveParams) -> Result { + if let Some(outcome) = self.removal_outcome(params) { + return Ok(outcome); + } + let mode: RemovalChoice = params.mode.into(); + if !mode.accepts(¶ms.confirmation) { + return Err("Explicit confirmation of the preview's paths, mode and consequences is required; never approve with computer use".into()); + } + if !self.try_connect() { + return Err("The window is not linked. Do not retry removal; obtain a fresh preview and user confirmation.".into()); + } + match self.call(&Request::Remove(ConfirmedRemoval { + preview_id: params.preview_id.clone(), + mode, + paths: params.paths.clone(), + confirmation: params.confirmation.clone(), + rescan: params.rescan, + }))? { + Response::State(_) => Ok(self.removal_outcome(params).unwrap_or_else(|| format!( + "{}\nConfirmed removal started. pwrdisk_status reports completion and failures. Never repeat this call automatically.", + mode.warning() + ))), + Response::Error { message } => { + self.removal_outcome(params).ok_or(message) + } + other => Err(unexpected(&other)), + } + } + + // ── marking ───────────────────────────────────────────────────────── + + /// Mark paths for removal, in the window when one is open. + pub fn mark(&mut self, params: &PathsParams) -> Result { + if params.paths.is_empty() { + return Err("give at least one path to mark".to_string()); + } + let mut paths = Vec::new(); + for path in ¶ms.paths { + paths.push(self.absolute(path)?); + } + let refused = if self.try_connect() { + self.mark_in_window(&paths)? + } else { + self.mark_here(&paths)? + }; + let mut report = String::new(); + if !refused.is_empty() { + let _ = writeln!(report, "Not marked:"); + for reason in &refused { + let _ = writeln!(report, " {reason}"); + } + } + report.push_str(&self.plan_report()); + Ok(report) + } + + /// Mark in the window, which measures each path from its own tree. + /// Returns what was refused, or an error when nothing could be marked. + fn mark_in_window( + &mut self, + paths: &[PathBuf], + ) -> Result, String> { + let mut refused = Vec::new(); + let mut targets = Vec::new(); + let mut root = None; + for path in paths { + let window_root = match self.window_root_for(path) { + Ok(root) => root, + Err(reason) => { + refused.push(reason); + continue; + } + }; + if *path == window_root { + refused.push(format!( + "{} is the scanned root; mark what is inside it instead", + self.show(path) + )); + continue; + } + // A scan held here may know the size already; the window + // measures regardless. + let (bytes, is_dir) = self + .locate(path) + .map_or((0, false), |f| (f.node.bytes, f.node.is_dir())); + targets.push(MarkRequest { + path: path.clone(), + bytes, + is_dir, + }); + root = Some(window_root); + } + let Some(root) = root else { + return Err(refused.join("\n")); + }; + match self.call(&Request::Mark { root, targets })? { + Response::Marked { refused: more, .. } => { + for item in more { + // The window's reason usually names the path already. + let shown = self.show(&item.path); + refused.push(if item.reason.contains(&shown) { + item.reason + } else { + format!("{shown}: {}", item.reason) + }); + } + } + Response::State(_) => {} + Response::Error { message } => return Err(message), + other => return Err(unexpected(&other)), + } + if self.marks.is_empty() && !refused.is_empty() { + return Err(refused.join("\n")); + } + Ok(refused) + } + + /// Mark against this process's own scans, with no window to ask. + fn mark_here(&mut self, paths: &[PathBuf]) -> Result, String> { + let mut refused = Vec::new(); + let mut targets = Vec::new(); + for path in paths { + let found = match self.locate(path) { + Ok(found) => found, + Err(reason) => { + refused.push(reason); + continue; + } + }; + if found.crumbs.is_empty() { + refused.push(format!( + "{} is the scanned root; mark what is inside it instead", + self.show(&found.path) + )); + continue; + } + targets.push(Target { + hidden: is_hidden(&found.path), + is_dir: found.node.is_dir(), + bytes: found.node.bytes, + path: found.path, + }); + } + if targets.is_empty() { + return Err(refused.join("\n")); + } + for target in targets { + if !self.marks.iter().any(|known| known.path == target.path) { + self.marks.push(target); + } + } + Ok(refused) + } + + /// Unmark paths, or everything. + pub fn unmark(&mut self, params: &PathsParams) -> Result { + let mut paths = Vec::new(); + for path in ¶ms.paths { + paths.push(self.absolute(path)?); + } + let previous = self.marks.clone(); + if paths.is_empty() { + self.marks.clear(); + } else { + self.marks.retain(|target| !paths.contains(&target.path)); + } + if let Err(reason) = + self.try_connect_for_request(Some(&Request::Unmark { paths })) + { + self.marks = previous; + return Err(reason); + } + Ok(self.plan_report()) + } + + /// The scan roots the marks fall under, each once: the window's root + /// when it covers a mark, else a scan's here, else the mark's parent. + fn roots_of(&self, marks: &[Target]) -> Vec { + let mut roots: Vec = Vec::new(); + for mark in marks { + let root = self + .window + .as_ref() + .filter(|state| mark.path.starts_with(&state.root)) + .map(|state| state.root.clone()) + .or_else(|| { + self.scans + .iter() + .filter(|scan| mark.path.starts_with(&scan.root)) + .max_by_key(|scan| scan.root.as_os_str().len()) + .map(|scan| scan.root.clone()) + }) + .unwrap_or_else(|| { + mark.path + .parent() + .map_or_else(|| mark.path.clone(), Path::to_path_buf) + }); + if !roots.contains(&root) { + roots.push(root); + } + } + roots + } + + /// What is marked, what the guards keep back, and what it frees. + pub fn plan_report(&mut self) -> String { + // Linking can replace our marks; describe the same state as the + // window line, including after an explicit unmark. + let window = self.window_line(); + let mut out = String::new(); + if self.marks.is_empty() { + out.push_str("Nothing is marked.\n"); + out.push_str(&window); + return out; + } + let total: u64 = self.marks.iter().map(|mark| mark.bytes).sum(); + let _ = writeln!( + out, + "Marked {} \u{00b7} {}", + self.marks.len(), + human_bytes(total) + ); + let marks = self.marks.clone(); + let mut plans = Vec::new(); + for root in self.roots_of(&marks) { + let mine: Vec = marks + .iter() + .filter(|mark| mark.path.starts_with(&root)) + .cloned() + .collect(); + plans.push(plan(&mine, &root)); + } + if self.window.is_none() { + plans = union_reports(plans); + } + for plan in plans { + out.push_str(&self.report_plan(plan)); + } + out.push_str(&window); + out + } + + /// Bounds from the tree that owns this accepted selection. + fn selection_estimate(&self, plan: &mut Plan) -> SelectionEstimate { + if let Some(window) = &self.window { + // Only the window owns the linked tree. Never substitute an old + // local scan or add per-mark estimates across clone groups. + return window + .estimate + .as_ref() + .filter(|estimate| { + window.root == plan.root + && !window.scanning + && window.scanned + && estimate.paths + == plan + .targets + .iter() + .map(|t| t.path.clone()) + .collect::>() + }) + .cloned() + .unwrap_or_else(|| SelectionEstimate::unknown(plan)); + } + let mut unmeasured = false; + let mut selected: Option>> = None; + plan.estimate_selection(|targets| { + let mut nodes = Vec::with_capacity(targets.len()); + let mut unknown = Estimate::default(); + for target in targets { + if let Ok(found) = self.locate(&target.path) { + if found.scan.options.apparent_size + || (cfg!(target_os = "macos") + && !found.scan.options.apfs_clone_metadata) + { + unmeasured = true; + unknown.upper = + unknown.upper.saturating_add(target.bytes); + unknown.partial = true; + } else { + nodes.push(found.node); + unknown.partial |= found.scan.unreadable > 0 + || found.scan.options.max_depth.is_some(); + } + } else { + unknown.upper = unknown.upper.saturating_add(target.bytes); + unknown.partial = true; + } + } + // The first call covers every target: keep its nodes for the + // shared total instead of locating each mark again. + if selected.is_none() { + selected = Some(nodes.clone()); + } + let measured = sharing::estimate(nodes); + Estimate { + lower: measured.lower, + upper: measured.upper.saturating_add(unknown.upper), + partial: measured.partial || unknown.partial, + } + }); + let mut estimate = SelectionEstimate::of(plan) + .with_shared(selected.unwrap_or_default()); + if unmeasured { + estimate.upper = None; + } + estimate + } + + /// Accepted targets, covered marks, guard refusals and savings bounds. + fn report_plan(&self, mut plan: Plan) -> String { + let mut out = String::new(); + let root = plan.root.clone(); + let estimate = self.selection_estimate(&mut plan); + for target in &plan.targets { + let _ = writeln!( + out, + " {:>9} {}{}", + human_bytes(target.bytes), + self.show(&target.path), + if target.is_dir { "/" } else { "" }, + ); + } + if !plan.covered.is_empty() { + let _ = writeln!( + out, + "Covered by another mark ({}): {}", + plan.covered.len(), + plan.covered + .iter() + .map(|target| self.show(&target.path)) + .collect::>() + .join(", ") + ); + } + if !plan.blocked.is_empty() { + let _ = writeln!(out, "Kept back ({}):", plan.blocked.len()); + for blocked in &plan.blocked { + let _ = writeln!( + out, + " {} {}", + self.show(&blocked.path), + blocked.reason + ); + } + } + out.push_str(&estimate_report(&estimate)); + match space_info(&root).ok() { + Some(space) => { + let after = space.after_removing(estimate.on_volume); + let _ = writeln!( + out, + "Projects {} on {}: {} free now, {} after.", + human_bytes(estimate.on_volume), + device_for(&root).unwrap_or_else(|| self.show(&root)), + human_bytes(space.available), + human_bytes(after.available), + ); + } + None => { + let _ = writeln!( + out, + "Projects {} on the volume of {}.", + human_bytes(estimate.on_volume), + self.show(&root) + ); + } + } + if plan.foreign() > 0 { + let _ = writeln!( + out, + "Listed {} on other volumes, excluded from this projection.", + human_bytes(plan.foreign()) + ); + } + if plan.unattributed() > 0 { + let _ = writeln!( + out, + "{} whose volume cannot be told is not counted either.", + human_bytes(plan.unattributed()) + ); + } + out + } + + /// Open the review screen in the window, launching one if needed. + pub fn review(&mut self) -> Result { + if self.marks.is_empty() { + return Err( + "Nothing is marked. pwrdisk_mark some paths first.".to_string() + ); + } + let marks = self.marks.clone(); + let roots = self.roots_of(&marks); + let mut roots = roots.iter(); + let mut root = roots.next().cloned().ok_or("no root for the marks")?; + // A new window must cover every offline scan root, rather than + // starting on one and immediately refusing the other marks. + for other in roots { + while !other.starts_with(&root) { + if !root.pop() { + return Err( + "The marked paths have no common scan root. Review \ + marks on one drive at a time." + .to_string(), + ); + } + } + } + self.ensure_link(&root)?; + if let Response::Error { message } = self.call(&Request::Review)? { + return Err(message); + } + let _ = self.call(&Request::State); + // The window starts in the trash whenever this machine has one, and + // otherwise deletes; the agent has to say which before the user + // presses Enter. + let backend = detect_trash_backend(); + let how = if self.marks.iter().any(|target| { + disktree_core::cleanup::inspection_reason(&target.path).is_some() + }) { + "Caches go through Cache cleanup: after Check owners the user chooses, for each path, Skip, the owner's exact command, or Delete files, which has its own tick in the confirmation. Unavailable or unsupported owners are reported per path and never fall back to deleting files".into() + } else if backend.is_available() { + format!( + "Enter moves the marks to {}, where they can be recovered \ + and their space comes back only once it is emptied; \ + permanent deletion is a choice away and always asks first", + backend.label() + ) + } else { + "This system has no trash, so Enter deletes the marks \ + permanently; tell the user that before they confirm" + .to_string() + }; + Ok(format!( + "The review screen is open in PwrDisk: {} marked. \ + The user decides there. {how}. Afterwards pwrdisk_status \ + reports what was actually freed.\n{}", + self.marks.len(), + self.plan_report() + )) + } + + // ── status ────────────────────────────────────────────────────────── + + /// Everything this session knows, in a screenful. + pub fn status(&mut self) -> String { + let now = now(); + let mut out = String::new(); + let _ = writeln!( + out, + "PwrDisk {} MCP server serving {}. Every removal requires user \ + confirmation of the exact paths and mode; never approve \ + through computer use.", + env!("CARGO_PKG_VERSION"), + self.client + ); + out.push_str(&system_line()); + out.push_str(retention_notice()); + out.push('\n'); + out.push_str(&self.window_line()); + out.push('\n'); + if self.scans.is_empty() { + if self.link.is_none() { + out.push_str( + "Scans: none yet. pwrdisk_scan with no arguments scans \ + the home directory in seconds; disk: true scans the \ + volume.\n", + ); + } + } else { + out.push_str(if self.link.is_some() { + "Scans held here, unused while the window is open:\n" + } else { + "Scans:\n" + }); + for scan in &self.scans { + let _ = writeln!( + out, + " {} {} \u{00b7} {} files \u{00b7} {} \u{00b7} took \ + {:.1} s", + self.show(&scan.root), + human_bytes(scan.tree.root().bytes), + human_count(scan.tree.root().files), + age(now, scan.at), + scan.elapsed.as_secs_f64(), + ); + } + } + if let Some(removal) = + self.window.as_ref().and_then(|state| state.removal.clone()) + { + for report in &removal.cleanup { + let _ = writeln!(out, "{}", report.description()); + } + let _ = writeln!( + out, + "Last removal: {} \u{00b7} {} {} \u{00b7} {} failed \ + \u{00b7} {} reported \u{00b7} {} observed volume change \u{00b7} {}", + removal.mode, + removal.removed, + if removal.mode == "owner_cleanup" { + "cleanup steps succeeded" + } else { + "removed" + }, + removal.failed, + human_bytes(removal.bytes), + crate::report::observed(removal.observed), + age(now, removal.at), + ); + } + if let Some(ledger) = self + .window + .as_ref() + .and_then(|state| state.removals.as_ref()) + { + out.push_str(&crate::report::ledger(ledger, now)); + } + if self.marks.is_empty() { + out.push_str("Marked: nothing.\n"); + } else { + let total: u64 = self.marks.iter().map(|mark| mark.bytes).sum(); + let _ = writeln!( + out, + "Marked: {} \u{00b7} {} (pwrdisk_mark with no new paths, or \ + pwrdisk_unmark, shows the plan)", + self.marks.len(), + human_bytes(total) + ); + } + out.push_str(&volumes_report()); + out + } +} + +/// Guarded offline plans, combined for reporting only. Removal still needs a +/// window. Drive/UNC roots stay separate: neither clones nor hardlinks cross +/// those namespaces, and there is no common path to attribute their meter to. +fn union_reports(plans: Vec) -> Vec { + let mut groups = std::collections::BTreeMap::>::new(); + for plan in plans { + let namespace = plan + .root + .ancestors() + .last() + .unwrap_or(&plan.root) + .to_path_buf(); + groups.entry(namespace).or_default().push(plan); + } + groups + .into_values() + .map(|mut plans| { + if plans.len() == 1 { + return plans.pop().expect("one plan"); + } + // Each path already passed guards against its own scanned root. + let mut common = plans[0].root.clone(); + for plan in &plans[1..] { + while !plan.root.starts_with(&common) && common.pop() {} + } + let targets: Vec<_> = plans + .iter() + .flat_map(|plan| plan.targets.iter().cloned()) + .collect(); + let mut union = plan(&targets, &common); + for plan in plans { + union.blocked.extend(plan.blocked); + union.covered.extend(plan.covered); + } + union + }) + .collect() +} + +fn version_notice(window: &State) -> String { + if window.app_version.is_empty() { + format!( + "GUI application version unavailable. {}\n", + disktree_link::RECONNECT_MCP + ) + } else if window.app_version != env!("CARGO_PKG_VERSION") { + format!( + "Release mismatch: MCP server {}; GUI {}. Link protocol {} is compatible, so the connection remains usable. {}\n", + env!("CARGO_PKG_VERSION"), + window.app_version, + VERSION, + disktree_link::RECONNECT_MCP, + ) + } else { + String::new() + } +} + +struct RankedCandidate { + value: Option, + estimate: disktree_core::planning::Report, +} + +fn rank_candidates( + reports: Vec, + by: RankBy, +) -> Vec { + let mut ranked: Vec<_> = reports + .into_iter() + .map(|estimate| { + let value = if estimate.accepted.is_empty() { + None + } else { + match by { + RankBy::Private => estimate + .private_allocation + .filter(|_| estimate.metadata_complete), + RankBy::ReclaimLower => { + estimate.reclaim.as_ref().map(|bounds| bounds.lower) + } + } + }; + RankedCandidate { value, estimate } + }) + .collect(); + ranked.sort_by_key(|candidate| std::cmp::Reverse(candidate.value)); + ranked +} + +const fn retention_notice() -> &'static str { + "Retention preflight: not performed by the scan or estimate. Before promising recovered space, use pwrdisk_retention for each selected volume on macOS and read the system skill reference. Snapshot presence is a retention risk, not proof of bytes held by these paths; absence does not rule out other snapshots or open files. Immediate recovered bytes are unknown, even for private allocation and reclaim lower bounds." +} + +fn estimate_report(estimate: &SelectionEstimate) -> String { + let mut out = format!( + "Selected-set reclaim estimate: {}–{}{}. Before snapshots, open files \ + and changes since the scan; actual freed space can be lower.\n", + human_bytes(estimate.lower), + estimate + .upper + .map_or_else(|| "unknown upper bound".into(), human_bytes), + if estimate.partial { + " (incomplete scan or metadata)" + } else { + "" + }, + ); + out.push_str(retention_notice()); + out.push('\n'); + // APFS reference counts include clones outside the scan, which can + // never be selected: say why the estimate is below the listed bytes. + if estimate.shared > 0 { + let _ = writeln!( + out, + "{} of the selection is APFS clone blocks. They count only when \ + every clone of them is selected; a clone left unselected, or \ + outside this scan, keeps them.", + human_bytes(estimate.shared) + ); + } + out +} + +/// Every volume a person would call a disk, fullest first. +fn volumes_report() -> String { + let mut out = String::new(); + let volumes: Vec<_> = volumes().into_iter().filter(worth_listing).collect(); + if volumes.is_empty() { + return out; + } + out.push_str("Volumes, fullest first:\n"); + for volume in volumes.iter().take(8) { + match volume.space { + Some(space) => { + let _ = writeln!( + out, + " {} {} free of {} ({:.0}% used){}", + volume.point.display(), + human_bytes(space.available), + human_bytes(space.total), + f64::from(space.used_fraction()) * 100.0, + volume + .device + .as_deref() + .map_or_else(String::new, |device| format!( + " {device}" + )), + ); + } + None => { + let _ = writeln!( + out, + " {} free space unknown", + volume.point.display() + ); + } + } + } + out +} + +/// Whether a volume is one a person would call a disk: the system's own +/// slices, device files, simulator images and automount stubs are left +/// out, as is anything under a gigabyte. +fn worth_listing(volume: &disktree_core::space::Volume) -> bool { + const GIB: u64 = 1024 * 1024 * 1024; + let point = volume.point.to_string_lossy(); + let system = [ + "/System/Volumes/", + "/private/", + "/dev", + "/Library/Developer/CoreSimulator/", + "/proc", + "/sys", + "/run", + "/boot/efi", + "/snap/", + ] + .iter() + .any(|prefix| point.starts_with(prefix)); + !system + && volume + .device + .as_deref() + .is_none_or(|device| !device.starts_with("map ")) + && volume.space.is_some_and(|space| space.total >= GIB) +} + +/// Where a path landed in a scan held here. +struct Located<'a> { + scan: &'a Scan, + path: PathBuf, + crumbs: Vec, + node: Node<'a>, +} + +/// What a scan report is made of, whichever side did the walking. +struct ScanFacts { + root: PathBuf, + tree: TreeSummary, + space: Option, + device: Option, + top: Listing, + insights: Vec, +} + +impl ScanFacts { + fn of_local(scan: &Scan) -> Self { + Self { + root: scan.root.clone(), + tree: TreeSummary { + bytes: scan.tree.root().bytes, + files: scan.tree.root().files, + dirs: u64::from(scan.tree.root().dirs), + scanned_at: scan.at, + elapsed_ms: u64::try_from(scan.elapsed.as_millis()) + .unwrap_or(u64::MAX), + unreadable: scan.unreadable, + apparent_size: scan.options.apparent_size, + include_hidden: scan.options.include_hidden, + }, + space: scan.space.map(|space| Space { + total: space.total, + free: space.free, + available: space.available, + }), + device: scan.device.clone(), + top: Listing::of( + &scan.root, + scan.tree.root().bytes, + &scan.root, + scan.tree.root(), + TOP, + ), + insights: scan + .insights + .iter() + .map(|candidate| Insight { + path: path_of( + &scan.root, + scan.tree.root(), + &candidate.crumbs, + disktree_core::path_style::PathStyle::Native, + ), + bytes: candidate.bytes, + what: candidate.finding.describe(), + }) + .collect(), + } + } +} + +/// A dotfile or dot-directory by name. +fn is_hidden(path: &Path) -> bool { + path.file_name() + .is_some_and(|name| name.to_string_lossy().starts_with('.')) +} + +/// An answer of a shape the request does not take: an old window. +fn unexpected(response: &Response) -> String { + format!( + "the window answered with something unexpected ({}). {}", + match response { + Response::State(_) => "state", + Response::Marked { .. } => "marked", + Response::Listing(_) => "listing", + Response::Found(_) => "found", + Response::Estimate(_) => "estimate", + Response::RemovalPreview(_) => "removal_preview", + Response::Ok => "ok", + Response::Error { .. } => "error", + }, + disktree_link::RECONNECT_MCP, + ) +} + +/// Walk `root` with `options` and keep what is needed later. Blocking; +/// the server runs it off the protocol thread. +pub fn run_scan(root: PathBuf, options: ScanOptions) -> Result { + let started = Instant::now(); + let handle = ScanHandle::spawn(root.clone(), options.clone()); + let outcome = loop { + if let Some(outcome) = handle.poll() { + break outcome; + } + std::thread::sleep(Duration::from_millis(50)); + }; + let tree = outcome.map_err(|error| { + format!("scan of {} failed: {error}", root.display()) + })?; + let snapshot = handle.progress.snapshot(); + let at = now(); + let insights = worth_a_look(tree.root(), at, INSIGHTS); + Ok(Scan { + space: space_info(&root).ok(), + device: device_for(&root), + root, + tree: Arc::new(tree), + options, + at, + elapsed: started.elapsed(), + unreadable: snapshot.errors, + insights, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use disktree_core::tree::Draft; + #[cfg(any(unix, windows))] + use disktree_link::{Incoming, Listener, Mark, Refused, Removal}; + #[cfg(any(unix, windows))] + use std::sync::Mutex; + #[cfg(any(unix, windows))] + use std::sync::atomic::{AtomicBool, Ordering}; + #[cfg(any(unix, windows))] + use std::thread; + + fn endpoint(dir: &Path) -> PathBuf { + #[cfg(windows)] + { + PathBuf::from(format!( + r"\\.\pipe\pwrdisk-test-{}", + dir.file_name().expect("temp name").to_string_lossy() + )) + } + #[cfg(not(windows))] + { + dir.join("window.sock") + } + } + + /// A small tree on disk: a cache, a build directory, a checkout with a + /// large file, and a stray download. + fn fixture() -> tempfile::TempDir { + let temp = tempfile::TempDir::new().expect("tempdir"); + for (path, bytes) in [ + (".cache/pip/blob.bin", 400_000_usize), + ("src/app/target/debug/app", 300_000), + ("src/app/Cargo.toml", 100), + ("src/app/main.rs", 2_000), + ("Downloads/image.iso", 250_000), + ("notes/todo.txt", 500), + ] { + let file = temp.path().join(path); + std::fs::create_dir_all(file.parent().expect("parent")) + .expect("mkdir"); + std::fs::write(&file, vec![b'x'; bytes]).expect("write"); + } + temp + } + + /// Apparent sizes, so the numbers are the bytes written, not blocks. + #[cfg(any(unix, windows))] + fn apparent() -> ScanOptions { + ScanOptions { + apparent_size: true, + ..ScanOptions::default() + } + } + + /// Scan here, as the server does when no window is open. + fn scanned(session: &mut Session, root: &Path) -> String { + let plan = session + .prepare_scan(&ScanParams { + path: Some(root.to_path_buf()), + apparent_size: true, + ..ScanParams::default() + }) + .expect("prepare"); + let ScanPlan::Local { root, options } = plan else { + panic!("no window, so the scan runs here: {plan:?}"); + }; + let scan = run_scan(root, options).expect("scan"); + session.store_scan(scan) + } + + fn unlinked(dir: &Path) -> Session { + Session::detached(endpoint(dir), None) + } + + fn worktrees(root: &Path) -> Scan { + use disktree_core::sharing::{Allocation, CloneInfo}; + use disktree_core::tree::{Metric, NodeKind, aggregate}; + const MIB: u64 = 1024 * 1024; + let mut tree = Draft::directory("fixture"); + for index in 0..11 { + let name = format!("worktree-{index:02}"); + std::fs::create_dir(root.join(&name)).expect("fixture directory"); + let mut dir = Draft::directory(name); + let bytes = 10 * 1024 * MIB - 50 * MIB; + let mut clone = Draft::entry("shared", NodeKind::File, bytes); + clone.allocation = Some(Box::new(Allocation { + bytes, + identity: None, + links: 1, + followed: false, + clone: Some(CloneInfo { + device: 1, + id: 42, + references: 11, + private_bytes: Some(0), + data_bytes: bytes, + }), + })); + dir.children.push(clone); + dir.children.push(Draft::entry( + "private", + NodeKind::File, + 50 * MIB, + )); + tree.children.push(dir); + } + let mut tree = Tree::from(tree); + aggregate(&mut tree, Metric::Bytes); + Scan { + root: root.into(), + tree: Arc::new(tree), + options: ScanOptions::default(), + at: now(), + elapsed: Duration::ZERO, + unreadable: 0, + space: None, + device: None, + insights: vec![], + } + } + + #[test] + #[cfg(windows)] + fn offline_reports_keep_distinct_windows_drives_separate() { + let mut first = Plan::default(); + first.root = r"C:\fixture".into(); + let mut second = Plan::default(); + second.root = r"D:\fixture".into(); + let reports = union_reports(vec![first, second]); + assert_eq!(reports.len(), 2); + assert_eq!(reports[0].root, Path::new(r"C:\fixture")); + assert_eq!(reports[1].root, Path::new(r"D:\fixture")); + } + + #[test] + fn standalone_union_completes_groups_across_separate_scan_roots() { + let temp = tempfile::tempdir_in(std::env::current_dir().expect("cwd")) + .expect("fixture"); + let root = temp.path().canonicalize().expect("root"); + let scan = worktrees(&root); + let mut session = unlinked(&root); + let mut paths = Vec::new(); + for node in scan.tree.root().children() { + let root = root.join(node.name()); + std::fs::write(root.join("shared"), b"synthetic allocation") + .expect("fixture volume identity"); + paths.push(root.join("shared")); + session.store_scan(Scan { + root, + tree: Arc::new(Tree::copy_of(node)), + options: ScanOptions::default(), + at: now(), + elapsed: Duration::ZERO, + unreadable: 0, + space: None, + device: None, + insights: vec![], + }); + } + let report = session + .mark(&PathsParams { paths }) + .expect("mark across scans"); + let bytes = 10 * 1024 * 1024 * 1024 - 50 * 1024 * 1024; + let range = format!("{}–{}", human_bytes(bytes), human_bytes(bytes)); + assert!(report.contains(&range), "{report}"); + assert_eq!(report.matches("Selected-set reclaim estimate:").count(), 1); + assert!( + report.contains(&format!("Projects {}", human_bytes(bytes))), + "{report}" + ); + } + + #[test] + fn standalone_plan_projects_the_selected_union_and_reports_unknown_marks() { + let temp = tempfile::tempdir_in(std::env::current_dir().expect("cwd")) + .expect("fixture"); + let root = temp.path().canonicalize().expect("root"); + let scan = worktrees(&root); + let paths: Vec<_> = scan + .tree + .root() + .children() + .iter() + .take(10) + .map(|node| root.join(node.name())) + .collect(); + let mut session = unlinked(&root); + session.store_scan(scan); + let report = session.mark(&PathsParams { paths }).expect("mark"); + assert!(report.contains("100 GiB"), "{report}"); + assert!(report.contains("500 MiB–500 MiB"), "{report}"); + assert!(report.contains("Projects 500 MiB"), "{report}"); + assert!(!report.contains("Projects 100 GiB"), "{report}"); + assert!(report.contains("snapshots"), "{report}"); + let mut unknown = plan( + &[Target { + path: root.join("missing"), + bytes: 123, + is_dir: false, + hidden: false, + }], + &root, + ); + let estimate = session.selection_estimate(&mut unknown); + assert_eq!( + (estimate.lower, estimate.upper, estimate.on_volume), + (0, Some(123), 0) + ); + assert!(estimate.partial); + session.scans[0].options.apparent_size = true; + let mut unmeasured = plan(session.marks(), &root); + let estimate = session.selection_estimate(&mut unmeasured); + assert_eq!(estimate.lower, 0); + assert_eq!(estimate.on_volume, 0); + assert_eq!(estimate.upper, None); + assert!(estimate.partial); + } + + #[test] + fn a_scan_reports_totals_the_top_level_and_findings() { + let temp = fixture(); + let mut session = unlinked(temp.path()); + let report = scanned(&mut session, temp.path()); + assert!(report.starts_with("Scanned "), "{report}"); + assert!(report.contains("6 files"), "{report}"); + assert!(report.contains(".cache/"), "{report}"); + assert!(report.contains("Top level, largest first:"), "{report}"); + assert!(report.contains("Next: pwrdisk_ls"), "{report}"); + assert_eq!(session.scans().len(), 1); + // Scanning again replaces, not duplicates. + scanned(&mut session, temp.path()); + assert_eq!(session.scans().len(), 1); + } + + #[test] + fn ls_needs_a_scan_and_then_lists_largest_first() { + let temp = fixture(); + let mut session = unlinked(temp.path()); + let missing = session + .ls(&LsParams { + path: temp.path().join("src"), + ..LsParams::default() + }) + .expect_err("nothing scanned"); + assert!(missing.contains("pwrdisk_scan"), "{missing}"); + + scanned(&mut session, temp.path()); + let listing = session + .ls(&LsParams { + path: temp.path().to_path_buf(), + limit: Some(2), + show: false, + }) + .expect("ls"); + let lines: Vec<&str> = listing.lines().collect(); + // Header, then .cache (400k), src (302.1k), then the rest. + assert!(lines[1].contains(".cache/"), "{listing}"); + assert!(lines[2].contains("src/"), "{listing}"); + assert!(lines[3].contains("2 more"), "{listing}"); + + let outside = session + .ls(&LsParams { + path: PathBuf::from("/definitely/elsewhere"), + ..LsParams::default() + }) + .expect_err("outside"); + assert!(outside.contains("outside the scanned roots"), "{outside}"); + } + + #[test] + fn find_filters_by_kind_size_name_and_reclaim() { + let temp = fixture(); + let mut session = unlinked(temp.path()); + scanned(&mut session, temp.path()); + + let files = session + .find(&FindParams { + kind: Some(KindName::File), + min_bytes: Some(200_000), + ..FindParams::default() + }) + .expect("find"); + assert!(files.contains("blob.bin"), "{files}"); + assert!(files.contains("image.iso"), "{files}"); + let app_path = Path::new("debug").join("app"); + assert!(files.contains(&app_path.display().to_string()), "{files}"); + assert!(!files.contains("todo.txt"), "{files}"); + + let reclaim = session + .find(&FindParams { + reclaimable: true, + ..FindParams::default() + }) + .expect("find"); + // A manifest does not make a standalone profile binary disposable. + // Keep the topmost cache once, without its contents. + assert!(reclaim.contains(".cache/"), "{reclaim}"); + assert!(!reclaim.contains("target/"), "{reclaim}"); + assert!(!reclaim.contains("blob.bin"), "{reclaim}"); + + let named = session + .find(&FindParams { + name: Some("ISO".into()), + ..FindParams::default() + }) + .expect("find"); + assert!(named.starts_with("1 match "), "{named}"); + + let none = session + .find(&FindParams { + name: Some("nothing-here".into()), + ..FindParams::default() + }) + .expect("find"); + assert!(none.contains("Nothing"), "{none}"); + } + + /// A scan inside another one is not searched twice. + #[test] + fn find_counts_nested_scans_once() { + let temp = fixture(); + let mut session = unlinked(temp.path()); + scanned(&mut session, temp.path()); + scanned(&mut session, &temp.path().join("src")); + let found = session + .find(&FindParams { + name: Some("main.rs".into()), + ..FindParams::default() + }) + .expect("find"); + assert!(found.starts_with("1 match "), "{found}"); + } + + #[test] + fn marks_are_planned_with_the_guards_and_without_a_window() { + let temp = fixture(); + let mut session = unlinked(temp.path()); + scanned(&mut session, temp.path()); + + let root_refused = session + .mark(&PathsParams { + paths: vec![temp.path().to_path_buf()], + }) + .expect_err("the root alone"); + assert!(root_refused.contains("scanned root"), "{root_refused}"); + // With a good path beside it, the root is reported and the rest + // is marked. + let partial = session + .mark(&PathsParams { + paths: vec![ + temp.path().to_path_buf(), + temp.path().join("notes"), + ], + }) + .expect("one of two"); + assert!(partial.starts_with("Not marked:"), "{partial}"); + assert!(partial.contains("Marked 1"), "{partial}"); + session + .unmark(&PathsParams { paths: vec![] }) + .expect("clear"); + + let plan = session + .mark(&PathsParams { + paths: vec![ + temp.path().join(".cache"), + temp.path().join("src/app/target"), + // Inside the first mark: covered, not counted twice. + temp.path().join(".cache/pip"), + ], + }) + .expect("mark"); + assert!(plan.starts_with("Marked 3"), "{plan}"); + assert!(plan.contains("Covered by another mark (1)"), "{plan}"); + assert!(plan.contains("Selected-set reclaim estimate:"), "{plan}"); + assert!( + plan.contains(if disktree_link::SUPPORTED { + "Window: none open, and none can be opened" + } else { + "Window: no link on this system yet" + }), + "{plan}" + ); + assert_eq!(session.marks().len(), 3); + + let fewer = session + .unmark(&PathsParams { + paths: vec![temp.path().join(".cache/pip")], + }) + .expect("unmark"); + assert!(fewer.starts_with("Marked 2"), "{fewer}"); + let none = session + .unmark(&PathsParams { paths: vec![] }) + .expect("unmark all"); + assert!(none.starts_with("Nothing is marked."), "{none}"); + + let review = session.review().expect_err("nothing to review"); + assert!(review.contains("Nothing is marked"), "{review}"); + } + + fn estimate_json(text: &str) -> disktree_core::planning::Report { + let (_, json) = text.split_once('\n').expect("JSON after introduction"); + serde_json::Deserializer::from_str(json) + .into_iter() + .next() + .expect("report") + .expect("valid report") + } + + #[test] + fn ranking_prefers_private_data_to_large_clones_and_keeps_unknown_last() { + use disktree_core::planning::{self, Context}; + let temp = tempfile::tempdir_in(std::env::current_dir().expect("cwd")) + .expect("fixture"); + let root = temp.path().canonicalize().expect("root"); + let scan = clone_copies_with_plain(&root, 3, 6 * 1024 * 1024); + let mut context = Context::of(&root, &scan.options, scan.at, 0); + // Synthetic clone metadata on every test host; no real clone probe. + context.clone_metadata = true; + let estimate = |name: &str| { + planning::estimate( + &scan.tree, + context.clone(), + &[root.join(name)], + None, + 0, + ) + .expect("estimate") + }; + let clone = estimate("copy-a"); + let plain = estimate("plain"); + assert!(clone.listed_bytes > plain.listed_bytes); + let mut unknown = clone.clone(); + unknown.private_allocation = None; + unknown.reclaim = None; + let mut incomplete = clone.clone(); + incomplete.metadata_complete = false; + for by in [RankBy::Private, RankBy::ReclaimLower] { + let ranked = rank_candidates( + vec![unknown.clone(), clone.clone(), plain.clone()], + by, + ); + assert!(ranked[0].value.expect("plain") > 0); + assert_eq!(ranked[0].estimate.accepted, [root.join("plain")]); + assert_eq!(ranked[1].value, Some(0), "known clone zero"); + assert_eq!(ranked[2].value, None, "unknown is not zero"); + } + assert_eq!( + rank_candidates(vec![incomplete], RankBy::Private)[0].value, + None + ); + let union = + planning::estimate(&scan.tree, context, &copies(&root), None, 0) + .expect("union"); + assert!( + union.reclaim.expect("union bounds").lower + > clone.reclaim.expect("alone bounds").upper + ); + } + + /// Proposals inform; only a preview of the person's decisions can be + /// confirmed, and only by its own phrase, which names deleting files. + #[test] + fn cache_proposals_cannot_be_confirmed_until_every_path_is_decided() { + use disktree_core::cleanup::{ + DELETE_CACHE_FILES, Decision, Issue, Problem, Proposal, + RUN_OWNER_CLEANUP, + }; + let temp = fixture(); + let mut session = unlinked(temp.path()); + let path = temp.path().join("Downloads"); + let undecided = RemovalPreview { + preview_id: String::new(), + root: temp.path().to_path_buf(), + mode: RemovalChoice::OwnerCleanup, + paths: vec![], + bytes: 0, + estimate: disktree_link::SelectionEstimate::unknown( + &disktree_core::removal::Plan::default(), + ), + limit_percent: 5, + volumes: vec![], + expires_in_seconds: 300, + cleanup: vec![], + proposals: vec![Proposal { + selected: path.clone(), + bytes: 7, + is_dir: true, + hint: Some("cache".into()), + owner: None, + operations: vec![], + issue: Some(Issue::new(Problem::UnknownOwner, "no owner")), + delete: None, + delete_issue: None, + }], + decisions: vec![], + files: None, + confirmation: String::new(), + consent: "1. proposal".into(), + }; + let text = session.cleanup_preview_text(&undecided); + assert!(text.contains("Nothing is approved"), "{text}"); + assert!(text.contains("Never suggest delete_files yourself")); + assert!(session.pending_removal.is_none(), "nothing to confirm"); + + let decided = RemovalPreview { + preview_id: "decided".into(), + paths: vec![path.clone()], + decisions: vec![Decision::DeleteFiles], + files: Some(RemovalChoice::Permanent), + confirmation: DELETE_CACHE_FILES.into(), + consent: "Delete files directly, not through their owner (1)" + .into(), + ..undecided + }; + let text = session.cleanup_preview_text(&decided); + assert!(text.contains(DELETE_CACHE_FILES)); + assert!( + text.contains("Owner approval is not approval to delete files") + ); + let owner_only = RemoveParams { + preview_id: "decided".into(), + mode: RemovalModeName::OwnerCleanup, + paths: vec![path], + confirmation: RUN_OWNER_CLEANUP.into(), + rescan: false, + }; + assert!( + session.removal_confirmation_message(&owner_only).is_err(), + "owner approval does not confirm deleting files" + ); + session.cleanup_preview_text(&decided); + let message = session + .removal_confirmation_message(&RemoveParams { + confirmation: DELETE_CACHE_FILES.into(), + ..owner_only + }) + .expect("exact phrase"); + assert!(message.contains("Delete files directly")); + + let params: RemovalPreviewParams = + serde_json::from_value(serde_json::json!({ + "mode": "owner_cleanup", + "decisions": [{"path": "/x", "action": "delete_files"}], + "delete_files_mode": "permanent" + })) + .expect("decisions parse"); + assert_eq!( + params.decisions.expect("one")[0].action, + CleanupActionName::DeleteFiles + ); + } + + #[test] + fn ranking_is_read_only_and_apparent_measurements_are_unavailable() { + let temp = fixture(); + let mut session = unlinked(temp.path()); + scanned(&mut session, temp.path()); + let before = session.marks.clone(); + let text = session + .rank(&RankParams { + paths: vec![ + temp.path().join("Downloads"), + temp.path().join("notes"), + ], + by: RankBy::Private, + }) + .expect("rank"); + let (_, json) = text.split_once('\n').expect("JSON"); + let value: serde_json::Value = serde_json::Deserializer::from_str(json) + .into_iter() + .next() + .expect("value") + .expect("JSON"); + assert!(value["candidates"][0]["value"].is_null()); + assert!( + value["selection_union"]["context"]["apparent_size"] + .as_bool() + .expect("mode") + ); + assert_eq!(session.marks, before); + assert!(session.pending_removal.is_none()); + assert!( + session + .rank(&RankParams { + paths: vec![], + by: RankBy::Private + }) + .is_err() + ); + } + + #[test] + fn hypothetical_selection_preserves_the_offline_cart_and_scan() { + let temp = fixture(); + let mut session = unlinked(temp.path()); + scanned(&mut session, temp.path()); + let kept = Target { + path: temp.path().join("notes"), + bytes: 123, + is_dir: true, + hidden: false, + }; + session.marks.push(kept.clone()); + let root = session.scans[0].root.clone(); + let at = session.scans[0].at; + let text = session + .estimate_paths(&EstimateParams { + paths: vec![ + temp.path().join("Downloads"), + temp.path().join("Downloads"), + ], + ..EstimateParams::default() + }) + .expect("estimate"); + let report = estimate_json(&text); + assert_eq!(report.accepted, [temp.path().join("Downloads")]); + assert_eq!(report.covered.len(), 1); + assert!(report.reclaim.is_none(), "apparent fixture"); + assert_eq!(session.marks(), [kept]); + assert_eq!(session.scans.len(), 1); + assert_eq!(session.scans[0].root, root); + assert_eq!(session.scans[0].at, at); + assert!(session.link.is_none()); + } + + #[cfg(any(unix, windows))] + #[test] + fn hypothetical_selection_reads_the_window_without_greeting_or_handover() { + let temp = fixture(); + let socket = endpoint(temp.path()); + let window_root = temp.path().join("src"); + let mut session = Session::detached(socket.clone(), None); + // A stale, broader local tree and offline cart must not be adopted. + scanned(&mut session, temp.path()); + let window = FakeWindow::open(&socket, &window_root); + let kept = Target { + path: temp.path().join("Downloads"), + bytes: 1, + is_dir: true, + hidden: false, + }; + session.marks.push(kept.clone()); + let text = session + .estimate_paths(&EstimateParams { + paths: vec![ + window_root.join("app"), + temp.path().join("Downloads"), + ], + ..EstimateParams::default() + }) + .expect("window estimate"); + let report = estimate_json(&text); + assert_eq!(report.context.root, window_root); + assert_eq!(report.accepted.len(), 1); + assert_eq!(report.refused.len(), 1); + assert_eq!(session.marks(), [kept]); + assert!(window.marks().is_empty()); + assert!(session.link.is_none()); + assert!(session.window.is_none()); + assert!(matches!( + window.asked().as_slice(), + [Request::State, Request::Estimate { .. }] + )); + } + + #[cfg(any(unix, windows))] + #[test] + fn hypothetical_selection_refuses_remote_or_old_peers_without_local_fallback() + { + for remote in [true, false] { + let temp = fixture(); + let scan = + run_scan(temp.path().to_path_buf(), apparent()).expect("scan"); + let socket = endpoint(temp.path()); + let window = FakeWindow::with_tree( + &socket, + FakeTree { + protocol: if remote { VERSION } else { VERSION - 1 }, + root: scan.root.clone(), + tree: Arc::clone(&scan.tree), + marks: vec![], + remote: remote.then(|| "contrived-host".into()), + busy: false, + options: scan.options.clone(), + unreadable: 0, + removed: Vec::new(), + }, + ); + let mut session = Session::detached(socket, None); + session.store_scan(scan); + let error = session + .estimate_paths(&EstimateParams { + paths: vec![temp.path().join("Downloads")], + ..EstimateParams::default() + }) + .expect_err("cannot substitute local tree"); + assert!( + error.contains(if remote { + "SSH host" + } else { + "restart/reconnect" + }), + "{error}" + ); + assert!(matches!(window.asked().as_slice(), [Request::State])); + } + } + + /// A stand-in for the window: holds a real tree of the fixture, answers + /// over the real socket the way the app does, and records what it was + /// asked. + #[cfg(any(unix, windows))] + struct FakeWindow { + listener: Arc, + asked: Arc>>, + marks: Arc>>, + stop: Arc, + } + + #[cfg(any(unix, windows))] + struct FakeTree { + protocol: u32, + root: PathBuf, + tree: Arc, + marks: Vec, + /// The SSH host the window shows, as a window on one answers. + remote: Option, + /// A removal is running: marks are refused, as the app does. + busy: bool, + options: ScanOptions, + unreadable: u64, + /// What a removal since the scan took, with its scanned bytes: the + /// window keeps it in the tree and flags it, as the app does. + removed: Vec<(PathBuf, u64)>, + } + + #[cfg(any(unix, windows))] + impl FakeTree { + fn note_removal(&self, entry: &mut disktree_link::Entry, path: &Path) { + entry.removed = + self.removed.iter().any(|(gone, _)| path.starts_with(gone)); + if !entry.removed { + entry.removed_bytes = self + .removed + .iter() + .filter(|(gone, _)| gone.starts_with(path)) + .map(|(_, bytes)| bytes) + .sum(); + } + } + + fn state(&self, screen: &str) -> State { + let targets: Vec<_> = self + .marks + .iter() + .map(|mark| Target { + path: mark.path.clone(), + bytes: mark.bytes, + is_dir: mark.is_dir, + hidden: false, + }) + .collect(); + let mut plan = plan(&targets, &self.root); + plan.estimate_selection(|targets| { + sharing::estimate(targets.iter().filter_map(|target| { + target + .path + .strip_prefix(&self.root) + .ok() + .and_then(|relative| self.tree.root().descend(relative)) + .map(|(_, node)| node) + })) + }); + State { + version: self.protocol, + app_version: "0.13.0".into(), + root: self.root.clone(), + current: self.root.clone(), + screen: screen.into(), + scanning: false, + scanned: true, + estimate: Some(SelectionEstimate::of(&plan)), + marks: self.marks.clone(), + space: None, + removal_operation: None, + removal: Some(Removal { + mode: "trash".into(), + removed: 2, + failed: 0, + bytes: 700_000, + freed: Some(0), + observed: Some(-28_311_552), + at: now() - 120, + cleanup: vec![], + }), + removals: Some(disktree_link::RemovalLedger { + cohorts: vec![disktree_link::RemovalCohort { + mode: "trash".into(), + removed: 2, + failed: 0, + reported: 700_000, + private: Some(650_000), + observed: Some(-28_311_552), + started: now() - 125, + finished: now() - 120, + }], + reported: 700_000, + private: Some(650_000), + observed: Some(-28_311_552), + }), + tree: Some(TreeSummary { + bytes: self.tree.root().bytes, + files: self.tree.root().files, + dirs: u64::from(self.tree.root().dirs), + scanned_at: now() - 30, + elapsed_ms: 1_500, + unreadable: self.unreadable, + apparent_size: self.options.apparent_size, + include_hidden: self.options.include_hidden, + }), + insights: vec![Insight { + path: self.root.join(".cache"), + bytes: 400_000, + what: "reclaimable: cache".into(), + }], + remote: self.remote.clone(), + } + } + + fn answer(&mut self, request: &Request) -> Response { + if let Some(host) = &self.remote + && !matches!(request, Request::Hello { .. } | Request::State) + { + return Response::error(disktree_link::remote_refusal(host)); + } + if self.busy && matches!(request, Request::Mark { .. }) { + return Response::error("a removal is running"); + } + match request { + Request::Hello { .. } | Request::State => { + Response::State(self.state("explore")) + } + Request::Scan { root, .. } => { + self.tree = Arc::new( + disktree_core::scan::scan(root, apparent()) + .expect("scan"), + ); + self.root.clone_from(root); + Response::State(self.state("explore")) + } + Request::Ls { path, limit } => { + let Some((_, node)) = + path.strip_prefix(&self.root).ok().and_then( + |relative| self.tree.root().descend(relative), + ) + else { + return Response::error("not in the window's tree"); + }; + let mut listing = Listing::of( + &self.root, + self.tree.root().bytes, + path, + node, + *limit, + ); + self.note_removal(&mut listing.entry, path); + for child in &mut listing.children { + self.note_removal(child, &path.join(&child.name)); + } + Response::Listing(listing) + } + Request::Find(request) => { + let filter = match request.filter() { + Ok(filter) => filter, + Err(message) => return Response::error(message), + }; + let found = query::find( + &self.root, + self.tree.root(), + &filter, + request.limit, + ); + let mut found = FoundList::of(&found); + for item in &mut found.matches { + self.note_removal(&mut item.entry, &item.path); + } + Response::Found(found) + } + Request::Estimate { + paths, + peer_scope, + peer_limit, + } => { + let context = disktree_core::planning::Context::of( + &self.root, + &self.options, + 1, + self.unreadable, + ); + match disktree_core::planning::estimate( + &self.tree, + context, + paths, + peer_scope.as_deref(), + *peer_limit, + ) { + Ok(report) => Response::Estimate(report), + Err(message) => Response::error(message), + } + } + Request::Mark { targets, .. } => { + let mut refused = Vec::new(); + for target in targets { + let node = + target.path.strip_prefix(&self.root).ok().and_then( + |relative| self.tree.root().descend(relative), + ); + let Some((_, node)) = node else { + refused.push(Refused { + path: target.path.clone(), + reason: "not in the window's tree".into(), + }); + continue; + }; + if !self.marks.iter().any(|m| m.path == target.path) { + self.marks.push(Mark { + path: target.path.clone(), + bytes: node.bytes, + is_dir: node.is_dir(), + }); + } + } + Response::Marked { + state: self.state("explore"), + refused, + } + } + Request::Unmark { paths } if paths.is_empty() => { + self.marks.clear(); + Response::State(self.state("explore")) + } + Request::Unmark { paths } => { + self.marks.retain(|mark| !paths.contains(&mark.path)); + Response::State(self.state("explore")) + } + Request::Show { .. } | Request::Review => Response::Ok, + Request::PrepareRemoval { .. } | Request::Remove(_) => { + Response::error( + "removal is unavailable in the stand-in window", + ) + } + } + } + } + + #[cfg(any(unix, windows))] + impl FakeWindow { + fn open(socket: &Path, root: &Path) -> Self { + Self::showing(socket, root, None) + } + + /// A window showing `remote`, an SSH host, rather than this + /// computer. + fn showing(socket: &Path, root: &Path, remote: Option<&str>) -> Self { + Self::serving(socket, root, remote, false) + } + + /// A window in the middle of a removal, refusing new marks. + fn removing(socket: &Path, root: &Path) -> Self { + Self::serving(socket, root, None, true) + } + + fn serving( + socket: &Path, + root: &Path, + remote: Option<&str>, + busy: bool, + ) -> Self { + let fake = FakeTree { + protocol: VERSION, + root: root.to_path_buf(), + tree: Arc::new( + disktree_core::scan::scan(root, apparent()).expect("scan"), + ), + marks: Vec::new(), + remote: remote.map(str::to_owned), + busy, + options: apparent(), + unreadable: 0, + removed: Vec::new(), + }; + Self::with_tree(socket, fake) + } + + fn with_tree(socket: &Path, mut fake: FakeTree) -> Self { + let listener = Arc::new(Listener::bind_at(socket).expect("bind")); + let asked = Arc::new(Mutex::new(Vec::new())); + let marks: Arc>> = Arc::new(Mutex::new(Vec::new())); + let stop = Arc::new(AtomicBool::new(false)); + let (l, a, m, s) = ( + Arc::clone(&listener), + Arc::clone(&asked), + Arc::clone(&marks), + Arc::clone(&stop), + ); + thread::spawn(move || { + while !s.load(Ordering::Relaxed) { + for incoming in l.drain() { + if let Incoming::Request { request, reply, .. } = + incoming + { + a.lock().expect("asked").push(request.clone()); + let response = fake.answer(&request); + m.lock().expect("marks").clone_from(&fake.marks); + reply.send(response); + } + } + thread::sleep(Duration::from_millis(5)); + } + }); + Self { + listener, + asked, + marks, + stop, + } + } + + fn asked(&self) -> Vec { + self.asked.lock().expect("asked").clone() + } + + fn marks(&self) -> Vec { + self.marks.lock().expect("marks").clone() + } + } + + #[cfg(any(unix, windows))] + impl Drop for FakeWindow { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + let _ = &self.listener; + } + } + + #[cfg(any(unix, windows))] + #[test] + fn linked_plan_uses_window_union_even_with_a_conflicting_local_scan() { + let temp = tempfile::tempdir_in(std::env::current_dir().expect("cwd")) + .expect("fixture"); + let root = temp.path().canonicalize().expect("root"); + let scan = worktrees(&root); + let socket_dir = tempfile::tempdir().expect("socket fixture"); + let socket = endpoint(socket_dir.path()); + let _window = FakeWindow::with_tree( + &socket, + FakeTree { + protocol: VERSION, + root: root.clone(), + tree: Arc::clone(&scan.tree), + marks: vec![], + remote: None, + busy: false, + options: ScanOptions::default(), + unreadable: 0, + removed: Vec::new(), + }, + ); + let paths: Vec<_> = scan + .tree + .root() + .children() + .iter() + .take(10) + .map(|node| root.join(node.name())) + .collect(); + let mut session = Session::detached(socket, None); + // The agent's old scan has no sharing facts; the window owns truth. + let mut stale = scan; + let mut draft = stale.tree.root().to_draft(); + for dir in &mut draft.children { + dir.children[0].allocation = None; + } + let mut tree = Tree::from(draft); + disktree_core::tree::aggregate( + &mut tree, + disktree_core::tree::Metric::Bytes, + ); + stale.tree = Arc::new(tree); + session.store_scan(stale); + let report = session.mark(&PathsParams { paths }).expect("linked mark"); + assert!(report.contains("500 MiB–500 MiB"), "{report}"); + assert!(report.contains("Projects 500 MiB"), "{report}"); + let status = session.status(); + assert!(status.contains("0.13.0"), "{status}"); + assert!(status.contains("Release mismatch:"), "{status}"); + assert!(status.contains("connection remains usable"), "{status}"); + assert!(status.contains("restart/reconnect"), "{status}"); + assert!( + status.contains(concat!(env!("CARGO_PKG_VERSION"), " MCP server")), + "{status}" + ); + let review = session.review().expect("review"); + assert!(review.contains("500 MiB–500 MiB"), "{review}"); + assert!(!review.contains("100 GiB to free"), "{review}"); + + // Incomplete, missing or mismatched link state never falls back to + // the raw allocation or the agent's conflicting local scan. + for failure in ["scanning", "missing", "changed"] { + let window = session.window.as_mut().expect("window"); + match failure { + "scanning" => window.scanning = true, + "missing" => { + window.scanning = false; + window.estimate = None; + } + _ => { + window.estimate = Some(SelectionEstimate { + paths: vec![], + lower: u64::MAX, + upper: Some(u64::MAX), + on_volume: u64::MAX, + partial: false, + shared: 0, + }); + } + } + let mut plan = plan(session.marks(), &root); + let estimate = session.selection_estimate(&mut plan); + assert_eq!(estimate.on_volume, 0, "{failure}"); + assert_eq!(estimate.lower, 0, "{failure}"); + assert!(estimate.partial, "{failure}"); + } + let mut wire = + serde_json::to_value(session.window.as_ref().expect("window")) + .expect("state JSON"); + let fields = wire.as_object_mut().expect("object"); + fields.remove("app_version"); + fields.remove("estimate"); + let mut state: State = + serde_json::from_value(wire).expect("optional metadata"); + assert!(state.app_version.is_empty()); + assert!(version_notice(&state).contains("version unavailable")); + state.app_version = env!("CARGO_PKG_VERSION").into(); + assert!(version_notice(&state).is_empty()); + session.window = Some(state); + let mut plan = plan(session.marks(), &root); + let estimate = session.selection_estimate(&mut plan); + assert_eq!( + (estimate.lower, estimate.upper, estimate.on_volume), + (0, None, 0) + ); + assert!(estimate.partial); + } + + #[cfg(any(unix, windows))] + #[test] + fn incompatible_state_is_refused_before_adopting_marks_or_handing_over() { + let temp = fixture(); + let socket = endpoint(temp.path()); + let window = FakeWindow::with_tree( + &socket, + FakeTree { + protocol: VERSION - 1, + root: temp.path().into(), + tree: Arc::new( + disktree_core::scan::scan(temp.path(), apparent()) + .expect("scan"), + ), + marks: vec![], + remote: None, + busy: false, + options: apparent(), + unreadable: 0, + removed: Vec::new(), + }, + ); + let mut session = Session::detached(socket, None); + let mark = Target { + path: temp.path().join("notes"), + bytes: 500, + is_dir: true, + hidden: false, + }; + session.marks.push(mark.clone()); + assert!(!session.try_connect()); + assert!(session.link.is_none() && session.window.is_none()); + assert_eq!(session.marks(), &[mark]); + let reason = session.unlinked.as_deref().expect("explicit refusal"); + assert!( + reason.contains("Incompatible PwrDisk link protocols"), + "{reason}" + ); + assert!(reason.contains("restart/reconnect"), "{reason}"); + assert!(reason.contains("updated installation"), "{reason}"); + assert!( + window + .asked() + .iter() + .all(|r| matches!(r, Request::Hello { .. })) + ); + } + + #[cfg(any(unix, windows))] + #[test] + fn status_reuses_window_measurement_context_without_scanning() { + let temp = fixture(); + let tree = Arc::new( + disktree_core::scan::scan(temp.path(), apparent()) + .expect("fixture scan"), + ); + for (apparent_size, include_hidden, unreadable) in + [(true, false, 7), (false, true, 0)] + { + let socket_dir = tempfile::TempDir::new().expect("socket dir"); + let socket = endpoint(socket_dir.path()); + let window = FakeWindow::with_tree( + &socket, + FakeTree { + protocol: VERSION, + root: temp.path().to_path_buf(), + tree: Arc::clone(&tree), + marks: Vec::new(), + remote: None, + busy: false, + options: ScanOptions { + apparent_size, + include_hidden, + ..ScanOptions::default() + }, + unreadable, + removed: Vec::new(), + }, + ); + let mut session = Session::detached(socket, None); + let status = session.status(); + assert!( + status.contains(if apparent_size { + "apparent sizes" + } else { + "allocated sizes" + }), + "{status}" + ); + assert!( + status.contains(if include_hidden { + "hidden entries included" + } else { + "hidden entries skipped" + }), + "{status}" + ); + assert!( + status.contains(&format!("{unreadable} unreadable")), + "{status}" + ); + if cfg!(target_os = "macos") { + assert!( + status.contains("APFS clones share blocks"), + "{status}" + ); + assert!( + status.contains("not guaranteed freed space"), + "{status}" + ); + } + assert!(session.scans().is_empty()); + assert!(session.marks().is_empty()); + assert!(window.asked().iter().all(|request| matches!( + request, + Request::Hello { .. } | Request::State + ))); + } + } + + #[cfg(target_os = "macos")] + #[test] + fn private_tmp_is_a_candidate_but_guards_refuse_it_locally_and_linked() { + use disktree_core::{ + classify::classify, + tree::{Metric, NodeKind, aggregate}, + }; + // Only a synthetic tree represents /; no scan, write or mark of real data. + let mut root = Draft::directory("/"); + let mut private = Draft::directory("private"); + let mut tmp = Draft::directory("tmp"); + tmp.children + .push(Draft::entry("fixture", NodeKind::File, 123)); + private.children.push(tmp); + root.children.push(private); + let mut root = Tree::from(root); + aggregate(&mut root, Metric::Bytes); + classify(&mut root); + let tree = Arc::new(root); + for linked in [false, true] { + let temp = tempfile::TempDir::new().expect("endpoint"); + let socket = endpoint(temp.path()); + let window = linked.then(|| { + FakeWindow::with_tree( + &socket, + FakeTree { + protocol: VERSION, + root: PathBuf::from("/"), + tree: Arc::clone(&tree), + marks: Vec::new(), + remote: None, + busy: false, + options: apparent(), + unreadable: 0, + removed: Vec::new(), + }, + ) + }); + let mut session = Session::detached(socket, None); + if !linked { + session.scans.push(Scan { + root: PathBuf::from("/"), + tree: Arc::clone(&tree), + options: apparent(), + at: now(), + elapsed: Duration::ZERO, + unreadable: 0, + space: None, + device: None, + insights: Vec::new(), + }); + } + let report = session + .find(&FindParams { + reclaimable: true, + ..FindParams::default() + }) + .expect("find"); + assert!(report.starts_with("1 match "), "{report}"); + assert!( + report.contains("cleanup candidate: temporary"), + "{report}" + ); + assert!(report.contains("Removal blocked: /private/tmp — part of the system under /private"), "{report}"); + assert!(report.contains("not guaranteed freed space"), "{report}"); + assert!(session.marks().is_empty()); + if let Some(window) = window { + assert!(window.marks().is_empty()); + assert!(window.asked().iter().all(|request| matches!( + request, + Request::Hello { .. } | Request::Find(_) + ))); + } + } + } + + #[cfg(target_os = "macos")] + #[test] + fn apfs_allocation_is_reported_even_above_volume_usage() { + let temp = fixture(); + let mut session = unlinked(temp.path()); + scanned(&mut session, temp.path()); + let mut facts = ScanFacts::of_local(&session.scans()[0]); + facts.tree.bytes = 2_000_000; + facts.tree.apparent_size = false; + facts.space = Some(Space { + total: 1_000_000, + free: 500_000, + available: 500_000, + }); + let report = session.scan_report(&facts); + assert!(report.contains("1.9 MiB"), "{report}"); + assert!(report.contains("400% of what is used"), "{report}"); + assert!( + report.contains("summed allocation can exceed volume usage"), + "{report}" + ); + assert!(report.contains("not guaranteed freed space"), "{report}"); + } + + /// Three directories, each holding one full clone of a group APFS + /// counts `references` members of, beside a plain directory. + fn clone_copies(root: &Path, references: u32) -> Scan { + clone_copies_with_plain(root, references, 12 * 1024 * 1024) + } + + fn clone_copies_with_plain( + root: &Path, + references: u32, + plain_bytes: u64, + ) -> Scan { + use disktree_core::sharing::{Allocation, CloneInfo}; + use disktree_core::tree::{Metric, NodeKind, aggregate}; + const MIB: u64 = 1024 * 1024; + let mut tree = Draft::directory("fixture"); + for name in ["copy-a", "copy-b", "copy-c", "plain"] { + std::fs::create_dir(root.join(name)).expect("fixture directory"); + let mut dir = Draft::directory(name); + let mut file = Draft::entry( + "data", + NodeKind::File, + if name == "plain" { + plain_bytes + } else { + 12 * MIB + }, + ); + if name != "plain" { + file.allocation = Some(Box::new(Allocation { + bytes: 12 * MIB, + identity: None, + links: 1, + followed: false, + clone: Some(CloneInfo { + device: 1, + id: 9, + references, + private_bytes: Some(0), + data_bytes: 12 * MIB, + }), + })); + } + dir.children.push(file); + tree.children.push(dir); + } + let mut tree = Tree::from(tree); + aggregate(&mut tree, Metric::Bytes); + Scan { + root: root.into(), + tree: Arc::new(tree), + options: ScanOptions::default(), + at: now(), + elapsed: Duration::ZERO, + unreadable: 0, + space: None, + device: None, + insights: vec![], + } + } + + fn copies(root: &Path) -> Vec { + ["copy-a", "copy-b", "copy-c"] + .iter() + .map(|name| root.join(name)) + .collect() + } + + #[test] + fn clone_rows_split_shared_bytes_and_a_complete_group_frees_one_copy() { + let temp = tempfile::tempdir_in(std::env::current_dir().expect("cwd")) + .expect("fixture"); + let root = temp.path().canonicalize().expect("root"); + let mut session = unlinked(&root); + let report = session.store_scan(clone_copies(&root, 3)); + assert!( + report.contains("APFS clones: 36 MiB of this is shared"), + "{report}" + ); + assert!( + report.contains("\u{2248} 24 MiB is counted again"), + "{report}" + ); + let listing = session + .ls(&LsParams { + path: root.clone(), + limit: None, + show: false, + }) + .expect("ls"); + let row = |name: &str| { + listing + .lines() + .find(|line| line.contains(&format!(" {name}/ "))) + .unwrap_or_else(|| panic!("{name} in {listing}")) + .to_string() + }; + for name in ["copy-a", "copy-b", "copy-c"] { + assert!( + row(name).contains( + "0 B private \u{00b7} 12 MiB shared with other APFS \ + clones \u{00b7} frees \u{2248} 0 B alone" + ), + "{listing}" + ); + } + assert!( + row("plain").ends_with(" plain/ 1 files \u{00b7} age unknown") + ); + let found = session + .find(&FindParams { + path: Some(root.clone()), + kind: Some(KindName::Dir), + ..FindParams::default() + }) + .expect("find"); + assert_eq!(found.matches("shared with other APFS clones").count(), 3); + + let one = session + .mark(&PathsParams { + paths: vec![root.join("copy-a")], + }) + .expect("mark one"); + assert!(one.contains("estimate: 0 B\u{2013}0 B"), "{one}"); + assert!(one.contains("12 MiB of the selection is APFS clone")); + assert!(!one.contains("Frees"), "{one}"); + session.unmark(&PathsParams::default()).expect("unmark"); + let all = session + .mark(&PathsParams { + paths: copies(&root), + }) + .expect("mark all"); + assert!(all.contains("estimate: 12 MiB\u{2013}12 MiB"), "{all}"); + assert!(all.contains("36 MiB of the selection is APFS clone")); + } + + /// Three 10 GiB worktrees sharing all but 100 MiB each. `modified` + /// puts the private 100 MiB inside the clone file (a rewritten + /// clone); otherwise it is a separate, ordinary file beside a full + /// clone. + fn worktree_trio(root: &Path, modified: bool) -> Scan { + use disktree_core::sharing::{Allocation, CloneInfo}; + use disktree_core::tree::{Metric, NodeKind, aggregate}; + const MIB: u64 = 1024 * 1024; + let mut tree = Draft::directory("fixture"); + for name in ["wt-a", "wt-b", "wt-c"] { + std::fs::create_dir(root.join(name)).expect("fixture directory"); + let mut dir = Draft::directory(name); + let (bytes, private) = if modified { + (10_240 * MIB, 100 * MIB) + } else { + (10_140 * MIB, 0) + }; + let mut file = Draft::entry("objects", NodeKind::File, bytes); + file.allocation = Some(Box::new(Allocation { + bytes, + identity: None, + links: 1, + followed: false, + clone: Some(CloneInfo { + device: 1, + id: 77, + references: 3, + private_bytes: Some(private), + data_bytes: bytes, + }), + })); + dir.children.push(file); + if !modified { + dir.children.push(Draft::entry( + "own", + NodeKind::File, + 100 * MIB, + )); + } + tree.children.push(dir); + } + let mut tree = Tree::from(tree); + aggregate(&mut tree, Metric::Bytes); + Scan { + root: root.into(), + tree: Arc::new(tree), + options: ScanOptions::default(), + at: now(), + elapsed: Duration::ZERO, + unreadable: 0, + space: None, + device: None, + insights: vec![], + } + } + + #[test] + fn marking_a_worktree_trio_one_by_one_frees_one_copy_at_the_end() { + const MIB: u64 = 1024 * 1024; + for modified in [false, true] { + let temp = + tempfile::tempdir_in(std::env::current_dir().expect("cwd")) + .expect("fixture"); + let root = temp.path().canonicalize().expect("root"); + let mut session = unlinked(&root); + session.store_scan(worktree_trio(&root, modified)); + let mut seen = Vec::new(); + for name in ["wt-a", "wt-b", "wt-c"] { + let report = session + .mark(&PathsParams { + paths: vec![root.join(name)], + }) + .expect("mark"); + let mut plan = plan(session.marks(), &root); + let estimate = session.selection_estimate(&mut plan); + assert_eq!(estimate.on_volume, estimate.lower, "{report}"); + seen.push((estimate.lower, estimate.upper)); + } + // Each worktree's own 100 MiB until the last clone of the + // group is selected; then the shared data counts, once. + let lower: Vec = + seen.iter().map(|(lower, _)| *lower).collect(); + assert_eq!( + lower, + [100 * MIB, 200 * MIB, (300 + 10_140) * MIB], + "modified={modified}" + ); + if !modified { + // Full clones beside ordinary files: exact, no range. + let upper: Vec<_> = + seen.iter().map(|(_, upper)| *upper).collect(); + assert_eq!( + upper, + [Some(100 * MIB), Some(200 * MIB), Some(10_440 * MIB)] + ); + } + eprintln!("modified={modified}: {seen:?}"); + } + } + + #[test] + fn a_clone_outside_the_scan_keeps_every_shared_block() { + let temp = tempfile::tempdir_in(std::env::current_dir().expect("cwd")) + .expect("fixture"); + let root = temp.path().canonicalize().expect("root"); + let mut session = unlinked(&root); + session.store_scan(clone_copies(&root, 4)); + let all = session + .mark(&PathsParams { + paths: copies(&root), + }) + .expect("mark all"); + assert!(all.contains("estimate: 0 B\u{2013}0 B"), "{all}"); + assert!(all.contains("outside this scan, keeps them"), "{all}"); + session.unmark(&PathsParams::default()).expect("unmark"); + let plain = session + .mark(&PathsParams { + paths: vec![root.join("plain")], + }) + .expect("mark plain"); + assert!(plain.contains("estimate: 12 MiB\u{2013}12 MiB"), "{plain}"); + assert!(!plain.contains("APFS clone"), "{plain}"); + } + + /// The reproduction behind the clone rows: `cp -c -R` twice and a plain + /// `cp -R`, scanned for real. Skipped where the temporary directory + /// cannot clone (not APFS). + #[cfg(target_os = "macos")] + #[test] + fn real_apfs_clones_read_as_shared_and_free_nothing_alone() { + const MIB: u64 = 1_000_000; + // The system-tree guard refuses canonical /private, so stay in the + // checkout, which is APFS on any Mac that builds this. + let temp = tempfile::tempdir_in(std::env::current_dir().expect("cwd")) + .expect("fixture"); + let root = temp.path().canonicalize().expect("root"); + let src = root.join("src"); + std::fs::create_dir(&src).expect("mkdir"); + for index in 0..12_u8 { + // Distinct, incompressible-enough content per file. + let data: Vec = (0..MIB) + .map(|i| (i as u8).wrapping_mul(31).wrapping_add(index)) + .collect(); + std::fs::write(src.join(format!("f{index}.bin")), data) + .expect("write"); + } + let copy = |flags: &[&str], to: &str| { + std::process::Command::new("cp") + .args(flags) + .arg(&src) + .arg(root.join(to)) + .status() + .expect("cp") + .success() + }; + if !copy(&["-c", "-R"], "clone-a") { + eprintln!("skipped: {} cannot clone files", root.display()); + return; + } + assert!(copy(&["-c", "-R"], "clone-b")); + assert!(copy(&["-R"], "plain")); + let scan = + run_scan(root.clone(), ScanOptions::default()).expect("scan"); + let listing = Listing::of( + &scan.root, + scan.tree.root().bytes, + &root, + scan.tree.root(), + 10, + ); + let entry = |name: &str| { + listing + .children + .iter() + .find(|child| child.name == name) + .unwrap_or_else(|| panic!("{name}")) + .clone() + }; + let clone = entry("clone-a").clones.expect("clone facts"); + assert!(clone.private <= 8 * 1024, "{clone:?}"); + assert!(clone.shared >= 12 * MIB - 64 * 1024, "{clone:?}"); + assert_eq!(entry("plain").clones, None); + let mut session = unlinked(&root); + session.store_scan(scan); + let marked = |session: &mut Session, name: &str| { + let report = session + .mark(&PathsParams { + paths: vec![root.join(name)], + }) + .expect("mark"); + session.unmark(&PathsParams::default()).expect("unmark"); + let mut plan = plan( + &[Target { + path: root.join(name), + bytes: entry(name).bytes, + is_dir: true, + hidden: false, + }], + &root, + ); + (report, session.selection_estimate(&mut plan)) + }; + let (report, estimate) = marked(&mut session, "clone-a"); + assert!(estimate.lower < 64 * 1024, "{report}"); + assert!( + report.contains("of the selection is APFS clone"), + "{report}" + ); + let (report, estimate) = marked(&mut session, "plain"); + assert!(estimate.lower >= 12 * MIB, "{report}"); + assert!(!report.contains("APFS clone"), "{report}"); + + // Without allocated blocks there is nothing to split. + let mut apparent = unlinked(&root); + let report = apparent.store_scan( + run_scan( + root.clone(), + ScanOptions { + apparent_size: true, + ..ScanOptions::default() + }, + ) + .expect("apparent scan"), + ); + assert!(!report.contains("private"), "{report}"); + assert!(!report.contains("APFS clones:"), "{report}"); + } + + #[cfg(any(unix, windows))] + #[test] + fn with_a_window_open_its_tree_is_what_the_agent_reads() { + let temp = fixture(); + let socket = endpoint(temp.path()); + let window = FakeWindow::open(&socket, temp.path()); + let mut session = Session::detached(socket, None); + session.set_client("claude-code"); + // No scan here at all: everything comes from the window. + assert!(session.scans().is_empty()); + + let listing = session + .ls(&LsParams { + path: temp.path().join("src"), + limit: Some(5), + show: false, + }) + .expect("ls over the link"); + assert!(listing.contains("app/"), "{listing}"); + assert!(listing.contains("% of "), "{listing}"); + + let outside = session + .ls(&LsParams { + path: PathBuf::from("/definitely/elsewhere"), + ..LsParams::default() + }) + .expect_err("outside the window"); + assert!(outside.contains("window's tree"), "{outside}"); + assert!(outside.contains("pwrdisk_scan"), "{outside}"); + + let reclaim = session + .find(&FindParams { + reclaimable: true, + ..FindParams::default() + }) + .expect("find over the link"); + assert!(reclaim.contains(".cache/"), "{reclaim}"); + assert!(!reclaim.contains("target/"), "{reclaim}"); + + // The window measures the mark; a path it does not have is refused. + let plan = session + .mark(&PathsParams { + paths: vec![ + temp.path().join(".cache"), + temp.path().join("not-there"), + ], + }) + .expect("mark"); + assert!(plan.starts_with("Not marked:"), "{plan}"); + assert!(plan.contains("not in the window's tree"), "{plan}"); + assert!(plan.contains("Marked 1"), "{plan}"); + assert_eq!(window.marks()[0].bytes, 400_000); + assert_eq!(session.marks()[0].bytes, 400_000); + + // A scan goes to the window and is read back from it. + let plan = session + .prepare_scan(&ScanParams { + path: Some(temp.path().to_path_buf()), + apparent_size: true, + ..ScanParams::default() + }) + .expect("prepare"); + let ScanPlan::Window { root } = plan else { + panic!("a linked window scans: {plan:?}"); + }; + let report = session + .window_scan(&root) + .expect("poll") + .expect("the fake finishes at once"); + assert!(report.starts_with("Scanned "), "{report}"); + assert!(report.contains("6 files"), "{report}"); + assert!(report.contains("Top level, largest first:"), "{report}"); + assert!(report.contains("reclaimable: cache"), "{report}"); + assert!(report.contains("Window: open on"), "{report}"); + assert!(session.scans().is_empty(), "nothing is scanned here"); + + let status = session.status(); + assert!(status.contains("Claude Code"), "{status}"); + assert!(status.contains("Last removal: trash"), "{status}"); + assert!( + status.contains("-27 MiB observed volume change"), + "{status}" + ); + assert!(!status.contains("0 B freed"), "{status}"); + assert!(status.contains("Removed since the scan"), "{status}"); + assert!(status.contains("Total: 684 KiB reported"), "{status}"); + assert!(status.contains("scanned "), "{status}"); + assert!(!status.contains("Scans: none yet"), "{status}"); + + let asked = window.asked(); + assert!( + matches!(asked[0], Request::Hello { ref client, .. } if client == "Claude Code") + ); + for wanted in ["ls", "find", "mark", "scan"] { + assert!( + asked.iter().any(|request| match request { + Request::Ls { .. } => wanted == "ls", + Request::Find(_) => wanted == "find", + Request::Mark { .. } => wanted == "mark", + Request::Scan { .. } => wanted == "scan", + _ => false, + }), + "{wanted} went to the window: {asked:?}" + ); + } + } + + #[cfg(any(unix, windows))] + #[test] + fn listings_say_what_the_window_removed_since_its_scan() { + let temp = fixture(); + let socket = endpoint(temp.path()); + let mut fake = FakeTree { + protocol: VERSION, + root: temp.path().to_path_buf(), + tree: Arc::new( + disktree_core::scan::scan(temp.path(), apparent()) + .expect("scan"), + ), + marks: Vec::new(), + remote: None, + busy: false, + options: apparent(), + unreadable: 0, + removed: Vec::new(), + }; + fake.removed = vec![(temp.path().join(".cache/pip"), 400_000)]; + let _window = FakeWindow::with_tree(&socket, fake); + let mut session = Session::detached(socket, None); + session.set_client("claude-code"); + + let root = session + .ls(&LsParams { + path: temp.path().to_path_buf(), + limit: Some(10), + show: false, + }) + .expect("ls"); + let cache = root + .lines() + .find(|line| line.contains(".cache/")) + .expect("still listed"); + assert!( + cache.contains("of it removed since the scan"), + "part of it went: {root}" + ); + let notes = root.lines().find(|l| l.contains("notes/")).unwrap(); + assert!(!notes.contains("removed"), "neighbours unchanged: {root}"); + + let inside = session + .ls(&LsParams { + path: temp.path().join(".cache"), + limit: Some(10), + show: false, + }) + .expect("ls"); + let pip = inside.lines().find(|l| l.contains("pip/")).unwrap(); + assert!(pip.contains("removed since the scan"), "{inside}"); + assert!(!pip.contains("of it removed"), "it went whole: {inside}"); + + let found = session + .find(&FindParams { + name: Some("blob".into()), + ..FindParams::default() + }) + .expect("find"); + assert!(found.contains("removed since the scan"), "{found}"); + } + + #[test] + #[cfg(any(unix, windows))] + fn with_a_window_open_marks_live_there_and_review_opens_it() { + let temp = fixture(); + let socket = endpoint(temp.path()); + let window = FakeWindow::open(&socket, temp.path()); + let mut session = Session::detached(socket, None); + + let plan = session + .mark(&PathsParams { + paths: vec![temp.path().join(".cache")], + }) + .expect("mark"); + assert!(plan.starts_with("Marked 1"), "{plan}"); + assert!(plan.contains("Window: open on"), "{plan}"); + assert!(plan.contains("1 mark"), "{plan}"); + + let shown = session + .ls(&LsParams { + path: temp.path().join("src"), + limit: None, + show: true, + }) + .expect("ls with show"); + assert!(shown.contains("Listings never move"), "{shown}"); + + let review = session.review().expect("review"); + assert!(review.contains("review screen is open"), "{review}"); + + let asked = window.asked(); + assert!( + !asked + .iter() + .any(|request| matches!(request, Request::Show { .. })) + ); + assert!( + asked + .iter() + .any(|request| matches!(request, Request::Review)) + ); + } + + #[cfg(any(unix, windows))] + #[test] + fn marks_made_before_the_window_opened_are_handed_over() { + let temp = fixture(); + let socket = endpoint(temp.path()); + let mut session = Session::detached(socket.clone(), None); + scanned(&mut session, temp.path()); + session + .mark(&PathsParams { + paths: vec![temp.path().join("Downloads")], + }) + .expect("mark offline"); + assert_eq!(session.marks().len(), 1); + + let window = FakeWindow::open(&socket, temp.path()); + let review = session.review().expect("review"); + assert!(review.contains("1 marked"), "{review}"); + let asked = window.asked(); + let handed = asked.iter().find_map(|request| match request { + Request::Mark { targets, .. } => Some(targets.clone()), + _ => None, + }); + assert_eq!( + handed.map(|targets| targets[0].path.clone()), + Some(temp.path().join("Downloads")) + ); + } + + #[cfg(unix)] + #[test] + fn covered_marks_use_the_windows_root_for_handover() { + let temp = fixture(); + let socket = temp.path().join("window.sock"); + let mut session = Session::detached(socket.clone(), None); + scanned(&mut session, temp.path()); + session + .mark(&PathsParams { + paths: vec![temp.path().join("src/app/target")], + }) + .expect("mark offline"); + + let root = temp.path().join("src"); + let window = FakeWindow::open(&socket, &root); + session.status(); + assert_eq!(session.marks().len(), 1); + assert_eq!(window.marks().len(), 1); + assert!(window.asked().iter().all(|request| match request { + Request::Mark { root: sent, .. } => *sent == root, + Request::Hello { .. } | Request::State => true, + _ => false, + })); + } + + #[cfg(unix)] + #[test] + fn linking_never_moves_the_window_to_cover_earlier_marks() { + let temp = fixture(); + let socket = temp.path().join("window.sock"); + let mut session = Session::detached(socket.clone(), None); + // Separate scan roots used to cause a Mark request for each root, + // leaving the user's window on the last one. + scanned(&mut session, &temp.path().join(".cache")); + scanned(&mut session, &temp.path().join("src")); + let paths = vec![ + temp.path().join(".cache/pip"), + temp.path().join("src/app/target"), + ]; + session + .mark(&PathsParams { + paths: paths.clone(), + }) + .expect("mark offline"); + + // One mark is covered, but none should be sent until all fit. + let window = FakeWindow::open(&socket, &temp.path().join(".cache")); + let status = session.status(); + assert!(status.contains("not followed"), "{status}"); + assert!(status.contains("pwrdisk_scan"), "{status}"); + let report = session.plan_report(); + for path in &paths { + assert!(report.contains(&path.display().to_string()), "{report}"); + } + assert_eq!(session.marks().len(), 2); + assert!(session.link.is_none()); + assert!(window.marks().is_empty()); + session.review().expect_err("keep the window where it is"); + assert!(window.asked().iter().all(|request| matches!( + request, + Request::Hello { .. } | Request::State + ))); + + let scan = session + .prepare_scan(&ScanParams { + path: Some(temp.path().to_path_buf()), + ..ScanParams::default() + }) + .expect("explicit scan covers both marks"); + assert!(matches!(scan, ScanPlan::Window { .. })); + assert_eq!(session.marks().len(), 2); + assert_eq!(window.marks().len(), 2); + let asked = window.asked(); + let scan_at = asked + .iter() + .position(|request| matches!(request, Request::Scan { .. })) + .expect("explicit scan"); + let mark_at = asked + .iter() + .position(|request| matches!(request, Request::Mark { .. })) + .expect("handover"); + assert!(scan_at < mark_at, "{asked:?}"); + assert!(matches!( + &asked[mark_at], + Request::Mark { root, targets } + if root == temp.path() && targets.len() == 2 + )); + session.review().expect("review the handed-over marks"); + } + + #[cfg(unix)] + #[test] + fn a_scan_that_does_not_cover_earlier_marks_keeps_them_here() { + let temp = fixture(); + let socket = temp.path().join("window.sock"); + let mut session = Session::detached(socket.clone(), None); + scanned(&mut session, temp.path()); + let path = temp.path().join("Downloads"); + session + .mark(&PathsParams { + paths: vec![path.clone()], + }) + .expect("mark offline"); + + let window = FakeWindow::open(&socket, &temp.path().join("notes")); + for root in [temp.path().join("src"), path.clone()] { + let error = session + .prepare_scan(&ScanParams { + path: Some(root), + ..ScanParams::default() + }) + .expect_err("the mark must be inside the requested root"); + assert!(error.contains("containing all marked paths"), "{error}"); + assert_eq!(session.marks()[0].path, path); + assert!(session.link.is_none()); + } + assert!(window.asked().iter().all(|request| matches!( + request, + Request::Hello { .. } | Request::State + ))); + } + + #[cfg(unix)] + #[test] + fn a_mark_missing_from_the_windows_tree_is_kept_and_explained() { + let temp = fixture(); + let socket = temp.path().join("window.sock"); + let mut session = Session::detached(socket.clone(), None); + scanned(&mut session, temp.path()); + let path = temp.path().join("notes/todo.txt"); + session + .mark(&PathsParams { + paths: vec![path.clone(), temp.path().join("Downloads")], + }) + .expect("mark offline"); + std::fs::remove_file(&path).expect("remove fixture file"); + + let window = FakeWindow::open(&socket, temp.path()); + let status = session.status(); + assert!(status.contains("not in the window's tree"), "{status}"); + assert!(status.contains("they are kept here"), "{status}"); + assert_eq!(session.marks().len(), 2); + assert_eq!(window.marks().len(), 1, "partial handover is reported"); + assert!(session.link.is_none()); + } + + #[cfg(unix)] + #[test] + fn unmark_after_a_partial_handover_clears_both_copies() { + for clear_all in [false, true] { + let temp = fixture(); + let socket = temp.path().join("window.sock"); + let mut session = Session::detached(socket.clone(), None); + scanned(&mut session, temp.path()); + let missing = temp.path().join("notes/todo.txt"); + let accepted = temp.path().join("Downloads"); + session + .mark(&PathsParams { + paths: vec![missing.clone(), accepted.clone()], + }) + .expect("mark offline"); + std::fs::remove_file(&missing).expect("remove fixture file"); + + let window = FakeWindow::open(&socket, temp.path()); + let unrelated = temp.path().join(".cache"); + Session::detached(socket, None) + .mark(&PathsParams { + paths: vec![unrelated.clone()], + }) + .expect("mark in the window separately"); + session.status(); + assert_eq!(window.marks().len(), 2, "partial handover"); + assert_eq!(session.marks().len(), 2); + + let report = session + .unmark(&PathsParams { + paths: if clear_all { vec![] } else { vec![accepted] }, + }) + .expect("unmark accepted paths in both places"); + if clear_all { + assert!(window.marks().is_empty()); + assert!(report.starts_with("Nothing is marked."), "{report}"); + assert!(session.marks().is_empty()); + } else { + assert_eq!(window.marks().len(), 1); + assert_eq!(window.marks()[0].path, unrelated); + assert!(report.starts_with("Marked 1"), "{report}"); + assert_eq!(session.marks()[0].path, missing); + // The other mark still cannot be handed over. Clearing it + // later must not bring the accepted path back on reconnect. + session + .unmark(&PathsParams::default()) + .expect("clear remaining mark"); + } + session.status(); + assert!(session.marks().is_empty()); + assert!(window.marks().is_empty()); + assert!(window.asked().iter().any(|request| { + matches!(request, Request::Unmark { paths } if paths.is_empty()) + })); + } + } + + #[cfg(unix)] + #[test] + fn review_launches_one_window_covering_every_offline_scan_root() { + let temp = fixture(); + let socket = temp.path().join("window.sock"); + let windows = Arc::new(Mutex::new(Vec::new())); + let launched = Arc::clone(&windows); + let expected = temp.path().to_path_buf(); + let launch_socket = socket.clone(); + let launcher = Box::new(move |root: &Path| { + assert_eq!(root, expected, "launch on the common ancestor"); + launched + .lock() + .expect("windows") + .push(FakeWindow::open(&launch_socket, root)); + Ok(()) + }); + let mut session = Session::detached(socket, Some(launcher)); + scanned(&mut session, &temp.path().join(".cache")); + scanned(&mut session, &temp.path().join("src")); + session + .mark(&PathsParams { + paths: vec![ + temp.path().join(".cache/pip"), + temp.path().join("src/app/target"), + ], + }) + .expect("mark offline"); + + let review = session.review().expect("launch and review both marks"); + assert!(review.contains("2 marked"), "{review}"); + assert!(session.link.is_some()); + let (marks, asked) = { + let windows = windows.lock().expect("windows"); + assert_eq!(windows.len(), 1); + (windows[0].marks(), windows[0].asked()) + }; + assert_eq!(marks.len(), 2); + assert!( + asked + .iter() + .any(|request| matches!(request, Request::Review)) + ); + assert!(asked.iter().all(|request| match request { + Request::Mark { root, targets } => { + root == temp.path() && targets.len() == 2 + } + Request::Scan { .. } | Request::Show { .. } => false, + _ => true, + })); + } + + /// A window that will not take the marks made before it linked is not + /// followed: the marks stay here, and the agent is told why instead of + /// losing them. + #[cfg(any(unix, windows))] + #[test] + fn marks_a_window_refuses_are_kept_and_explained() { + let temp = fixture(); + let socket = endpoint(temp.path()); + let mut session = Session::detached(socket.clone(), None); + scanned(&mut session, temp.path()); + session + .mark(&PathsParams { + paths: vec![temp.path().join("Downloads")], + }) + .expect("mark offline"); + + let _window = FakeWindow::removing(&socket, temp.path()); + let status = session.status(); + assert!(status.contains("a removal is running"), "{status}"); + assert_eq!(session.marks().len(), 1, "the mark is kept"); + let review = session.review().expect_err("not followed"); + assert!(review.contains("did not take the marks"), "{review}"); + } + + /// A listing is answered even when the window cannot follow it. + #[cfg(any(unix, windows))] + #[test] + fn ls_with_show_keeps_the_listing_when_the_window_cannot_follow() { + let temp = fixture(); + let socket = endpoint(temp.path()); + let _window = + FakeWindow::showing(&socket, temp.path(), Some("build-box")); + let mut session = Session::detached(socket, None); + scanned(&mut session, temp.path()); + let listing = session + .ls(&LsParams { + path: temp.path().join("src"), + limit: None, + show: true, + }) + .expect("the listing stands"); + assert!(listing.contains("app/"), "{listing}"); + assert!(listing.contains("Window: not shown."), "{listing}"); + } + + /// A window showing an SSH host holds another machine's paths: the + /// session works on this computer without it, never hands it a mark, + /// and says why when asked to show or review. + #[cfg(any(unix, windows))] + #[test] + fn a_window_on_an_ssh_host_is_not_driven() { + let temp = fixture(); + let socket = endpoint(temp.path()); + let window = + FakeWindow::showing(&socket, temp.path(), Some("build-box")); + let mut session = Session::detached(socket, None); + + let status = session.status(); + assert!(status.contains("SSH host build-box"), "{status}"); + + // Reads and marks fall back to this session's own scan. + scanned(&mut session, temp.path()); + let plan = session + .mark(&PathsParams { + paths: vec![temp.path().join(".cache")], + }) + .expect("mark here"); + assert!(plan.starts_with("Marked 1"), "{plan}"); + assert!(plan.contains("SSH host build-box"), "{plan}"); + assert_eq!(session.marks().len(), 1); + + let review = session.review().expect_err("no review on a host"); + assert!(review.contains("SSH host build-box"), "{review}"); + assert!(review.contains("This computer"), "{review}"); + let shown = session + .show_path(&ShowParams { + path: temp.path().join("src"), + }) + .expect_err("no show on a host"); + assert!(shown.contains("SSH host build-box"), "{shown}"); + + assert!( + window.asked().iter().all(|request| matches!( + request, + Request::Hello { .. } | Request::State + )), + "only hello and state reach a window on a host: {:?}", + window.asked() + ); + assert!(window.marks().is_empty()); + } + + #[test] + fn client_names_read_like_products() { + let temp = fixture(); + let mut session = unlinked(temp.path()); + session.set_client("claude-code"); + assert_eq!(session.client(), "Claude Code"); + session.set_client("codex-cli"); + assert_eq!(session.client(), "Codex"); + session.set_client("claude-ai"); + assert_eq!(session.client(), "Claude"); + session.set_client("zed"); + assert_eq!(session.client(), "zed"); + session.set_client(""); + assert_eq!(session.client(), "an agent"); + } +} diff --git a/crates/disktree-mcp/src/skills.rs b/crates/disktree-mcp/src/skills.rs new file mode 100644 index 00000000..f0a1cac1 --- /dev/null +++ b/crates/disktree-mcp/src/skills.rs @@ -0,0 +1,301 @@ +//! The skills `pwrdisk mcp` carries: how to use its tools well, and what +//! each system hides from a scan or must never lose. +//! +//! They are compiled in from `skills/` and served three ways, so every +//! client finds them: as `skill:///` resources, through the +//! skills extension's `skills/list` and `skills/get`, and as prompts. The +//! list of files is written out here: a URI is looked up, never turned +//! into a path, so nothing outside these files can be read through it. + +use serde_json::{Map, Value, json}; +use sha2::{Digest as _, Sha256}; + +/// The skills extension, as servers that carry skills declare it. +pub const EXTENSION: &str = "io.modelcontextprotocol/skills"; + +/// One file of a skill. +#[derive(Debug)] +pub struct File { + /// Relative to the skill's directory: `SKILL.md`, `references/…`. + pub path: &'static str, + pub text: &'static str, +} + +/// A skill: its directory's name and its files, `SKILL.md` first. +#[derive(Debug)] +pub struct Skill { + pub name: &'static str, + pub files: &'static [File], +} + +// Plain literals throughout: CI's change classifier finds every +// `include_str!` path and keeps it out of the docs-only allowlist. +pub const SKILLS: &[Skill] = &[ + Skill { + name: "pwrdisk-explain-usage", + files: &[File { + path: "SKILL.md", + text: include_str!( + "../../../skills/pwrdisk-explain-usage/SKILL.md" + ), + }], + }, + Skill { + name: "pwrdisk-free-space", + files: &[ + File { + path: "SKILL.md", + text: include_str!( + "../../../skills/pwrdisk-free-space/SKILL.md" + ), + }, + File { + path: "references/macos.md", + text: include_str!( + "../../../skills/pwrdisk-free-space/references/macos.md" + ), + }, + File { + path: "references/linux.md", + text: include_str!( + "../../../skills/pwrdisk-free-space/references/linux.md" + ), + }, + File { + path: "references/windows.md", + text: include_str!( + "../../../skills/pwrdisk-free-space/references/windows.md" + ), + }, + ], + }, +]; + +/// A file's address. +pub fn uri(skill: &str, path: &str) -> String { + format!("skill://{skill}/{path}") +} + +impl Skill { + /// The skill's own file. + pub const fn skill_md(&self) -> &File { + &self.files[0] + } + + /// The address of its `SKILL.md`, which names the skill. + pub fn uri(&self) -> String { + uri(self.name, self.skill_md().path) + } + + /// The `SKILL.md` frontmatter, one `key: value` per line, as JSON. + pub fn frontmatter(&self) -> Map { + frontmatter(self.skill_md().text) + } + + /// What the frontmatter says the skill is for. + pub fn description(&self) -> String { + self.frontmatter() + .get("description") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string() + } + + /// The skills extension's entry: the address, the frontmatter, and + /// every file with its digest and size, so a client can cache them. + pub fn manifest(&self) -> Value { + let resources: Vec = self + .files + .iter() + .map(|file| { + json!({ + "uri": uri(self.name, file.path), + "digest": digest(file.text), + "size": file.text.len(), + }) + }) + .collect(); + json!({ + "uri": self.uri(), + "frontmatter": self.frontmatter(), + "resources": resources, + }) + } +} + +/// The skill named `name`. +pub fn named(name: &str) -> Option<&'static Skill> { + SKILLS.iter().find(|skill| skill.name == name) +} + +/// The skill whose `SKILL.md` is at `uri`. +pub fn by_uri(uri: &str) -> Option<&'static Skill> { + SKILLS.iter().find(|skill| skill.uri() == uri) +} + +/// The text at `uri`: an exact match against the files above, or nothing. +pub fn read(address: &str) -> Option<&'static str> { + SKILLS.iter().find_map(|skill| { + skill + .files + .iter() + .find(|file| uri(skill.name, file.path) == address) + .map(|file| file.text) + }) +} + +/// `sha256:` and the hex digest, as the skills extension writes it. +pub fn digest(text: &str) -> String { + let hash = Sha256::digest(text.as_bytes()); + let mut out = String::with_capacity(7 + hash.len() * 2); + out.push_str("sha256:"); + for byte in hash { + use std::fmt::Write as _; + let _ = write!(out, "{byte:02x}"); + } + out +} + +/// The `key: value` lines between the opening `---` and the next. Our +/// skills keep every value on one line, so no YAML parser is needed; a +/// test holds them to that. +pub fn frontmatter(text: &str) -> Map { + let mut fields = Map::new(); + let Some(rest) = text.strip_prefix("---\n") else { + return fields; + }; + for line in rest.lines().take_while(|line| *line != "---") { + if let Some((key, value)) = line.split_once(": ") { + fields.insert(key.trim().to_string(), json!(value.trim())); + } + } + fields +} + +/// The reference for the system this server runs on, if there is one. +pub const fn platform_reference() -> Option<&'static str> { + if cfg!(target_os = "macos") { + Some("references/macos.md") + } else if cfg!(windows) { + Some("references/windows.md") + } else if cfg!(unix) { + Some("references/linux.md") + } else { + None + } +} + +/// What a prompt hands the agent: the skill, then this system's reference, +/// so one message holds what it needs here. +pub fn prompt_text(skill: &Skill) -> String { + let mut text = skill.skill_md().text.to_string(); + let reference = platform_reference().and_then(|path| { + named("pwrdisk-free-space")? + .files + .iter() + .find(|file| file.path == path) + }); + if let Some(reference) = reference { + text.push_str("\n---\n\n"); + text.push_str(reference.text); + } + text +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_skill_has_frontmatter_that_names_it() { + for skill in SKILLS { + let text = skill.skill_md().text; + assert_eq!(skill.skill_md().path, "SKILL.md"); + assert!(text.starts_with("---\n"), "{}", skill.name); + let end = text[4..].find("\n---\n").expect("closing ---"); + // One `key: value` per line: what [`frontmatter`] reads. + for line in text[4..4 + end].lines() { + assert!(line.contains(": "), "{}: {line}", skill.name); + } + let fields = skill.frontmatter(); + assert_eq!(fields["name"], skill.name); + let description = skill.description(); + assert!(!description.is_empty(), "{}", skill.name); + // Agent hosts cut descriptions at 1024 characters. + assert!(description.len() <= 1024, "{}", skill.name); + } + } + + #[test] + fn every_skill_address_in_a_skill_resolves() { + for skill in SKILLS { + for file in skill.files { + let mut rest = file.text; + while let Some(at) = rest.find("skill://") { + let tail = &rest[at..]; + let end = tail + .find(|c: char| c == '`' || c.is_whitespace()) + .unwrap_or(tail.len()); + let address = tail[..end].trim_end_matches(['.', ',']); + assert!( + read(address).is_some(), + "{}/{} points at {address}", + skill.name, + file.path + ); + rest = &tail[end..]; + } + } + } + } + + #[test] + fn only_listed_files_are_read() { + assert!(read("skill://pwrdisk-free-space/SKILL.md").is_some()); + for address in [ + "", + "skill://pwrdisk-free-space", + "skill://pwrdisk-free-space/", + "skill://pwrdisk-free-space/SKILL.md/", + "skill://pwrdisk-free-space/SKILL.md?x=1", + "skill://pwrdisk-free-space/../pwrdisk-explain-usage/SKILL.md", + "skill://pwrdisk-free-space/%2e%2e/Cargo.toml", + "skill://unknown/SKILL.md", + "file:///etc/passwd", + ] { + assert!(read(address).is_none(), "{address}"); + } + } + + #[test] + fn manifests_list_every_file_with_its_digest() { + let skill = named("pwrdisk-free-space").expect("free-space"); + let manifest = skill.manifest(); + assert_eq!(manifest["uri"], "skill://pwrdisk-free-space/SKILL.md"); + let resources = manifest["resources"].as_array().expect("files"); + assert_eq!(resources.len(), skill.files.len()); + for (entry, file) in resources.iter().zip(skill.files) { + assert_eq!(entry["size"], file.text.len()); + assert_eq!(entry["digest"], digest(file.text)); + } + // A known digest, so the format does not drift. + assert_eq!( + digest("abc"), + "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + } + + #[test] + fn a_prompt_carries_this_systems_reference() { + let skill = named("pwrdisk-explain-usage").expect("explain"); + let text = prompt_text(skill); + assert!(text.starts_with(skill.skill_md().text)); + if cfg!(target_os = "macos") { + assert!(text.contains("# PwrDisk on macOS")); + } else if cfg!(windows) { + assert!(text.contains("# PwrDisk on Windows")); + } else { + assert!(text.contains("# PwrDisk on Linux")); + } + } +} diff --git a/crates/disktree-scan/src/main.rs b/crates/disktree-scan/src/main.rs index 2b9ad573..e333e23b 100644 --- a/crates/disktree-scan/src/main.rs +++ b/crates/disktree-scan/src/main.rs @@ -48,7 +48,7 @@ fn main() -> io::Result<()> { println!( "disktree-scan — read-only SSH scan helper\n\ usage: disktree-scan --stdio-v1\n\ - Used by: disktree ssh HOST [PATH]\n\ + Used by: pwrdisk ssh HOST [PATH]\n\ Reads a versioned JSON request from stdin and streams a \ snapshot to stdout. No deletion commands." ); diff --git a/crates/disktree-scan/tests/stdio.rs b/crates/disktree-scan/tests/stdio.rs index b29f4c7c..80b7a32d 100644 --- a/crates/disktree-scan/tests/stdio.rs +++ b/crates/disktree-scan/tests/stdio.rs @@ -2,9 +2,13 @@ use std::io::{BufRead as _, BufReader, Write as _}; use std::process::{Command, Stdio}; +#[cfg(unix)] use disktree_core::remote::{Request, read_snapshot}; use disktree_core::scan::ScanOptions; +// The helper runs here, so this machine is the host, and clients only +// accept Unix hosts. +#[cfg(unix)] #[test] fn executable_returns_a_read_only_snapshot() { let dir = tempfile::tempdir().unwrap(); @@ -32,8 +36,8 @@ fn executable_returns_a_read_only_snapshot() { read_snapshot(&mut BufReader::new(child.stdout.take().unwrap())) .unwrap(); assert!(child.wait().unwrap().success()); - assert_eq!(snapshot.tree.bytes, 5); - assert_eq!(snapshot.tree.files, 1); + assert_eq!(snapshot.tree.root().bytes, 5); + assert_eq!(snapshot.tree.root().files, 1); assert_eq!(snapshot.header.root, dir.path().canonicalize().unwrap()); assert_eq!(std::fs::read(file).unwrap(), b"hello"); } @@ -101,6 +105,9 @@ fn disconnect_stops_a_helper_even_when_its_output_is_blocked() { wait_bounded(&mut helper.0); } +// The helper runs here, so this machine is the host, and clients only +// accept Unix hosts. +#[cfg(unix)] #[test] fn a_live_supervised_client_receives_a_complete_snapshot() { let dir = tempfile::tempdir().unwrap(); @@ -116,7 +123,7 @@ fn a_live_supervised_client_receives_a_complete_snapshot() { let snapshot = read_snapshot(&mut BufReader::new(helper.0.stdout.take().unwrap())) .unwrap(); - assert_eq!(snapshot.tree.files, 1); + assert_eq!(snapshot.tree.root().files, 1); assert!(helper.0.wait().unwrap().success()); drop(input); } @@ -125,25 +132,33 @@ fn a_live_supervised_client_receives_a_complete_snapshot() { #[test] fn memory_and_core_limits_are_installed_before_reading_a_request() { let mut helper = supervised_helper(); - // No startup chatter on stderr: wait for the kernel limit itself - // while the helper is still blocked waiting for its first request. + // The helper installs these limits in separate syscalls. Wait for both + // in one snapshot, keeping stdin open and empty throughout. let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); let limits = loop { let limits = std::fs::read_to_string(format!("/proc/{}/limits", helper.0.id())) .unwrap(); - if limits.lines().any(|line| { + let address_limited = limits.lines().any(|line| { line.starts_with("Max address space") && line .split_whitespace() .nth(3) .and_then(|value| value.parse::().ok()) .is_some_and(|value| value <= 1 << 30) - }) { + }); + let core_disabled = limits.lines().any(|line| { + line.starts_with("Max core file size") + && line.split_whitespace().skip(4).take(2).eq(["0", "0"]) + }); + if address_limited && core_disabled { break limits; } - assert!(std::time::Instant::now() < deadline); + assert!( + std::time::Instant::now() < deadline, + "helper did not install resource limits:\n{limits}" + ); assert!(helper.0.try_wait().unwrap().is_none()); std::thread::yield_now(); }; @@ -161,6 +176,7 @@ fn memory_and_core_limits_are_installed_before_reading_a_request() { let values: Vec<_> = core.split_whitespace().collect(); assert_eq!(values[4], "0"); assert_eq!(values[5], "0"); + assert!(helper.0.try_wait().unwrap().is_none()); } #[cfg(target_os = "linux")] @@ -239,6 +255,9 @@ fn assert_bounded_stream_memory(root: &std::path::Path) { drop(input); } +// The helper runs here, so this machine is the host, and clients only +// accept Unix hosts. +#[cfg(unix)] #[test] fn executable_discovers_roots_without_scanning_a_path() { let mut helper = supervised_helper(); diff --git a/docs/accessibility-audit-2026-10-31.md b/docs/accessibility-audit-2026-10-31.md new file mode 100644 index 00000000..abbb12d6 --- /dev/null +++ b/docs/accessibility-audit-2026-10-31.md @@ -0,0 +1,1195 @@ +# PwrDisk accessibility audit — 2026-10-31 + +Tracking: [PWR-27](https://linear.app/pwrdrvr/issue/PWR-27). + +## Result and scope + +**PwrDisk's core graphical workflow is not independently usable through +the inspected macOS accessibility tree.** Controls from GPUI Base expose +some useful semantics, but the file tree, selected-path details, marked +list, document text and much of the application state are missing. This +audit records failures and explicit validation gaps; it is not a claim of +WCAG conformance or a successful three-platform screen-reader test. + +The audited production source is **v0.14.0, +`4d68f6cb3ca6742529faf3f4436278da11d486d2`**. The audit PR adds only this +report, a fixture generator, test-only contrast measurements and keyboard +regressions. It does not change the production UI or port upstream UI. +Re-run against a new commit after remediation; do not carry these outcomes +forward as proof about a later build. + +Repository guidance and the full PWR-27 description were read first. Its +comments were empty. The earlier history investigation, PwrRoute audits +and PwrDisk PR #26's cleanup-advice inspection are not accessibility +evidence for this audit. + +## Environments and evidence limits + +| Environment | Build and tools | Result and limitation | +| --- | --- | --- | +| macOS | 27.0.1, build 26A434, Apple Silicon; local `cargo build --locked -p disktree-app`; debug v0.14.0; native CUA AX inspection and keyboard input | Native AX and selected keyboard/visual scenarios tested. The isolated `/tmp/PwrDisk-A11y.app` launcher executes this worktree's binary. An already-running installed PwrDisk was inspected only to identify it, then left untouched; its tree is not baseline evidence. | +| VoiceOver | System VoiceOver app; version not obtained | **BLOCKED.** Cmd-F5 did not produce a running VoiceOver. Direct launch through computer use timed out with `-10005: timeoutReached`; subsequent app inventory reported `isRunning: false`. No spoken output, rotor, speech cadence or VoiceOver navigation result is claimed. | +| Windows | Discovered WindowsVM peer: Windows 11 build 26200, x64 | **BLOCKED.** Peer was disconnected. No audited Windows binary, UIA snapshot, Narrator/NVDA version or runtime result. A toolkit Windows adapter in source is not Windows verification. | +| Linux | Dedicated Sandboxer `sb_ypcbvzmzum`, Ubuntu 24.04.5 LTS, x86_64, kernel 6.18.56-sandboxer; base `pwrdisk-base-us-east`, us-east | Build, lint, harness tests and isolated SSH integration ran at the exact baseline commit. These are not native AT tests. | +| Orca / AT-SPI | Same Linux VM | **BLOCKED.** `DISPLAY` and `WAYLAND_DISPLAY` unset, no X11 socket, `command -v orca` empty, no installed Orca/pyatspi version. Xvfb and dbus-run-session exist, but there is no usable desktop/AT session in the available controller. Neither X11 nor Wayland screen-reader behavior was verified. | + +Native AX is direct semantic evidence, not a substitute for speech testing. +Harness focus is GPUI focus, not VoiceOver focus. The controller consistently +reported the native window as AX focused even after application keyboard +selection changed. A missing AX focused item is a finding; it does not prove +that no internal focus handle exists. + +Live inspection used a 2880×1800 capture (1440×900 logical surface), default +dark appearance, 100% UI zoom and the supported maximum 175% UI zoom. +Light appearance and small/zoomed layouts have harness/source coverage as +specified below. OS display/text scaling and OS high-contrast modes were +not changed or verified. Screenshots include the real volume meter even +with a contrived scan, so live captures were not published as wholly +contrived evidence. No scan of the user's home was initiated. + +## Reproduce + +Use a fresh worktree/destination, with no real data in the fixture. Python +3 is required. The generator refuses an existing root and never removes +or overwrites an existing tree. + +```sh +# Start on the audit PR's checkout to use its fixture generator. +python3 scripts/a11y-fixture.py /tmp/pwrdisk-a11y-new +git checkout --detach 4d68f6cb3ca6742529faf3f4436278da11d486d2 +cargo build --locked -p disktree-app +target/debug/pwrdisk --apparent-size +``` + +On Windows choose an unused temporary path and run +`target\debug\pwrdisk.exe --apparent-size`. On macOS `/tmp` resolves to +`/private/tmp`; compare canonical paths. The default fixture has 135 files, +including hidden data, an empty file/directory, nested cache data, 128 small +files, a long name and `Résumé 日本語.txt`. Payloads and timestamps are fixed; +directory timestamps and allocated block sizes are not. Use apparent size +for comparable figures. The live root was `/tmp/pwrdisk-a11y-20261031`. +Use `--entries 50000` in a separate fresh fixture for a longer scan; the +default fixture completes too quickly for a live progress announcement +test. Permission-denied and successful SSH discovery require separate +controlled fixtures; do not infer their AT behavior from this local scan. + +For each native run record the commit, binary/build profile, OS/AT version, +theme, logical dimensions, display scale and UI/text scale. Inspect with +VoiceOver/native AX, Narrator or NVDA/UIA, and Orca/AT-SPI respectively: + +1. Launch without a path. Traverse forward/backward with Tab/Shift-Tab; + inspect host/path field names, values, root rows, selected source, + disabled states and instructions. Try arrows and Escape. Reopen with + `v`. Enter `-audit-invalid` in the host field and Return: validation + must occur without an SSH connection. Compare the visible error with + the accessibility tree and announcements. +2. Enter only the fresh fixture path in the path input and Return. In the + observed build this required a pointer click to seed field focus; + keyboard-only startup did not provide a working Tab route. Observe + scan progress, indeterminate/busy state, Escape cancellation and retry + using a larger fixture. Read progress/error/completion without a stream + of sampled-path announcements. +3. Explore with Tab/Shift-Tab, arrows, Enter and Backspace; filter with `/`. + Compare names, sizes, hierarchy, current root, selection and active + descendant with the visual result. Mark using Space, review with `c`, + change modes with `m`/`p`, return with Escape. Check marked/blocked + reasons and free-space projections. **Do not press Enter or an approval + key in live Review; do not activate its removal control.** +4. Open Help with `?`, inspect all shortcuts and modal boundaries, try + background navigation keys, dismiss with Escape. Open Settings with + Cmd+, on macOS (Ctrl+, elsewhere); inspect every pane and each copy + action. Open Changelog, License, Third-Party Notices and Logs. Read, + search, select, scroll and copy without a pointer. Close auxiliary + windows and check focus restoration. Do not change release channels or + removal limits as part of reading Settings. +5. Check native menus on macOS; on Windows/Linux test F10/Alt, arrows, + activation and Escape. Check disabled items, submenu order and focus + return. Repeat relevant screens in light/dark/high-contrast appearance, + at minimum window sizes and large UI/OS text/display scale, with long + paths, and with reduced motion enabled. + +Removal confirmation and destructive outcomes are **harness-only** here. +Existing tests operate on temporary trees and verify unmarked neighbors. +Any future interactive destructive test needs a human operator; never use +computer use, AX, UIA or AT-SPI to approve removal. + +## Audit matrix + +`PASS` means only the stated assertion passed. `FAIL` means an observed or +source-demonstrated defect. `BLOCKED` means an unavailable runtime or +controller capability. `NOT TESTED` identifies an unexercised case. +Evidence: **M** = live macOS native AX/keyboard/visual observation; +**H** = GPUI window harness (macOS and Linux); **S** = source inspection; +**C** = computed production-color diagnostic. H/S/C do not establish native +screen-reader interoperability. **Every native Windows and Linux row below +is BLOCKED** for the environment reasons above, including menu, contrast, +scale and motion runtime checks. Spoken VoiceOver results are also BLOCKED +for every row. See [PWR-36](https://linear.app/pwrdrvr/issue/PWR-36). + +| Area / promise | macOS native semantics / visual result | Keyboard / additional evidence | Finding | +| --- | --- | --- | --- | +| Startup has no implicit scan | NOT TESTED through AT | PASS H: `startup_chooser_never_scans_before_explicit_acceptance` | Preserve | +| Source input names, values and relationships | FAIL M: two unnamed text fields; entered host value not observable in AX snapshot | FAIL M: repeated Tab/Shift-Tab left native focus on window; pointer needed for path input | F2, F3 | +| Mount/source choices and reading order | FAIL M: visible mount rows and source explanation absent; no selected root row exposed | PASS H: arrows and explicit acceptance; full keyboard reachability FAIL M | F2, F3 | +| Source modal containment/restoration | FAIL M: background toolbar still exposed, no dialog in AX snapshot | PASS H: background mark/review/filter/rescan keys contained; Escape restores application root focus | F3 | +| SSH invalid destination/error | FAIL M: visible `invalid SSH destination`, unchanged AX | PASS H: invalid host cannot start scan/change existing source; M field activation worked after pointer focus | F2 | +| Successful SSH chooser and authentication failures | NOT TESTED M/AT | PASS H: simulated remote source/error cases; PASS Linux SSH integration, not native AT | PWR-36 | +| Scan progress, busy, cancel and completion | NOT TESTED native progress: default tree completed before capture; FAIL S: progress/notice strings have no semantic status/progress nodes | PASS H: initial/widening scan Escape cancel and retry; preview/progress remain bounded and non-actionable | F2 | +| Explore file hierarchy and selection | FAIL M: no file/tree nodes, sizes, hierarchy or selected-item state | PASS M/H: Tab/arrows move visual selection; Enter/Backspace handled in harness | F1 | +| Filter / search | FAIL S: explore filter is custom key-fed text without input/result semantics | PASS H: typing, Enter and Escape; no native speech result | F1, F2 | +| Marks and review rows | FAIL M: marked paths, row reasons and summary text absent; Unmark button alone does not name the row | PASS M/H: Space and c open review; Escape returns | F1 | +| Review mode names/selected state | PASS M: `Move to trash` / `Delete permanently` radio buttons and selected state track m/p | PASS M/H: mode keys; no live approval attempted | Preserve | +| Removal alert names/description/actions | NOT TESTED native AX or speech | PASS H: open, contain background shortcuts, Tab/Shift-Tab remain in application dialog, Escape restores Review/root focus, files retained | F3; PWR-36 | +| Destructive completion and unmarked neighbors | NOT TESTED interactively by design | PASS H: existing permanent-removal and link tests operate on temporary trees | Preserve | +| Toolbar/control names and actions | FAIL M: `<`, `>`, `−`, `+` names lack purpose/context; radio/checkbox names and state present | PASS M: field/button activation where exercised; all safe control actions not individually tested | F2, F3 | +| Disabled-state metadata | FAIL M/S: visually disabled Scan controls still ordinary AX buttons; Base test records missing disabled flag | Click action removal in Base is not a disabled-state announcement; native disabled-action invocation NOT TESTED | F3 | +| Native macOS menus | PASS M: named File/Edit/View/Go/Window/Help headings exposed | BLOCKED: native Help menu click did not complete; controller required refresh, Ctrl-F2 made no observable change. Popup keyboard operation not verified | PWR-36 | +| Off-macOS app/menu popovers | BLOCKED native | FAIL S: custom clickable Div rows without roles; root menu handling only dismisses on Escape; full platform keyboard behavior NOT TESTED | F3 | +| Settings pane order/content | FAIL M: pane selectors/titles/descriptions absent; Tab changes panes with AX focus at window | PASS M/H: pane cycling, updates shortcuts; control-by-control traversal FAIL M | F3, F4 | +| About / copy names | FAIL M: two indistinguishable `Copy` buttons, no surrounding identity text | Safe actions exposed; complete keyboard-only copy path NOT TESTED | F4 | +| Help shortcut overlay | FAIL M: no added AX content or modal role; underlying controls remain | PASS H: background navigation/action keys contained, Escape restores operation; FAIL M: sheet clipped vertically | F3, F4, F6 | +| Changelog / License / Notices | FAIL M: only Copy and native window controls; no text, headings or document reading order | PASS M: close returns to Settings; Tab/PageDown did not expose document navigation; scrolling outcome NOT TESTED | F4 | +| Logs | FAIL M: unnamed search, no log text; Wrap/Mark/Live exposed as buttons without observed state semantics | PASS H: filtering/rotation/selection/copy; Cmd-F exposed no AX focused search item in live check | F3, F4 | +| Progress/error/selection/mark/free-space announcements | FAIL M/S for missing current readable state; speech/cadence BLOCKED | No measured announcement frequency; cannot claim throttling or silence is correct | F1, F2 | +| Light/dark text and non-text contrast | FAIL C: ratios below thresholds, table below | PASS H only means both appearances draw; light native appearance NOT TESTED | F5 | +| Color-independent meaning | PASS M/S: reclaimable hatch, visible Marked text, sizes, selection outline; FAIL S: color/fading carries age/filter state without equivalent semantic file content | Combined selected+marked, unreadable and all color-vision simulations NOT TESTED | F1, F5 | +| Main UI zoom / clipping | PASS M: zoom grows UI through 175%; FAIL M: Help clipped at 100% and 175%; 200% unsupported by configured steps | PASS H: chooser/progress bounds at small dimensions/large rem; all-screen minimum-size sweep NOT TESTED | F6 | +| Auxiliary zoom / OS scaling | FAIL S: main zoom handler not shared with auxiliary windows | OS text/display scale and high-contrast runtime checks NOT TESTED on macOS; BLOCKED Windows/Linux | F6; PWR-36 | +| Long/Unicode names and tiny targets | PASS M: Unicode name drawn; long tile name clipped; FAIL for accessible full-path alternative (F1) | Target pixel/spacing sweep NOT TESTED; small controls/tiles require measurement | F1, F6 | +| Reduced motion | FAIL S: custom LayoutTransition creation/sampling does not read `cx.reduce_motion()` | OS preference runtime toggle NOT TESTED; no claim that Base preference import disables custom animation | F7 | + +### Native AX evidence excerpts + +These are transcribed relevant portions, not complete raw dumps. Window +controls and menu headings are omitted below. Indices are transient. + +```text +Source chooser: + container + button < + button > + radio button (selected, settable, boolean) Size + radio button (selectable, settable, boolean) Files + radio button (selectable, settable, boolean) Age + checkbox (settable, boolean) Hidden files, Value: on + checkbox (settable, boolean) Apparent size, Value: on + button − + button + + button Power Efficiency: Balanced + button This computer + text field + button Connect SSH + text field + button Scan directory + button Cancel + button Scan selected root + focused UI element: standard window + +Explore after Tab: + toolbar controls as above + button Open + button Mark for removal + button Source… + no file nodes or selected path/size; focused UI element: standard window + +Review after p: + button Unmark + radio button (selectable, settable, boolean) Move to trash + radio button (selected, settable, boolean) Delete permanently + button Save list… + button Copy as prompt + button Save delete script… + button Copy delete script + button Back + button Delete 0 items… + +License / Third-Party Notices / Changelog after frame settles: + button Copy + no document text; focused UI element: standard window + +Logs: + button Copy path + button Reveal + text field + button Wrap + button Mark + button Live + no log text; focused UI element: standard window +``` + +The live review mark was a hidden fixture directory held back by the plan; +the zero executable item count is not evidence of a deletion-count bug. +The held-back explanation was visible but missing from AX, which is the +finding. The harness separately marks a removable `junk` directory. + +## Severity-ranked findings and remediation + +High means a required task or essential information is unavailable to an +affected user. Medium means a serious preference/usability failure with a +potential alternative. Severity is task impact, not a conformance ruling. +Each issue is in the **PwrDisk** Linear project, linked under PWR-27. + +| ID | Severity | Observed failure / reproduction | Remediation | +| --- | --- | --- | --- | +| F1 | High | Scan fixture, Tab/arrows, Space, c: visual files/selection/marks/review exist without corresponding accessible data | [PWR-29](https://linear.app/pwrdrvr/issue/PWR-29): semantic scalable file navigation, selection, marks and review; stable IDs and safe actions | +| F2 | High | Startup two unnamed inputs; `-audit-invalid` + Return shows an error absent from AX; progress/status lack semantic nodes | [PWR-30](https://linear.app/pwrdrvr/issue/PWR-30): named inputs/values/relationships, selected source, progress/errors/free-space status and measured announcement throttling | +| F3 | High | Tab does not traverse startup controls; overlays expose background controls; application focus is not an AX item; disabled metadata incomplete | [PWR-31](https://linear.app/pwrdrvr/issue/PWR-31): traversal, visible focus, modal/menu containment, useful restoration and disabled semantics | +| F4 | High | ? / Settings / documents / Logs expose action fragments but omit readable content and context | [PWR-32](https://linear.app/pwrdrvr/issue/PWR-32): structured text/panes/documents/logs, contextual names and keyboard reading/scrolling | +| F5 | High | Run contrast diagnostic: default palettes fail text/state thresholds; semantic alternatives to color-carried age/filter meaning absent | [PWR-33](https://linear.app/pwrdrvr/issue/PWR-33): production contrast thresholds and non-color state equivalents | +| F6 | High | Help overflows at 100% and 175%; main zoom capped at 175%, auxiliary windows lack shared zoom route | [PWR-34](https://linear.app/pwrdrvr/issue/PWR-34): scrolling/reflow/scaling, long paths and target-size measurements; verify capture-specific sidebar clipping independently | +| F7 | Medium | Source: descend/history transitions always create/sample LayoutTransition irrespective of reduced motion | [PWR-35](https://linear.app/pwrdrvr/issue/PWR-35): honor preference in custom navigation animation and test final geometry/history | +| G1 | High validation gap | VoiceOver unavailable, Windows peer disconnected, Linux without desktop/Orca; native scaling/menu/AT scenarios incomplete | [PWR-36](https://linear.app/pwrdrvr/issue/PWR-36): finish native platform and AT matrix, keep unobserved cells explicit | + +### Contrast measurements + +Run against the audit test code (using the unchanged production palettes): + +```sh +cargo test --locked -p disktree-app audit_contrast_report -- --ignored --nocapture +``` + +The diagnostic computes sRGB relative luminance after alpha compositing +the text over an opaque fill. It samples all **11** categories, all **5** +age buckets and depths **0–4**. Numbers are minima per pair. Text uses a +4.5:1 reference; selection ring versus adjacent fill uses 3:1. Exit 0 means +the report ran, **not** that contrast passed. The output intentionally +reports known failures outside the normal regression gate. + +References: W3C's [contrast minimum](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html) +and [non-text contrast](https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html) +explain these thresholds. [Reflow](https://www.w3.org/WAI/WCAG22/Understanding/reflow.html) +and [target size](https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum.html) +inform the outstanding scaling/target checks. These are evaluation +references, not a claim that this native-app audit determines conformance. + +| Pair | Tokyo Night | Flexoki Light | Required | +| --- | ---: | ---: | ---: | +| Normal tile name | **3.856 FAIL** | 6.162 PASS | 4.5 | +| Dim tile size | **2.083 FAIL** | **2.393 FAIL** | 4.5 | +| Selected ring versus tile fill | 3.610 PASS | **2.285 FAIL** | 3.0 | +| Marked name on marked fill | 5.460 PASS | **3.967 FAIL** | 4.5 | +| Secondary caption at 75% on background | 5.131 PASS | **3.872 FAIL** | 4.5 | +| Text on highlighted action | 8.547 PASS | **3.184 FAIL** | 4.5 | + +These are flat-fill calculations, not raster measurements of glyph edges +or hatch intersections. Not every view uses every pair. Hover, filtered, +unreadable, combined marked/selected, disabled, borders, focus indicators, +custom Omarchy themes and OS high-contrast modes need additional rendered +checks. Distinct hue tests in the existing palette suite do not establish +contrast or color-independent meaning. + +## Toolkit bridge investigation + +The lockfile selects GPUI Kit/Base **0.6.6**, GPUI pre **0.3.6**, Omarchy +**0.1.3**, and AccessKit **0.24.1**. Adapter implementations exist for +macOS (`SubclassingAdapter`), Windows (`Adapter`, WM_GETOBJECT handling), +and Linux X11/Wayland (`accesskit_unix::Adapter`). macOS buttons/radio +buttons/checkboxes observed above demonstrate that the bridge is active. +It is incorrect to describe GPUI as having no accessibility support. + +The GPUI accessibility guide requires IDs and roles; ordinary string +children are not automatically a readable document. PwrDisk chiefly uses +plain Div/string content and a painted canvas; inspection found only one +explicit app accessibility label override (Power Efficiency). The canvas +needs a semantic navigation path. GPUI supports synthetic accessibility +children, but their existence does not make this canvas accessible. +`debug_selector` identifiers used by harness tests are not accessible +names or roles. + +There is also a concrete toolkit gap: GPUI Base's +`button::tests::accessibility_role_label_and_disabled_action_surface` +explicitly asserts `!disabled.is_disabled()` and explains that the GPUI +interface lacks a disabled-state setter even though AccessKit supports +one. Removing the Click action is not equivalent to conveying disabled +state. Input names/values/focus and modal semantics need investigation in +both the app and toolkit, without attributing every missing app role to +the platform bridge. Windows and Linux adapter correctness remains +unverified here. PWR-31 tracks the owning-layer work. + +Relevant baseline source: [views](../crates/disktree-app/src/views.rs), +[state](../crates/disktree-app/src/state.rs), +[treemap](../crates/disktree-app/src/treemap_view.rs), +[Settings](../crates/disktree-app/src/settings.rs), +[documents](../crates/disktree-app/src/doc_window.rs), +[Logs](../crates/disktree-app/src/logs_window.rs), +[appearance](../crates/disktree-app/src/appearance.rs), +[palette](../crates/disktree-app/src/palette.rs), and +[scale tokens](../crates/disktree-app/src/ui.rs). + +## Upstream remediation candidates + +Inspected PR descriptions and full diffs on 2026-10-31; both were open. +Neither was built or run in this audit, and neither was imported. + +* [tobi/disktree #51](https://github.com/tobi/disktree/pull/51), head + `b7879541c4dfc709009725b376bc0d138a8f2e3c`: virtualized row view, + expansion, arrows, shared selection/marks/filter and offscreen-row + composition test. Useful groundwork for a scalable alternative to + spatial tiles. The reviewed diff has no tree/list roles, accessibility + item states/relationships or AT results. Virtualization must not make + offscreen files unreachable to AT. Evaluate selected pieces in PWR-29, + coordinated with [PWR-28](https://linear.app/pwrdrvr/issue/PWR-28). +* [tobi/disktree #58](https://github.com/tobi/disktree/pull/58), head + `c9f454d5e8cac841be265c01f11eba18984060d5`: fixed themes, persistence, + and alpha-composited contrast tests. Useful calculation/test patterns. + Its `tile_names_stay_readable_on_every_fill` covers nine categories, + normal labels, category/age/marked fills and theme variants. It does not + cover PwrDisk's two extra categories, 50%-opacity size text, all status + captions/actions, focus/state boundaries, high-contrast OS behavior or + screen-reader usability. Evaluate narrowly in PWR-33; theme picker and + persistence are independent product work. + +## Regression coverage and verification + +New `audit_` regressions in [tests.rs](../crates/disktree-app/src/tests.rs) +verify Help background-key containment and resumed marking, source-picker +background-key containment and focus restoration, and removal-dialog +background-key containment plus Tab/Shift-Tab containment and Escape +cancellation. The confirmation test never sends the final approval action. +Files and marks remain after cancellation. These preserve existing safety +and keyboard promises; they do not encode missing semantics as acceptable +behavior. + +The palette suite adds a regression for alpha-composited contrast math +(black/white 21:1, transparent 1:1, half-white on black about 5.281:1) and +an explicitly ignored diagnostic for the table above. Future color fixes +need threshold assertions over corrected production colors. No production +fix is claimed by passing the math or keyboard tests. + +Existing harness tests cover scan/cancel/retry, explicit chooser +acceptance, invalid SSH input, metric/selection preservation, filtering, +marks/review, removal guards, Settings, documents, Logs, both appearances, +and bounded chooser/progress layouts. They draw frames or inspect state, +not native AX/UIA/AT-SPI. The headless platform does not activate native AT; +native semantic regressions still need to be added with the remediation. + +```sh +cargo test --locked -p disktree-app audit_ -- --include-ignored --nocapture +cargo xtask lint +cargo xtask test +``` + +Baseline Linux verification in the dedicated VM used +`scripts/sandboxer/verify.sh all`: + +| Step | Exit | Seconds | +| --- | ---: | ---: | +| setup | 0 | 2 | +| lint | 0 | 16 | +| test | 0 | 30 | +| portable build | 0 | 84 | +| SSH integration | 0 | 7 | +| all | 0 | — | + +Final audit-commit verification is recorded in the PR, including the +commit SHA and platform result. Documentation/test-only changes do not +have a before/after production window change. The audit publishes text +and numeric evidence; future visible remediations require contrived +before/after PR attachments under [the screenshot procedure](pr-screenshots.md). + +## Remediation observations (separate from the v0.14.0 baseline) + +### PWR-29: file navigation and review + +Source: `0568e97cff3c29beebd3a70556e8f3de0765f93d`, debug macOS build, +2026-10-31. Binary SHA-256: +`98dfba4cde4a3c79b79c71cb86e0a2f7ae9d3918280855fdbd32cc0074e09a22`. +The original matrix above remains a record of the production baseline. + +The new **Show accessible file list** control opens a directory-at-a-time +list over the completed scan. Right/Enter opens a directory, Left/Backspace +returns to its parent, Up/Down selects, Space marks and c reviews. Explicit +100-entry pages bound layout/AX work without silently dropping later entries. +Rows use lossless absolute-path identifiers; category, size, age, unreadable, +filter and mark context have text equivalents. Review pages expose all marks, +row explanations and the selected removal mode/recoverability summary. +This is a navigation alternative, not an expansion of the painted canvas. + +| Promise | Native macOS AX / keyboard observation | Harness / source evidence | +| --- | --- | --- | +| File data and hierarchy | PASS for inspected fixture: list, full paths, directory/file kind, byte and formatted sizes, category, age and selected state exposed; Right/Left changed the named directory | PASS: nested absolute paths and filtering regression | +| Long / Unicode paths | PASS: full `Résumé 日本語.txt` and long-name path exposed under `documents` | PASS: 235 Unicode-named fixture files | +| Offscreen entries and counts | PASS: `many-small-files` reports 128 entries; PageDown exposes 101–128, selects `item-000100.txt`, and includes `item-000127.txt` | PASS: page boundaries at 99/100/200; bounded row composition; source supplies set position/count | +| Marks and review | PASS for inspected fixture: marked path, exact byte count, included/blocked/covered counts, mode and recoverability exposed; no live approval | PASS: existing removal guards and destructive harness tests; new safe-mark/navigation tests | +| Accessible identity / state | Stable path author IDs and selection updates observed | PASS: role, name, selected flag, author ID and non-UTF-8 collision regressions | +| Native focused item / speech | NOT VERIFIED: controller still reports the standard window as focused despite selected-state updates; no spoken-output result | Source provides a focusable list and active-descendant metadata; this is not native focus or speech evidence. PWR-31/PWR-36 remain open | +| Windows UIA / Narrator / NVDA | BLOCKED: WindowsVM still disconnected | No Windows runtime result | +| Linux AT-SPI / Orca | BLOCKED: dedicated VM has neither DISPLAY/WAYLAND_DISPLAY nor Orca | Linux checks are recorded separately in the PR | + +Fixture: `scripts/a11y-fixture.py`, 135 invented files on a disposable APFS +disk image named **A11yFixtures**, root `/Volumes/A11yFixtures/Projects`. +macOS 27.0.1 / 26A434, Apple Silicon, dark appearance, 1440×900 logical, +100% UI zoom. The isolated Before/After launchers leave installed PwrDisk +untouched. Before uses audit head `12d2bef` (unchanged production UI); +contrived window-only before/after images are attached to the remediation PR. +OS scaling, high contrast and spoken screen-reader output were not tested. + +macOS `cargo xtask lint`, `cargo xtask test` and debug build passed. Linux +Sandboxer `sb_uihqpdf98b`, Ubuntu 24.04.5 x86_64, verified the implementation +commit; final build/integration status is recorded in the PR. No native Linux +result is inferred from those checks. + +Upstream #51 was re-evaluated narrowly: its virtual row composition and +shared selection/marks are useful patterns, but its row-index IDs, row cap +and absence of accessibility roles do not satisfy this issue. No upstream +commits or theme/list redesign were imported. + +### PWR-30: source fields and current status + +Source `9729798`, debug macOS binary SHA-256 +`40b43a26cea199b307cf0b8e543de628918da262acf634b2c43aadea6e821809`, +same contrived Projects fixture, OS and scale as PWR-29 above. + +| Promise | Observed native macOS AX | Harness / source | +| --- | --- | --- | +| Persistent source names and values | PASS: `SSH destination` and `Root directory to scan` exposed; entered `-audit-invalid` observable as the host value | Field semantics include current values and descriptions | +| Validation context | PASS: `invalid SSH destination` exposed and included in field descriptions after Return; no SSH connection attempted | Invalid flags distinguish connection and path errors; existing invalid-host/path and discovery regressions remain green | +| Source instructions | PASS: explicit Scan acceptance, nested-mount/symlink cautions and remote read-only context exposed | Source list has selected-root metadata and stable mount-path IDs; native mount traversal remains unverified | +| Current state and volume | PASS: completed scan, fixture root, marked count and 506 MiB available of 512 MiB exposed | Marked plan byte totals and estimates are independently readable; no extra per-frame mark scan | +| Progress/cancel/errors | Live progress not exercised: small fixture completes before inspection | PASS: two-second progress cache, error bypass, immediate cancel and completion regression; indeterminate progress/busy metadata; sampled paths omitted | +| Announcements | BLOCKED for speech/cadence; exposing a polite live region is not a spoken-output pass | Source live metadata and throttling only | + +macOS lint, full workspace tests (including 219 app tests) and debug build +passed. Dedicated Linux VM `sb_uihqpdf98b` at `9729798`: setup 0 (2s), lint +0 (5s), test 0 (14s), portable build 0 (44s), isolated SSH 0 (3s), all 0. +These are build/harness/integration results, not AT-SPI or Orca evidence. +Native focus/modal containment, Windows UIA/AT, speech, OS scaling and high +contrast remain open under PWR-31/PWR-36. Changes add semantic metadata; +the visible source/status presentation is unchanged, so screenshots do not +show the repaired names/values. No real scan or live removal was performed. + +### PWR-31: focus, modal boundaries and menus + +Source `08a2b7f865d76db375b38cb5693ac1727cfa6186`, debug macOS binary +SHA-256 `d4e7b7c11f5b21314dff6a9edfc7f5ea6c08769d2655bad04b5ae866ddbf6d1a`. +Tab/Shift-Tab traverse controls and composite navigation; n/Shift-n retain +sibling stepping. Escape returns to file navigation. Modal traversal stays +inside its scope and dismissal restores the invoking focus handle. Explicit +tracked handles carry their own tab metadata: element styles alone did not +make the root/file lists reachable; strengthened regressions caught this. + +| Promise | Native macOS result | Harness / source | +| --- | --- | --- | +| Visible traversal | PASS inspected case: Tab adds a visible focus edge to Size while retaining file selection | PASS: Tab reaches file navigation without changing selection; 50,000 empty files remain reachable in bounded pages | +| Source fields / root list | PASS keyboard: Tab reaches host and path inputs; keystrokes appear as values `a` and `b`; no acceptance or SSH connection | PASS: forward/reverse traversal reaches both inputs and the root list, stays in modal and restores originating control | +| Help / source AX boundaries | PASS inspected trees: named dialogs exposed and application background controls absent from full AX snapshots | PASS: modal background shortcuts contained, safe Escape cancellation; opaque overlays contain pointer input | +| Disabled actions | PASS: history and unconnected Scan buttons report disabled in native AX | Supported synthetic parent metadata supplies the flag omitted by the pinned button; Click remains removed by the base control | +| Settings navigation | PASS: named Settings panes tab group and four tab states; Tab leaves Updates selected; Ctrl+PageDown selects Safety without changing a preference | PASS: pane navigation and control traversal regressions; Ctrl+PageUp/PageDown replace pane-cycling Tab | +| Custom menu | NOT TESTED natively on Windows/Linux | PASS: arrows, Escape and Enter on the safe Keyboard Shortcuts action; menu/item/shortcut metadata and scroll-follow | +| Removal alert | NOT TESTED natively by design | PASS: named alert metadata, keyboard containment and Escape retain files; destructive coverage remains harness-only | +| AT focus / speech | Controller still reports the standard window as focused; no speech/navigation result | GPUI focus and active-descendant metadata do not establish VoiceOver/UIA/AT-SPI behavior | + +macOS lint, full workspace tests (225 app tests) and debug build passed. +Linux `sb_uihqpdf98b` at this commit: setup 0 (1s), lint 0 (5s), test 0 +(12s), portable build 0 (43s), isolated SSH 0 (2s), all 0. Native Windows, +Linux desktop/Orca, speech, native menu operation and OS scaling/high-contrast +remain unverified under PWR-36. Help content/reflow findings remain tracked +under PWR-32/PWR-34. + +Contrived before/after focus images use PWR-30 head `21ae8fe` and this commit, +the same Projects/APFS fixture, default dark appearance and 100% UI zoom. +Both windows were fitted with macOS's window Zoom action: 2992×1878 pixel +captures (1496×939 logical at 2×). The initial offscreen capture had white +clipped edges and was replaced; that capture artifact is not a layout fix. +Before, Tab changes the selected tile; after, it focuses Size. No removal +confirmation was activated through computer use or accessibility APIs. + +### PWR-31 review corrections: modal intent and foreground keys + +Production source `d256dff65b5f95c8cd8d02b39f9a57daac982679` corrects the +three findings from PR #42's review at `e0f643c`. All six new +`focus_review_` window-harness tests fail on the reviewed production code +and pass after the correction. They use generated temporary trees only. + +| Promise | Reviewed behavior | Observed harness result after correction | +| --- | --- | --- | +| Focused modal actions | Enter on Cancel starts removal or accepts a scan root | Enter/Space on removal Cancel leave marks and files intact; source Cancel starts no scan; focused Delete removes only its marked temporary directory | +| Foreground Escape | An indexing interception consumes Escape ahead of foreground screen commands | Running requests a removal stop while preserving the background scan; Review/Done return to Explore with the refresh intact | +| Settings pane traversal | Focusable pane selectors are omitted from the tab order | Forward and reverse traversal reach each of the four pane selectors | +| Application menu trigger | Focusable trigger is omitted from the tab order | Forward and reverse traversal reach the trigger; Enter opens its menu and Escape restores focus | + +The modal's Confirm action is handled by the focused button using the same +callback as pointer activation. Dialog defaults apply only to their +container, root list or input context. Scan-specific Escape interception is +limited to Explore. Settings panes and the custom menu trigger explicitly +register as tab stops. These corrections change keyboard behavior, without +adding a visible layout or style; the existing contrived focus images keep +their original build provenance. + +macOS 27.0.1 arm64: `cargo xtask lint`, full workspace tests (251 app passed, +2 ignored; 233 core passed, 7 ignored), and the normal debug app build pass. +Ubuntu 24.04.5 x86_64 Sandboxer `sb_uihqpdf98b`, same production source: +setup 0 (1s), lint 0 (7s), tests 0 (16s), portable build 0 (45s), isolated +SSH 0 (2s), all 0. + +Native AX/UIA/AT-SPI and VoiceOver/Narrator/NVDA/Orca were not rerun for +these corrections. The Windows peer is disconnected; Windows verification +is pending CI. Native keyboard/AT containment and OS display/text scaling, +high contrast and speech remain separate acceptance gaps. The Running +cancellation-routing test uses an empty removal plan to avoid a deletion +race. Actual removal and confirmation coverage is confined to the +contrived-filesystem harness; no computer-use or accessibility API approved +removal. + +### PWR-31 review corrections: foreground Escape and Help menus + +Production source `471fbf02fe0bbc07e9a5b48782c65c4c22818975` corrects the +two keyboard-routing findings from PR #42's review at `040e68a`. Three new +`routing_review_` window-harness tests fail on that reviewed source and +pass after the correction. Every scan uses a generated temporary tree. + +| Promise | Reviewed behavior | Observed harness result after correction | +| --- | --- | --- | +| Search Escape during widening | Cancels the background scan and leaves search open | Clears search in treemap and file-list views without changing the scan epoch or cancelling; the next Escape cancels the scan | +| Menu Escape during widening | Cancels the scan before dismissing the foreground menu | Breadcrumb, power and application menus dismiss while the scan continues; a subsequent Escape cancels | +| Help owns keyboard navigation | Existing menus remain active behind Help | Both `?` and the keyboard-shortcuts action close all three menu types before Help opens; Down/Enter cannot navigate the underlying directory or change marks | + +The root handler delegates scan-time Escape to the existing dispatcher, +which already gives menus, search and applied filters precedence over scan +cancellation. `open_help` clears menu state for both shortcut and action +entry points. The focused tests retain the existing tree and verify the +contrived files remain present. No removal is requested by these tests. + +macOS 27.0.1 arm64: `cargo xtask lint`, full workspace tests (254 app passed, +2 ignored; 233 core passed, 7 ignored), and the normal debug app build pass. +Ubuntu 24.04.5 x86_64 Sandboxer `sb_uihqpdf98b`, same production source: +setup 0 (1s), lint 0 (14s), tests 0 (23s), portable build 0 (43s), isolated +SSH 0 (2s), all 0. The sandbox was stopped after verification. + +These are harness/source results. Native AX/UIA/AT-SPI and +VoiceOver/Narrator/NVDA/Orca were not rerun; Windows verification awaits CI. +Native menu/AT containment, OS display/text scaling, high contrast and +speech remain separate acceptance gaps. No native removal confirmation or +accessibility action was performed. These routing corrections add no new +layout or styling; the earlier contrived focus images keep their original +build provenance. + +### PWR-31 integration with main's dialog, toast and Settings changes + +Merge `4c71496866c9162b363c305eafdacf21dac3ec05` brings PR #42 onto main at +`cb3565d` (#50 platform footers and source switch, #51 update toasts, #52 +grouped Settings). It keeps main's layout and reapplies this PR's modal +actions, conditional dialog defaults, disabled metadata, tab stops and +focus restoration to it. Two follow-ups apply the PR's own rules to what +main added: + +| Promise | Integrated behavior before follow-up | After | +| --- | --- | --- | +| Disabled metadata | The update toast's held "Restart after the removal" used the pinned button's `disabled`, which omits the native flag | `semantic_disabled`, like every other disabled button (`133183a`) | +| Visible Settings focus | Main marks the shown pane with a left accent bar; focus recoloured that bar, so focus on the shown pane was invisible and a focused pane looked shown | Focus draws the app's full accent outline on a wrapper; the bar stays the selection (`0ea7fe8`) | + +Contrived images: `pwrdisk` debug builds of main `cb3565d` and `0ea7fe8`, +scanning Projects on the APFS image A11yFixtures, macOS 27.0.1, Settings +window 1000×681 logical (2000×1362 capture), dark, 100% UI zoom. Before, +one Tab in a fresh Settings switches to Safety with no focus mark; after, +two Tabs focus the Safety tab with an outline while Updates stays shown. +Keys were sent with System Events; nothing was removed or confirmed. + +macOS 27.0.1 arm64 at `0ea7fe8`: `cargo xtask lint`, full workspace tests +(268 app passed, 2 ignored; 233 core passed, 7 ignored) and the debug app +build pass. One test run aborted when gpui-omarchy's theme-file watcher +thread woke inside `an_agent_marks_shows_and_reviews_over_the_link`; the +unchanged rerun passed. Ubuntu 24.04.5 x86_64 Sandboxer `sb_uihqpdf98b`, +same source: setup 0 (1s), lint 0 (5s), tests 0 (12s; 264 app, 221 core), +portable build 0 (44s), isolated SSH 0 (2s), all 0; stopped afterward. + +The watcher failure was resolved by the November 2 follow-up below. + +The Settings outline was observed in the native macOS window only. Native +AX/UIA/AT-SPI and VoiceOver/Narrator/NVDA/Orca were not rerun for the +integration; Windows is verified by CI. The native acceptance gaps above +remain open. + +### PWR-32: auxiliary text and keyboard reading + +Implementation `e47e994`, Copy-name correction `0cb8d3e`, rebased on main +`cece3b9`. Final macOS debug binary SHA-256: +`0495f8e49c8cea040fa9d67c8182137ec7f769b34f205449bf30b9b78313917d`. +The native log example at `e47e994` reuses the production views with an +explicitly supplied invented log and no preference file; it never opens the +production log, scans, or removal UI. + +| Surface | Observed native macOS AX / keyboard | Harness / source | +| --- | --- | --- | +| Help | PASS inspected sheet: heading and all shortcut descriptions exposed; background absent | Existing modal/keyboard tests remain green | +| Settings | PASS About: pane/card headings, descriptions, version/build/source values and project URLs exposed | Named groups scope repeated field/value IDs; channels expose radio state and retain keyboard activation | +| Contextual Copy | Initial native run found that the base button overwrote `aria_label`; corrected through its supported `accessibility_label` API. PASS final native names: Copy checkout path, Copy branch or tag, Copy commit, Copy complete License | Copy actions retain their existing payloads; complete-document clipboard regression passes | +| Documents | PASS: all 22 license lines; End reaches notices line 25,779 and exposes its final rows | PASS: long-notices Home/End brings virtual rows into view and keyboard Copy copies the complete source. Changelog contributes heading/paragraph semantics and block navigation | +| Logs | PASS invented 300-line log: named search, level/mode states, Unicode rows, selected lines 1 and 300, paused/live summary. Search for invented line 299 exposes one match | PASS keyboard Home/End, selected-line copying and existing search/rotation/empty-log tests. Input Escape action is captured to return to the log reader | +| Announcements / focus | No spoken-output result; native controller still reports the standard window as focused | Appending lines/counts deliberately have no live-region metadata; this does not prove AT announcement behavior | + +macOS 27.0.1 / 26A434 arm64, default dark, 100% UI zoom. Native fixture log: +`/private/tmp/pwrdisk-a11y-invented.log`, 300 invented INFO lines with Unicode. +No real logs, diagnostics, removal approval or deletion were used. Closing +document and Settings windows returned to the fixture main window; useful +AT focus restoration and speech still require an actual screen reader. + +Final `0cb8d3e`: macOS lint, full workspace tests (234 app tests) and debug +main/example builds passed. Dedicated Ubuntu 24.04.5 x86_64 Sandboxer: +setup 0 (1s), lint 0 (4s), tests 0 (11s), portable build 0 (44s), isolated +SSH 0 (2s), all 0. The earlier integrated `e47e994` run also passed all +five checks. These results cover the rebased PWR-29/30/31 implementation; +their historical native observations above retain their original SHAs. + +Windows UIA/Narrator/NVDA, Linux AT-SPI/Orca, actual VoiceOver reading, +OS scaling/high contrast and document reflow are not verified here. +Semantic text/names do not produce a meaningful pixel comparison; operator +review of the native evidence in lieu of before/after images is required +before merging. Visible reflow/scaling changes belong to PWR-34. + +### PWR-32 on main's Settings and About redesign + +PR #43 moves onto main `a63a726` (after #42, #52 grouped Settings and #55 +About header) as one implementation commit plus this record; #42's merged +commits are omitted. Main had replaced the Settings panes this work named, +so its semantics are applied to the new ones rather than restoring the old +layout: + +| Surface on main | Applied | +| --- | --- | +| Pane head, cards, fields | Pane title and card titles are headings; heads, cards and fields are named groups; labels, descriptions and values are readable text | +| Safety | The "Applies to" statement is readable; load errors and save notes are alerts | +| Updates grid | Each channel tile is a radio button named for its slot and purpose, with its toggled state; Enter/Space pick, arrows move as the window's keys do; the channel caption, follow/picked line and status are readable | +| About header (#55) | Version is a heading; the build line keeps its whole text as its label when the painted line is cut short | +| Copy buttons | Diagnostics, checkout, branch or tag and commit Copy buttons carry distinct names, prefixed "Copied:" after use | + +The native fixture example has since become a debug build's `pwrdisk +logs-fixture LOG` (`crates/disktree-app/src/logs_fixture.rs`), which opens +the same Logs window with no module list to keep in step. The earlier +native macOS AX observations above were made on the old Settings layout; +they were not repeated on main's panes. The Settings/About part of this +record is harness/source evidence only. + +Contrived Logs images: debug builds of main `a63a726` and this PR, with +`HOME` set to a temporary folder holding 300 invented INFO lines (plus the +three lines each run writes), macOS 27.0.1, Logs window 1120×721 logical +(2240×1442 capture), dark, 100% UI zoom. Help › Logs was opened with +System Events, then Escape and End: main selects nothing; this PR selects +the last line and shows its copy bar. Nothing was scanned beyond a 4 MiB +invented folder, and nothing was removed. + +### PWR-32 review corrections: Tab order, roles and first step + +A high-effort review of PR #43 at `dd9f2f9` found that Tab could not +reach several of the controls this work exposes. In GPUI `focusable()` +alone is not a tab stop, and Tab from the auxiliary windows' title-strip +buttons had no handler at all. Four new `aux_review_` window-harness tests +cover the corrections; every log and document is invented. + +| Promise | Reviewed behavior | After | +| --- | --- | --- | +| Logs controls reachable | Mode and level segments, context-line items and Include diagnostics were focusable but not tab stops; Tab from Copy path/Reveal stayed put | All are tab stops; the shared frame takes Tab (and the text field's indent actions) above the strip, so Tab cycles both ways and Space toggles a level | +| Document Copy | Tab from the title strip's Copy stayed put | Tab reaches the reader from Copy and back | +| Channel radios | Focusable but not a tab stop | One stop for the group, on the picked channel | +| Mode semantics | Filter/Highlight exposed as independent checkboxes | Radio buttons; levels stay checkboxes | +| First keyboard step | Down with no selection selected line 2 | Down starts at line 1, Up at the last line | +| Changelog layout | The scroll area had shrunk to the column width | Window-wide scroll area again; each block keeps the column's width and padding | + +Tab handling moved from the Logs, document and Settings bodies to +`aux_window::frame`. Page Up/Down share one named step. macOS 27.0.1: +lint passes; workspace tests pass (275 app, 233 core) with +`an_agent_marks_shows_and_reviews_over_the_link` skipped. That test passes +alone three times. In full runs on this Mac it now aborts when +gpui-omarchy's theme-file watcher wakes inside it, and does so on the +unreviewed `dd9f2f9` too, which passed earlier the same day. Native AX and +screen readers were not rerun for these corrections. + +The watcher failure was resolved by the November 2 follow-up below. + +### PWR-33: contrast and non-color state cues + +Source `08402c3`, macOS binary SHA-256 +`5f963423d6a1d56f17f4d451f2906a4cecffa990f1faa3af65f43cf80fa3d782`. +Production label colors now use the exact category/age/depth/filter/marked +fill. A passing theme ink is retained; otherwise an opaque black or white +ink is chosen. Name and value runs carry the same opaque tile background, +so hatch cannot become a different text surface. Marked/covered, filtered +and unreadable labels also have text cues; selection has a thicker ring. +Age and category retain readable equivalents in the file list/sidebar. + +| Check | Observed result | +| --- | --- | +| Production tile-state regression | PASS: 8,910 combinations across all 11 categories, six age choices (category plus five buckets), depths 0–4, three filter states and three marked/covered states, using default dark/light and deliberately low-contrast synthetic custom colors. Names/values >=4.5:1; selection/hover/mark/unreadable boundary inks >=3:1 against the actual fill | +| Captions / highlighted action | PASS numeric regression: opaque caption ink and highlighted-action text >=4.5:1; hover computes its own composited ground and ink | +| Alpha behavior | Regression initially failed: GPUI `opacity(1)` multiplies the existing alpha. Final code explicitly resets alpha; the opacity/contrast regression passes | +| Native default dark | PASS inspected rendering: matched contrived cache mark, explicit `[marked]` labels, brighter size values and thicker selected ring, fitted 2992×1878 captures at 100% UI zoom | +| Native light / custom / high contrast | NOT VERIFIED here. The synthetic custom-color regression is not a native custom-theme or OS high-contrast result | +| Hatch / filter / unreadable rendering | Production color and background paths covered by source/threshold checks; native intersections and all combined visual states still need the PWR-36 matrix | + +macOS lint, full workspace tests (235 app tests) and debug build passed. +Ubuntu 24.04.5 x86_64 Sandboxer at this source: setup 0 (1s), lint 0 (4s), +test 0 (11s), portable build 0 (43s), isolated SSH 0 (3s), all 0. An earlier +run at `944d042` correctly failed the alpha regression; it is superseded. + +The ignored audit diagnostic retains the legacy formulas to reproduce the +baseline. The production state regression is the threshold gate, not an AT +or WCAG certification. Upstream #58 was used narrowly to compare the +contrast calculation/test pattern; no commits, theme picker, persistence, +font or independent layout redesign were imported. Windows/Linux native +rendering, high contrast and actual AT results remain explicit gaps. + +### PWR-33 review corrections: theme rings and highlight ink + +Source `e02dd98`, rebased onto main `7cfb099`. A review found that the +first pass changed more of main's look than contrast required: + +| Finding | Correction and evidence | +| --- | --- | +| Highlighted text ink | `on_highlight` keeps main's choice (background ink on dark themes, bright on light) and falls back only when that fails 4.5:1. Native dark capture: the highlighted Mark for removal button keeps its dark text | +| Ring translucency | Rings went through the text rule, which forces alpha to 1. `palette::boundary_on` keeps the themed ring, translucency included, when it already meets 3:1 over the fill, and falls back to `ink_on` otherwise. The 8,910-combination regression checks the colour actually painted | +| Text cue coverage | Harness test: marking `junk` labels it `[marked] junk`, and every covered tile's label starts with `[marked] ` | +| Label prefix density | Not changed. Repeating `[marked]`/`[filtered]` on covered and filtered tiles is a design question; the operator holds a to-do card to mock alternatives in Claude Design | + +macOS 27 arm64: lint, workspace tests (276 app passed, 2 ignored; the +link test passed alone, as above) and debug build passed. Native default +dark before (`7cfb099`) and after (`e02dd98`) captures use the same +135-file contrived tree with `cache` marked and `.hidden` selected; no +removal was approved or performed. Light, custom and high-contrast native +rendering and AT results remain the PWR-36 gaps listed above. +Ubuntu 24.04.5 x86_64 Sandboxer at `e02dd98`: setup 0 (2s), lint 0 +(12s), test 0 (24s), portable build 0 (83s), isolated SSH 0 (3s), all 0. + +### PWR-34: reflow and shared UI scaling + +Final implementation `16f7570`; macOS main binary SHA-256 +`f61fa6b61bf17643e810408e9ca568fa7f533ebd6cb4ce469fb3ebdcc6f5b77d`; +native fixture example SHA-256 +`b0cad63bb67174d6965838d66e4ca7ef07ec3e69a3f5186fc62779309b9ccf79`. +Interface zoom now spans 75–200% and is shared by existing/new main, +Settings, document and Logs windows. This is application zoom, separate +from OS display/text scaling. Help keeps a bounded reading lane, heading, +Close action and visible scroll-key guidance. Narrow controls wrap below +the strip; free-space/source information remains visible when the sidebar +is hidden. Short file lists retain a complete entry above compact actions, +with full path/action names in AX. Scrolled file/review rows retain their +content height. Documents rewrap using measured glyph widths and preserve +relative reading position; complete Copy always uses the original source. + +| Surface | Native macOS observation | Harness / source | +| --- | --- | --- | +| Help | PASS inspected 100% and 200%: heading/Close remain in the window, End reaches final review shortcuts, Home returns to the start | PASS bounds, usable lane height and keyboard scroll at 900×600 / 16 and 32 px rem | +| Shared scale | PASS: Settings and License inherit the main window's 200%; reset in an auxiliary window restores normal main layout | Session-wide scale plus redraw/sync of existing and newly opened views | +| Settings | PASS inspected Safety: text reflows, End reaches the final option; selected 5% retained without preference edits | PASS 640×480 / 200% pane/navigation bounds and scroll; labels/values wrap | +| Documents / native menu | PASS: native Help → View License opens the document at 200%; 35 wrapped lines, final text reachable. Reset reflows to 22 lines | PASS 640×480 / 200%, end navigation and full-source keyboard Copy; Changelog PageUp/Down scrolls within long blocks | +| Minimum file reader | PASS final light-preset fixture: 900×600 requested content, 200%, one complete selected entry, full action/path AX names, Down selects the next entry; volume/source remain visible | Regression first failed with a 4 px viewport and shrinking rows. Final bounds require a complete line plus padding and retain intrinsic row heights | +| Logs | Native 200% log reading not exercised in this pass | PASS minimum-size Unicode wrapping and pixel paging inside one oversized line. Earlier paging regression was 0 → 0; final paging progresses without changing selection | +| Review | Native destructive route not exercised | PASS 900×600 / 200% safe End scrolling; files retained. Explanation/list stack, rows/footer wrap and retain content height | +| Targets | Native minimum reader supplies the larger target alternative to tiny painted tiles | PASS depth controls >=24 logical pixels at minimum/maximum UI zoom; file rows remain >=24 at 75% | +| Short progress sidebar | Existing regression caught an overly broad toolbar wrap; final wide layout preserves its scroll room | PASS free-space/progress/stop reachability regression and full workspace suite | + +The light rendering used the shipped Flexoki Light preset explicitly in +`a11y-fixture --tree /Volumes/A11yFixtures/Projects --light`, under the +unchanged macOS appearance. It is native GPUI rendering, not proof of an +OS light/high-contrast setting or a custom theme. The requested 900×600 +fixture yields a 1800×1202 window capture at 2× backing scale. Help's matched +100% pair uses `08402c3` and `8b612ee` (Help code retained at the final head), +2992×1878 fitted window captures; the 200% reader pair uses `8b612ee` and +`16f7570`, 1800×1202. All filesystem data is the invented APFS fixture. + +A controller click on the offscreen About license action did not open it +at 200%; the native Help-menu action did. Actual AT activation/scroll-to- +focus still needs verification. The controller still reports window focus; +no VoiceOver speech result is inferred from these observations. + +Final macOS lint, full workspace tests (243 app tests), main and fixture +builds passed. Ubuntu 24.04.5 x86_64 Sandboxer at `16f7570`: setup 0 (1s), +lint 0 (5s), tests 0 (14s), portable build 0 (44s), isolated SSH 0 (3s), +all 0. Earlier failed reflow runs are superseded; they exposed the progress +and reading-lane regressions fixed here. Native Windows/Linux desktop, +VoiceOver/Narrator/NVDA/Orca, OS display/text scaling and high contrast remain +unverified. UI zoom and a 2× capture backing scale do not establish those +OS/AT results. No removal approval was performed through native APIs or +computer use. + +### PWR-34 rebase and review corrections + +Source `d5990e3` and later, rebased onto main after #45 (contrast), #60 and +#61. Main's Settings redesign (grouped panes with an accent bar) landed +after this work was written, so the narrow-window rules were carried onto +it: below `ui::COMPACT_WINDOW_REMS` (50 rem) the panes wrap in a row above +the content and the group headings step out; Tab stays with +`aux_window::frame`, which now also takes interface zoom for every +auxiliary window. The fixed 20-line Page Up/Down step (`PAGE_STEP`) is gone: +documents page by the measured view and Logs scrolls within wrapped lines. + +#60 replaced the `a11y-fixture` example with a debug build's +`pwrdisk logs-fixture LOG`, so the example's `--tree`/`--light` mode cited +above no longer exists. Its earlier observations stand as recorded at +`16f7570`; a contrived tree now opens with plain `pwrdisk ROOT`. After #61, +on-screen macOS checks run in the PwrSuiteLab headed E2E VM, never on the +operator's desktop. + +| Review finding | Correction | +| --- | --- | +| Review scroll keys ran before the strip's app menu | An open menu takes its keys first, so its arrows move through rows instead of scrolling the review behind it (Linux, Windows) | +| Compact "Mark / unmark" not in its accessible name | Visible text is "Mark or unmark", inside "Mark or unmark selected path" (WCAG 2.5.3) | +| Notices re-wrapped on every pixel of a resize | Wrapping is keyed on whole monospace columns | +| Scrolling guidance appended under Hyprland | Moved under Keys in `docs/guide.md` | +| Duplicate compact threshold and checks | One named token; view settings decide inline once; the compact space line is built only when shown | + +macOS arm64 (headless gate): lint, workspace tests (289 app passed, 2 +ignored; 234 core passed, 7 ignored). The GPUI theme-watcher abort described +above also struck `the_agent_overlay_opens_and_closes`; it and the link test +pass alone. Ubuntu 24.04.5 x86_64 Sandboxer at `d5990e3`: setup 0 (8s), +lint 0 (17s), test 0 (17s), portable build 0 (49s), isolated SSH 0 (2s), +all 0. Native AT, OS scaling and high contrast remain the PWR-36 gaps above. + +#### November 2 follow-up: headless theme watching + +gpui-omarchy 0.1.3 watches `$HOME` and theme ancestors even when no Omarchy +theme exists. Any non-access event sends on an async channel, waking a +GPUI foreground task from the FSEvents thread. The deterministic scheduler +rejects that wake; a late wake can panic while async-task unwinds and abort +the process. PR #74 routed both agent tests through the shared initializer, +which cancels following immediately. The initializer now registers the +same base/control bindings and applies Tokyo Night without starting a +native watcher. Production theme following is unchanged. + +On macOS 27.0.1 arm64, `de5fbb0`, `305f69c` and post-#74 `00da039` each +passed five ordinary full app-suite runs. With writes every 2 ms in an +isolated temporary `$HOME`, both older revisions failed five of five runs +with the FSEvents scheduler violation; `00da039` passed five of five. These +controlled failures exited 101 rather than reproducing SIGABRT. The bug +predates #68, whose ordinary suite median was 6.26 s versus 8.57 s before +it; these samples do not support a slowdown explanation. The historical +change in ambient filesystem traffic cannot be reconstructed from them. + +### PWR-35 remediation: reduced motion + +Production source `24cc28afe058f3893fa6805c7198570c1f090fa2` refreshes the +SDK's system motion preference before directory navigation and during +transition frames. The pinned base SDK samples macOS/Windows at startup +but does not follow subsequent native changes on those platforms. Enter, +ascend and history now land directly when reduced motion is enabled; an +active transition is discarded on the next frame. User-driven zoom stays +available. No upstream UI redesign or dependency upgrade is included. + +| Layer | Observed result | +| --- | --- | +| Harness | PASS: two regressions failed before the change and pass after it. Immediate enter/ascend/history/wheel navigation, final layout, marks and user zoom retained; enabling reduced motion clears an active transition, disabling it allows subsequent transitions | +| Native macOS preference | PASS subset on macOS 27.0.1 arm64: System Settings AX reports Reduce motion off → on → off, restored to its initial value. One running contrived-tree fixture reports normal descent `reduced=false transitioning=true depth=1`, return with the OS preference on `reduced=true transitioning=false depth=0`, then forward with the restored preference `reduced=false transitioning=true depth=1` | +| Native process | Fixture SHA-256 `cb19f7a034b46df12cb95f4299dd56fa80f86426bd533464d625c728617d9899`, `--tree /Volumes/A11yFixtures/Projects --trace-motion`; only policy/transition/depth/scale flags are traced, no scanned paths | +| Gate | macOS lint, full workspace tests (245 app tests), main and fixture builds PASS. Ubuntu 24.04.5 x86_64 Sandboxer at `24cc28a`: setup 0 (1s), lint 0 (5s), tests 0 (15s), portable build 0 (43s), isolated SSH 0 (3s), all 0 | + +Native preference switching establishes the macOS policy bridge and +navigation state, not perceptual motion sensitivity or AT speech. Native +mid-transition toggling is covered only by the harness. Native Windows +and Linux desktop motion preferences remain unverified. Still images of +the final destination do not distinguish the removed transition; operator +acceptance of the native trace plus failing-before/passing-after harness +evidence is requested before merge. No removal was approved through +computer use or accessibility APIs. + +### PWR-35 rebase and review corrections + +Rebased onto main after #46. #60 retired the `a11y-fixture` example, so the +`--tree … --trace-motion` invocation and the fixture hash cited above no +longer exist; that trace stands as recorded at `24cc28a`, and the motion +policy and code paths it exercised are unchanged. The review moved the +platform re-read inside a running transition: an idle frame no longer asks +macOS or Windows for the preference, while starting a transition and each of +its frames still do. The harness cannot reach that re-read (GPUI's test +scheduler never asks the platform), so live OS toggling stays native +evidence. + +Headed macOS evidence after the rebase, in a macOS virtual machine against +the contrived tree (`scripts/a11y-fixture.py`), with Reduce motion turned on +before launch and confirmed through `NSWorkspace`, then restored. Entering +`cache` with Return was recorded at 60 frames per second: + +| Build | Distinct frames | Result | +| --- | --- | --- | +| main `a05da0d` | 7 | Five in-between frames: the folder zooms despite the preference | +| this change `e7fe166` | 2 | The start and the destination: navigation lands directly | + +The same runs tried to toggle the preference while the app was running. +Writing it with `defaults` reached new processes but not the running app, +which re-reads only when the system announces the change, so those clips +show nothing about live following and are not counted. Live toggling rests on +the earlier native trace above and the harness's mid-flight cancel. + +### PWR-36 remediation: native evidence and remaining acceptance + +The baseline above remains a historical result for `4d68f6cb`. The +following matrix records the remediation stack separately from that +baseline. A passing harness assertion does not establish a native API or +screen-reader result. All eight remediation issues remain In Progress and +the PRs remain drafts while native acceptance is incomplete. + +| Issue / focused PR | Source and harness | Native evidence | Remaining acceptance | +| --- | --- | --- | --- | +| PWR-29 / [#38](https://github.com/pwrdrvr/PwrDisk/pull/38) | Paged file reader, raw path IDs, full metadata, selection, marks, review summaries; large-list, guard and PR #38 focus/pagination regressions | macOS AX file/page/Unicode/selected/review subset observed. Linux X11 AT-SPI file names, roles, metadata, selection and advertised actions observed in this pass | Actual AT reading/action/focus, review on Windows/Linux; removal approval remains human/harness only | +| PWR-30 / [#40](https://github.com/pwrdrvr/PwrDisk/pull/40) | Source inputs, validation, value-backed polite status, foreground phases, in-flight roots and sampled counters; five PR #40 review regressions | Earlier macOS AX host/root value, error/completion/volume subset; earlier Linux final status and volume names observed | Native live announcements/throttling, SSH success/failure and cancellation across readers; corrected announcement values have source/harness evidence only | +| PWR-31 / [#42](https://github.com/pwrdrvr/PwrDisk/pull/42) | Tab order, modal containment/restoration, disabled controls, menu keys | macOS AX modal boundaries and keyboard subset; Linux advertised menu/button actions read without invoking them | AT focus/activation; Windows/Linux custom menus; Linux disabled-state mapping discrepancy below | +| PWR-32 / [#43](https://github.com/pwrdrvr/PwrDisk/pull/43) | Settings/Help/document text, original-source Copy, log navigation/search/selection | macOS AX readable auxiliary subset; native Logs End/search/selection at 200% in this pass | AT reading order/actions and native platforms; final native search value `299` observed after controller recovery | +| PWR-33 / [#45](https://github.com/pwrdrvr/PwrDisk/pull/45) | Production tile-state contrast thresholds across 8,910 combinations; text backing and non-color cues | Contrived default dark rendering and later explicit light preset inspected | OS high contrast, real custom themes, remaining control/caption contexts and Windows/Linux appearance; no whole-window contrast certification | +| PWR-34 / [#46](https://github.com/pwrdrvr/PwrDisk/pull/46) | Shared 75–200% UI scale; minimum reading lanes, reflow and target checks | macOS Help/Settings/License/file reader subset; native Logs check found the additional search collapse fixed here | OS display/text scaling, all supported desktop/AT combinations and scroll-to-focus | +| PWR-35 / [#47](https://github.com/pwrdrvr/PwrDisk/pull/47) | Immediate navigation and active-transition cancellation regressions | macOS OS preference off/on/off in one running fixture; initial value restored | Native Windows/Linux motion policy and perceptual/AT evaluation | +| PWR-36 / [#48](https://github.com/pwrdrvr/PwrDisk/pull/48) | Read-only AT-SPI diagnostic, direct file-reader fixture, native-discovered Logs/label corrections | Results below; unavailable cases stay explicit | Windows UIA/Narrator/NVDA; VoiceOver; Orca, real X11/Wayland desktop, OS scaling/high contrast | + +#### Native-discovered corrections + +At 200% in a 1120×720 requested Logs window, the search field collapsed +to its icon and overlapped the Filter control. The search wrapper used a +zero flex basis, letting neighboring controls consume its width. It now +retains the existing `LOG_FILTER` minimum and lets the controls wrap. The +footer truncates the visual path while retaining its complete accessible +text. The strengthened regression fails before (275 px input at the +640×480 stress size) and passes after at widths 640, 880 and 1120, 32 px +rem. The wrapped line remains present. + +The matched native images use only the invented 300-line Unicode log, +macOS 27.0.1 arm64, 200% application zoom, 2240×1442 window captures at 2× +backing scale. Before: source `24cc28a`, fixture SHA-256 +`cb19f7a034b46df12cb95f4299dd56fa80f86426bd533464d625c728617d9899`. +After: source `4364396`, SHA-256 +`d6facbbecb1923e2185b8c45066cfe9aefb31f5c0f7d205b03f05a9b96066fd4`. +The final semantic-only corrections do not alter this layout. End selects +line 300 with its complete Unicode accessible name; clearing selection +removes the copy overlay. Typing `299` leaves one matching line. The search +control initially omitted its typed value in AX; production now supplies +`aria_value`. The native recheck initially timed out repeatedly. After controller +recovery at `2cef5c5`, AX exposes the typed value `299` and one matching +line (300), establishing the corrected value export. An owned fixture +sample during the timeout showed AppKit event-loop/AX Raise work without +establishing a cause. No reader speech is inferred. + +Linux also exposed an empty static-label name despite an application +`aria_label`. The pinned AT-SPI adapter derives a static label's name from +its value (`label_comes_from_value`); the shared text helper now supplies +both on Linux. The file and review summaries use that shared helper. +A macOS comparison showed that supplying static values there made the +controller report static text as settable even with the read-only flag; +this workaround is therefore scoped to Linux, preserving the original +macOS/Windows label metadata. This is a focused export correction with +the native result below. + +#### Native platform/AT matrix + +| Layer | Result and conditions | +| --- | --- | +| macOS AX | PASS subsets documented per issue, under macOS 27.0.1 build 26A434 arm64. The controller continues to identify the window as focused; this does not establish VoiceOver focus. Final Logs value `299` and one matching line observed at `2cef5c5` after controller recovery; static-label values are scoped to Linux to preserve macOS metadata | +| VoiceOver | NOT RUN: baseline launch failed. Temporary enablement was subsequently authorized, but the native UI tool reports its application session stopped. The setting was left unchanged; no speech or announcement-cadence result is claimed | +| Windows native build/UIA | BLOCKED: Windows 11 build 26200 x64 peer remains disconnected on recheck | +| Narrator/NVDA | BLOCKED with the Windows peer; neither version nor speech was observed | +| Linux native AT-SPI | Native GPUI X11 fixture under Xvfb and an isolated session/AT-SPI bus; Mesa llvmpipe software Vulkan. File-list/status observations and remaining state issue below. This is not the window harness | +| Orca | BLOCKED: not installed and no usable real desktop/audio reader session supplied. No speech or reader navigation claimed from the AT-SPI query | +| Linux real X11 / Wayland | NOT RUN: Xvfb has no desktop window manager/compositor. Real Omarchy/GNOME/KDE focus, menus, Wayland and rendering remain unverified | +| UI zoom | macOS native 200% subsets observed; 75–200% harness checks. UI zoom is distinct from OS scaling | +| OS display/text scaling and high contrast | NOT RUN across platforms; 2× backing scale, explicit light preset and synthetic low-contrast theme are not substitutes | +| Destructive confirmation | Never invoked through computer use, AX, UIA or AT-SPI. Destructive behavior is tested only by the temporary-tree harness or left to a human | + +The Linux probe is `scripts/a11y-atspi-read.py --pid PID`, executed inside +the fixture's own desktop/session bus. It reads roles, names, descriptions, +states, relations, values/text where supported, and available action names; +it never invokes an action or starts a reader. `a11y-fixture --tree ROOT +--files` opens the production reader directly without simulated input. +The isolated bus enables `org.a11y.Status.IsEnabled` at `/org/a11y/bus`; +that flag is test setup, not proof of a running screen reader. Initial +wrong-path setup attempts did not find an application and are superseded +by the successful bus configuration. + +Ubuntu 24.04.5 x86_64 versions: at-spi2-core 2.52.0-1build1, pyatspi +2.46.1-1, Xvfb 21.1.12-1ubuntu1.9, Mesa 25.2.8. Preliminary native reads +at `2956ca4`/`4364396` established list box/list item names, raw complete +Unicode/long paths, sizes, categories, ages, selected state, checked radio +and checkbox states, final scan/volume status, and advertised click actions. +The settled root snapshot at `0e7b57a` contained 35 nodes, seven file items, +one selected item and no focused node. No action was invoked; no +relationships were reported for the sampled entries. These reads use only +`a11y-fixture` PIDs, never another application's tree. + +One remaining native FAIL is concrete: disabled Back/Previous/Next +controls advertise no action or focus stop but AT-SPI still reports +Enabled/Sensitive. Source/harness and macOS AX expose disabled correctly. +The pinned `accesskit_atspi_common` 0.19.1 state mapping adds +Enabled/Sensitive for controls without read-only support. An application +claim of a correct native disabled state would be false; a platform fix +and reader verification are tracked as follow-up work. + +At `89c6a26`, native AT-SPI now reports the full static file-summary name +(`/tmp/pwrdisk-atspi-volume/Projects · 7 entries · showing 1–7`), rather +than an empty label. The native fixture SHA-256 is +`4eb8a9690668736b8194187e635b1540e8a51c499466c230a904f2e7ed8f5258`. +The final fixtures are on a dedicated 512 MiB tmpfs with 135 invented files; +status reports 508 MiB available of 512 MiB. Unicode and the complete +long-name file were observed separately under its documents root. The +initial root-capacity values from the disposable VM are superseded by +this bounded contrived-volume check. + +Final macOS static-text check at production `6af7f1a` PASS subset: the +file-summary text and mark/volume summaries remain readable in AX and are +no longer reported as settable after scoping static values to Linux. The +fixture SHA-256 is +`fa205a03eddec466e3f3335d1a39d4a88fa8ba8bd836499d5dd6f49b3c3a032b`. +The successful native Logs query-value check used `2cef5c5`, SHA-256 +`30e8b2b8c0fdd93dd4b05c5da0b8103909011dcdeaa504eb75899e594d4393a1`; +its input-value code is retained at the final production head. Earlier +controller timeouts are superseded for these specific export checks, not +for actual VoiceOver or OS scaling. + +Final production source `6af7f1a8282f0e8b1e94be75a72de436f0d1ace2`: +macOS lint, full workspace tests (245 app tests; 232 core tests), normal +app and fixture builds PASS. Main/portable builds and embedded SSH helpers were also +verified throughout the stack. Ubuntu 24.04.5 x86_64 Sandboxer: setup 0 +(0s), lint 0 (5s), tests 0 (14s), portable build 0 (57s), isolated SSH 0 +(3s), all 0; final native fixture build 0 (53.65s). Final Linux fixture +SHA-256 `41ee44b27489f61d7b127e827e104822e1641f95638139d623a6923fa32301b8`. +The final AT-SPI query exits 0 with 35 nodes, seven file items, one selected +item, the complete static summary name and final contrived-volume status. +The disabled-state discrepancy remains observed. + +The task-owned native windows were closed and the APFS fixture detached. +Reduce Motion was restored to its initial off value; VoiceOver was left +off. Remaining native acceptance is on the PwrAgent to-do card +“Complete native accessibility acceptance before merging the PR stack.” +No PR was merged and no removal confirmation was automated. + + +### PR #38 review corrections: focus and pagination + +The four findings were reproduced against `3c92a33` using only temporary +contrived filesystem fixtures. Fix commit +`0613879e46fa46e78809c291834f219d975bb662` adds five window-harness +regressions, each failing before and passing after: + +| Finding | Before | Observed correction | +| --- | --- | --- | +| Focused file list, rescan, Escape | The list's absent focus owner prevents cancellation | Focus moves to the persistent root before the list disappears; Escape cancels; a subsequent completed scan restores list focus when appropriate | +| Entry 99, Tab/Shift-Tab | Selection reaches entry 100 while page 0 remains rendered | Shared sibling navigation updates page, scroll and selection; Space safely marks the visible selected row | +| File Previous after filtering 450 entries to 150 | Page counter 4 becomes 3, still rendering effective page 1 | Previous uses the effective page and reaches page 0 in one click | +| Review Previous after marks shrink from 4,801 to 1,201 | The same stale-counter failure | One click reaches page 0; all 4,801 fixture files remain | +| Enter/Right on a file; Left/Backspace/u at the scanned root | No-op navigation resets the page and hides selection | Page and selection remain visible; an actual directory change resets pagination | + +At `0613879`, macOS 27.0.1 arm64 lint, full workspace tests (229 app +passed, two ignored; 232 core passed, seven ignored) and normal app build +PASS. Ubuntu 24.04.5 x86_64 Sandboxer `sb_uihqpdf98b`: setup 0 (1s), +lint 0 (6s), tests 0 (15s), portable build 0 (56s), isolated SSH 0 (3s), +all 0. + +Separate native macOS keyboard/AX observation: 128 invented files on a +disposable APFS image named A11yReviewFixtures. PageDown, Up, Tab selects +`item-000100.txt`. Before, the accessible list still reports entries 1–100 +without a selected row; after, it reports entries 101–128 with the selected +row. Return, Left and Backspace preserve that page and selection. Matched +2992×1878 window captures, dark at 100% application zoom, are attached in +[PR #38](https://github.com/pwrdrvr/PwrDisk/pull/38). Normal app SHA-256: + +- Before `3c92a33`: + `843d85a2c4b4908bc56d02a43680e8c36713943de98cacb225da0b98ef227930`. +- After `0613879`: + `606c6a9fbc97a5eaecef43d2e28dbbfe5c2ee765ea014468bfa6eb0d1ecafe13`. + +The dependent focus PR also assigns the navigation focus handle to the +painted treemap. Its integration now tests visibility of either navigation +view before transferring focus. Its existing Tab-order regression caught +and verifies that distinction. The later control-traversal policy remains: +Tab moves between controls, while n/Shift-n exercise shared sibling +navigation. PR #38 retains its original Tab/Shift-Tab regression. + +The restacked production source +`ec5847b292cdbd05c54215b3aad836d7a3a03d58` passes macOS lint, full workspace +tests (250 app passed, two ignored; 232 core passed, seven ignored), and +normal app build. Ubuntu 24.04.5 x86_64 Sandboxer at the same source: +setup 0 (0s), lint 0 (5s), tests 0 (12s), portable build 0 (43s), isolated +SSH 0 (3s), all 0. The first integration run's Tab-order failure is +superseded by the visibility correction and these passing gates. + +No screen-reader speech was tested in this review pass. The Windows peer +remains disconnected. VoiceOver, UIA/Narrator/NVDA, Orca, real Linux +desktops, OS display/text scaling and high-contrast acceptance gaps in the +native matrix remain open; no harness result replaces them. No removal +confirmation was activated through computer use or accessibility APIs. +The task-owned test windows were closed and the disposable APFS image was +detached. Existing native acceptance work remains tracked separately. + +### PR #40 review corrections: live values and active status + +Reviewed source `d3941b1` supplied labels without values on both live +status nodes. The pinned `accesskit_macos` 0.26.3 event generator queues +live announcements only when the consumer node has a value, and reads the +announcement text from that value. This was confirmed in the local +dependency source; it is not a native speech observation. + +Fix `3640f6821162780a441559e6941161590cf267bb` routes both +`current-status` and `marked-summary` through one read-only polite status +helper with matching labels and values. It resolves the foreground screen +before applying scan context. Widening names the worker's `scan_root` and +clears sampled text immediately on a new root, while file/byte counters +remain sampled at two seconds. Background scan metadata does not advertise +the foreground Escape-cancels instruction. + +| Contrived regression | Before | Observed source/harness correction | +| --- | --- | --- | +| Current progress, error and completion status | Live value absent | Value matches the label | +| Marked-path summary | Live value absent | Same shared value-backed status helper | +| Cancel widening, then Review/Running/Done, including a previous scan error | Old scan state hides the active phase | Active phase leads; previous scan state remains separate | +| Harness removal completes and immediately starts a refresh | Indexing hides removal completion and advertises Escape cancellation | Removal completion remains primary; refresh is background context | +| Consecutive widening roots within two seconds | Old subtree or cached root is announced | Each in-flight root is named immediately; counters remain sampled | + +All five regressions fail before and pass after. At `3640f68`, macOS +27.0.1 arm64 lint, full workspace tests (236 app passed, two ignored; +232 core passed, seven ignored) and normal app build PASS. Ubuntu +24.04.5 x86_64 Sandboxer `sb_uihqpdf98b`: setup 0 (1s), lint 0 (7s), +tests 0 (17s), portable build 0 (45s), isolated SSH 0 (2s), all 0. + +The complete restacked production source +`10cff5159935359b9ba04539c7715398a18aebac` passes macOS lint, full +workspace tests (255 app passed, two ignored; 232 core passed, seven +ignored) and normal app build. Final Linux verification: setup 0 (1s), lint 0 (8s), tests 0 (19s), portable build 0 (49s), isolated SSH 0 (3s), all 0. + +These are semantic metadata and status-string changes; the visible layout +does not change. No new before/after image can establish an announcement +value or spoken result. + +Native evidence remains separate. The operator subsequently authorized +temporary VoiceOver enablement, but the native UI tool reports the +application session stopped, so no setting was changed and no VoiceOver +delivery/cadence result is claimed. The Windows peer remains disconnected +on recheck. Native AX live notifications, UIA, AT-SPI, VoiceOver, +Narrator/NVDA/Orca, OS display/text scaling and high-contrast checks remain +explicitly unverified for this correction. No removal was approved through +computer use or accessibility APIs; the destructive regression operates +only on contrived temporary-tree harness files. + +### PWR-36 rebase and review corrections + +Rebased onto main after #47. #60 retired the `a11y-fixture` example, so the +commit that taught it `--files` was dropped, and the invocations above +(`a11y-fixture --tree ROOT --files`, its PIDs) no longer exist on main. The +native reads stand as recorded at their cited sources; a contrived tree now +opens with plain `pwrdisk ROOT`, and the file reader is one key away. +`scripts/a11y-atspi-read.py` says so. On-screen macOS checks run in the +PwrSuiteLab headed E2E VM, never on the operator's desktop. + +| Review finding | Correction | +| --- | --- | +| Folding the footer spacer into the log path left none while searching | A spacer stands in when the path is hidden, so the note and search hint stay at the right edge | +| The diagnostic script named the retired example | It names `pwrdisk ROOT` | +| No harness assertion for the search field's exposed value | Not added: the harness has no reader for accessibility values, so the value stays native evidence | + +### PWR-33 follow-up: tile state without repeated words + +The "Label prefix density" row above left a design question open: a +`[marked] ` or `[filtered] ` prefix repeats on every tile inside a mark or +a search, and on a narrow tile it is all that fits, so the name is lost. +Five treatments were mocked in Claude Design on one contrived tree (a mark +at the root, inside the mark, typing in Find); the operator chose +zero-width text styling. + +| State | Cue now | Was | +| --- | --- | --- | +| Marked, or inside a mark | Name struck through, in the marked ink; the mark keeps its 2 px ring; the trail strikes a crumb that is marked or inside a mark | `[marked] ` on every label | +| Typing in Find | The matched part of a match's name is underlined, by the same ASCII-case rule the filter uses (`filter::find_ignoring_case`); non-matches are dimmed, unchanged, with no word added | `[filtered] ` on every non-match | +| Unreadable | `! ` prefix and the warning corner, unchanged: rare, and two characters | same | + +Neither line takes any width from the name. Both are at least 1 px, in +the label's own ink, so the 4.5:1 label regression covers them. The accessible file list and the +selection status keep the words ("marked", "inside a marked directory", +"unreadable", "does not match filter") for assistive technology, unchanged. + +| Check | Observed result | +| --- | --- | +| Marked and covered labels | Harness test: marking `junk` labels it `junk`, struck; every covered label is struck and carries no prefix; nothing else is struck; `goes_with_a_mark` is true for `junk` and `junk/deeper`, false for `keep` and the root | +| Find matches | Harness test: typing `BLOB` underlines exactly `blob` in each labelled `blob.bin`; no label starts with a bracketed word | +| Underline placement | A lab capture showed GPUI's run underline clipped away in a deeper directory's 1 rem band. The underline is now painted at GPUI's position, raised to stay inside the label's region; a unit test covers the clamp, and `find_ignoring_case` returns byte ranges on character boundaries (`Résumé cache.txt`) | diff --git a/docs/artifact-classification.md b/docs/artifact-classification.md new file mode 100644 index 00000000..86781009 --- /dev/null +++ b/docs/artifact-classification.md @@ -0,0 +1,67 @@ +# Detected artifacts and cleanup suggestions + +Artifact identity, identification evidence and cleanup suitability are +separate. A detection never authorizes marking or removal. A suggestion +means a plausible, relatively lower-risk candidate for human review; it +does not mean safe to delete. Size and age do not establish disposability. + +The selection panel and MCP listings report the artifact, its evidence +(`name convention` or `tool layout`), and one of these assessments: + +| Assessment | Examples | Next step | +| --- | --- | --- | +| Detected | VM disks, Git history, worktrees, diagnostic logs | Inspect ownership and whether the data is still needed. It may contain unique work. | +| Detected | VM snapshots / checkpoints | Review and consolidate through the VM app. Never remove individual files from a snapshot chain. | +| Detected | Saved VM memory / suspend state | Resume the VM and shut it down normally. Let the VM app release its saved state; memory can also belong to checkpoints. | +| Suggested for review | Recognized dependency caches, installed packages, compiler intermediates | Check local edits, stop builds and running environments, and prefer the owner's cleanup operation. Rebuilding, reinstalling or downloading may be needed. | + +The **Virtual machines** legend chip filters this inventory. Agents can +use `pwrdisk_find` with `category: "virtual-machines"`; `reclaimable: true` +keeps cleanup candidates and excludes detected VM data. + +A distinctive name is weaker identification evidence than a documented +multi-component layout. Neither proves that files have no local edits or +that the owner is idle. pnpm stores retain an additional check against the +scanned version-directory structure. Scans starting below the store remain +detection-only because they cannot verify the owning store's layout. +Incomplete scans may also omit that evidence. + +VM ownership wins over cache names. Bundles and known Tart, VirtualBox, +Minikube and Docker VM directories cannot become suggestions because a +child happens to be named `cache`, `tmp` or `node_modules`. Lima and Colima +extensionless disk files are recognized without labeling their whole tool +homes as VMs. A candidate containing protected data loses its whole-parent +suggestion. A displayed size is not a promise of recovered bytes: VM disks, +snapshot chains, APFS clones and open files can retain or share storage. + +## Imported developer layouts + +The structural rules and 350-case positive/negative corpus were ported from +[DiskHound](https://github.com/huntharo/diskhound), revision +`0b0209b469ab5afd8d562f57460e668cae94a659`. Its MIT notice is included in +`licenses/bundled.txt` and the generated third-party notices. + +Coverage includes JS/TypeScript dependencies and frontend output; Rust, +Python, Gradle/Maven/Scala, Go, .NET, C/C++ and CMake; Ruby/Bundler, +Composer, Dart/Flutter, Swift/Xcode, Elixir/Erlang, Haskell and Zig caches; +Terraform provider downloads; and compiler and package-manager caches. +Git metadata, worktree conventions and diagnostic logs are detections. +Git ownership still applies when a scan starts inside `.git`, including +repositories stored within dependencies or caches. + +The boundary is the recognized subtree, never a parent inferred from it. +For example, `target/debug/deps` is Rust output and `target/scala-3.3` is +JVM output. Neither labels all of `target`, even beside `Cargo.toml`. +Likewise `.yarn/cache` excludes patches, `.terraform/providers` excludes +state and backend configuration, and Python `site-packages` excludes +environment executables and activation scripts. Generic `build`, `dist`, +`out`, `bin`, `obj`, whole tool homes and unknown custom layouts are not +added by these rules. Existing general cache/temporary-name heuristics +remain review candidates, with the same VM and Git protections. + +Classification reads only the completed scan, with no new filesystem +probes. Detailed metadata is derived from paths on demand. The tree keeps +its existing node size, and a bounded six-component rule window and +operation-count tests guard classification cost. SSH paths use POSIX rules +on every client. Existing marking, confirmation, capacity and removal +guards apply to every assessment. diff --git a/docs/assets/buttons/download-linux-arm64.png b/docs/assets/buttons/download-linux-arm64.png new file mode 100644 index 00000000..078eff9b Binary files /dev/null and b/docs/assets/buttons/download-linux-arm64.png differ diff --git a/docs/assets/buttons/download-linux-x64.png b/docs/assets/buttons/download-linux-x64.png new file mode 100644 index 00000000..1bbec61c Binary files /dev/null and b/docs/assets/buttons/download-linux-x64.png differ diff --git a/docs/assets/buttons/download-mac.png b/docs/assets/buttons/download-mac.png new file mode 100644 index 00000000..1ac517ca Binary files /dev/null and b/docs/assets/buttons/download-mac.png differ diff --git a/docs/assets/buttons/download-windows-arm64.png b/docs/assets/buttons/download-windows-arm64.png new file mode 100644 index 00000000..f36291e5 Binary files /dev/null and b/docs/assets/buttons/download-windows-arm64.png differ diff --git a/docs/assets/buttons/download-windows-x64.png b/docs/assets/buttons/download-windows-x64.png new file mode 100644 index 00000000..b98cf37c Binary files /dev/null and b/docs/assets/buttons/download-windows-x64.png differ diff --git a/docs/building.md b/docs/building.md new file mode 100644 index 00000000..adbb4b09 --- /dev/null +++ b/docs/building.md @@ -0,0 +1,121 @@ +# Building PwrDisk from source + +Most people want the signed installers linked from the +[README](../README.md#install). This page is for building it yourself and +for working on it. + +## Linux + +```sh +git clone https://github.com/pwrdrvr/PwrDisk +cd PwrDisk +make install +``` + +`make install` builds a release binary and puts three things under `~/.local` +(no root needed): + +- `~/.local/bin/pwrdisk` +- a desktop entry, so PwrDisk is in the launcher and in a file manager's + **Open with** for a directory (it adds a handler; it never becomes the + default) +- an icon + +`sudo make install PREFIX=/usr/local` installs system-wide; `make uninstall` +removes exactly what was installed. + +If another installed version wins on `PATH`, the installer warns which one. +Run `export PATH="$HOME/.local/bin:$PATH"` and add that setting to your shell +configuration so the locally installed build takes precedence. + +For Linux builds with embedded SSH helpers, also install the two Rust +standard-library targets (no external C cross-compiler is needed): + +```sh +rustup target add x86_64-unknown-linux-musl aarch64-unknown-linux-musl +``` + +You need Rust 1.97 or newer and a Wayland or X11 session with a GPU that GPUI +can drive (Vulkan). Distributions often package an older Rust; +[rustup](https://rustup.rs) installs a current one. The repo pins 1.97 in +`rust-toolchain.toml`, so with rustup the right toolchain is fetched on the +first build even if `rustup default` points at something older. + +## macOS + +Build it with Rust 1.97 or newer and Xcode or its Command Line Tools. +macOS does not come with Rust; install it with [rustup](https://rustup.rs). + +```sh +make install # ~/Applications/PwrDisk.app, and ~/.local/bin/pwrdisk +make uninstall +``` + +`make bundle` (or `cargo xtask bundle`) builds `target/bundle/PwrDisk.app`, +a zip of it and a DMG laid out like the release's, signed ad hoc; add +`--universal` for both architectures. To sign and notarize a build for +others, with a Developer ID certificate in the keychain and credentials +saved by `xcrun notarytool store-credentials`: + +```sh +NOTARY_PROFILE= cargo xtask bundle \ + --sign "Developer ID Application: Name (TEAMID)" --notarize +``` + +A build that was not signed and notarized (one you made yourself and copied +to another Mac, say) is stopped by Gatekeeper: macOS says it "is damaged +and can't be opened" or "cannot be verified". Clear the mark once: + +```sh +xattr -dr com.apple.quarantine /Applications/PwrDisk.app +``` + +(Or open it once, then choose **Open Anyway** in System Settings › Privacy & +Security.) + +## Windows + +Build it with Rust 1.97 or newer, from +[rustup](https://rustup.rs), and the MSVC toolchain (Visual Studio Build +Tools, C++ workload): + +```powershell +git clone https://github.com/pwrdrvr/PwrDisk +cd PwrDisk +cargo build --release # target\release\pwrdisk.exe +``` + +## Develop + +```sh +make run # release build, opening the source/root chooser +make lint # rustfmt --check, then clippy with every warning an error +make test # scanner, layout and removal tests, plus window-harness tests +make test-ssh # real localhost SSH scans/errors; Linux, bun + openssh required +make ci # lint, then test +``` + +The lint gate is strict on purpose: `clippy::all` and `clippy::pedantic` are +errors, and every exception is written down with its reason in `Cargo.toml`. +The window-harness tests draw real frames and press real keys — including one +that marks a directory, confirms the deletion and checks that the files are +gone while their neighbours are not. + +| path | what lives there | +| --- | --- | +| `crates/disktree-core` | scanning, the tree, the squarified layout, free space and removal — no UI | +| `crates/disktree-mcp` | `pwrdisk mcp`: the agent's tools and skills over stdio, on `disktree-core` | +| `crates/disktree-link` | the socket between a window and an agent, and its messages | +| `skills/` | the skills `pwrdisk mcp` compiles in: explain usage, free space, and each system's cautions | +| `crates/disktree-app/src/state.rs` | every action the interface can take, and the key map | +| `crates/disktree-app/src/views.rs` | the screens | +| `crates/disktree-app/src/treemap_view.rs` | painting the mosaic and its labels | +| `crates/disktree-app/src/ui.rs` | the spacing, type and size scale, in `rem` | +| `crates/disktree-app/src/tests.rs` | end-to-end tests through a real window | +| `packaging/`, `assets/`, `Makefile` | the desktop entry, the icon, and install | + +The interface follows the +[GPUI Kit design guides](https://gpui-kit.com/versions/main/docs/design-guides/): +every size is on one `rem` scale so interface zoom keeps its proportions, +primary is reserved for what Enter does, and the only question the app asks is +the one it cannot take back. diff --git a/docs/guide.md b/docs/guide.md new file mode 100644 index 00000000..886f81f3 --- /dev/null +++ b/docs/guide.md @@ -0,0 +1,783 @@ +# Using PwrDisk + +Everything the [README](../README.md) leaves out: each screen, every key, +how sizes are measured, scanning servers over SSH, working with an AI +agent, and what is different on macOS and Windows. Building from source is +in [building.md](building.md). + +- [Starting a scan](#starting-a-scan) +- [Choosing sources and roots](#choosing-sources-and-roots) +- [The screen](#the-screen) +- [Marking](#marking) +- [Zooming and going in](#zooming-and-going-in) +- [Removing](#removing) +- [Keys](#keys) +- [What it measures](#what-it-measures) +- [The whole disk](#the-whole-disk) +- [Servers over SSH (read-only)](#servers-over-ssh-read-only) +- [With an AI agent](#with-an-ai-agent) +- [Updates](#updates) +- [On macOS](#on-macos) +- [On Windows](#on-windows) +- [What it refuses to do](#what-it-refuses-to-do) +- [On Hyprland](#on-hyprland) + +## Starting a scan + +```sh +pwrdisk # choose a local/SSH source and root +pwrdisk ~ # explicitly scan home +pwrdisk --disk # the whole disk it lives on +pwrdisk ~/src # or any directory +pwrdisk --help # options: apparent size, follow links, skip hidden, … +``` + +PwrDisk is built with [GPUI](https://gpui-kit.com/) through +[gpui-omarchy](https://github.com/huacnlee/gpui-omarchy), so on Omarchy it +follows your theme and behaves like the rest of the desktop. Elsewhere it +follows the system's light or dark setting. + +## Choosing sources and roots + +Launch without a path and the chooser lists **This computer**'s mounts. +Switch to **SSH host**, enter an SSH alias or `user@host` and press +**Connect** to list that machine's instead. Discovery reads that machine's +mount namespace, not file contents. It never starts a scan or probes +mounted network filesystems just to fill the list. + +The list ends with a **Directory** row: type an absolute path there, or +choose **Choose…** for the system's folder picker on this computer. Select +a mount or the Directory row and press **Scan**; Enter does the same, and +in the host field it connects. Escape or **Cancel** closes the chooser and +returns to the current scan, or the idle welcome screen at startup; a click +outside it does not. + +During exploration, press `v`, click **Source…** beside the disk name, +or click the PwrDisk logo to reopen the same chooser. The source being +browsed is shown explicitly, and connecting never retargets an existing +scan. Changing machines on acceptance clears the old machine's marks, +identity and navigation history; an absolute path is not an identity +across hosts. A rescan that detects a changed or lost remote machine +identity also clears marks, even if the SSH alias is unchanged. + +Pseudo-filesystems, snapshots and automount triggers are filtered out. +Linux bind mounts and btrfs subvolumes remain individually selectable, +even when they share a device. Free space is measured only after choosing +a root. Explicit command-line paths and `--disk` still start directly; +`ssh HOST --check [PATH]` remains the headless scan command. + +## The screen + +- **Top:** the trail from `/`, then **Treemap | List**, how the directory is + drawn, and what is measured — **Size**, **Files** or **Age**, **Hidden + files**, **Apparent size**, and the depth drawn. The list shows the same + directory one entry per row and is the view for screen readers. When the + window is too narrow for every control, the ones used least move into + **⋮** at the end of the bar: the scan options first, then back, forward + and depth, then Size | Files | Age. In the + tree a crumb goes there, and its ▾ lists its siblings, largest first with + their share and size, to jump sideways (arrows and Enter work too). Above + the scanned root a crumb is dimmer, and clicking it widens the scan to + there (see [The whole disk](#the-whole-disk)). +- **Under it:** the scan totals and the filter when one is typed, and on + its own row the legend. Each entry carries what it holds of the whole + scan, in the same unit as the tiles. The row never wraps: kinds that + hold nothing, or less than a thousandth of the scan, and then the + smallest when the row runs out of room, wait in a **+N** menu at its + end. Setting one there moves it onto the row, where its state shows. +- **Mosaic:** colour is the *kind* of data — code, agent scratch, + toolchains, synced files, git, media, documents, caches, virtual + machines — at one muted level, lighter with depth. A diagonal hatch is + a cleanup suggestion to review (caches, sync history, package stores, + build output), independent of colour; it never says the contents are + safe to lose. Top-level directories carry a strip of their colour and a + name band; deeper open directories a slim label row. In **Age** mode + colour is the last write instead, from this week to older. +- **Legend:** each entry is also a filter. Click it once to show only that + kind (or age), again to hide it, and a third time to show it again. + Kinds set to only add up ("Code" and "Cache" show both), while + **Suggested** narrows them to their cleanup suggestions. The mosaic lays + out only what passes, at its own size, and a folder that only partly + passes says so: `48G of 196G`. Kind and age filters apply together, so + "old code" is a click in each mode. **Show all** or `esc` clears them. + When nothing in the folder on screen passes, the mosaic or list says + so, and whether anything elsewhere in the scan does. + A filter changes what is shown, never what a mark takes: marking a + folder that is only partly shown marks all of it, and the panel says so. +- **Panel:** the selection (its size set large, share of the scan, files, + last write, and for a checkout what git says — changes, stashes, unpushed + commits); for a recognized artifact, whether it is only *Detected* or + *Suggested for review*, how it was identified and what to do first, as + [the classification notes](artifact-classification.md) describe; what + is marked; *Worth a look*, the largest cleanup suggestions and agent + findings to review; then, pinned above the disk, the marks taken together — + how much is marked, what removing all of it frees, and the way to the + review screen; and the disk, free now and after the marks. An empty + list is one line: *Marked* says "Space to mark" and *Worth a look* + "none". On a short window (under 48 rem, 768 px at the default size) + the share, files, last write and kind fold into one line under the size + that opens them again, the selection's label goes, and the line inviting + an AI agent shows only once one is connected; Help › Connect an AI Agent + (MCP)… is always there. The assessment and Mark never fold. What still + does not fit scrolls; the disk stays in view. Drag the panel's left edge + to resize it; double-click the edge to reset. + +One colour is kept apart: amber marks the selection, the main action, and +cleanup suggestions. + +The kinds come from directory names and a few shapes (a bare git repository, +a pnpm store, and the tool layouts in +[the classification notes](artifact-classification.md), such as +`target/debug/deps`). Some of the names are specific to one machine; see +`crates/disktree-core/src/classify.rs`. + +## Marking + +Space, X, Enter and the arrows act on the tile under the mouse if the mouse +moved last, and on the keyboard selection after you use an arrow or n. + +A click selects the tile under the pointer. A second click on the +selection, slow or as a double-click, opens one level toward it: the +directory on screen's child that holds it, however deep the tile is +drawn, with the tile still selected so the next click opens the next +level. One double- or triple-click never opens more than one level. The +pointer turns into a hand over a selection a click would open, and the +tile's hover card names the directory a click or a double-click opens. + +A marked tile takes the danger colour, and so does everything inside it: +removing a directory takes its contents with it. Marking a directory absorbs +any marks already inside it, and something inside a marked directory cannot be +marked or kept on its own; its panel offers to unmark the directory instead. +Marking is reversible — press it again — and the saving is never counted twice. + +## Zooming and going in + +Scroll to magnify toward the pointer. The wheel magnifies until the directory +under the pointer fills the view, and the next notch goes into it — one +continuous motion, with the directory's contents growing into place. Scroll the +other way to come back out. Enter goes into the selected directory at any +depth, and Backspace or Escape goes up one level. `<` and `>`, beside the +Size / Files / Age switch, go back and forward through the directories visited, +as do `alt ←` `alt →` (also `⌘[` `⌘]` on macOS) and the mouse's side +buttons. `+` and `-` magnify without going in; `0` resets. + +## Removing + +`c` (or **Review…**) opens the list of everything marked. Unmark anything +there, then choose: + +- **Move to trash** — the default when a trash is available. On macOS that is + the system Trash, the same move as Finder's (on another disk, that disk's + own Trash; network shares often have none). Elsewhere it is `trash-put` + from trash-cli, then `gio trash`, then a built-in XDG trash. Recoverable + until the trash is emptied, so it commits directly. +- **Delete permanently** — `rm -rf` semantics. It always asks first, in a dialog + that names what goes and how much comes back. + +One removal may take only so much of a disk: 5% of the volume's capacity +by default, counting everything marked. A mark that would pass it is not +made by Space or **Mark for removal**: the button reads **Over 5% limit**, +and the ▾ beside it holds **Mark anyway**, which names the share. Review +then shows each disk the removal takes past the limit, its share against +the limit, and keeps the commit button off until you type the phrase it +shows, such as `delete 20% of my disk` (`trash …` to the trash), or +`delete 20% and 19% of my disks` when marks on a disk mounted inside the +scan pass the limit there too. Each disk counts on its own, and removal +holds each to the share you typed for it and every other disk to the +limit: if what is marked has grown past that when the removal starts, +nothing is removed. +Settings › Safety sets the limit (1%, 5%, 10%, 25%, 50% or Off) and what +Review asks past it (type a phrase, tick a box, or nothing more). Neither +lets an agent past the limit. + +The commit is the footer's right-hand button; beside it, **Move & rescan** +(**Delete & rescan…** in permanent mode, `shift enter`) does the same and +then scans again. **Back** is beside them; **Export** and **Unmark all** sit +on the left. While a removal runs, **Stop after this item** (or `esc`) ends +it once the item in hand is done. + +Without a rescan, the tree stays as the scan found it, so the next batch +can be marked straight away; a rescan of a whole disk takes minutes. What +was removed stays where it was, greyed out, with its hover card saying +**Removed since the scan**, and cannot be marked again. Every size on +screen is still the scan's; a directory marked around something already +removed counts only what is left in it. The next scan clears all of it. + +The Done screen lists every removal since the last scan three ways: +**reported**, the listed size of what went, a clone counted in every place +it appears; **private**, what the scan saw as theirs alone; and +**observed**, the volume's free space after minus before, which other +programs change too. With more than one removal, a total row adds the +first two and measures the third from the first removal's start to the +last one's end. The Disk section keeps the total as **Freed since scan** +until the next scan. + +## Keys + +| key | does | +| --- | --- | +| `space` / `x` | mark or unmark the tile you point at | +| `ctrl`-click (`⌘`-click on macOS) | mark without moving the selection | +| click, then click again (or double-click) | select a tile, then open one level toward it | +| `enter` | open that directory, at any depth | +| `⌫` / `esc` | go up one directory | +| `alt ←` `alt →` | back and forward through where you have been | +| `←` `↑` `↓` `→` | move between tiles at this level | +| `tab` / `shift-tab` | next / previous control; Escape returns to files | +| `n` / `shift-n` | next / previous largest sibling | +| scroll | zoom toward a directory, then go into it | +| `shift`-scroll | pan the magnified view | +| `[` `]` | draw fewer or more levels at once | +| `-` `=` `0` | magnify, shrink, reset the view | +| `ctrl =` `ctrl -` `ctrl 0` (`⌘` on macOS) | interface zoom, 75–200%, shared by all windows | +| `/` | filter by name: only matches keep their colour; `enter` shows only them, `esc` clears | +| click a legend entry | show only that kind or age, then hide it, then show it again; `esc` clears | +| `c` | review the marked list | +| `t` | size, files or age: what areas and colours say | +| `ctrl 1` `ctrl 2` (`⌘` on macOS) | treemap or file list; the list is read by screen readers | +| `d` | disk usage or apparent size | +| `i` | include or skip hidden entries | +| `r` | scan again | +| `esc` while scanning | stop the scan | +| `v` | choose a local/SSH source and root | +| `ctrl o` (`⌘O` on macOS) | choose another directory to scan | +| `g` | the whole disk | +| `p` | show or hide the selection line | +| `o` | show it in Finder, File Explorer or the file manager | +| right-click | show that tile in Finder, File Explorer or the file manager | +| `shift u` | updates: the version, the release channel, check now | +| `?` | every key | +| `q` | quit, on Linux; ⌘Q on macOS and Alt+F4 on Windows | + +On macOS the menu bar also has ⌘⇧R to show the selection in Finder, ⌘R to +rescan, ⌘[ and ⌘] for back and forward, and ⌘Q, ⌘H and ⌘W (closing the +window quits); other ⌘ chords are left to the system. On Linux and Windows +the same work with ctrl, with F5 to rescan too. + +On the review screen: `m` trash, `p` permanent, `!` or **Unmark all** +clears the list, `u` or Edit › Undo (⌘Z, Ctrl+Z) puts it back, `enter` +commits, `esc` goes back. Or hand the list on instead of acting on it from +**Export**: `s` saves it as a text file, one path per line, `e` and `y` +save or copy a delete script, and `a` copies a prompt for a +coding agent: free the space by removing what you picked, checking each path +first (git work that exists nowhere else, a tool's own clean command) and +touching nothing else. A name holding a newline is left out of the list and +escaped in the prompt, so it cannot pass for another path. + +Help keeps its heading and Close button visible while the shortcut list +scrolls. Use arrows, PageUp/PageDown and Home/End to read it. Settings panes +scroll with PageUp/PageDown and Home/End; Ctrl+PageUp/PageDown still switches +panes. Documents wrap to the window and scale. Logs uses PageUp/PageDown to +scroll within long wrapped lines, while Up/Down selects lines for copying. + +## What it measures + +- **Disk usage** by default: `st_blocks × 512`, the number `du` reports and the + space that actually comes back when a file is deleted. Apparent size (what + `ls -l` shows) is one toggle away. +- **Hardlinks once.** Two names for one inode cost one file. +- **Hidden entries included**, because `~/.cache` is often the biggest thing in + a home directory. Symlinks are not followed. +- **The projection counts one volume.** The meter shows the scanned volume's + free space, so it adds up only the marks whose bytes come back to that + volume, by the same rule the scan bounds the volume with. With `-X`, a mark + on a disk mounted inside the tree, on a network share or in a snapshot + subvolume is left out of the projection — removing it gives its space back + somewhere else, or, in a snapshot, shares its blocks with the live files — + and the panel and the review screen say what was left out. A mark whose + volume cannot be told is not claimed either. + +The scan follows [dust](https://github.com/bootandy/dust)'s approach: one rayon +scope per root, a completion counter per directory so no directory is built +before its last subdirectory lands, and one bottom-up pass that aggregates sizes +and removes duplicate hardlinks. + +## The whole disk + +Click `/` (or any directory above the scanned root) in the trail, press +`g`, run `pwrdisk --disk`, or use the launcher's *Scan the whole disk* +action. `g` and `--disk` scan the disk your home directory lives on — `/` +on Omarchy and on macOS. On macOS the Data volume's second mount, +`/System/Volumes/Data`, exposes only its private `.fseventsd` and +`.Spotlight-V100` stores: `/Users`, `/Applications` and the rest would be +the same files again under other names. + +Widening is memoized: the tree already measured is handed to the wider walk +and reused where it is reached, so going from `~` to `/` reads only what is +outside `~` (on this machine, seconds instead of a full rescan). The current +view stays on screen until the wider tree lands, which then opens with the +directory you came from selected. Going back down is just navigation. + +By default a scan stops at **every nested mount point**, including bind +mounts and same-device btrfs subvolumes. Boundaries are checked by path, +before metadata or directory reads, so an automounted NAS is not activated +just to measure its parent. Choose `/home`, `/var/log`, or another mount as +its own root rather than implicitly traversing it from `/`. + +Local `-X` explicitly crosses mounts; remote streaming scans reject it. +A local mark on another volume is still removed, but is not added to the +metered volume's free-space projection. + +Without root, some system directories cannot be read; they are counted as +unreadable in the top bar rather than guessed at. + +## Servers over SSH (read-only) + +```sh +pwrdisk ssh dev # connect and choose a remote root +pwrdisk ssh user@server /var # an explicit remote path +pwrdisk ssh dev --disk # the disk containing the remote home +pwrdisk ssh dev -a /srv # apparent size instead of allocated blocks +``` + +Linux builds made with `make build` / `cargo xtask portable` include static +**x86-64 and ARM64 Linux scanners appended to the executable**. SSH detects +the server's OS/CPU and uploads the matching scanner only when its checked +cache is missing or damaged. The cache is private and content-addressed under +`~/.cache/disktree/ssh//` (or the server's `XDG_CACHE_HOME`). +Uploads are checksum-verified and atomically installed; there is no sudo, +system-package change or dependency on the server's glibc version. + +This uses stable Rust's musl targets rather than Cosmopolitan: the existing +Rust/rayon/rustix scanner has no supported stable Cosmopolitan target. These +are Linux binaries, not a single executable for every OS; ARM64 is built and +ELF-validated, while x86-64 was also executed against a real server. + +You can extract a helper without opening a window, or test the entire +SSH/deployment/scan path headlessly: + +```sh +pwrdisk extract-scanner x86_64 ./disktree-scan +pwrdisk extract-scanner aarch64 ./disktree-scan-arm64 +pwrdisk ssh dev --check /var/log +``` + +The appended manifest stores architecture, byte ranges and SHA-256 hashes. +Do not run `strip` after packaging: it discards the trailer. The Linux release +pipeline strips first, embeds last, and ships that single file. Appending to +signed macOS/Windows executables needs platform-specific signature handling; +those builds do not yet embed helpers. + +For a development or non-Linux desktop build without the trailer, install +the small **disktree-scan** helper on the server first: + +```sh +# On the server, inside the checkout: +make install-scan # ~/.local/bin/disktree-scan; no GUI deps +# Or: +cargo install --path crates/disktree-scan --locked +``` + +The helper can be on the server's **non-interactive SSH PATH** or at +`~/.local/bin/disktree-scan` (the default install location); PwrDisk tries +both. A binary copied from another machine must match the server's OS, +architecture and runtime. The manually built native helper may need the +server's libc; the embedded Linux helpers are static. PwrDisk never runs +sudo or changes the server's configuration. +SSH keeps your normal authentication settings. When launched from a +terminal, it can ask for a password or key passphrase there; GUI launches +need key/agent access or a working SSH askpass helper. Connect once with +`ssh dev` to verify access and accept its host key. + +The protocol also supports lightweight root discovery, separate from a scan: +it reads the target's mount namespace without walking or probing the listed +paths. Same-device mounts remain distinct choices; capacity is unknown +until a root is explicitly selected. Discovery requests omit scan fields, +so outdated helpers reject them instead of silently scanning their home. + +The Linux/macOS helper streams a depth-first walk directly to stdout. It +never constructs a tree or retains a directory's children: memory scales +with open ancestors, not file count. Deep directories are not rejected +at an arbitrary depth; filesystem errors are reported as unreadable. +Hardlink identities are sent to the desktop, which uses the local scanner's +compact identity index to count each inode once. The helper keeps no +per-file identity table in negotiated desktop-de-duplication mode; links +outside the chosen root cannot fill one. Older clients retain bounded +helper-side accounting for wire compatibility. A resource limit fails +explicitly instead of returning a partial tree. Symlinks are not followed, +and every nested mount is skipped, even a bind mount or same-device +subvolume. Select those as separate roots. + +While indexing, the sidebar shows a progress bar and estimated percentage +for whole-volume scans, using measured file bytes versus the drive's used +space at scan start. Shared blocks, snapshots and unreadable paths affect +this estimate; it stays below 100% while scanning and does not predict +time remaining. Folder, filtered, apparent-size and cross-volume scans +have no known total. Live file and directory counts, measured bytes, read +errors, elapsed time and average files per second remain visible. After +enumeration, the status changes to **Building treemap** while totals and +categories finish. Counters and paths use monospace type in fixed lanes; +changing values do not re-center or reflow the screen. Narrow windows use +a compact progress footer instead. + +Ordinary local walks and current SSH helpers paint a **live top-level +overview** before the full tree arrives. These are measured contributions, +not complete directory sizes. Updates are limited to once a second, in +arrival order, with at most 128 named buckets plus an overflow bucket. The +preview is kept separate from the real tree: it cannot be navigated, +marked or removed. On completion the full, actionable treemap replaces it; +on error or cancellation the preview is discarded. The Windows file-table +fast path still waits for its complete tree. Remote scans also show a +sampled recent directory and connection / helper setup / indexing / treemap +stages. Progress uses a single replaceable snapshot, not a growing event +queue; path updates are throttled to five per second. There is no guessed +percentage: the total is unknown until the walk finishes. Older helpers +still provide counters from their streamed records, without path samples. + +One compressed SSH connection carries a bounded JSON request on stdin and +compact postorder records on stdout. The client keeps stdin open so the +helper exits on disconnect, including while scanning or blocked on output. +Linux helpers also enforce a 1 GiB address-space ceiling, disable core dumps, +and stop after five minutes. File contents never cross the connection and +paths are never interpolated into remote shell commands. Only the desktop +retains the complete tree for offline navigation; its memory still scales +with entry count. The native Windows helper currently retains the original +tree-building scan path. + +Remote mode is **export-only**. Mark with Space, open review with `c`, then: + +- **Copy as prompt** (`a`): includes the SSH host, remote OS, scan root, + selected paths, sizes and cleanup precautions. It requires verifying the + actual scanned hostname and machine ID before any destructive operation, + and stopping if either check fails or cannot be performed. +- **Save list…** (`s`): remote paths, one per line, saved locally. +- **Copy delete script** (`y`), or **Save delete script…** (`e`): a + GNU/Linux shell script, copied to the clipboard or saved locally. + Running it without arguments only previews the selection. After reviewing + it, `sh pwrdisk-delete.sh --delete` connects to the named SSH host and + runs the exported commands there, never against the local paths. + +There are no trash/delete buttons or removal-mode choices in remote review. +Deletion shortcuts and removal entry points are disabled too. Git inspection, +local folder selection and file-manager reveal are disabled so remote names +cannot accidentally act on this computer. Free space is sampled when the +scan starts, **not live**; press `r` to refresh. + +Before deleting, scripts compare the server's actual kernel hostname and +machine ID against the identity captured in the scan—not the SSH alias. +Missing identity or any mismatch aborts. The check runs on the SSH target, +not the computer launching the wrapper. Pasting the script previews it by +default and runs in a subshell, so its exit cannot close your terminal. + +Exports are not an automatic cleanup recommendation. Scripts refuse system +paths, the scan root, home or its ancestors, symlinked/changed canonical paths, +and paths containing mount points. Control-character names are omitted. +These checks do not eliminate filesystem races or tell you whether git work +is backed up; review the script and prefer a tool's own cleanup command for +tool-owned data. The remote helper itself has no delete operation. + +## With an AI agent + +PwrDisk is also an [MCP](https://modelcontextprotocol.io) server, so an +agent such as Claude Code or Codex can do the looking while you keep the +deciding. One command connects it, and there is nothing to configure, sign +in to or approve: the agent runs `pwrdisk mcp` as you, over stdio, and can +do no more than your shell can. + +```sh +claude mcp add --scope user pwrdisk -- pwrdisk mcp +``` + +(Codex: `codex mcp add pwrdisk -- pwrdisk mcp`. Any other client: a +server named `pwrdisk` with the command `pwrdisk` and the argument `mcp`. +On macOS the command lives inside the app, at +`PwrDisk.app/Contents/MacOS/pwrdisk`. **Settings › Agents (MCP)** shows +the bare command line and each client's command with the binary's full +path and a Copy button, and who is connected. **Help › Connect an AI +Agent (MCP)…** and the **Connect an AI agent (MCP)** line under the disk +open it; on a short window that line waits until an agent connects.) + +Then ask it what is eating your disk. The agent walks the tree largest +first, lists every cache, build directory and package store at once, and +proposes what can go. It marks what you agree to, and marking is all it +does by default. `pwrdisk_review` opens the marked list for you to approve; +the agent must never approve it through computer use. For requested MCP +removal, `pwrdisk_removal_preview` returns the exact paths and an explicit +Trash or permanent mode. After you confirm that operation, the destructive +`pwrdisk_remove` tool requires interactive confirmation through the MCP +client. Clients without form elicitation use human review instead. Trash +may be recoverable until emptied; permanent deletion cannot be undone +through PwrDisk. Settings > Safety sets the per-operation limit: 5% of each +volume's capacity by default, for both UI and MCP removal. The app rechecks +the guards and re-measures the complete selection before removing anything. + +When a PwrDisk window is open, its tree is what the agent reads. `ls`, +`find` and `scan` are answered from the mosaic on screen, a mark is +measured from it, and the two of you see the same numbers. The agent's +marks appear in the mosaic and in the free-space meter as it makes them, +`ls` and `find` never navigate; `show` moves the view only when you ask, a scan it asks for runs in +the window, and the header names the agent and its last action while it is +connected. With no window open the agent scans on its own, in seconds for a +home directory, and can open a window for the review. Without a display it +works headless and says so. A window showing an SSH server is not followed: +the agent's tools measure this computer, and PwrDisk does not remove files +over SSH. + +`pwrdisk_remove` does not rescan unless asked (`rescan: true`), so the +agent can find and mark the next batch at once. Until a rescan, +`pwrdisk_ls` and `pwrdisk_find` still list removed paths with the scan's +sizes, but say **removed since the scan** on each, and on a directory that +lost part of itself, how much of it went; marking a removed path is +refused. `pwrdisk_status` lists every removal since the scan, +reported, private and observed, with their total. + +The tools: `pwrdisk_status`, `pwrdisk_scan`, `pwrdisk_ls`, +`pwrdisk_find`, `pwrdisk_show`, `pwrdisk_mark`, `pwrdisk_unmark` and +`pwrdisk_review`, `pwrdisk_removal_preview` and `pwrdisk_remove`. Each `mark` answers with the real plan: what the guards +below keep back and why, what another mark already covers, and the free +space it gives back on the volume, counted the way the meter counts it. + +The server carries its own skills, so the agent knows how to use the tools +and what to be careful of before it starts: + +| skill | for | +| --- | --- | +| `pwrdisk-explain-usage` | where the space went, read-only: never marks anything | +| `pwrdisk-free-space` | freeing space: agree the list with you first, unless you gave a standing instruction, then mark and hand over the review | +| `pwrdisk-free-space/references/` | macOS, Linux and Windows: what each hides from a scan (snapshots, clones, cloud placeholders), what PwrDisk refuses, and what never to propose | + +They are served as `skill://` resources, through the skills extension's +`skills/list`, and as the prompts `free-space` and `explain-usage` (in +Claude Code, `/mcp__pwrdisk__free-space`), which add the reference for the +system the server runs on. The files are in `skills/`. + +The window listens on an endpoint only you can reach: a Unix socket in +`$XDG_RUNTIME_DIR` or `$TMPDIR`, or a local Windows named pipe, +`\\.\pipe\pwrdisk-`. The pipe grants access only to your Windows +account and rejects remote clients. The agent verifies the connected pipe +is owned by your account before exchanging messages. Set `PWRDISK_LINK` to +choose another socket path or local pipe name. On macOS, Linux and Windows, +the agent's marks appear in the open window and `pwrdisk_review` opens its +review screen. + +## Updates + +A copy installed from the DMG, Setup.exe or the MSI checks the project's +GitHub releases when it starts and every six hours, and downloads a newer +release in the background. The download installs when PwrDisk quits, or at +once from **Restart to update**. Nothing is sent but the request for the +release list. + +**Check for Updates…** (in the PwrDisk menu on macOS, the strip's menu +elsewhere) checks at once and answers in a toast at the lower left of the +main window, above the screen's buttons. While it works the toast says so, +and while it downloads it shows how far along it is. Then it answers: up +to date, an update ready to install, or why the check failed. An answer +goes after eight seconds; resting the pointer on it holds it. + +An update ready to install, found by any check, stays in a toast with +**Restart to update** until you restart or choose **Later**. Later puts away +that version only: a newer one, or Check for Updates…, brings it back. The +title strip offers it too, as **0.15.0 ready · Restart**, Later or not. +Restarting forgets your marks, and it waits while a removal runs. + +**Shift-U** opens the Updates panel: the version, what the last check found, +**Check now**, and the release channel: + +| Channel | Gets | +| --- | --- | +| Stable · Latest | Releases promoted after a check. The default. | +| Stable · Prerelease | Candidates for the next stable release. | +| Beta · Latest | Beta builds (`-beta` tags). | +| Beta · Prerelease | The newest alpha (`-alpha` tags); may not work. | + +Until you pick one, a copy follows the channel its own version implies, so +a beta keeps getting betas. Picking an older line downloads its release on +**Check now**, and it installs only from **Restart to switch**. + +Copies that did not come from an installer — the Linux tarball, `make +install`, `cargo build` — do not update themselves; download the next +release. + +## On macOS + +To see privacy-protected files, give PwrDisk **Full Disk Access** in System +Settings › Privacy & Security (the panel offers a button when it is missing), then +reopen it. Without it macOS hides Mail, Messages, Safari, other apps' data +and the Trash, and PwrDisk counts them as unreadable. Started from a +terminal, it is the terminal that needs the access. macOS also asks once +each for Desktop, Documents and Downloads. + +Full Disk Access does not override filesystem ownership and permissions. +Administrator-owned service stores can still be unreadable. Unknown contents +are never reported as zero bytes or as absent software. To inspect a store +explicitly, include hidden entries, remove any scan depth limit, and use the +directory chooser to scan it directly. Read access must be arranged outside +PwrDisk; the app does not request elevation or install a privileged helper. + +What is different from Linux: + +- **Free space** is what `df` reports. Finder's figure is larger: it counts + purgeable space (caches and local snapshots macOS will clear on its own). +- **Cloned files** (copies APFS shares blocks between, as Finder's Duplicate + makes) remain counted in full in the treemap. The scan line separately + reports bytes in cloned files and estimated repeated data-fork allocation. + The selection panel and a tile's hover card split the listed bytes into + private and shared: shared bytes are clone blocks another clone, inside + the scan or outside it, may still hold. In `pwrdisk mcp`, every + `pwrdisk_scan`, `pwrdisk_ls` and `pwrdisk_find` row with clone blocks + reads `0 B private · 11 MiB shared with other APFS clones · frees ≈ 0 B + alone`, and the scan and listing headers say how much is counted again + and what the files take on disk. Rows without clones, and every row off + APFS or in an apparent-size scan, read as before. + The panel's marked total, the review and the permanent-delete + confirmation estimate savings from the accepted set of marks together; + the selection's own line says what that entry frees removed on its own, + which for one of several clones can be far less. Complete clone groups credit + shared data once; a remaining hardlink retains its file data. Unknown or + modified sharing and allocation outside the data fork supply a range, + with only its lower bound used by the volume meter. Unknown private sizes + contribute zero to that bound. Snapshots and open files can retain blocks, + and changing files can stale the estimate; rescan to refresh it. The final + result still measures the volume's actual free-space change. + Clone hints come from bulk directory reads; only potentially shared files + need a private-size query. A bounded, sharded cache reuses confirmed full + clones within their observed reference count, separately on each real + APFS volume and each scan. Modified clones are measured individually. + Unsupported filesystems or kernels fall back to + the ordinary listing without clone detection. Apparent-size scans do not + collect clone metadata. +- **Time Machine's local snapshots** are not files and do not appear; they + are part of the gap between the scan and the disk's used space. +- **Cloud-only folders** (iCloud Drive, Dropbox and the like, evicted to the + server) are not opened, so a scan never downloads them. + +### FSEvents history and Spotlight indexes + +Local macOS scans categorize **FSEvents history** (`.fseventsd`) and +**Spotlight index** (`.Spotlight-V100`) when their files are readable. The +**macOS service stores** panel appears only when the scan measures at least +one store. If both are unreadable or outside the scan, it stays hidden and +adds no permission request or Full Disk Access hint. Other unreadable files +can still produce the existing privacy hint. + +When one store is measurable, the other retains an honest **Unavailable** or +**Outside scan** label; partial results say **measured · incomplete**. Select +a service tile for Apple's guidance. Access is determined from the scan, +rather than assuming Full Disk Access overrides ownership permissions. +On a startup disk the stores live in `/System/Volumes/Data`; external volumes +have their own stores. Home-directory and SSH scans do not show this panel. + +The figures are allocated file bytes (`st_blocks × 512`), unless apparent size +is selected, and are already part of the scan total. They are not additional +APFS volume, container or snapshot figures. Hardlinks are counted once across +the tree; shared APFS clone blocks and snapshots mean measured bytes are not +a promise of space freed. The rest of the second Data mount stays excluded, +so firmlinked user files are not counted again. + +FSEvents stores persistent filesystem change history that backup and sync +apps can use. At an administrator's explicit discretion, Apple's supported, +root-only [`FSEventsPurgeEventsForDeviceUpToEventId` API](https://developer.apple.com/documentation/coreservices/1447985-fseventspurgeeventsfordeviceupto) +can shorten old history. It destroys history for **every consumer on that +volume**, and those consumers may need a full rescan. Apple's +[FSEvents guide](https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/FSEvents_ProgGuide/UsingtheFSEventsFramework/UsingtheFSEventsFramework.html) +advises against routine purging and requires an explicit administrator request +and confirmation. PwrDisk only explains this option; it does not call it or +suggest raw deletion of `.fseventsd`. + +An administrator implementing a chosen retention cutoff would resolve the +volume's current `st_dev`, obtain an event ID with +`FSEventsGetLastEventIdForDeviceBeforeTime`, and only then use the purge API. +The installed macOS SDK's `FSEvents.h` documents this function's time argument +as **seconds since January 1, 1970**, despite its `CFAbsoluteTime` type. The +archived guide describes the usual 2001 epoch instead; check the target SDK +contract rather than applying that conversion. No retention cutoff or space +saving is guaranteed by PwrDisk. + +Spotlight's index supports file and content search. Keep indexing for that +functionality, exclude selected folders through +[Spotlight Search Privacy](https://support.apple.com/guide/mac-help/prevent-spotlight-searches-in-files-mchlp2811/mac), +or have an administrator choose whether a volume should be indexed. The +installed `mdutil(1)` manual describes `-s` as a read-only status query, +`-i on|off` as the indexing choice, and `-X` as removing the index directory: +**`-X` does not itself disable indexing**. An erased index may be rebuilt when +indexing is enabled, consuming space and work again; disabling indexing reduces +search coverage. A failed status query is unknown, not evidence of disabled + +## On Windows + +The same program, with Windows' answers to the questions above: + +- **Disk usage** is the allocation NTFS reports for each file: whole + clusters, less for a compressed or sparse file, nothing for one small + enough to live in its file record. It arrives with the directory listing + itself (`FileIdExtdDirectoryInfo`), so it costs no more than the walk. + Hardlinks count once on NTFS. +- **The whole disk** is the drive your profile is on, usually `C:\`. A + folder another volume is mounted on is a link, like a junction, and is + not entered, so a scan stays on one volume; `-l` follows links, and with + them mounted folders. +- **Run as administrator** and the whole disk is read from NTFS's master + file table instead of walked, as WizTree does: one pass over the table in + large reads. On a 4-million-file `C:\` that took about 3.4 s against 11.2 + s for WizTree and about 20 s for the walk. It also sees what the walk is + refused, such as System Volume Information. It is used only for a whole + NTFS drive, since a folder would still cost the whole table, and not with + `-l`, whose links the table does not follow. PwrDisk flushes the volume + after its own removals so the rescan shows them; changes other programs + made seconds before may not show yet. + Started without admin rights, PwrDisk walks as before. On a whole NTFS + drive without `-l`, or once Windows refuses the walk a folder, the side + panel offers **Restart as Administrator**, which reopens the same folder + and options through the UAC prompt; during a widening scan, the wider + folder being scanned. +- **Move to trash** is the Recycle Bin, through the shell, which asks + before destroying anything it cannot recycle. +- **Refused besides the rules below:** Windows, Program Files and + ProgramData, what Windows keeps at the top of its drive (System Volume + Information, Recovery, Boot, and the page and hibernation files, which + Settings turns off), any folder holding your profile, such as + `C:\Users`, and every profile in the folder Windows keeps them in + (`C:\Users\*`, `Public` and `Default` included), since an elevated + PwrDisk may run as another account and can reach them all. What is + inside a profile can still be removed, as under your own. Names compare + without regard to case, as Windows compares them. +- **Hidden** means a name starting with a dot, or the hidden attribute, so + `-H` drops `AppData` as Explorer hides it. +- **The theme** follows Windows' light or dark setting, since there is no + Omarchy theme to follow. It does on macOS too, and on GNOME and KDE. + +## What it refuses to do + +The removal rules live in `crates/disktree-core/src/removal.rs`, and each one is +tested: + +- only paths under the scanned root can be removed; +- the filesystem root, the scanned root and your home directory are refused; +- a mount point is refused, and so is anything with a mount point inside it, + since removing it would reach into another filesystem; permanent deletion + also stops at a mount boundary rather than descending into one (a btrfs + subvolume that is not mounted goes with its directory, as the scan shows + it); +- a directory holding your home directory or a system tree is refused (on + macOS `/Users` is on the same volume as `/`, and `/opt` holds + `/opt/homebrew`); +- every account's folder is refused, and so is the folder holding them: + `/Users` and each folder in it on macOS, `/home` and each folder in it + on Linux (by either name where `/home` links to `/var/home`, as on + Fedora's atomic editions), the profiles folder (usually `C:\Users`) and + each profile on Windows. What is inside one stays removable; +- these are asked before a mark is made: the panel says why instead of + offering **Mark for removal**, and Space marks nothing; +- one removal may take only so much of a disk, 5% by default (see + [Removing](#removing)); +- system trees (`/usr`, `/etc`, `/boot`, `/var/lib`, `/nix/store`, + `/gnu/store`, Homebrew's prefix on macOS and Linux, …) are + refused even where permissions would allow it: packages own them, and + pacman, paccache or `journalctl --vacuum` are the tools; +- a symlink is unlinked, never followed; +- nothing is passed through a shell — a file called `-rf` is just a file; +- selecting a checkout never runs a program it names: git is asked with its + fsmonitor, hooks and pager off, and a checkout that defines its own filter + drivers is not asked for its status at all ("changes unknown"). + +## On Hyprland + +Hyprland tiles new windows, so PwrDisk opens into whatever tile it is given. +It is designed for a roomy window; float it, or give it a rule. The window +class is `pwrdisk`. + +``` +windowrule = float, class:^(pwrdisk)$ +windowrule = size 1400 900, class:^(pwrdisk)$ +``` diff --git a/docs/headed-e2e-pwrsuitelab.md b/docs/headed-e2e-pwrsuitelab.md new file mode 100644 index 00000000..e42b3177 --- /dev/null +++ b/docs/headed-e2e-pwrsuitelab.md @@ -0,0 +1,233 @@ +# Mac GUI checks in PwrSuiteLab + +Anything that needs an on-screen macOS window — a PR screenshot, a +VoiceOver or native accessibility check, a look at a screen the +window-harness tests cannot judge — runs in the dedicated headed E2E Tart +VM of PwrSuiteLab, never on the operator's Mac. A window launched on the +operator's Mac takes focus, and synthetic keys or clicks land in whatever +app the operator is using; that has happened. +[AGENTS.md](../AGENTS.md#testing-on-a-desktop) has the rule. + +This file covers macOS only. Linux builds, lint, tests and SSH integration +run in [Sandboxer](sandboxer.md), which has no desktop. A Linux or Windows +window that the lab cannot show is a question for the operator, never a +reason to use the local desktop. + +## Through PwrSuiteLab Control MCP + +The only route is the PwrSuiteLab Control MCP. If its tools are not +available to this thread, stop and ask the operator. There is no local +fallback and no script fallback. + +The served skills are the procedure, and they win over this file when the +two disagree. Discover the live tools and their schemas first, then read +`skill://manage-pwrlab-e2e/SKILL.md` (`skills/list` → `skills/get` → +`resources/read`; older clients `resources/list` → `resources/read`). +`skill://inspect-pwrlab/SKILL.md` explains `lab_status`, and +`skill://operate-pwrlab/SKILL.md` covers lab operations. In PwrAgent, find +the tools with `search_mcp_tools` and call them with `call_mcp_tool`. Keep +the Control MCP connection open. A connection granted Operate may call its +exposed actions; one granted Read only may not, and a `permission_denied` +is reported, not worked around. + +1. Call `lab_status` and take the exact target of the dedicated E2E role. + Never pick a GitHub Actions runner or the physical Mac's desktop. Check + status again just before submitting: the VM can stop, or another owner + can take it, while the job is being prepared. `lab_e2e_run` starts the + VM when needed; no `lab_e2e_acquire` is needed first. +2. Commit the change and use this thread's clean, committed worktree, by + its absolute path. Never discard changes to make it clean. Only + committed `HEAD` travels: no ignored files, host environment or + credentials, and no push is needed. +3. Call `lab_e2e_run` with top-level `target`, `agent_name`, + `project_name` (`PwrDisk`) and `thread_name` (the current thread's + title), plus `pr_number` as a string of digits only when a PR is known. + These are display labels: no paths or credentials in them. +4. The `job` holds `repository` (that absolute path), `setup` (an ordered + array of argv arrays), `command` (one argv array), `artifacts` (at most + 16 checkout-relative paths; symlinks and `..` are refused) and + `timeout_seconds` (checkout, setup and command together, at most + 14400). Optional `cwd` is relative to the checkout. These are argv + arrays, not shell strings: a pipeline, a loop or a shell function needs + `["bash", "-c", "..."]`. +5. Keep the request ID and the `run_id`. Poll `lab_request_status` until + the launch request completes; `job_state: running` means the job + started, not that it passed. Then call `lab_e2e_collect` with the + target and `run_id`, polling its request if it is still executing. It + downloads `e2e.log` and the artifacts to the returned + `artifact_directory`, which is relative to the PwrSuiteLab checkout + Control uses, not to this worktree; if you cannot resolve it, ask the + operator rather than search for it. Report the commit, the exit code, + and which artifacts are missing; tell a setup failure from a check that + failed. Keep raw logs and images out of Git, and never paste `e2e.log` + lines, guest paths or the local artifact directory into a PR, issue or + commit message. Summarize the failure in your own words. + +After the job, Control collects its artifacts and stops a VM it started for +you, so a stopped VM is normal: call `lab_e2e_collect` with the saved +`run_id` first, since collected results come back with the VM stopped. Only +if it reports the run was never collected (`e2e_vm_stopped`), start that +exact target with `lab_e2e_start` when capacity permits and collect again. +Never rerun a job only to retrieve its artifacts. + +## PwrDisk in the guest + +PwrDisk is a Rust workspace, and `rust-toolchain.toml` pins its toolchain, +which rustup provisions on the first `cargo` call. `cargo build --release` +(or `make build`) produces `target/release/pwrdisk`; `make bundle` produces +`target/bundle/PwrDisk.app` when a check needs the bundle. `pwrdisk ` +scans that path directly and skips the source chooser. + +The guest's command environment loads an existing Cargo setup. If `cargo` +or rustup is missing, install it noninteractively in `setup`. That runs in +the guest only; never install tools on the host as a workaround. + +Synthetic input, AX scripting, `osascript` and `screencapture` are fine +inside the guest, from the job's command; never through a viewer on the +host. That is what the guest is for. Capture only the PwrDisk window, and +write into a checkout-relative directory, because artifacts are paths +relative to the guest's checkout. Build fixtures on the `Fixtures` disk +image only, never in the checkout or the guest's home: their paths, volume +and free space describe the lab. + +### Example job + +A shape to adapt, not a tested recipe. Replace every `<...>`; drop +`pr_number` when no PR is known. + +```json +{ + "target": "", + "agent_name": "", + "project_name": "PwrDisk", + "thread_name": "", + "pr_number": "", + "job": { + "repository": "", + "setup": [ + ["bash", "-c", "command -v cargo >/dev/null || curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none"], + ["bash", "-c", "source \"$HOME/.cargo/env\" 2>/dev/null; cargo build --release --locked"] + ], + "command": ["bash", "-c", ""], + "artifacts": ["target/lab-shots"], + "timeout_seconds": 3600 + } +} +``` + +The `command` script builds the contrived tree from +[pr-screenshots.md](pr-screenshots.md) on a disk image named `Fixtures`, +opens PwrDisk on it, waits for its window, captures only that window and +quits: + +```sh +set -euo pipefail +shots=target/lab-shots # relative to the checkout, as artifacts must be +mkdir -p "$shots" +pid= +cleanup() { + # kill is asynchronous: wait, or the detach finds the volume busy. + [ -n "$pid" ] && { kill "$pid"; wait "$pid"; } 2>/dev/null || true + hdiutil detach -force /Volumes/Fixtures 2>/dev/null || true +} +trap cleanup EXIT + +# A stale mount would put this image at "/Volumes/Fixtures 1". +[ ! -e /Volumes/Fixtures ] || { echo 'Fixtures already mounted' >&2; exit 1; } +hdiutil create -ov -size 512m -fs APFS -volname Fixtures \ + -attach target/fixtures.dmg +root=/Volumes/Fixtures/Projects +mkdir -p "$root"/{atlas/build,atlas/src,beacon/node_modules,photos/2024} +fill() { dd if=/dev/urandom of="$1" bs=1048576 count="$2" 2>/dev/null; } +fill "$root/atlas/build/app.bin" 120 +fill "$root/beacon/node_modules/bundle.js" 40 +fill "$root/photos/2024/IMG_0001.raw" 80 + +target/release/pwrdisk "$root" & +pid=$! + +# The CGWindowID of PwrDisk's main window, for screencapture -l. +cat > target/window-id.swift <<'EOF' +import CoreGraphics +let pid = Int(CommandLine.arguments[1])! +let all = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) +for w in all as? [[String: Any]] ?? [] { + if w[kCGWindowOwnerPID as String] as? Int == pid, + w[kCGWindowLayer as String] as? Int == 0 { + print(w[kCGWindowNumber as String]!) + break + } +} +EOF +wid= +for _ in $(seq 60); do + wid=$(swift target/window-id.swift "$pid" 2>/dev/null || true) + [ -n "$wid" ] && break + sleep 1 +done +[ -n "$wid" ] || { echo "no PwrDisk window" >&2; exit 1; } +sleep 5 # the scan finishes and the treemap draws + +# +screencapture -o -x -l "$wid" "$shots/.png" +``` + +Check the images after collecting them. A capture that shows only the +desktop, or a shell that cannot send keys or read AX, means the guest is +missing a permission such as Screen Recording or Accessibility. Report that +to the operator as a baseline issue; do not change the VM's settings, its +login or its access to work around it. + +For "before" images, run the same job against a clean, committed worktree +of `main` (`git fetch origin main && git worktree add --detach +origin/main`), with the same tree, the same window size and `before` +names. Remove it with `git worktree remove ` afterwards. + +## Interactive work + +A check that needs a person at the guest, such as a VoiceOver walk-through, +is for the operator. To put PwrDisk there, run a job whose command builds +the fixture, launches `target/release/pwrdisk ` and keeps it open (for +example `sleep ` within `timeout_seconds`), then call +`lab_e2e_open` while it runs so the operator can use it. `lab_e2e_acquire` +(same top-level target and attribution, no `job`) and `lab_e2e_release` +reserve the display without a job; a reservation stages no source, so it +puts no PwrDisk build in the guest. Release only this connection's own +reservation, never after a job has consumed it. + +The Screen Sharing viewer that `lab_e2e_open` shows runs on the operator's +desktop. It is for the operator to use. Never drive it with computer use, +`osascript`, `cliclick`, AX actions or window moves. Input that the agent +sends goes only through a job's `command`, which runs in the guest. + +## Files, not the clipboard + +Lab VMs start with clipboard sharing off: Tart's text-only sync echoes back +and strips images and rich text from the operator's clipboard. Inputs travel +in the committed source `lab_e2e_run` stages; outputs come back as +`lab_e2e_collect` artifacts. Never use the shared clipboard, and never ask +the operator to paste into or copy from the guest. + +## Errors, ownership and recovery + +`Invalid arguments` (`-32602`) is a schema mismatch, not a lost grant. +Refresh the schema, check the three attribution fields, their top-level +place, `pr_number` as a string and the argv shapes, and report it if a +corrected call still fails. After a launch or transport failure, inspect the +returned run before retrying: the job may already be running. + +An `interrupted` result is not a pass. A held lock's age is an observation, +not an expiry. Preserve locks and use the guarded `lab_e2e_recover` for an +orphaned workload; never delete a lock or end another owner's session. +Control owns SSH, identity and host trust: no raw SSH, no guessed users or +keys, no new host keys. A missing baseline prerequisite is an +operator-authorized repair, not part of a job. + +## Keep the lab out of this repository + +PwrDisk is public. Host and guest names, addresses, targets, users, keys, +fingerprints, paths on the lab's or the operator's machines, and capacity +live only in PwrSuiteLab, and stay out of code, docs, commit messages, PR +bodies, issues and fixtures. Target values come from `lab_status` at run +time. What belongs here is that the lab exists, its name, and the public +Control tools and job contract: enough to use it, never enough to map it. diff --git a/docs/owner-cleanup.md b/docs/owner-cleanup.md new file mode 100644 index 00000000..437ab202 --- /dev/null +++ b/docs/owner-cleanup.md @@ -0,0 +1,194 @@ +# Cache cleanup + +A cache name, category or `regenerable` hatch is an inspection lead, not +permission to delete. Review steers marked caches to **Cache cleanup**, +where the person decides each marked path on its own: + +* **Skip** (the default): nothing happens to it. +* **Run the owner's command**: the exact allowlisted command shown for it, + for its owner's whole actual scope. Offered only when that command + resolved; see the allowlist below. +* **Delete files**: delete exactly that selected path directly, without + its owner, by Trash or permanently. A separate destructive intent with + its own disclosure and its own consent. + +Ordinary Trash and Permanent removal still refuse recognized cache paths, +cache wrappers and opaque cache tags, including caches inside a selected +parent: deleting a cache's files happens only as a Delete files decision. + +## How this reconciles with the earlier guard policy + +| Before | Now | What still holds | +| --- | --- | --- | +| One Owner cleanup mode for the whole list; a missing CLI, unsupported version or failed probe refused the entire preview | Check owners returns one proposal per marked path; a failure is that proposal's status | Preview is read-only, off the UI thread, with the same probes, timeouts and shim/proxy refusals | +| Approval meant running every command shown | Each path is decided; Skip is the default and nothing is chosen for the person | An agent cannot decide for the person | +| Raw deletion of a recognized cache was always refused | Allowed only as an explicit Delete files decision for that exact path, never the owner's wider scope | Removal guards, protected folders, the capacity limit and Review's over-limit confirmation, permissions, and an in-use check | +| "No raw deletion fallback" | Unchanged: a missing, unsupported, refused, failed or cancelled owner command deletes nothing else | Deleting those files instead needs a new review and its own decision | +| Unknown caches were refused | Unknown owner, "not known to be disposable"; Delete files is offered with a runtime/installation warning | PwrDisk never labels an unknown cache disposable; agents inspect first and never suggest Delete files | +| Exports: marked paths only; raw scripts refuse caches | Unchanged | Owner scopes never widen an export | + +## Initial allowlist + +Commands below are argument lists, executed directly with an absolute +resolved executable. `ROOT` is the owner's queried configured root; it is +never inferred solely from a directory name. PwrDisk does not use `npx`, +`uvx`, a package download, a project script or a shell to find a missing CLI. + +| Owner | Accepted stable versions | Query | Cleanup and actual scope | +| --- | --- | --- | --- | +| npm packages | 9–11 | `npm config get cache` | `npm cache clean --force --cache ROOT`; entire `ROOT/_cacache` only | +| npm npx | 11.2–11.x | `npm config get cache` | `npm cache npx rm --force --cache ROOT`; entire `ROOT/_npx` only | +| uv | 0.11.x | `uv cache dir` | `uv cache clean --cache-dir ROOT`; whole cache, using uv's exclusive cache lock, without `--force` | +| pip | 23–26 | `pip cache dir` | `pip --cache-dir ROOT cache purge`; HTTP and wheel entries in that cache; other files can remain | +| Cypress | 13–15 | `cypress cache path` | `CYPRESS_CACHE_FOLDER=ROOT cypress cache clear`; ALL cached binary versions, including ones other projects use | + +The version is queried first. Unknown output, prereleases, unsupported +versions, non-executable launchers and failed configuration queries withhold +the owner command for that path; the proposal says which. A command missing from PwrDisk's inherited PATH means unavailable, +not that the software is uninstalled. Relative PATH entries are ignored. pip resolution also accepts `pip3` when +`pip` is unavailable. +Known version-manager shims (including shimmed `env node` interpreters) are +refused before version probing, because a probe can otherwise install a +missing runtime. Expose the actual installed CLI/runtime directly on PATH. +npm must resolve to its installed `npm-cli.js`; downloading proxy launchers +such as Corepack are unsupported. +Relative PATH entries are removed from the captured execution environment; +non-UTF-8 environments fail closed instead of silently losing configuration. +Only macOS and Linux have execution adapters; Windows cache recognition +remains available, but shell-based Windows launchers are unsupported. Delete +files is not offered on Windows either: it is checked for programs using the +path right before it runs, and that check exists only on macOS and Linux, so +it would always be refused. + +Queries run from the user's home with the app's environment, so user config +and environment overrides apply. Project-only configuration must be made +available explicitly to that environment; PwrDisk never searches projects or +evaluates Puppeteer JavaScript config. A stale/default selection that does +not match the queried root is refused, rather than redirected to a different +cache. Selecting a subtree expands to the owner's complete scope. Selecting +the npm wrapper previews its supported sibling caches separately. + +| Inspection-only owner | Why automatic cleanup is unavailable | +| --- | --- | +| pnpm | `store prune` can also affect metadata, dlx/runtime caches and global virtual-store state outside a selected store; these scopes are not modeled here | +| Homebrew | `brew cleanup`, including `--prune=all`, also removes old installed formula versions and stale locks outside the selected cache | +| Playwright | `uninstall` manages browser installations and package references; no adapter models that wider scope | +| Puppeteer | The browser API and interactive `browsers clear --path` exist; resolving the correct installed API/configuration and its confirmation is not implemented | +| codex-runtimes, gh, Electron, VS Code C++ and unknown caches | No verified owner adapter; inspect the owning installation and its supported lifecycle | + +## Proposals + +**Check owners** (MCP: `pwrdisk_removal_preview` with `mode: +"owner_cleanup"` and no decisions) resolves each marked path on a worker +without cleaning. Each proposal carries: + +* the path, its size, and why it is treated as a cache; +* each resolved operation: owner and version, absolute executable, + argument list with boundaries, environment overrides, working directory, + configured cache root and actual scope, whether that scope is wider than + the selection, effects, limitations and recoverability (none through + PwrDisk or Trash); +* otherwise the problem, in one vocabulary used everywhere: not found on + PATH, unsupported launcher, unsupported version (naming the versions that + run), version check failed, configuration check failed, no cleanup + command, unknown owner, not the configured cache, refused by guards; +* whether Delete files is offered and what it means: that the owner is not + involved, any recognized caches inside the path (a bounded look, three + levels deep), and for an unknown owner that PwrDisk does not know the + path is disposable. + +A path the removal guards refuse offers neither action. A command whose +whole scope fails the guards, crosses a volume, contains an external link, +overlaps another command's scope or cannot be measured is withdrawn from +the proposals that asked for it, with the reason. + +## Decisions and confirmation + +Decisions that would act on the same files twice are refused: a path left +on Skip, or given another action, may not lie inside a chosen command's +scope or a path being deleted. Choose the same action for both. Paths +chosen for the same owner scope run its command once. + +In the window, Review shows each proposal under its mark with Skip, Run +and Delete files; Delete files by Trash or Permanently is chosen once for +the run (Trash by default where it exists). The confirmation lists each +command verbatim, each path deleted directly with its consequence, and +what is skipped. Deleting files has its own tick; the button stays +disabled without it, even when the commands alone could be confirmed. +Changing a decision clears the tick. + +Over MCP the agent shows every proposal and asks the person per path, then +previews again with `decisions` (every marked path once: `skip`, `owner` or +`delete_files`) and `delete_files_mode` (`trash` or `permanent`) when any +path deletes files. Without decisions nothing can be confirmed. A decided +preview is single-use, bound to the scan, marks and decisions, expires +within five minutes, and has its own confirmation text naming each +intent: `RUN OWNER CLEANUP`, `DELETE CACHE FILES`, `TRASH CACHE FILES`, or +`RUN OWNER CLEANUP AND DELETE CACHE FILES` / `... AND TRASH CACHE FILES`. +`pwrdisk_remove` needs the preview ID, its exact ordered paths, mode +`owner_cleanup`, that text and the client's interactive confirmation. +Owner approval never confirms deleting files. The agent's decisions run; +the window's own choices never stand in for them. Computer use cannot +approve. + +## Execution and results + +The usual root/home/system/mount/symlink protections apply to every +step. The configured capacity limit (5% per volume by default) charges each +command's full scope and each deleted path; the worker re-measures first, +and only that ceiling refuses the whole run. A step that can no longer be +measured is refused on its own. + +Steps run one at a time. Before each owner command the worker re-reads the +executable's identity and re-probes version and configured root against +the captured environment, rechecks the scope, and checks whether the owner +is running; before each deletion it checks for a process running from, +inside or naming the path, or for a recognized cache any running instance +of its owner. An owner counts as running under any name it launches by: +npm's and npx's node entry points, `pip3` and versioned names such as +`pip3.12`, and uv's `uvx`. Detection is best effort; close owning tools +first. uv's own lock adds coordination; known `UV_LINK_MODE=symlink` is +refused because installed environments can depend on cache files. + +A failed step reports why and the run moves on to the next. Probes time +out after ten seconds; commands after ten minutes. Stop kills the current +owner process group; that step reads cancelled, may be partly done, and the +rest read not reached. Nothing is retried automatically. npm logging and +rotation and pip log writes are disabled for these invocations so files +outside the approved scope stay untouched. + +Every marked path gets a result: succeeded, failed with its problem and +detail, cancelled, skipped, or not reached. A succeeded command means the +owner exited successfully, not that its root or all its allocation went. +Results keep scope allocation (the scan's size, an upper bound) separate +from the volume's measured availability before and after, which can fall. +Other activity, open files, hardlinks, APFS clones and snapshots can keep +blocks; PwrDisk never alters snapshots. Cache cleanup always rescans, +including after a partial failure, and never marks a retained cache root as +deleted. + +## Exports + +Exports remain limited to the marked paths, even when a command's scope +is wider or a path is chosen for Delete files. Lists and agent prompts +never inherit a wider scope. Save/copy raw deletion scripts refuse Cache +cleanup mode and recognized cache selections; an export cannot stand in +for an owner command or for a decision made in Review. Tags and owner +layouts on ancestors protect contained subdirectories and files, including +caches relocated through CLI settings. + +## Upstream scope evidence + +- [npm cache documentation](https://docs.npmjs.com/cli/cache/), + [npm 11.2 release notes](https://github.com/npm/cli/releases/tag/v11.2.0), + [npm 11.6.2 cache implementation](https://github.com/npm/cli/blob/v11.6.2/lib/commands/cache.js) + and [log rotation](https://github.com/npm/cli/blob/v11.6.2/lib/utils/log-file.js). +- [uv cache documentation](https://docs.astral.sh/uv/concepts/cache/) and + [0.11.0 cleanup lock handling](https://github.com/astral-sh/uv/blob/0.11.0/crates/uv/src/commands/cache_clean.rs). + Older uv releases do not provide that same cache-wide coordination. +- [pip cache](https://pip.pypa.io/en/stable/cli/pip_cache/) and + [Cypress cache location and clearing](https://docs.cypress.io/app/references/advanced-installation). +- [pnpm store scope](https://pnpm.io/cli/store), + [Homebrew cleanup](https://docs.brew.sh/Manpage#cleanup-options-formulacask-), + [Playwright uninstall](https://playwright.dev/docs/browsers#uninstall-browsers), + [Puppeteer browser CLI implementation](https://github.com/puppeteer/puppeteer/blob/puppeteer-v24.26.1/packages/browsers/src/CLI.ts). diff --git a/docs/performance/apfs-accounting/README.md b/docs/performance/apfs-accounting/README.md new file mode 100644 index 00000000..e7055f6e --- /dev/null +++ b/docs/performance/apfs-accounting/README.md @@ -0,0 +1,165 @@ +# APFS accounting and bounded selection work + +## PwrDisk port + +Ported from [huntharo/disktree#3](https://github.com/huntharo/disktree/pull/3) +at `87c02c7` onto PwrDisk main `8f63e4d`, 2026-10-29. PwrDisk already +contains the queue and mark-resolution fixes through +[PwrDisk#5](https://github.com/pwrdrvr/PwrDisk/pull/5); this port adds the +APFS scanner, accepted-set estimates and display changes without replaying +that performance history. PwrDisk branding and release packaging remain. + +Fresh local validation on Apple silicon: `cargo xtask lint` passed; +`cargo xtask test` passed 108 app, 200 core, 4 helper integration and 3 xtask +tests. Seven opt-in core tests and one manual interaction test remain +ignored. The release app build and `pwrdisk --help` smoke check passed. +Windows-target core Clippy passed with all targets and features. +Windows binaries were not executed locally. The suite includes real APFS +clone, modified-clone, hardlink, followed-link and resource-fork fixtures, +selection-cache invalidation, remote boundaries and operation budgets. + +An additional real APFS fixture contains one 8 MiB file and two `cp -c` +copies. The same port binary scanned each selection root with clone metadata +disabled and enabled: + +| Scan root | Listed, both modes | Estimate, disabled | Estimate, enabled | +| --- | ---: | ---: | ---: | +| Two copies; original outside root | 16 MiB | 16 MiB | 0 B | +| Original and both copies | 24 MiB | 24 MiB | 8 MiB | + +Both enabled estimates had equal lower/upper bounds and no unknown private +sizes. This is accounting evidence, not a timing benchmark or a comparison +against a separately built main binary. No home scan was run. No deletion +was performed in this fixture; the normal test suite uses its own temporary +trees to exercise removal guards and removal. + +## Historical Disktree evidence + +The following evidence was recorded on the source Disktree branch before +the PwrDisk port. Validated on macOS 26.6.1, Apple silicon, Rust 1.97, +2026-10-14. The baseline is +[huntharo/disktree#3](https://github.com/huntharo/disktree/pull/3) +at `e9b4996`; the tests below exercise the source branch's accepted-set +accounting. No new home-directory or whole-volume benchmark +was run. Earlier scan timings in the PR describe older implementations. + +## Accounting regressions + +The isolated baseline source snapshot failed both tests in +[regression-red.log](regression-red.log): + +| Selection | Baseline estimate | Required result | +| --- | ---: | ---: | +| Two complete synthetic clones, 80 shared bytes | 0 B | 80 B once | +| Charged name of a 4 KiB file with a retained hardlink | 4 KiB | 0 B | + +The checked-in sharing tests now cover complete groups across directories, +separate marks, hardlinks both within and across those marks, unknown real +volume identity, missing private metadata, changed metadata, followed files +and directories, grouping limits, and modified clones. Real APFS tests use +`cp -c`, hardlinks, followed symlinks and a resource fork. The window test +marks separate clone paths, changes tile metric, draws review/confirmation, +checks warm plan reuse, changes the selection and replaces the scan tree. + +`ATTR_CMNEXT_REALDEVID` scopes grouping and cache reuse. Ordinary `st_dev` +can alias APFS System and Data volumes on this host. Missing real identity +never permits grouping or cross-file metadata reuse. + +An 8 MiB original and two full clones retain 24 MiB of listed allocation. +Marking only the two copies estimates 0 B. Marking all three estimates +8 MiB, once, before snapshot/open-file effects. A retained hardlink prevents +crediting its inode, even if that inode owns the tree's nonzero weight. +Followed symlinks cannot authorize freeing their targets' file data. + +The private-size attribute measures the data fork. In the real resource-fork +fixture it remains zero while all-fork allocation grows by 4 KiB. The +complete clone group's range is therefore 8 MiB to 8 MiB + 4 KiB; the lone +copy's range is 0 to 4 KiB. That unmeasured fork allocation never inflates the +meter's lower estimate. Bounds describe scan observations, not guaranteed +changes to volume free space: snapshots, open files and filesystem changes +still matter. The final outcome uses measured free space. + +## Work and memory bounds + +The main-only red/green proof is separate in +[PR #9](https://github.com/huntharo/disktree/pull/9) and +[mark-resolution](../mark-resolution/README.md). This branch incorporates +that fix and reuses one lazy sibling resolver per accounting cache miss. +One mark is one queued path, independent of its descendant count. The +1,024-mark case is a stress workload, with no usage telemetry establishing +that it is common. The earlier 6.60 s measured four forced Explore draws +and eight prepares, not a scan or one click. +[Individual interaction evidence](../mark-resolution/interactions.md) +separates Space, hover and Review, includes smaller queues, and records +render/plan counts with zero scan refreshes. Its timings compare the +isolated main-only snapshots, not this APFS feature branch. +The [expanded queue fixes](../mark-resolution/expanded/README.md) are also +integrated: an ordered mark index replaces repeated ancestor/descendant scans, +parent absorption compacts once, and Review builds status indexes from each +fresh plan. Disjoint construction is O(M D log M), absorption is +O(M + K log M) plus ancestor lookup, and row-status work is expected +O(B + C + L), with L <= 1,200. Exact membership now costs O(log M). +The saved main-only audit remains historical; its depth, mount and unusual +classification cases remain deferred. + +Removal authorization remains fresh on every plan and in the worker. + +Selected subtrees merge bounded maps small to large: expected +`O(K log K)` total map work for K visited entries, without mark-pair or +clone-group-pair comparisons. Unchanged accepted sets reuse estimates by +weak tree identity, root and accepted paths. Single marked subtrees use +precomputed scan summaries; ordinary aggregated subtrees need no second +walk. Tree replacement and changed accepted paths invalidate reuse. Tile +metric never changes removal byte units. Fresh guards and target sorting +still cost work per plan; the entire UI is not claimed to be constant time. + +[budget-green.log](budget-green.log) records operation counts with marks, +clone groups and hardlink names growing together: + +| Groups | Marked directories | Leaf entries | Accounting operations | +| ---: | ---: | ---: | ---: | +| 128 | 256 | 512 | 1,790 | +| 1,024 | 2,048 | 4,096 | 14,334 | + +Eight times the workload costs 8.01 times the operations. The test enforces +both a 16x ratio ceiling and an absolute ceiling of 40 operations per group. +This measures accounting operations, not wall-clock speed or kernel work. + +Metadata queries run in directory workers. A per-scan cache has 64 mutex +shards, with no lock held during filesystem queries and no clone-result +channel or dedicated consumer. Reuse requires a known real device, a clone +ID, a full-sharing bulk flag, a confirmed zero-private sample, and matching +all-fork/data-fork allocation. An observed reference count limits reuse; +hardlink aliases do not spend another clone-reference slot. Modified or +unknown observations are measured individually. Races may duplicate first +queries. Cache tests grow both groups and members: 128 groups x 128 members +need 128 measurement callbacks, and 1,024 x 1,024 need 1,024, instead of one +per member. These are deterministic callback counts, not measured speedups. + +The cache caps groups and exceptional hardlink identities independently at +at most one million entries, distributed across shards. Scan summaries cap +clone-group and hardlink maps separately at one million entries. Crossing a +limit keeps private lower estimates, drops unproved group credit, and marks +accounting partial. Leaf metadata uses one sparse box; it no longer copies +a boxed clone result or allocates a second sharing box per clone. The Node +size budget remains 104 bytes, versus upstream's 88-byte layout. + +## Reproduce + +```sh +cargo xtask lint +cargo xtask test +cargo test -p disktree-core selected_set_work -- --nocapture +cargo test -p disktree-core clone_cache -- --nocapture +cargo test -p disktree-core macos::clone_tests -- --nocapture +cargo run --release -p disktree-core --example scan_accounting -- PATH +``` + +Local validation: lint passed; 89 window/app, 174 core and 3 xtask tests passed; +two existing core tests and the opt-in interaction timing test remained +ignored in the normal suite. The interaction timing test was also run +explicitly and passed on the combined branch. The latest optional replay +passed on retry after GPUI reported filesystem-watcher thread activity as +nondeterministic in the first attempt; its local timings are not used for +the isolated main-only comparisons. No private file contents were +inspected and no user files were removed by this investigation. diff --git a/docs/performance/apfs-accounting/budget-green.log b/docs/performance/apfs-accounting/budget-green.log new file mode 100644 index 00000000..e317869f --- /dev/null +++ b/docs/performance/apfs-accounting/budget-green.log @@ -0,0 +1,9 @@ + Compiling disktree-core v0.11.0 (/Users/huntharo/.codex/worktrees/mujumhxf/disktree/crates/disktree-core) + Finished `test` profile [optimized + debuginfo] target(s) in 1.53s + Running unittests src/lib.rs (target/debug/deps/disktree_core-8aad222ba4e32dfe) + +running 1 test +selected-set accounting operations 128->1024 groups: [1790, 14334] +test sharing::reclaim::tests::selected_set_work_scales_with_members_even_when_groups_and_marks_grow ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 175 filtered out; finished in 0.19s diff --git a/docs/performance/apfs-accounting/regression-red.log b/docs/performance/apfs-accounting/regression-red.log new file mode 100644 index 00000000..6abf3dc5 --- /dev/null +++ b/docs/performance/apfs-accounting/regression-red.log @@ -0,0 +1,57 @@ + Compiling libc v0.2.189 + Compiling crossbeam-utils v0.8.23 + Compiling crossbeam-epoch v0.9.21 + Compiling crossbeam-deque v0.8.8 + Compiling autocfg v1.5.1 + Compiling objc2 v0.6.4 + Compiling bitflags v2.13.2 + Compiling getrandom v0.4.3 + Compiling rustix v1.1.4 + Compiling core-foundation-sys v0.8.7 + Compiling objc2-encode v4.1.0 + Compiling rayon-core v1.13.0 + Compiling cfg-if v1.0.4 + Compiling percent-encoding v2.3.2 + Compiling memchr v2.8.3 + Compiling once_cell v1.21.4 + Compiling either v1.18.0 + Compiling fastrand v2.5.0 + Compiling log v0.4.34 + Compiling iana-time-zone v0.1.65 + Compiling rustc-hash v2.1.3 + Compiling num-traits v0.2.19 + Compiling objc2-foundation v0.3.2 + Compiling trash v5.2.9 + Compiling errno v0.3.14 + Compiling sysinfo v0.31.4 + Compiling rayon v1.12.0 + Compiling chrono v0.4.45 + Compiling tempfile v3.27.0 + Compiling disktree-core v0.11.0 (/private/var/folders/07/183kkj1d7l59l67s4tq0dmyr0000gn/T/disktree-accounting-red-e2t2vxnq/crates/disktree-core) + Finished `test` profile [optimized + debuginfo] target(s) in 7.74s + Running unittests src/lib.rs (target/debug/deps/disktree_core-8aad222ba4e32dfe) + +running 2 tests + +thread 'sharing::tests::regression_complete_clone_group' (403629209) panicked at crates/disktree-core/src/sharing.rs:218:9: +assertion `left == right` failed + left: 0 + right: 80 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace +test sharing::tests::regression_complete_clone_group ... FAILED + +thread 'sharing::tests::regression_retained_hardlink' (403629210) panicked at crates/disktree-core/src/sharing.rs:227:9: +assertion `left == right` failed + left: 4096 + right: 0 +test sharing::tests::regression_retained_hardlink ... FAILED + +failures: + +failures: + sharing::tests::regression_complete_clone_group + sharing::tests::regression_retained_hardlink + +test result: FAILED. 0 passed; 2 failed; 0 ignored; 0 measured; 158 filtered out; finished in 0.00s + +error: test failed, to rerun pass `-p disktree-core --lib` diff --git a/docs/performance/apfs-clone-cost/README.md b/docs/performance/apfs-clone-cost/README.md new file mode 100644 index 00000000..d9204080 --- /dev/null +++ b/docs/performance/apfs-clone-cost/README.md @@ -0,0 +1,150 @@ +# What APFS clone accounting costs a scan + +Measured 2026-11-04 on an Apple M5 Max (18 cores, 64 GiB, APFS, macOS +27), against `fce13fb` (v0.17.0). The machine was never quiet: load +averaged 12 to 17 through every run, so runs alternate between builds, +each in a fresh process. + +## Where the time went + +On a directory of agent worktrees (8.95 million files, 1.33 million +directories, 7.8 million of the files APFS clones) clone accounting made +a scan 17 s slower: 44 s against 27 s without it. Nearly all of it was +system time (455 s against 277 s), and none of it was the per-file +private-size reads: the per-scan cache already held those to 206 thousand +for 7.8 million clones, and skipping them altogether saved under 2 s. + +The cost was in the directory listing. `getattrlistbulk` was asked for +three clone attributes; asking for each alone over the same tree (wall +time of the whole `tree_memory` run): + +| asked for | run | +| --- | --- | +| none | 26.8 s | +| `ATTR_CMNEXT_REALDEVID` | 27.0 s | +| `ATTR_CMNEXT_CLONEID` | 28.0 s | +| `ATTR_CMNEXT_EXT_FLAGS` | 42.8 s | +| all three | 45.0 s | + +`ATTR_CMNEXT_CLONE_REFCNT` costs what the flags do. Both cost only for +files that were ever cloned (about 1.5 us of wall time each), and the +cost grows with the threads listing at once: 3 us of system time a clone +on 4 threads, 7.6 us on 8, 20 us on 16. A lookup the kernel serializes, +which listing with fewer threads does not avoid. + +## Why the flags can be read once a group + +Apple documents the grouping. getattrlist(2) says `ATTR_CMNEXT_CLONEID` +"uniquely identifies the data stream associated with the file system +object. Useful for finding which files are pure clones of each other (as +they will have the same clone-id)", and `EF_SHARES_ALL_BLOCKS` means the +file "is a full clone". The Apple File System Reference (2020-06-22) +gives the stream's side: an inode's `private_id` is "the unique +identifier used by this file's data stream", extents belong to that +identifier, and the reference count lives in the stream's own record +(`j_dstream_id_val_t.refcnt`). "May share" is per inode +(`INODE_WAS_CLONED`, `INODE_WAS_EVER_CLONED`), but a file whose stream +another file uses was either cloned or made by cloning. + +No document says the flags agree across a group in so many words, so a +standalone probe checked it. It listed every file with the group, the +flags and the reference count: + +| tree | files | groups | groups whose files disagree | +| --- | ---: | ---: | ---: | +| agent worktrees | 8,946,147 | 1,055,645 | 0 | +| a home Library | 2,180,829 | 1,625,470 | 0 | +| a folder of checkouts | 371,930 | 300,332 | 0 | + +"Shares all blocks" was set on exactly the files whose stream is shared +(reference count of two or more), and every such file also had "may +share". A modified clone gets a stream, and a group, of its own. + +## What changed + +* **Listing.** A directory whose parent's files were clones two to one or + more is listed with the group only. A file then takes its flags from + its group when the scan has sampled one of its files (the cache keeps + a sample of every group that shares all its blocks, and only of + those), or reads its own in the read that measures its private size, + which most clones made anyway. A file never cloned costs one such read + where the flags cost it nothing, about twice what the flags cost a + clone, hence two to one. Other directories list the flags as before. +* **Records.** Files of a group whose record says the same share it: the + tree kept 8.1 million 16-byte records for 129 thousand groups. +* **Sharing pass.** Near the top of the tree each worker folded runs of + subdirectories into maps of its own, and with the same clones in every + worktree each held nearly every group: 18 copies of 129 thousand. + Subdirectories are now merged into their parent as each finishes. + +## Results + +Scan time and the scan's peak physical footprint (`tree_memory`), three +interleaved rounds: + +| tree | build | scan | peak | tree | +| --- | --- | --- | --- | --- | +| worktrees, 8.95 M files | before | 43.9 / 44.0 / 43.9 s | 1594 / 1587 / 1536 MiB | 1049 MiB | +| | after | 31.5 / 31.2 / 31.4 s | 1279 / 1280 / 1310 MiB | 932 MiB | +| | clone accounting off | 26.6 / 26.2 / 26.4 s | 969 / 971 / 967 MiB | 854 MiB | +| home Library, 2.18 M files | before | 13.0 / 13.1 / 13.1 s | 508 / 508 / 513 MiB | 270 MiB | +| | after | 11.6 / 12.4 / 12.2 s | 510 / 507 / 502 MiB | 262 MiB | +| checkouts, 372 k files | before | 0.97 / 0.97 s | 116 / 116 MiB | 41 MiB | +| | after | 0.95 / 0.95 s | 117 / 114 MiB | 40 MiB | + +On the worktrees clone accounting now adds 5 s instead of 17.5 s, and +320 MiB instead of 590 MiB. + +## Same figures + +`tree_digest` now hashes every sharing figure (private and duplicate +bytes, unknown files, both estimate bounds, truncation) and each file's +allocation record. On a contrived tree of 880 thousand files (a source +of 20 thousand, 40 `cp -c` copies of it, modified clones, hardlinks and +files never cloned) it gives the same digest before and after, with +hardlink de-duplication on and off. The real trees change while they +are scanned, so they are not compared this way. + +Each change also has a test against a reference: + +* **Listing without flags, against listing with them** (a model): 2,000 + random sets of clone groups, each file resolved both ways with one + cache. Every file reads the same, and files that may share are read no + more often (`macos::resolve_tests`). +* **The same, on real APFS** (a scenario): worktrees cloned with `cp -c`, + with a modified clone, a file of a worktree's own, a hardlink and a + resource fork, scanned as listings choose and with flags in every + listing. Every node's figures agree, and some listing left the flags + out (`worktrees_scan_the_same_with_flags_in_every_listing`). +* **The sharing pass and shared records** (oracles): 300 random trees + deeper than the parallel levels, with clones across directories, + hardlinks and followed links. Every node's figures and every estimate + of one or two nodes agree on 2, 4 and 8 workers with one worker, and + with every record kept whole. Every directory also reads as one flat + directory of all its files would, an answer that never goes through + merging subdirectories (`sharing::tests::random_trees_*`). + +Each was checked by breaking what it guards: treating a sampled group +as only maybe shared, re-reading a file already read, keying shared +records without the reference count, keeping a group's last size +instead of its smallest, losing a subdirectory's figures, and a scan +whose listings all keep the flags each fail one. + +Two differences are possible, neither on an unchanging tree: + +* A file that cannot be read again by path (removed since it was listed) + in a directory listed without flags counts as a clone of unknown + private size; with flags, only a file flagged "may share" would. That + side never overstates a saving. +* Past one million clone groups, which groups the sharing pass keeps + depended on how its work was split, and now on which subdirectory + finishes first. The figures are marked partial either way. + +## Reproduce + +```sh +cargo run --release -p disktree-core --example tree_memory -- PATH +cargo run --release -p disktree-core --example tree_memory -- --no-clones PATH +NODEDUP=1 cargo run --release -p disktree-core --example tree_digest -- PATH +cargo test -p disktree-core a_listing_without_flags +``` diff --git a/docs/performance/mark-resolution/README.md b/docs/performance/mark-resolution/README.md new file mode 100644 index 00000000..e8d81b96 --- /dev/null +++ b/docs/performance/mark-resolution/README.md @@ -0,0 +1,227 @@ +# Large removal-queue performance + +The final combined scope and current validation are documented in +[expanded evidence](expanded/README.md): the original path-resolution and +removal-plan fixes plus efficient queue construction, one-pass parent +absorption and indexed Review status. The expanded regular budgets fail +before those additions and pass afterward, including 8,192-entry Review +queues. Current validation: 241 enabled tests and the required lint gate pass. + +A mark is one queued file or folder, regardless of how many files a marked +folder contains. The original 6.60-second stress result was four forced draws +and eight prepares of Explore; it was not one scan or one click. The expanded +report separates whole-queue construction, one parent action, four Review +draws and individual UI inputs, and includes fresh combined-head timings. + +The sections below preserve the original three fixes' measurements and +reproduction history. They are historical stage results; the expanded report +is the source for the final combined implementation and validation. + +Measured on 2026-10-14, Darwin arm64, Rust 1.97.1, repository development/test +profile (application opt-level 1, dependency opt-level 2). All trees and paths +are synthetic or inside private temporary directories. No home/volume scan, +real Trash operation, APFS accounting change or parent-branch edit was used. + +## What the timing means + +A mark is one independently queued file or directory, not every file inside a +marked directory. The 1,024-mark case is a large-queue stress test, not an +established frequent manual workload. The 6.60-second result is **four forced +draws/eight prepares of Explore with that queue already present**. It is not +one scan or one click. + +[Individual-action measurements and call-path explanation](interactions.md) +now cover 0, 1, 8, 32, 128 and 1,024 queued paths on a fixed real temporary +tree, using Space, pointer movement and Review inputs. Main already completes +those inputs in a few milliseconds with a handful of marks; the demonstrated +large improvement applies to large queues. At 1,024 queued folders, adding +one more or hovering takes about 1.1 seconds on main in that fixture. These +costs can recur on renders while interacting, rather than once per scan. + +## Broader follow-up audit + +[Additional rendering/scanning findings](additional-audit.md) document +the audit that identified queue construction, parent absorption and Review +status joins, now addressed in the expansion. Depth, mount-topology and the +case-sensitive classification edge case remain separate follow-ups. +Historical test-only probes and raw counts are included. + +## Red before green + +Base: `6c8d4ce6211bf135ff4e42890faebff1040e1846` (upstream/main and fork main). +Commit `5a3c92e` adds probes and budgets without changing the algorithms. +Both application budgets and the core removal budget fail there. Their exact +output is in [red.log](red.log) and [red-core.log](red-core.log). + +Fix: `1206fda1437c288a53c4625e9ed2f0df05a8997e`. The same budgets pass; +[green.log](green.log) also includes the additional dimension and warm-frame +checks. The baseline dimension test was temporarily applied to the red +snapshot before restoring the fixed sources; see +[red-dimensions.log](red-dimensions.log). + +The three red budgets grow marks from 128 to 1,024. Refresh and window fixtures +also grow sibling folders from 128 to 1,024, each containing one marked file: +N=256/2,048 non-root nodes, M=128/1,024 marks, D=2 path components. The removal +fixture uses disjoint paths in a deterministic permutation, so the sort does +real work and no early ancestor match hides the quadratic loop. + +| Production path | Main work at 128 / 1,024 marks | Growth | Fixed work at 128 / 1,024 marks | Growth | +| --- | ---: | ---: | ---: | ---: | +| `plan_against`, one plan | 9,187 / 537,027 | 58.5x | 1,314 / 15,298 | 11.6x | +| `Marks::refresh`, four refreshes | 34,048 / 2,107,392 | 61.9x | 2,560 / 20,480 | 8.0x | +| Real window, four forced draws | 68,312 / 4,215,000 | 61.7x | 856 / 5,336 | 6.2x | + +Every budget requires at most 16x work for 8x input, plus an absolute cap: +32 work units per mark for removal; 16 per mark per refresh for refresh; 16 per +mark per observed `prepare` for the window. No elapsed-time assertion is used. + +Removal units count sort comparisons and nesting-candidate checks. Resolution +units count mark visits and sibling-name comparisons before the fix; after the +fix they count mark visits, indexed sibling entries and component lookups. +These are logical work budgets, not CPU instruction counts. Hashing/comparing +long names and paths still costs their length. All probes are test-only. + +The GPUI harness forces notifications, draws the actual window and asserts +that `Disktree::prepare` ran at least once per draw: eight calls were observed +for four draws. This includes path lookups elsewhere in the screen, not just +the new resolver. It catches reintroducing a linear sibling search per mark +into `prepare`, even if a resolver microbenchmark still passes. + +## Wall measurements + +These are medians of three serial repetitions with `--test-threads=1` on the +same machine/profile. Fixture construction, compilation and mark insertion +are outside the timers. The window timer includes the real render path, +layout/painting work and freshly evaluated removal projections. Backing roots +are empty temporary directories, with the displayed trees constructed in +memory; these are scaling workloads, not a filesystem latency benchmark. + +| Workload at 1,024 marks | Main median | Fixed median | Speedup | +| --- | ---: | ---: | ---: | +| One removal plan | 398.13 ms | 23.24 ms | 17.1x | +| Four mark refreshes | 9.07 ms | 1.53 ms | 5.9x | +| Four window draws, eight prepares | 6,602.00 ms | 358.68 ms | 18.4x | + +Raw samples: [wall-red-repeats.log](wall-red-repeats.log) and +[wall-green-repeats.log](wall-green-repeats.log). Fixed warm draws have their +own timer and are excluded from the cold-window median above. Timings are +observations, not portable thresholds or a frame-rate guarantee. + +## Which variables actually cause the growth + +N is all scanned nodes, M is marked paths, D is path depth, R is the number +of refreshes/renders. F below is the number of first-level sibling folders. +The remaining single-child chains make depth independently controllable. + +| Folders F | Marks M | Depth D | Refreshes R | Main work | Fixed work | +| ---: | ---: | ---: | ---: | ---: | ---: | +| 128 | 8 | 2 | 1 | 1,012 | 160 | +| 1,024 | 8 | 2 | 1 | 8,180 | 1,056 | +| 1,024 | 64 | 2 | 1 | 63,648 | 1,280 | +| 128 | 8 | 16 | 1 | 1,124 | 384 | +| 128 | 8 | 2 | 8 | 8,096 | 1,280 | + +Main is linear in each of F, M, D and R when the others are held fixed. +It becomes quadratic when siblings and marks grow together. Repeating an +unchanged linear pass R times is O(items * R); calling it quadratic solely +because R can grow would misidentify the problem. Unmarked file counts do +not affect removal nesting at all, but sibling counts affect path lookup. + +On main: + +- Disjoint accepted removal marks cause M(M-1)/2 ancestor checks after sorting. +- Refresh resolves each marked path separately. At a broad directory, each + lookup scans siblings again: O(M*N) worst-case per refresh. +- `prepare` repeats analogous path-to-crumb searches for every mark on every + render, even when the tree and marks are unchanged. + +After the fix: + +- Nesting costs O(M log M) path comparisons plus M prefix checks. Guard keys + are computed once per accepted target, sorted using the guards' case and + macOS Data-volume semantics, and compared with the last retained outer + target. Display output retains the original path ordering. Including path + length L, this stage costs O(M log M * L) time and O(M * L) storage. +- One `Resolver` batch indexes each visited directory's siblings once. Let S + be those indexed entries (S <= N). Expected hash work is O(S + M*D) per + batch, with O(S) temporary index storage; untouched subtrees cost nothing. + `Marks::refresh` creates one batch per refresh, so R refreshes still cost + O(R * (S + M*D)). Path/name lengths are additional hashing/copying costs. +- `Marks::crumbs` stores O(M*D) crumbs, shared by `Arc`. An unchanged frame + reuses that set without resolving marked paths. The first frame after an + invalidation costs one batch. Visible tiles still require processing each + frame: O(T*R) at bounded display depth, where T is the laid-out tile count. + Ancestor-mark checks depend on depth; this does not claim depth-independent + work for arbitrarily deep crumb vectors. + +The real-window warm budget allows only 64 resolution units per observed +prepare, independent of M. Both mark counts measured 216 units over eight +prepares (other screen lookups); marked-path resolution was reused. It also +counts actual tile visits and verifies proportional work across repeated +frames. Merging tiny tiles means T need not grow with N. + +Fresh removal plans still evaluate guards, resolve filesystem paths and +attribute volumes for marks on every render. The sort remains O(M log M) +per plan, and mount-table/system-tree checks retain their existing costs. +These costs are visible in the remaining ~359 ms window workload. No removal +authorization is cached. The worker's fresh mount/link checks immediately +before deletion and descriptor-based deletion protections are unchanged. + +## Invalidation and semantics + +The display cache is invalidated by toggle, remove, clear and refresh, and +checks tree allocation identity, root path and metric. It stores a `Weak` +reference to the tree, so it cannot retain an old scan; the weak reference also +prevents address reuse from masquerading as the same tree. `Arc::make_mut` +dissociates that identity before in-place changes can affect a cached tree. + +Tests cover every boundary, metric reordering and replacement through the +window, missing paths, component boundaries, exact case-sensitive scan names, +first-match behavior for equal lossy names, and non-UTF-8 Unix paths. Removal +nesting uses the platform guard keys, with coverage for case variants, +duplicates, component prefixes and stable output ordering. Existing safety +and synthetic permanent-deletion tests remain green. + +Integration API: + +```rust +let mut resolver = marks::Resolver::new(root_path, tree); +let resolved = resolver.resolve(path); // Option<(Vec, &Node)> +``` + +Reuse a resolver for the whole batch. The old standalone `marks::find` was +removed when its production caller moved to this API. Display callers use +`Marks::crumbs(&Path, &Arc, Metric) -> Arc>>`; +callers have no revision-counter or manual invalidation obligation. + +## Original-stage verification and reproduction + +- `cargo xtask lint`: pass; [lint.log](lint.log). +- `cargo xtask test`: 78 app, 150 core and 3 xtask tests pass; + [tests.log](tests.log). Two pre-existing ignored core tests remain ignored. The new opt-in + interaction timing test is also ignored by the normal suite; it passes + when explicitly run on both main and fixed snapshots. +- `cargo test --workspace budget -- --nocapture`: all budgets pass. +- Three serial red repetitions fail the intended budgets (exit 101), followed + by three serial green repetitions passing them (exit 0). +- Local validation is macOS arm64. Other operating systems/architectures are + left to the repository's existing CI; no cross-platform result is claimed. + +The commit IDs in this report refer to pre-consolidation development +snapshots archived in [fork PR #9](https://github.com/huntharo/disktree/pull/9). +See the [historical fetch instructions](expanded/README.md#red-before-green). + +From a clean checkout at `5a3c92e`, reproduce the failures with: + +```sh +cargo test -p disktree-app budget -- --nocapture --test-threads=1 +cargo test -p disktree-core removal_nesting_budget -- --nocapture +``` + +At `1206fda`, run the green budgets and gates: + +```sh +cargo test --workspace budget -- --nocapture --test-threads=1 +cargo xtask lint +cargo xtask test +``` diff --git a/docs/performance/mark-resolution/additional-audit.log b/docs/performance/mark-resolution/additional-audit.log new file mode 100644 index 00000000..935b5e92 --- /dev/null +++ b/docs/performance/mark-resolution/additional-audit.log @@ -0,0 +1,50 @@ + Compiling disktree-core v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-core) + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Finished `test` profile [optimized + debuginfo] target(s) in 6.09s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 1 test +test tests::additional_render_complexity_audit ... audit bulk-mark M=128 ancestor-visits=8128 inside-visits=8256 wall=3.146875ms +audit absorb-parent M=128 retain-visits=8384 wall=294.333µs +audit blocked-review M=128 row-checks=66048 renders=8 per-render=8256 wall=119.267584ms +audit covered-review children=128 row-checks=67072 renders=8 per-render=8384 wall=135.083208ms +audit bulk-mark M=1024 ancestor-visits=523776 inside-visits=524800 wall=199.863084ms +audit absorb-parent M=1024 retain-visits=525824 wall=14.79025ms +audit blocked-review M=1024 row-checks=4198400 renders=8 per-render=524800 wall=1.101053583s +audit covered-review children=1024 row-checks=4206592 renders=8 per-render=525824 wall=1.23678775s +audit deep-breadcrumbs D=128 prefix-walks=65024 renders=8 per-render=8128 wall=12.958166ms +audit deep-breadcrumbs D=1024 prefix-walks=4190208 renders=8 per-render=523776 wall=33.87925ms +ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 79 filtered out; finished in 3.29s + + Running unittests src/lib.rs (target/debug/deps/disktree_core-9300e5ba20d6b25f) + +running 4 tests +test classify::tests::additional_classification_case_variant_audit ... audit case-variant-classify F=128 sibling-checks=16384 wall=84.834µs +audit case-variant-classify F=1024 sibling-checks=1048576 wall=2.682292ms +ok +test scan::tests::additional_scan_complexity_audit ... audit real-scan nested=false F=128 listed=128 aggregate-visits=129 wall=574.375µs +audit real-scan nested=false F=1024 listed=1024 aggregate-visits=1025 wall=2.407709ms +audit real-scan nested=true F=128 listed=256 aggregate-visits=257 wall=2.721ms +audit real-scan nested=true F=1024 listed=2048 aggregate-visits=2049 wall=18.88725ms +ok +test space::tests::additional_mount_complexity_audit ... audit mount-startup K=128 pairs=8128 wall=83.875µs +audit mount-startup K=1024 pairs=523776 wall=2.992958ms +ok +test treemap::tests::additional_layout_complexity_audit ... audit uncapped-squarify F=128 ratio-visits=682 wall=4.5µs +audit capped-layout F=128 ratio-visits=482 wall=44.834µs +audit uncapped-squarify F=1024 ratio-visits=12525 wall=24.375µs +audit capped-layout F=1024 ratio-visits=319 wall=21.125µs +ok + +test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 152 filtered out; finished in 0.47s + + Running unittests src/main.rs (target/debug/deps/xtask-0dc2df263f51d89e) + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 3 filtered out; finished in 0.00s + diff --git a/docs/performance/mark-resolution/additional-audit.md b/docs/performance/mark-resolution/additional-audit.md new file mode 100644 index 00000000..f915c96c --- /dev/null +++ b/docs/performance/mark-resolution/additional-audit.md @@ -0,0 +1,195 @@ +# Additional rendering and scanning complexity audit + +**Historical audit:** queue construction, parent absorption and Review status +joins below are now fixed by the [expanded PR #9](expanded/README.md). The +remaining depth, mount-topology and classification findings stay outside +that queue-focused scope. Counts in this file describe the audited snapshot, +not the final combined implementation. + +Audited on 2026-10-14 at `ab11b1fd884e950faa9902c0b3e0e870eb6815d9`: +main `6c8d4ce` plus PR #9's fixes. APFS feature code is outside this audit. +The cases below remain after the original three fixes. This follow-up records +findings; it adds no further runtime or API change. + +[Raw probe output](additional-audit.log) and the +[reproducible test-only probe patch](additional-audit.patch) preserve the +measurements. The probes drive production functions; Review and breadcrumb +measurements draw the real GPUI window. Fixtures are synthetic in-memory trees +or real private temporary trees. No real removal or whole-home scan ran. + +M = marks, B = blocked marks, C = covered marks, D = path depth, +F = entries in one directory, K = mount-table entries. All operation counts +below compare 128 with 1,024 of the named variable, an 8x increase. Counts are +deterministic; recorded wall times are single instrumented test-profile runs, +not latency budgets or production timing guarantees. + +## Confirmed follow-ups + +| Operation | Variable / measured scope | Work at 128 | Work at 1,024 | Growth | +| --- | --- | ---: | ---: | ---: | +| Build a queue by calling `toggle_mark` repeatedly | M, no renders | 16,384 mark visits | 1,048,576 | 64.0x | +| Mark a parent over marked children | M children, one action | 8,384 retain visits | 525,824 | 62.7x | +| Render Review with all paths blocked | M, per actual render | 8,256 comparisons | 524,800 | 63.6x | +| Render Review with children covered by one parent | M children, per actual render | 8,384 comparisons | 525,824 | 62.7x | +| Build deep breadcrumbs | D, per actual render | 8,128 prefix index steps | 523,776 | 64.4x | +| Detect repeated Linux mount views | K, one startup calculation | 8,128 mount-pair checks | 523,776 | 64.4x | +| Classify case variants of `node_modules` | F, one finishing pass | 16,384 sibling checks | 1,048,576 | 64.0x | + +### Queue construction and parent absorption: highest MCP relevance + +[`Disktree::toggle_mark`](../../../crates/disktree-app/src/state.rs) invokes +`marked_ancestor`, which scans all existing marks, then scans marks again for +paths inside the new target. Repeating the operation M times costs O(M^2) +even if every mark is a disjoint file and rendering is suppressed. The probe +calls the real state transition without drawing between insertions. At 1,024 +marks it measured about 200 ms with probes, versus 3 ms at 128. + +Marking a parent over K marked descendants then calls `Marks::remove` K +times. Each call compacts the ordered target vector with `retain`: +O(K*M), or O(M^2) when most marks are descendants. This is one user action, +not the cost of the parent's scan. The 1,024-child probe measured ~15 ms; +operation counts are the stronger scaling evidence. + +A future MCP batch API should normalize the entire queue once, preserving +mark ordering and path semantics. Merely suppressing redraws while looping +over the scalar marking API does not remove this cost. Parent absorption +should remove the whole descendant set with one compaction. Ancestor +membership can use indexed ancestor paths instead of scanning every mark. + +### Review: row-status joins still use repeated linear lookup + +[`views::review`](../../../crates/disktree-app/src/views.rs) runs +`covered.iter().any(...)` and `blocked.iter().find(...)` for every displayed +item. This is O(min(M, 1200) * (B+C)) in the general case. It behaves +quadratically below the 1,200-row cap when blocked/covered counts grow with +the queue; above the cap it has a bounded displayed-row factor. It is not an +unbounded quadratic pass over every file on disk. + +The ordinary accepted-path fixture in the original budget had B=C=0, so it +could not expose these joins. The new blocked fixture queues paths outside +the scanned root; guards refuse them, with no deletion attempt. The covered +fixture supplies an overlapping raw queue. Normal manual marking absorbs +such overlaps, so the latter represents a raw/programmatic queue or other +path-alias situations, rather than an ordinary manual selection sequence. + +Each test forces four Review draws and observes eight real renders. Logs +report both totals and comparisons per render. The ~1.10 s blocked and +~1.24 s covered wall samples at 1,024 are those **four-draw totals**, not +single clicks. A per-plan lookup map/set for row status would avoid repeated +searches while leaving removal guards freshly evaluated. + +### Breadcrumbs and deep filtering: depth-dependent costs + +[`Disktree::breadcrumbs`](../../../crates/disktree-app/src/state.rs) starts at +the scan root again for every successive prefix, producing D(D-1)/2 indexed +walk steps. It also clones crumb prefixes. The view later hides most of the +trail, after the full trail has already been materialized. Above-root path +ancestors are similarly copied before this display truncation. + +The probe sets current depth to 128 and 1,024 in memory and draws the actual +Explore window. Deep chains like this are an edge workload, not evidence +that a common shallow home directory suffers this cost. Walking the node +chain once and building only displayed breadcrumb targets would bound it. + +Separately, `Matches::keep` and marked-ancestor coloring hash successive crumb +prefixes. Hashing each prefix depends on its length, so these can also cost +O(D^2) per tile when the absolute path is deep and the filter/marks require +checking all ancestors. Those hash costs were source-audited, not separately +measured by this breadcrumb counter. They depend on path depth, not the +number of siblings in one folder. + +### Linux mount setup: topology-dependent, not file-count-dependent + +[`space::repeated_mounts_excluding`](../../../crates/disktree-core/src/space.rs) +compares each visible mount with previously kept mounts. The probe uses +independent synthetic devices so no early match masks K(K-1)/2 comparisons. +This runs while preparing a scan on systems with `/proc/self/mountinfo`. +The algorithm was measured on synthetic Linux mount metadata on macOS; +there was no actual Linux mount manipulation or Linux wall-time benchmark. + +Other code in that routine can scan the full mount table or exclusion list +inside these checks, so more complex topologies deserve separate bounds. +The volume picker has a similar linear search through already seen devices. +Removal guards and volume attribution also retain O(M*K) checks per plan. +None of these is quadratic in the number of files with a fixed mount table. +The simple 1,024-mount synthetic case took ~3 ms here, so this ranks below +queue construction and Review for the proposed MCP flow. + +### Directory classification: a real but unusual within-folder case + +[`classify::reclaim_of`](../../../crates/disktree-core/src/classify.rs) requests +a sibling search only for particular names: `target`, `node_modules`, and +`logs`. Ordinary folders do not trigger a sibling scan for every arbitrary +entry. That apparent generic F^2 pattern is therefore usually a false alarm. + +However, the directory-name match is ASCII case-insensitive. A case-sensitive +filesystem can contain many distinct spellings of `node_modules`, each of +which searches all siblings for an absent `package.json`. The probe creates +128/1,024 such names in memory and calls full `classify`, observing F^2 +comparisons. There are only 2^11 case variants of this particular name, so +this is a quadratic window up to a finite namespace bound, not an unbounded +quadratic algorithm for arbitrary folder sizes. These variants cannot all +coexist on a normal case-insensitive APFS volume; this is chiefly a Linux or +case-sensitive-volume edge case. It is scan finishing, not per-frame work. + +Precomputing the few manifest/sibling flags once per parent would remove the +case without adding fields to every scanned node. + +## Normal scanning and bounded layout did not show this problem + +The regular walk appends each directory entry once. Directory completion +moves completed children into their parent, and aggregation visits each node +once before sorting each folder's children. Hardlink de-duplication and +followed-directory detection use a bitmap/hash sets, not a search through all +previous files. The admission queue removes an admitted tail, avoiding a +front-removal shift per job. + +Actual fixed-one-thread scans of private temporary trees produced: + +| Fixture | Listed entries at 128 / 1,024 items | Aggregate node visits | +| --- | ---: | ---: | +| One directory of files | 128 / 1,024 | 129 / 1,025 | +| One directory of folders, one file in each | 256 / 2,048 | 257 / 2,049 | + +Those counts are linear. Sorting is O(sum(F_i log F_i)) over directories, +with additional filename/path-length and filesystem costs. This does not +prove every input or OS path is linear; it rules out a general sibling-pair +loop in the normal walk/aggregation paths exercised here. + +`treemap::squarify` recomputes worst aspect ratios across a growing row, which +is quadratic within a row. With unbounded equal-weight input, ratio-element +visits rose from 682 to 12,525 (18.4x at 8x input): superlinear, not a measured +64x file-count quadratic. The real layout caller keeps only 96 children plus +one merged tail per directory before this step. Its measured ratio work was +482 versus 319 at 128/1,024 source entries. Ranking all source entries still +costs O(F log F) on a layout cache miss; normal unchanged frames reuse layout. +The internal row rescan therefore is not currently an unbounded wide-folder +rendering blocker. + +Windows MFT enumeration builds parent indexes and sorts names rather than +repeatedly searching every sibling. One additional **unmeasured** metadata +candidate is `mft::table_layout`'s vector `numbers.contains` while collecting +extension records from the MFT's own attribute list. That can be O(E^2) in +extension-record count E on a fragmented MFT; E is not the total file count. +Windows runtime behavior was not tested in this macOS audit. + +## Reproduce without changing runtime code + +The commit IDs below are historical pre-consolidation snapshots; see the +[fetch instructions](expanded/README.md#red-before-green). + +From clean source at `ab11b1f` (or later evidence-only descendants): + +```sh +git apply docs/performance/mark-resolution/additional-audit.patch +cargo test --workspace additional_ -- --ignored --nocapture --test-threads=1 +git apply -R docs/performance/mark-resolution/additional-audit.patch +``` + +The patch adds counters gated by `cfg(test)` and ignored diagnostic tests. +All five diagnostic tests passed their correctness/call-path assertions. It +records counts rather than adding passing assertions that would enshrine +quadratic behavior. The patch was then removed: source remains byte-identical +to `ab11b1f`. The original lint/full-test result therefore still applies to +the unchanged runtime implementation. These findings need separate fixes +and corresponding failing budgets before their scaling can be called bounded. diff --git a/docs/performance/mark-resolution/additional-audit.patch b/docs/performance/mark-resolution/additional-audit.patch new file mode 100644 index 00000000..99a7e5f8 --- /dev/null +++ b/docs/performance/mark-resolution/additional-audit.patch @@ -0,0 +1,561 @@ +diff --git a/crates/disktree-app/src/marks.rs b/crates/disktree-app/src/marks.rs +index 3a86060..8d9578a 100644 +--- a/crates/disktree-app/src/marks.rs ++++ b/crates/disktree-app/src/marks.rs +@@ -18,6 +18,11 @@ pub mod work { + thread_local! { + pub static RESOLUTION: Cell = const { Cell::new(0) }; + pub static FRAMES: Cell = const { Cell::new(0) }; ++ pub static AUDIT_ROWS: Cell = const { Cell::new(0) }; ++ pub static AUDIT_RETAIN: Cell = const { Cell::new(0) }; ++ pub static AUDIT_ANCESTORS: Cell = const { Cell::new(0) }; ++ pub static AUDIT_INSIDE: Cell = const { Cell::new(0) }; ++ pub static AUDIT_CRUMBS: Cell = const { Cell::new(0) }; + pub static RENDERS: Cell = const { Cell::new(0) }; + pub static PLANS: Cell = const { Cell::new(0) }; + pub static REFRESHES: Cell = const { Cell::new(0) }; +@@ -31,6 +36,11 @@ pub mod work { + pub fn reset() { + RESOLUTION.set(0); + FRAMES.set(0); ++ AUDIT_ROWS.set(0); ++ AUDIT_RETAIN.set(0); ++ AUDIT_ANCESTORS.set(0); ++ AUDIT_INSIDE.set(0); ++ AUDIT_CRUMBS.set(0); + RENDERS.set(0); + PLANS.set(0); + REFRESHES.set(0); +@@ -91,7 +101,11 @@ impl Marks { + pub fn remove(&mut self, path: &Path) { + if self.index.remove(path) { + self.resolved = None; +- self.items.retain(|item| item.path != path); ++ self.items.retain(|item| { ++ #[cfg(test)] ++ work::AUDIT_RETAIN.set(work::AUDIT_RETAIN.get() + 1); ++ item.path != path ++ }); + } + } + +diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs +index 9713e0c..ce234ec 100644 +--- a/crates/disktree-app/src/state.rs ++++ b/crates/disktree-app/src/state.rs +@@ -1120,6 +1120,9 @@ impl Disktree { + }; + let mut crumbs: Vec = Vec::new(); + for &index in &self.crumbs { ++ #[cfg(test)] ++ crate::marks::work::AUDIT_CRUMBS ++ .set(crate::marks::work::AUDIT_CRUMBS.get() + crumbs.len()); + let Some(node) = + tree.resolve(&crumbs).and_then(|node| node.child(index)) + else { +@@ -1711,6 +1714,9 @@ impl Disktree { + .items() + .iter() + .filter(|item| { ++ #[cfg(test)] ++ crate::marks::work::AUDIT_INSIDE ++ .set(crate::marks::work::AUDIT_INSIDE.get() + 1); + item.path != path && item.path.starts_with(&path) + }) + .map(|item| item.path.clone()) +@@ -1738,7 +1744,12 @@ impl Disktree { + self.marks + .items() + .iter() +- .filter(|item| item.path != path && path.starts_with(&item.path)) ++ .filter(|item| { ++ #[cfg(test)] ++ crate::marks::work::AUDIT_ANCESTORS ++ .set(crate::marks::work::AUDIT_ANCESTORS.get() + 1); ++ item.path != path && path.starts_with(&item.path) ++ }) + .map(|item| item.path.clone()) + .min_by_key(|ancestor| ancestor.as_os_str().len()) + } +diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rs +index 04bcc6f..3d08a34 100644 +--- a/crates/disktree-app/src/tests.rs ++++ b/crates/disktree-app/src/tests.rs +@@ -2118,3 +2118,141 @@ fn marked_interaction_timings(cx: &mut TestAppContext) { + window.update(|window, _| window.remove_window()); + } + } ++ ++#[gpui_kit::test] ++#[ignore = "manual additional complexity audit on synthetic state/windows"] ++fn additional_render_complexity_audit(cx: &mut TestAppContext) { ++ use crate::marks::work; ++ use disktree_core::removal::Target; ++ use disktree_core::tree::{Node, NodeKind}; ++ ++ cx.update(gpui_omarchy::init); ++ let temp = tempfile::tempdir().expect("tempdir"); ++ let scan_root = temp.path().join("scan"); ++ std::fs::create_dir(&scan_root).expect("mkdir"); ++ for count in [128, 1024] { ++ let root_path = scan_root.clone(); ++ let mut tree = Node::directory("root"); ++ let mut parent = Node::directory("container"); ++ for index in 0..count { ++ parent.children.push(Node::entry( ++ format!("file-{index}"), ++ NodeKind::File, ++ 1, ++ )); ++ } ++ tree.children.push(parent); ++ let (view, window) = cx.add_window_view(move |_, cx| { ++ Disktree::with_tree(root_path.clone(), tree, options(), 3, cx) ++ }); ++ update(&view, window, |app, cx| { ++ work::reset(); ++ let start = std::time::Instant::now(); ++ for index in 0..count { ++ app.toggle_mark(&[0, index], cx); ++ } ++ assert_eq!(app.marks.len(), count); ++ eprintln!( ++ "audit bulk-mark M={count} ancestor-visits={} inside-visits={} wall={:?}", ++ work::AUDIT_ANCESTORS.get(), ++ work::AUDIT_INSIDE.get(), ++ start.elapsed() ++ ); ++ work::reset(); ++ let start = std::time::Instant::now(); ++ app.toggle_mark(&[0], cx); ++ assert_eq!(app.marks.len(), 1); ++ assert!(app.marks.contains(&scan_root.join("container"))); ++ eprintln!( ++ "audit absorb-parent M={count} retain-visits={} wall={:?}", ++ work::AUDIT_RETAIN.get(), ++ start.elapsed() ++ ); ++ app.marks.clear(); ++ for index in 0..count { ++ app.marks.toggle(Target { ++ path: temp.path().join(format!("outside-{index}")), ++ bytes: 1, ++ is_dir: false, ++ hidden: false, ++ }); ++ } ++ app.screen = Screen::Review; ++ }); ++ work::reset(); ++ let start = std::time::Instant::now(); ++ for _ in 0..4 { ++ update(&view, window, |_, cx| cx.notify()); ++ draw(window); ++ } ++ let frames = work::RENDERS.get(); ++ assert!(frames >= 4); ++ eprintln!( ++ "audit blocked-review M={count} row-checks={} renders={frames} per-render={} wall={:?}", ++ work::AUDIT_ROWS.get(), ++ work::AUDIT_ROWS.get() / frames, ++ start.elapsed() ++ ); ++ update(&view, window, |app, cx| { ++ // Manual marking absorbs these; raw/programmatic queues can ++ // still present overlapping targets to the review renderer. ++ app.marks.clear(); ++ let parent = app.target_at(&[0]).expect("parent"); ++ app.marks.toggle(parent); ++ for index in 0..count { ++ let child = app.target_at(&[0, index]).expect("child"); ++ app.marks.toggle(child); ++ } ++ cx.notify(); ++ }); ++ work::reset(); ++ let start = std::time::Instant::now(); ++ for _ in 0..4 { ++ update(&view, window, |_, cx| cx.notify()); ++ draw(window); ++ } ++ let frames = work::RENDERS.get(); ++ assert!(frames >= 4); ++ eprintln!( ++ "audit covered-review children={count} row-checks={} renders={frames} per-render={} wall={:?}", ++ work::AUDIT_ROWS.get(), ++ work::AUDIT_ROWS.get() / frames, ++ start.elapsed() ++ ); ++ window.update(|window, _| window.remove_window()); ++ } ++ for depth in [128, 1024] { ++ let root_path = scan_root.clone(); ++ let mut tree = Node::directory("x"); ++ tree.children ++ .push(Node::entry("payload", NodeKind::File, 1)); ++ for _ in 0..depth { ++ let mut parent = Node::directory("x"); ++ parent.children.push(tree); ++ tree = parent; ++ } ++ let (view, window) = cx.add_window_view(move |_, cx| { ++ Disktree::with_tree(root_path.clone(), tree, options(), 3, cx) ++ }); ++ update(&view, window, |app, cx| { ++ app.crumbs = vec![0; depth]; ++ app.selected = None; ++ cx.notify(); ++ }); ++ work::reset(); ++ let start = std::time::Instant::now(); ++ for _ in 0..4 { ++ update(&view, window, |_, cx| cx.notify()); ++ draw(window); ++ } ++ let frames = work::RENDERS.get(); ++ assert!(frames >= 4); ++ eprintln!( ++ "audit deep-breadcrumbs D={depth} prefix-walks={} renders={frames} per-render={} wall={:?}", ++ work::AUDIT_CRUMBS.get(), ++ work::AUDIT_CRUMBS.get() / frames, ++ start.elapsed() ++ ); ++ window.update(|window, _| window.remove_window()); ++ } ++} +diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs +index c23e91b..ff3acad 100644 +--- a/crates/disktree-app/src/views.rs ++++ b/crates/disktree-app/src/views.rs +@@ -2544,11 +2544,20 @@ fn review( + } + + for (index, item) in items.iter().take(LIST_LIMIT).enumerate() { +- let is_covered = +- covered.iter().any(|covered| covered.path == item.path); ++ let is_covered = covered.iter().any(|covered| { ++ #[cfg(test)] ++ crate::marks::work::AUDIT_ROWS ++ .set(crate::marks::work::AUDIT_ROWS.get() + 1); ++ covered.path == item.path ++ }); + let blocked_reason = blocked + .iter() +- .find(|blocked| blocked.path == item.path) ++ .find(|blocked| { ++ #[cfg(test)] ++ crate::marks::work::AUDIT_ROWS ++ .set(crate::marks::work::AUDIT_ROWS.get() + 1); ++ blocked.path == item.path ++ }) + .map(|blocked| blocked.reason.clone()); + list = list.child(mark_row( + index, +diff --git a/crates/disktree-core/src/classify.rs b/crates/disktree-core/src/classify.rs +index bfe24a7..82ffd9e 100644 +--- a/crates/disktree-core/src/classify.rs ++++ b/crates/disktree-core/src/classify.rs +@@ -17,6 +17,10 @@ use rayon::prelude::*; + + use crate::tree::Node; + ++#[cfg(test)] ++static AUDIT_SIBLINGS: std::sync::atomic::AtomicUsize = ++ std::sync::atomic::AtomicUsize::new(0); ++ + /// A kind of data, for colour. + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] + pub enum Category { +@@ -231,8 +235,14 @@ pub fn classify(root: &mut Node) { + root.reclaim = None; + for index in 0..root.children.len() { + let siblings = &root.children; +- let has_sibling = +- |wanted: &str| siblings.iter().any(|name| &*name.name == wanted); ++ let has_sibling = |wanted: &str| { ++ siblings.iter().any(|name| { ++ #[cfg(test)] ++ AUDIT_SIBLINGS ++ .fetch_add(1, std::sync::atomic::Ordering::Relaxed); ++ &*name.name == wanted ++ }) ++ }; + let child = &siblings[index]; + // A top-level directory with an unknown name takes the kind of its + // largest recognisable child: `~/world` is mostly `.git`. +@@ -303,8 +313,13 @@ fn kind_of( + if !child.is_dir() { + return (category, reclaim); + } +- let has_sibling = +- |wanted: &str| siblings.iter().any(|name| &*name.name == wanted); ++ let has_sibling = |wanted: &str| { ++ siblings.iter().any(|name| { ++ #[cfg(test)] ++ AUDIT_SIBLINGS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); ++ &*name.name == wanted ++ }) ++ }; + let child_category = category_of_name(&child.name) + .or_else(|| is_git_store(child).then_some(Category::Git)) + .unwrap_or(category); +@@ -616,4 +631,39 @@ mod tests { + assert!(!category.label().is_empty()); + } + } ++ #[test] ++ #[ignore = "manual case-sensitive sibling classification edge-case audit"] ++ fn additional_classification_case_variant_audit() { ++ for count in [128, 1024] { ++ let mut root = Node::directory("root"); ++ for index in 0..count { ++ let mut mask = 1; ++ let name: String = "node_modules" ++ .chars() ++ .map(|letter| { ++ if letter == '_' { ++ return letter; ++ } ++ let upper = index & mask != 0; ++ mask <<= 1; ++ if upper { ++ letter.to_ascii_uppercase() ++ } else { ++ letter ++ } ++ }) ++ .collect(); ++ root.children.push(Node::directory(name)); ++ } ++ AUDIT_SIBLINGS.store(0, std::sync::atomic::Ordering::Relaxed); ++ let start = std::time::Instant::now(); ++ classify(&mut root); ++ assert!(root.children.iter().all(|child| child.reclaim.is_none())); ++ eprintln!( ++ "audit case-variant-classify F={count} sibling-checks={} wall={:?}", ++ AUDIT_SIBLINGS.load(std::sync::atomic::Ordering::Relaxed), ++ start.elapsed() ++ ); ++ } ++ } + } +diff --git a/crates/disktree-core/src/scan.rs b/crates/disktree-core/src/scan.rs +index 693253a..ab27ea7 100644 +--- a/crates/disktree-core/src/scan.rs ++++ b/crates/disktree-core/src/scan.rs +@@ -283,6 +283,9 @@ pub fn scan(root: &Path, options: ScanOptions) -> io::Result { + Ok(node) + } + ++#[cfg(test)] ++static AUDIT_CLASSIFIED: AtomicUsize = AtomicUsize::new(0); ++ + struct WalkContext { + /// A subtree to reuse rather than walk. + known: Option, +@@ -328,6 +331,8 @@ impl WalkContext { + /// files, and a disk has millions of them. The name is moved out of + /// the entry last, so nothing copies it. + fn classify(&self, dir: &Path, entry: &mut impl Listed) -> Classified { ++ #[cfg(test)] ++ AUDIT_CLASSIFIED.fetch_add(1, Ordering::Relaxed); + let listing = match entry.listing() { + Ok(listing) => listing, + Err(error) => { +@@ -1855,4 +1860,49 @@ mod tests { + ); + } + } ++ #[test] ++ #[ignore = "manual normal-scan complexity audit on real temporary fixtures"] ++ fn additional_scan_complexity_audit() { ++ for nested in [false, true] { ++ for count in [128, 1024] { ++ let temp = tempfile::tempdir().expect("tempdir"); ++ for index in 0..count { ++ let name = format!("entry-{index:05}"); ++ let file = if nested { ++ let folder = temp.path().join(name); ++ fs::create_dir(&folder).expect("mkdir"); ++ folder.join("payload") ++ } else { ++ temp.path().join(name) ++ }; ++ fs::write(file, [b'x'; 64]).expect("write"); ++ } ++ AUDIT_CLASSIFIED.store(0, Ordering::Relaxed); ++ crate::tree::AUDIT_AGGREGATE.store(0, Ordering::Relaxed); ++ let start = std::time::Instant::now(); ++ let result = scan( ++ temp.path(), ++ ScanOptions { ++ apparent_size: true, ++ threads: crate::scan_threads::ScanThreads { ++ max_threads: 1, ++ ..crate::scan_threads::ScanThreads::default() ++ }, ++ ..ScanOptions::default() ++ }, ++ ) ++ .expect("scan"); ++ assert_eq!(result.files, count as u64); ++ let entries = AUDIT_CLASSIFIED.load(Ordering::Relaxed); ++ let aggregated = ++ crate::tree::AUDIT_AGGREGATE.load(Ordering::Relaxed); ++ assert_eq!(entries, count * if nested { 2 } else { 1 }); ++ assert_eq!(aggregated, entries + 1); ++ eprintln!( ++ "audit real-scan nested={nested} F={count} listed={entries} aggregate-visits={aggregated} wall={:?}", ++ start.elapsed() ++ ); ++ } ++ } ++ } + } +diff --git a/crates/disktree-core/src/space.rs b/crates/disktree-core/src/space.rs +index 8a2bc4e..5e2f8af 100644 +--- a/crates/disktree-core/src/space.rs ++++ b/crates/disktree-core/src/space.rs +@@ -7,6 +7,11 @@ + use std::io; + use std::path::{Path, PathBuf}; + ++#[cfg(test)] ++thread_local! { ++ static AUDIT_MOUNT_PAIRS: std::cell::Cell = const { std::cell::Cell::new(0) }; ++} ++ + /// A volume's capacity in bytes. + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] + pub struct SpaceInfo { +@@ -515,6 +520,8 @@ fn repeated_mounts_excluding( + let mut repeated: Vec = Vec::new(); + for mount in visible { + let elsewhere = kept.iter().find_map(|wider| { ++ #[cfg(test)] ++ AUDIT_MOUNT_PAIRS.set(AUDIT_MOUNT_PAIRS.get() + 1); + if !same_filesystem(wider, mount) { + return None; + } +@@ -1327,4 +1334,28 @@ map auto_home on /System/Volumes/Data/home (autofs, automounted, nobrowse) + let space = SpaceInfo::default(); + assert!((space.used_fraction() - 0.0).abs() < f32::EPSILON); + } ++ #[test] ++ #[ignore = "manual complexity audit on synthetic mount metadata"] ++ fn additional_mount_complexity_audit() { ++ for count in [128, 1024] { ++ let mounts: Vec<_> = (0..count) ++ .map(|index| MountView { ++ device: format!("8:{index}"), ++ source: format!("/dev/audit-{index}"), ++ fstype: "ext4".into(), ++ point: PathBuf::from(format!("/audit/mount-{index:05}")), ++ fs_root: PathBuf::from("/"), ++ }) ++ .collect(); ++ AUDIT_MOUNT_PAIRS.set(0); ++ let start = std::time::Instant::now(); ++ let duplicates = repeated_mounts(&mounts, Path::new("/")); ++ assert!(duplicates.is_empty()); ++ eprintln!( ++ "audit mount-startup K={count} pairs={} wall={:?}", ++ AUDIT_MOUNT_PAIRS.get(), ++ start.elapsed() ++ ); ++ } ++ } + } +diff --git a/crates/disktree-core/src/tree.rs b/crates/disktree-core/src/tree.rs +index 6991a86..8724560 100644 +--- a/crates/disktree-core/src/tree.rs ++++ b/crates/disktree-core/src/tree.rs +@@ -10,6 +10,10 @@ use rustc_hash::FxHashSet; + + use crate::classify::{Category, Reclaim}; + ++#[cfg(test)] ++pub(crate) static AUDIT_AGGREGATE: std::sync::atomic::AtomicUsize = ++ std::sync::atomic::AtomicUsize::new(0); ++ + /// What a node represents on disk. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub enum NodeKind { +@@ -352,6 +356,8 @@ fn aggregate_at( + depth: usize, + seen: Option<&Seen>, + ) { ++ #[cfg(test)] ++ AUDIT_AGGREGATE.fetch_add(1, Ordering::Relaxed); + if !node.is_dir() { + // Every name of a file has the file's size, so one that weighs + // nothing need not be remembered to be charged once. +diff --git a/crates/disktree-core/src/treemap.rs b/crates/disktree-core/src/treemap.rs +index 598b559..ce2fc50 100644 +--- a/crates/disktree-core/src/treemap.rs ++++ b/crates/disktree-core/src/treemap.rs +@@ -13,6 +13,11 @@ + use crate::filter::{Keep, Matches}; + use crate::tree::{Metric, Node}; + ++#[cfg(test)] ++thread_local! { ++ static AUDIT_RATIO: std::cell::Cell = const { std::cell::Cell::new(0) }; ++} ++ + /// An axis-aligned rectangle in viewport pixels. + #[derive(Clone, Copy, Debug, Default, PartialEq)] + pub struct Rect { +@@ -401,6 +406,8 @@ fn worst_ratio(areas: &[f64], row_sum: f64, side: f64) -> f64 { + } + let thickness = row_sum / side; + areas.iter().fold(0.0_f64, |worst, area| { ++ #[cfg(test)] ++ AUDIT_RATIO.set(AUDIT_RATIO.get() + 1); + if *area <= 0.0 || thickness <= 0.0 { + return worst; + } +@@ -722,4 +729,43 @@ mod tests { + let ratio = area_of("src") / area_of("unit_test.txt"); + assert!((ratio - 3.0).abs() < 0.05, "ratio {ratio}"); + } ++ #[test] ++ #[ignore = "manual row-complexity audit on synthetic layout"] ++ fn additional_layout_complexity_audit() { ++ for count in [128, 1024] { ++ let values = vec![1.; count]; ++ AUDIT_RATIO.set(0); ++ let start = std::time::Instant::now(); ++ let rects = squarify(&values, Rect::new(0., 0., 1024., 1024.)); ++ assert_eq!(rects.len(), count); ++ eprintln!( ++ "audit uncapped-squarify F={count} ratio-visits={} wall={:?}", ++ AUDIT_RATIO.get(), ++ start.elapsed() ++ ); ++ let mut root = Node::directory("root"); ++ for index in 0..count { ++ root.children.push(Node::entry( ++ format!("file-{index}"), ++ crate::tree::NodeKind::File, ++ 1, ++ )); ++ } ++ AUDIT_RATIO.set(0); ++ let start = std::time::Instant::now(); ++ let tiles = layout( ++ &root, ++ &[], ++ Rect::new(0., 0., 1024., 1024.), ++ Metric::Bytes, ++ &LayoutOptions::default(), ++ ); ++ assert!(!tiles.is_empty()); ++ eprintln!( ++ "audit capped-layout F={count} ratio-visits={} wall={:?}", ++ AUDIT_RATIO.get(), ++ start.elapsed() ++ ); ++ } ++ } + } diff --git a/docs/performance/mark-resolution/expanded/README.md b/docs/performance/mark-resolution/expanded/README.md new file mode 100644 index 00000000..c4493365 --- /dev/null +++ b/docs/performance/mark-resolution/expanded/README.md @@ -0,0 +1,229 @@ +# Expanded PR #9: construction, absorption and Review status + +This is the final evidence for the three queue issues discovered after the +original PR #9 fixes. The scope is queue construction, marking a parent over +marked descendants, and Review's blocked/covered row lookups. The existing +removal nesting, mark-refresh and cached-crumb fixes remain included. + +A mark is one independently queued file or folder. Marking a folder counts +once regardless of its descendant file count. Long queues are relevant to +programmatic/MCP control; no usage evidence establishes 1,024 independent +marks as a frequent manual workload. This PR does not add an MCP endpoint. + +## Trigger and denominator + +| Operation | What is timed | When the cost is paid | +| --- | --- | --- | +| Queue construction | All 1,024 state-level additions, before any drawing | Building a queue of disjoint paths; files and folders have separate budgets | +| Parent absorption | One call marking a parent over 1,024 child marks, plus an unrelated mark | That marking action, before rendering | +| Blocked/covered Review | Four forced draws, eight observed renders | Repeated Review rendering, including opening/updating the screen | +| Space, hover, C input | One input plus harness rendering/settling | Ordinary interaction with an already populated queue | + +The earlier 6.60 s number was four forced Explore draws/eight prepares on +main, not a single click, one scan, or the time to select all 1,024 paths. +Neither queue construction nor parent absorption here includes painting. +The Review wall measurements below do include row layout/painting and fresh +plan evaluation. Comparisons per render are reported separately from total +wall time. Timed input tests assert zero `Marks::refresh` calls: no rescan is +included in those numbers. + +## Red before green + +The development history was consolidated into one upstream contribution. +Commit IDs below identify the original measured snapshots, archived in +[fork PR #9](https://github.com/huntharo/disktree/pull/9); they are not +separate commits in the final branch. To reproduce a historical stage, +fetch its full SHA from `https://github.com/huntharo/disktree.git` before +checking it out. For example: + +```sh +git fetch https://github.com/huntharo/disktree.git \ + 57d4efde372e7f08e0a2b91a906ff3b870abaddc +git switch --detach FETCH_HEAD +``` + +At `57d4efde372e7f08e0a2b91a906ff3b870abaddc`, the new probes and budgets run +against the original queue/Review algorithms, with the earlier PR #9 fixes +already present. Four regular budgets fail: queue construction, parent +absorption, blocked Review and covered Review. See [red.log](red.log). +The added folder-only variant was also replayed against that unchanged +algorithm and fails; see [red-folders.log](red-folders.log). + +The original development commits were: + +- `e88b9e1`: ordered mark index, indexed ancestor lookup and one-pass + descendant absorption. +- `b71718f`: Review row indexes borrowed from each newly computed plan. +- `1c36fae`: the separate directory-insertion regression budget; it changes + test coverage, not runtime behavior. +- `d886865`: compatibility coverage for raw paths with redundant separators, + preserving the original shortest-stored-spelling ancestor choice. This + does not affect the canonical paths in the timing fixtures. + +The same regular budgets pass after the fixes. They grow input from 128 to +1,024 and require <=16x logical work, plus absolute caps. Queue mutation +allows <=32 units per mark; row status allows <=8 units per queued item per +observed render. Both Review variants also run at 8,192 entries and verify +that exactly 1,200 rows are built per render. + +| Measured path | Before, 128 / 1,024 | Combined fix, 128 / 1,024 | +| --- | ---: | ---: | +| Queue construction, all additions | 16,384 / 1,048,576 | 1,152 / 9,216 | +| Folder queue construction, all additions | 16,384 / 1,048,576 | 1,152 / 9,216 | +| Parent absorption, one action | 8,771 / 528,899 | 266 / 2,058 | +| Blocked Review status, per render | 8,256 / 524,800 | 384 / 3,072 | +| Covered Review status, per render | 8,384 / 525,824 | 386 / 3,074 | + +The blocked fixture queues paths outside the scanned root. The covered +fixture supplies a raw overlapping parent/children queue; normal manual +marking would absorb those overlaps. Both exercise status decoration through +planning and rendering only, with no removal attempt. + +At 8,192 items, both Review cases use 10,592 status units per render, while +keeping the 1,200-row cap. See [green.log](green.log). The tests drive +`Disktree::toggle_mark` or actual GPUI window draws, not an isolated index +helper. They verify surviving mark order, counts, directory/file kinds, +covered/blocked decorations, render counts and the row cap. + +The logical mutation units count mark visits before the fix; after the fix +they count ancestor/range requests, removals and compaction visits. They do +not count internal B-tree comparisons. The complexity guarantee below +includes that logarithmic factor. Review units count status construction and +row lookups after the fix, versus repeated comparison scans before it. These +are deterministic work budgets, not CPU instruction counts. + +## Three-run wall measurements + +Medians in milliseconds from three serial repetitions, macOS arm64, Rust +1.97.1, the repository test profile, `--test-threads=1`. Compilation and +fixture setup are excluded. These workloads use synthetic displayed trees +backed by empty private temporary roots; they establish scaling, not storage +throughput. Raw samples: [wall-before.log](wall-before.log) and +[wall-after.log](wall-after.log). + +| Workload at 1,024 marks | Before expansion | Combined fix | +| --- | ---: | ---: | +| Queue all 1,024 files, no drawing | 176.13 ms | 6.41 ms | +| One parent-absorption action | 15.60 ms | 0.47 ms | +| Blocked Review, four draws/eight renders | 1,003.88 ms | 883.69 ms | +| Covered Review, four draws/eight renders | 1,110.66 ms | 1,009.63 ms | + +Review's wall improvement is much smaller than its row-lookup work reduction: +the screen still lays out up to 1,200 rows and computes plans/guards. +Eliminating one quadratic join does not eliminate those linear and +O(M log M) costs. The larger 8,192-item capped cases took approximately +1.19 s blocked / 2.11 s covered for four draws in these instrumented runs. +No elapsed-time threshold or frame-rate claim is made. + +## Implementation and guarantees + +Let M be current marks, D path depth, K absorbed descendants, B blocked +entries, C covered entries and L displayed rows (L <= 1,200). Path lengths +add comparison/hashing/copying costs to the bounds below. + +`Marks` keeps its ordered `Vec` for display and replaces the private +exact-path hash set with a `BTreeSet`. Native `Path` ordering is by +components, so a strict descendant, if any, immediately follows a parent's +position in that ordered index. Prefix lookalikes such as `a-b`, `a.b` and +`ab` do not defeat that query. + +- Ancestor lookup visits path ancestors and queries the index, costing + O(D log M) index work rather than scanning M marks. +- A disjoint insertion proves that no descendants exist using an ordered + range query. Building M disjoint marks therefore costs O(M*D*log M), + instead of O(M^2). Both files and directories follow this path. +- A parent with K marked descendants compacts the item vector once and + removes those K keys: O(M + K log M), instead of K full compactions. +- Exact mark membership changes from expected hash O(1) to O(log M). The + index still stores one path per mark and adds no fields to scan nodes. +- Unmarking one item still compacts the ordered vector in O(M). Multiple + separately invoked parent actions can each require their own compaction; + this is a per-action bound, not a promise that arbitrary sequences of + scalar edits cost one pass in total. + +`Disktree::toggle_mark` and the existing public behavior stay intact: it +refuses a mark beneath an already marked ancestor, absorbs descendants, +keeps unrelated marks in their original order and reports the absorbed count. +Tree-to-crumb display caches are invalidated by the mutations, including the +new absorption operation. Refresh continues retaining missing paths at zero +bytes, and the ordered index stays consistent with those retained paths. + +`ReviewStatus` borrows covered paths and blocked reasons from the `Plan` +computed for the current render. Construction plus all row lookups costs +expected O(B + C + L) hashing work and O(B + C) temporary index storage. +The first blocked reason wins for duplicate paths, preserving the original +linear lookup's behavior. Item order, chips and the display cap remain. +No plan/status authorization is retained across renders. + +Tests preserve native path component/case semantics, exact non-UTF-8 paths, +first-reason behavior, parent mark retention, unrelated neighbours and cache +invalidation after absorption. Removal guards, measurement and execution +logic are unchanged; worker-side mount/link revalidation still occurs +immediately before deletion. Existing synthetic permanent-deletion tests +continue passing. + +## End-to-end input evidence + +The separate opt-in input benchmark uses real on-disk temporary directories: +1,025 sibling folders, one 64-byte file each, with the same 1,400x900 window +and both panels visible. Space queues one additional folder; hover and C +then run with that additional mark present. Three repetitions record the +actual render/prepare/plan counts and zero refreshes. These inputs cause two +or three renders in the harness, not universally one production frame. + +[interactions-main.log](interactions-main.log) replays main algorithms +(`5a3c92e`, tests/probes over main `6c8d4ce`) with the input test applied. +[interactions-final.log](interactions-final.log) runs the combined fixes +immediately afterward. [interactions-before.log](interactions-before.log) +is a separate control with only the original PR #9 fixes, before this +expansion. A generated table of the latest input medians is kept below. +These test-profile samples are observations, not release-app per-click +guarantees; small queues do not support a substantial speedup claim. + +| Already queued | Space: main → final | Hover: main → final | Review C: main → final | +| ---: | ---: | ---: | ---: | +| 0 | 3.52 → 3.52 ms | 3.64 → 3.58 ms | 3.10 → 3.07 ms | +| 1 | 3.79 → 3.76 ms | 3.94 → 3.87 ms | 3.47 → 3.43 ms | +| 8 | 5.14 → 5.01 ms | 5.28 → 5.14 ms | 5.82 → 5.74 ms | +| 32 | 8.70 → 7.23 ms | 8.85 → 7.43 ms | 13.53 → 12.19 ms | +| 128 | 41.54 → 16.13 ms | 40.85 → 16.26 ms | 62.99 → 38.19 ms | +| 1,024 | 1584.73 → 96.49 ms | 1575.83 → 97.78 ms | 1786.18 → 300.71 ms | + +## Validation and reproduction + +- `cargo xtask lint`: pass; [lint.log](lint.log). +- `cargo xtask test`: 88 app + 150 core + 3 xtask tests pass (241 total); + [tests.log](tests.log). Two pre-existing ignored core tests and the manual + timing test remain ignored by normal CI. +- `cargo test --workspace budget -- --nocapture --test-threads=1`: all + original and expanded budgets pass, including 8,192-entry Review cases. +- The opt-in input timing test passes when explicitly run. +- Local validation is macOS arm64. Other operating systems remain for the + repository's existing CI; no new cross-platform result is claimed. + +The first four red failures can be reproduced at `57d4efd`: + +```sh +cargo test -p disktree-app budget -- --nocapture --test-threads=1 +``` + +At the final head: + +```sh +cargo xtask lint +cargo xtask test +cargo test --workspace budget -- --nocapture --test-threads=1 +cargo test -p disktree-app marked_interaction_timings -- \ + --ignored --nocapture --test-threads=1 +``` + +These changes improve the existing state/render paths. Future programmatic +bulk control should still submit additions within one UI transaction rather +than require a redraw per tool call. Per-render plans continue processing +the queued items, and independently rendering R times still pays that cost +R times. No MCP transport/control implementation is included here. + +Deep breadcrumbs, Linux mount-topology checks and the unusual classification +case from the [broader audit](../additional-audit.md) remain separate +follow-ups. This PR is one main-based review unit for large removal queues; +it does not depend on the APFS feature branch. diff --git a/docs/performance/mark-resolution/expanded/green-marking.log b/docs/performance/mark-resolution/expanded/green-marking.log new file mode 100644 index 00000000..58d28114 --- /dev/null +++ b/docs/performance/mark-resolution/expanded/green-marking.log @@ -0,0 +1,54 @@ + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Finished `test` profile [optimized + debuginfo] target(s) in 7.25s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 1 test +test tests::queue_construction_budget ... queue-construction M=128 work=1152 wall=572.625µs +queue-construction M=1024 work=9216 wall=6.670083ms +ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 85 filtered out; finished in 0.13s + + Finished `test` profile [optimized + debuginfo] target(s) in 0.26s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 1 test +test tests::parent_absorption_budget ... parent-absorption M=128 work=266 compactions=130 wall=58.625µs +parent-absorption M=1024 work=2058 compactions=1026 wall=459.125µs +ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 85 filtered out; finished in 0.07s + + Finished `test` profile [optimized + debuginfo] target(s) in 0.27s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 13 tests +test marks::tests::display_path_shortens_the_home_prefix ... ok +test marks::tests::ordered_marks_keep_exact_non_utf8_paths ... ok +test marks::tests::ordered_marks_preserve_components_case_and_outermost_ancestor ... ok +test marks::tests::marking_the_same_path_twice_keeps_one_entry ... dimensions folders=128 M=8 D=2 R=1 work=160 wall=23.041µs +ok +test marks::tests::resolver_preserves_lossy_non_utf8_components ... ok +test marks::tests::toggling_marks_and_unmarks ... ok +test marks::tests::find_matches_whole_components_only ... ok +test marks::tests::resolver_preserves_scan_name_semantics ... ok +test marks::tests::refresh_re_reads_sizes_from_a_new_tree ... ok +test marks::tests::absorption_invalidates_cached_crumbs_and_keeps_missing_paths_indexed ... ok +test marks::tests::cached_crumbs_follow_every_invalidation_boundary ... ok +dimensions folders=1024 M=8 D=2 R=1 work=1056 wall=50.417µs +refresh M=128 N=256 R=4 work=2560 wall=232.083µs +dimensions folders=1024 M=64 D=2 R=1 work=1280 wall=58.625µs +dimensions folders=128 M=8 D=16 R=1 work=384 wall=27.083µs +dimensions folders=128 M=8 D=2 R=8 work=1280 wall=60.416µs +test marks::tests::refresh_dimension_budget ... ok +refresh M=1024 N=2048 R=4 work=20480 wall=1.545542ms +test marks::tests::refresh_resolution_budget ... ok + +test result: ok. 13 passed; 0 failed; 0 ignored; 0 measured; 73 filtered out; finished in 0.01s + diff --git a/docs/performance/mark-resolution/expanded/green-review.log b/docs/performance/mark-resolution/expanded/green-review.log new file mode 100644 index 00000000..b9d59fa2 --- /dev/null +++ b/docs/performance/mark-resolution/expanded/green-review.log @@ -0,0 +1,29 @@ + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Finished `test` profile [optimized + debuginfo] target(s) in 4.06s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 2 tests +test tests::blocked_review_status_budget ... review-status covered=false M=128 work=3072 renders=8 rows=128 per-render=384 wall=117.141208ms +review-status covered=false M=1024 work=24576 renders=8 rows=1024 per-render=3072 wall=918.023375ms +review-status covered=false M=8192 work=84736 renders=8 rows=1200 per-render=10592 wall=1.251237917s +ok +test tests::covered_review_status_budget ... review-status covered=true M=128 work=3088 renders=8 rows=129 per-render=386 wall=124.676334ms +review-status covered=true M=1024 work=24592 renders=8 rows=1025 per-render=3074 wall=1.058290834s +review-status covered=true M=8192 work=84736 renders=8 rows=1200 per-render=10592 wall=2.1404995s +ok + +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 86 filtered out; finished in 5.87s + + Finished `test` profile [optimized + debuginfo] target(s) in 0.26s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 2 tests +test views::tests::review_status_preserves_exact_paths_and_first_blocked_reason ... ok +test views::tests::review_status_keeps_non_utf8_paths_distinct ... ok + +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 86 filtered out; finished in 0.00s + diff --git a/docs/performance/mark-resolution/expanded/green.log b/docs/performance/mark-resolution/expanded/green.log new file mode 100644 index 00000000..62924d9e --- /dev/null +++ b/docs/performance/mark-resolution/expanded/green.log @@ -0,0 +1,57 @@ + Finished `test` profile [optimized + debuginfo] target(s) in 0.35s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 10 tests +test argument_tests::adaptive_budget_and_fixed_override_are_explicit ... ok +test argument_tests::invalid_worker_budgets_are_rejected ... ok +test marks::tests::refresh_dimension_budget ... dimensions folders=128 M=8 D=2 R=1 work=160 wall=24.375µs +dimensions folders=1024 M=8 D=2 R=1 work=1056 wall=48.083µs +dimensions folders=1024 M=64 D=2 R=1 work=1280 wall=52.167µs +dimensions folders=128 M=8 D=16 R=1 work=384 wall=26.25µs +dimensions folders=128 M=8 D=2 R=8 work=1280 wall=92.083µs +ok +test marks::tests::refresh_resolution_budget ... refresh M=128 N=256 R=4 work=2560 wall=203.5µs +refresh M=1024 N=2048 R=4 work=20480 wall=1.533958ms +ok +test tests::blocked_review_status_budget ... review-status covered=false M=128 work=3072 renders=8 rows=128 per-render=384 wall=107.112541ms +review-status covered=false M=1024 work=24576 renders=8 rows=1024 per-render=3072 wall=896.730708ms +review-status covered=false M=8192 work=84736 renders=8 rows=1200 per-render=10592 wall=1.196129834s +ok +test tests::covered_review_status_budget ... review-status covered=true M=128 work=3088 renders=8 rows=129 per-render=386 wall=122.642875ms +review-status covered=true M=1024 work=24592 renders=8 rows=1025 per-render=3074 wall=1.006027084s +review-status covered=true M=8192 work=84736 renders=8 rows=1200 per-render=10592 wall=2.109495042s +ok +test tests::folder_queue_construction_budget ... folder-queue M=128 work=1152 wall=542µs +folder-queue M=1024 work=9216 wall=6.55425ms +ok +test tests::marked_window_resolution_budget ... warm window M=128 prepares=8 resolution=216 tiles=1544 wall=60.956167ms +window M=128 N=256 draws=4 prepares=8 work=856 wall=61.972375ms +warm window M=1024 prepares=8 resolution=216 tiles=776 wall=332.587667ms +window M=1024 N=2048 draws=4 prepares=8 work=5336 wall=333.501ms +ok +test tests::parent_absorption_budget ... parent-absorption M=128 work=266 compactions=130 wall=57.667µs +parent-absorption M=1024 work=2058 compactions=1026 wall=472.542µs +ok +test tests::queue_construction_budget ... queue-construction M=128 work=1152 wall=554.417µs +queue-construction M=1024 work=9216 wall=6.531ms +ok + +test result: ok. 10 passed; 0 failed; 0 ignored; 0 measured; 79 filtered out; finished in 6.89s + + Running unittests src/lib.rs (target/debug/deps/disktree_core-9300e5ba20d6b25f) + +running 1 test +test removal::tests::removal_nesting_budget ... plan M=128 work=1314 wall=2.843041ms +plan M=1024 work=15298 wall=22.107625ms +ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 151 filtered out; finished in 0.03s + + Running unittests src/main.rs (target/debug/deps/xtask-0dc2df263f51d89e) + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 3 filtered out; finished in 0.00s + diff --git a/docs/performance/mark-resolution/expanded/interactions-before.log b/docs/performance/mark-resolution/expanded/interactions-before.log new file mode 100644 index 00000000..93d390f5 --- /dev/null +++ b/docs/performance/mark-resolution/expanded/interactions-before.log @@ -0,0 +1,65 @@ + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Finished `test` profile [optimized + debuginfo] target(s) in 6.06s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 1 test +test tests::marked_interaction_timings ... interaction action=mark-space repeat=1 marks=0->1 renders=3 prepares=3 plans=6 refreshes=0 wall=5.29ms +interaction action=hover repeat=1 marks=1->1 renders=2 prepares=2 plans=4 refreshes=0 wall=3.693417ms +interaction action=review-c repeat=1 marks=1->1 renders=3 prepares=1 plans=4 refreshes=0 wall=3.161125ms +interaction action=mark-space repeat=2 marks=0->1 renders=2 prepares=2 plans=4 refreshes=0 wall=3.493542ms +interaction action=hover repeat=2 marks=1->1 renders=2 prepares=2 plans=4 refreshes=0 wall=4.177458ms +interaction action=review-c repeat=2 marks=1->1 renders=3 prepares=1 plans=4 refreshes=0 wall=3.333041ms +interaction action=mark-space repeat=3 marks=0->1 renders=2 prepares=2 plans=4 refreshes=0 wall=3.531208ms +interaction action=hover repeat=3 marks=1->1 renders=2 prepares=2 plans=4 refreshes=0 wall=3.598083ms +interaction action=review-c repeat=3 marks=1->1 renders=3 prepares=1 plans=4 refreshes=0 wall=3.059417ms +interaction action=mark-space repeat=1 marks=1->2 renders=3 prepares=3 plans=6 refreshes=0 wall=6.413958ms +interaction action=hover repeat=1 marks=2->2 renders=2 prepares=2 plans=4 refreshes=0 wall=4.211334ms +interaction action=review-c repeat=1 marks=2->2 renders=3 prepares=1 plans=4 refreshes=0 wall=3.781ms +interaction action=mark-space repeat=2 marks=1->2 renders=2 prepares=2 plans=4 refreshes=0 wall=4.085666ms +interaction action=hover repeat=2 marks=2->2 renders=2 prepares=2 plans=4 refreshes=0 wall=4.282084ms +interaction action=review-c repeat=2 marks=2->2 renders=3 prepares=1 plans=4 refreshes=0 wall=3.605958ms +interaction action=mark-space repeat=3 marks=1->2 renders=2 prepares=2 plans=4 refreshes=0 wall=4.143666ms +interaction action=hover repeat=3 marks=2->2 renders=2 prepares=2 plans=4 refreshes=0 wall=4.118042ms +interaction action=review-c repeat=3 marks=2->2 renders=3 prepares=1 plans=4 refreshes=0 wall=3.837666ms +interaction action=mark-space repeat=1 marks=8->9 renders=3 prepares=3 plans=6 refreshes=0 wall=8.128709ms +interaction action=hover repeat=1 marks=9->9 renders=2 prepares=2 plans=4 refreshes=0 wall=5.588583ms +interaction action=review-c repeat=1 marks=9->9 renders=3 prepares=1 plans=4 refreshes=0 wall=6.106292ms +interaction action=mark-space repeat=2 marks=8->9 renders=2 prepares=2 plans=4 refreshes=0 wall=5.294584ms +interaction action=hover repeat=2 marks=9->9 renders=2 prepares=2 plans=4 refreshes=0 wall=5.593625ms +interaction action=review-c repeat=2 marks=9->9 renders=3 prepares=1 plans=4 refreshes=0 wall=6.023584ms +interaction action=mark-space repeat=3 marks=8->9 renders=2 prepares=2 plans=4 refreshes=0 wall=5.320958ms +interaction action=hover repeat=3 marks=9->9 renders=2 prepares=2 plans=4 refreshes=0 wall=5.340792ms +interaction action=review-c repeat=3 marks=9->9 renders=3 prepares=1 plans=4 refreshes=0 wall=5.888875ms +interaction action=mark-space repeat=1 marks=32->33 renders=3 prepares=3 plans=6 refreshes=0 wall=11.475584ms +interaction action=hover repeat=1 marks=33->33 renders=2 prepares=2 plans=4 refreshes=0 wall=8.573458ms +interaction action=review-c repeat=1 marks=33->33 renders=3 prepares=1 plans=4 refreshes=0 wall=13.598084ms +interaction action=mark-space repeat=2 marks=32->33 renders=2 prepares=2 plans=4 refreshes=0 wall=8.43825ms +interaction action=hover repeat=2 marks=33->33 renders=2 prepares=2 plans=4 refreshes=0 wall=8.692292ms +interaction action=review-c repeat=2 marks=33->33 renders=3 prepares=1 plans=4 refreshes=0 wall=13.951083ms +interaction action=mark-space repeat=3 marks=32->33 renders=2 prepares=2 plans=4 refreshes=0 wall=8.248416ms +interaction action=hover repeat=3 marks=33->33 renders=2 prepares=2 plans=4 refreshes=0 wall=9.179667ms +interaction action=review-c repeat=3 marks=33->33 renders=3 prepares=1 plans=4 refreshes=0 wall=14.361125ms +interaction action=mark-space repeat=1 marks=128->129 renders=3 prepares=3 plans=6 refreshes=0 wall=25.540333ms +interaction action=hover repeat=1 marks=129->129 renders=2 prepares=2 plans=4 refreshes=0 wall=17.300917ms +interaction action=review-c repeat=1 marks=129->129 renders=3 prepares=1 plans=4 refreshes=0 wall=41.825167ms +interaction action=mark-space repeat=2 marks=128->129 renders=2 prepares=2 plans=4 refreshes=0 wall=17.227209ms +interaction action=hover repeat=2 marks=129->129 renders=2 prepares=2 plans=4 refreshes=0 wall=17.180542ms +interaction action=review-c repeat=2 marks=129->129 renders=3 prepares=1 plans=4 refreshes=0 wall=39.642416ms +interaction action=mark-space repeat=3 marks=128->129 renders=2 prepares=2 plans=4 refreshes=0 wall=17.732042ms +interaction action=hover repeat=3 marks=129->129 renders=2 prepares=2 plans=4 refreshes=0 wall=18.09625ms +interaction action=review-c repeat=3 marks=129->129 renders=3 prepares=1 plans=4 refreshes=0 wall=45.706083ms +interaction action=mark-space repeat=1 marks=1024->1025 renders=3 prepares=3 plans=6 refreshes=0 wall=154.267542ms +interaction action=hover repeat=1 marks=1025->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=106.91175ms +interaction action=review-c repeat=1 marks=1025->1025 renders=3 prepares=1 plans=4 refreshes=0 wall=322.193416ms +interaction action=mark-space repeat=2 marks=1024->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=97.879042ms +interaction action=hover repeat=2 marks=1025->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=99.106959ms +interaction action=review-c repeat=2 marks=1025->1025 renders=3 prepares=1 plans=4 refreshes=0 wall=322.52575ms +interaction action=mark-space repeat=3 marks=1024->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=106.434417ms +interaction action=hover repeat=3 marks=1025->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=104.738875ms +interaction action=review-c repeat=3 marks=1025->1025 renders=3 prepares=1 plans=4 refreshes=0 wall=320.722334ms +ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 82 filtered out; finished in 4.32s + diff --git a/docs/performance/mark-resolution/expanded/interactions-final.log b/docs/performance/mark-resolution/expanded/interactions-final.log new file mode 100644 index 00000000..209a385f --- /dev/null +++ b/docs/performance/mark-resolution/expanded/interactions-final.log @@ -0,0 +1,66 @@ + Compiling disktree-core v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-core) + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Finished `test` profile [optimized + debuginfo] target(s) in 4.71s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 1 test +test tests::marked_interaction_timings ... interaction action=mark-space repeat=1 marks=0->1 renders=3 prepares=3 plans=6 refreshes=0 wall=5.246292ms +interaction action=hover repeat=1 marks=1->1 renders=2 prepares=2 plans=4 refreshes=0 wall=3.710917ms +interaction action=review-c repeat=1 marks=1->1 renders=3 prepares=1 plans=4 refreshes=0 wall=3.242042ms +interaction action=mark-space repeat=2 marks=0->1 renders=2 prepares=2 plans=4 refreshes=0 wall=3.513208ms +interaction action=hover repeat=2 marks=1->1 renders=2 prepares=2 plans=4 refreshes=0 wall=3.584084ms +interaction action=review-c repeat=2 marks=1->1 renders=3 prepares=1 plans=4 refreshes=0 wall=3.063ms +interaction action=mark-space repeat=3 marks=0->1 renders=2 prepares=2 plans=4 refreshes=0 wall=3.520209ms +interaction action=hover repeat=3 marks=1->1 renders=2 prepares=2 plans=4 refreshes=0 wall=3.578375ms +interaction action=review-c repeat=3 marks=1->1 renders=3 prepares=1 plans=4 refreshes=0 wall=3.073ms +interaction action=mark-space repeat=1 marks=1->2 renders=3 prepares=3 plans=6 refreshes=0 wall=5.520041ms +interaction action=hover repeat=1 marks=2->2 renders=2 prepares=2 plans=4 refreshes=0 wall=3.890709ms +interaction action=review-c repeat=1 marks=2->2 renders=3 prepares=1 plans=4 refreshes=0 wall=3.48725ms +interaction action=mark-space repeat=2 marks=1->2 renders=2 prepares=2 plans=4 refreshes=0 wall=3.755416ms +interaction action=hover repeat=2 marks=2->2 renders=2 prepares=2 plans=4 refreshes=0 wall=3.86925ms +interaction action=review-c repeat=2 marks=2->2 renders=3 prepares=1 plans=4 refreshes=0 wall=3.427584ms +interaction action=mark-space repeat=3 marks=1->2 renders=2 prepares=2 plans=4 refreshes=0 wall=3.751084ms +interaction action=hover repeat=3 marks=2->2 renders=2 prepares=2 plans=4 refreshes=0 wall=3.86175ms +interaction action=review-c repeat=3 marks=2->2 renders=3 prepares=1 plans=4 refreshes=0 wall=3.408333ms +interaction action=mark-space repeat=1 marks=8->9 renders=3 prepares=3 plans=6 refreshes=0 wall=7.470209ms +interaction action=hover repeat=1 marks=9->9 renders=2 prepares=2 plans=4 refreshes=0 wall=5.143125ms +interaction action=review-c repeat=1 marks=9->9 renders=3 prepares=1 plans=4 refreshes=0 wall=5.73275ms +interaction action=mark-space repeat=2 marks=8->9 renders=2 prepares=2 plans=4 refreshes=0 wall=5.014375ms +interaction action=hover repeat=2 marks=9->9 renders=2 prepares=2 plans=4 refreshes=0 wall=5.164583ms +interaction action=review-c repeat=2 marks=9->9 renders=3 prepares=1 plans=4 refreshes=0 wall=5.76775ms +interaction action=mark-space repeat=3 marks=8->9 renders=2 prepares=2 plans=4 refreshes=0 wall=5.006375ms +interaction action=hover repeat=3 marks=9->9 renders=2 prepares=2 plans=4 refreshes=0 wall=5.13825ms +interaction action=review-c repeat=3 marks=9->9 renders=3 prepares=1 plans=4 refreshes=0 wall=5.735209ms +interaction action=mark-space repeat=1 marks=32->33 renders=3 prepares=3 plans=6 refreshes=0 wall=11.012916ms +interaction action=hover repeat=1 marks=33->33 renders=2 prepares=2 plans=4 refreshes=0 wall=7.431459ms +interaction action=review-c repeat=1 marks=33->33 renders=3 prepares=1 plans=4 refreshes=0 wall=13.125583ms +interaction action=mark-space repeat=2 marks=32->33 renders=2 prepares=2 plans=4 refreshes=0 wall=7.209709ms +interaction action=hover repeat=2 marks=33->33 renders=2 prepares=2 plans=4 refreshes=0 wall=7.418334ms +interaction action=review-c repeat=2 marks=33->33 renders=3 prepares=1 plans=4 refreshes=0 wall=12.185875ms +interaction action=mark-space repeat=3 marks=32->33 renders=2 prepares=2 plans=4 refreshes=0 wall=7.22675ms +interaction action=hover repeat=3 marks=33->33 renders=2 prepares=2 plans=4 refreshes=0 wall=7.432875ms +interaction action=review-c repeat=3 marks=33->33 renders=3 prepares=1 plans=4 refreshes=0 wall=12.091458ms +interaction action=mark-space repeat=1 marks=128->129 renders=3 prepares=3 plans=6 refreshes=0 wall=24.179958ms +interaction action=hover repeat=1 marks=129->129 renders=2 prepares=2 plans=4 refreshes=0 wall=16.337667ms +interaction action=review-c repeat=1 marks=129->129 renders=3 prepares=1 plans=4 refreshes=0 wall=39.234959ms +interaction action=mark-space repeat=2 marks=128->129 renders=2 prepares=2 plans=4 refreshes=0 wall=16.130417ms +interaction action=hover repeat=2 marks=129->129 renders=2 prepares=2 plans=4 refreshes=0 wall=16.262167ms +interaction action=review-c repeat=2 marks=129->129 renders=3 prepares=1 plans=4 refreshes=0 wall=37.713833ms +interaction action=mark-space repeat=3 marks=128->129 renders=2 prepares=2 plans=4 refreshes=0 wall=16.075125ms +interaction action=hover repeat=3 marks=129->129 renders=2 prepares=2 plans=4 refreshes=0 wall=16.138417ms +interaction action=review-c repeat=3 marks=129->129 renders=3 prepares=1 plans=4 refreshes=0 wall=38.188041ms +interaction action=mark-space repeat=1 marks=1024->1025 renders=3 prepares=3 plans=6 refreshes=0 wall=143.247792ms +interaction action=hover repeat=1 marks=1025->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=99.35325ms +interaction action=review-c repeat=1 marks=1025->1025 renders=3 prepares=1 plans=4 refreshes=0 wall=302.670959ms +interaction action=mark-space repeat=2 marks=1024->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=96.486625ms +interaction action=hover repeat=2 marks=1025->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=95.861042ms +interaction action=review-c repeat=2 marks=1025->1025 renders=3 prepares=1 plans=4 refreshes=0 wall=300.70975ms +interaction action=mark-space repeat=3 marks=1024->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=95.268667ms +interaction action=hover repeat=3 marks=1025->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=97.78325ms +interaction action=review-c repeat=3 marks=1025->1025 renders=3 prepares=1 plans=4 refreshes=0 wall=298.794208ms +ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 88 filtered out; finished in 4.04s + diff --git a/docs/performance/mark-resolution/expanded/interactions-main.log b/docs/performance/mark-resolution/expanded/interactions-main.log new file mode 100644 index 00000000..800e1841 --- /dev/null +++ b/docs/performance/mark-resolution/expanded/interactions-main.log @@ -0,0 +1,66 @@ + Compiling disktree-core v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-core) + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Finished `test` profile [optimized + debuginfo] target(s) in 4.93s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 1 test +test tests::marked_interaction_timings ... interaction action=mark-space repeat=1 marks=0->1 renders=3 prepares=3 plans=6 refreshes=0 wall=5.255584ms +interaction action=hover repeat=1 marks=1->1 renders=2 prepares=2 plans=4 refreshes=0 wall=3.762417ms +interaction action=review-c repeat=1 marks=1->1 renders=3 prepares=1 plans=4 refreshes=0 wall=3.218458ms +interaction action=mark-space repeat=2 marks=0->1 renders=2 prepares=2 plans=4 refreshes=0 wall=3.503375ms +interaction action=hover repeat=2 marks=1->1 renders=2 prepares=2 plans=4 refreshes=0 wall=3.638375ms +interaction action=review-c repeat=2 marks=1->1 renders=3 prepares=1 plans=4 refreshes=0 wall=3.096042ms +interaction action=mark-space repeat=3 marks=0->1 renders=2 prepares=2 plans=4 refreshes=0 wall=3.517333ms +interaction action=hover repeat=3 marks=1->1 renders=2 prepares=2 plans=4 refreshes=0 wall=3.6145ms +interaction action=review-c repeat=3 marks=1->1 renders=3 prepares=1 plans=4 refreshes=0 wall=3.080083ms +interaction action=mark-space repeat=1 marks=1->2 renders=3 prepares=3 plans=6 refreshes=0 wall=5.511084ms +interaction action=hover repeat=1 marks=2->2 renders=2 prepares=2 plans=4 refreshes=0 wall=3.941834ms +interaction action=review-c repeat=1 marks=2->2 renders=3 prepares=1 plans=4 refreshes=0 wall=3.503667ms +interaction action=mark-space repeat=2 marks=1->2 renders=2 prepares=2 plans=4 refreshes=0 wall=3.788ms +interaction action=hover repeat=2 marks=2->2 renders=2 prepares=2 plans=4 refreshes=0 wall=3.90975ms +interaction action=review-c repeat=2 marks=2->2 renders=3 prepares=1 plans=4 refreshes=0 wall=3.466166ms +interaction action=mark-space repeat=3 marks=1->2 renders=2 prepares=2 plans=4 refreshes=0 wall=3.76825ms +interaction action=hover repeat=3 marks=2->2 renders=2 prepares=2 plans=4 refreshes=0 wall=3.96025ms +interaction action=review-c repeat=3 marks=2->2 renders=3 prepares=1 plans=4 refreshes=0 wall=3.458125ms +interaction action=mark-space repeat=1 marks=8->9 renders=3 prepares=3 plans=6 refreshes=0 wall=7.608625ms +interaction action=hover repeat=1 marks=9->9 renders=2 prepares=2 plans=4 refreshes=0 wall=5.284208ms +interaction action=review-c repeat=1 marks=9->9 renders=3 prepares=1 plans=4 refreshes=0 wall=5.894708ms +interaction action=mark-space repeat=2 marks=8->9 renders=2 prepares=2 plans=4 refreshes=0 wall=5.141833ms +interaction action=hover repeat=2 marks=9->9 renders=2 prepares=2 plans=4 refreshes=0 wall=5.286125ms +interaction action=review-c repeat=2 marks=9->9 renders=3 prepares=1 plans=4 refreshes=0 wall=5.815959ms +interaction action=mark-space repeat=3 marks=8->9 renders=2 prepares=2 plans=4 refreshes=0 wall=5.117792ms +interaction action=hover repeat=3 marks=9->9 renders=2 prepares=2 plans=4 refreshes=0 wall=5.267ms +interaction action=review-c repeat=3 marks=9->9 renders=3 prepares=1 plans=4 refreshes=0 wall=5.815375ms +interaction action=mark-space repeat=1 marks=32->33 renders=3 prepares=3 plans=6 refreshes=0 wall=12.998667ms +interaction action=hover repeat=1 marks=33->33 renders=2 prepares=2 plans=4 refreshes=0 wall=8.816834ms +interaction action=review-c repeat=1 marks=33->33 renders=3 prepares=1 plans=4 refreshes=0 wall=13.860541ms +interaction action=mark-space repeat=2 marks=32->33 renders=2 prepares=2 plans=4 refreshes=0 wall=8.695333ms +interaction action=hover repeat=2 marks=33->33 renders=2 prepares=2 plans=4 refreshes=0 wall=8.8455ms +interaction action=review-c repeat=2 marks=33->33 renders=3 prepares=1 plans=4 refreshes=0 wall=13.520791ms +interaction action=mark-space repeat=3 marks=32->33 renders=2 prepares=2 plans=4 refreshes=0 wall=8.686166ms +interaction action=hover repeat=3 marks=33->33 renders=2 prepares=2 plans=4 refreshes=0 wall=8.850291ms +interaction action=review-c repeat=3 marks=33->33 renders=3 prepares=1 plans=4 refreshes=0 wall=13.525542ms +interaction action=mark-space repeat=1 marks=128->129 renders=3 prepares=3 plans=6 refreshes=0 wall=58.431709ms +interaction action=hover repeat=1 marks=129->129 renders=2 prepares=2 plans=4 refreshes=0 wall=39.571ms +interaction action=review-c repeat=1 marks=129->129 renders=3 prepares=1 plans=4 refreshes=0 wall=62.991042ms +interaction action=mark-space repeat=2 marks=128->129 renders=2 prepares=2 plans=4 refreshes=0 wall=41.537667ms +interaction action=hover repeat=2 marks=129->129 renders=2 prepares=2 plans=4 refreshes=0 wall=42.52325ms +interaction action=review-c repeat=2 marks=129->129 renders=3 prepares=1 plans=4 refreshes=0 wall=63.378542ms +interaction action=mark-space repeat=3 marks=128->129 renders=2 prepares=2 plans=4 refreshes=0 wall=40.624666ms +interaction action=hover repeat=3 marks=129->129 renders=2 prepares=2 plans=4 refreshes=0 wall=40.849792ms +interaction action=review-c repeat=3 marks=129->129 renders=3 prepares=1 plans=4 refreshes=0 wall=62.616375ms +interaction action=mark-space repeat=1 marks=1024->1025 renders=3 prepares=3 plans=6 refreshes=0 wall=2.353868208s +interaction action=hover repeat=1 marks=1025->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=1.5475255s +interaction action=review-c repeat=1 marks=1025->1025 renders=3 prepares=1 plans=4 refreshes=0 wall=1.786180708s +interaction action=mark-space repeat=2 marks=1024->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=1.558053083s +interaction action=hover repeat=2 marks=1025->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=1.588539167s +interaction action=review-c repeat=2 marks=1025->1025 renders=3 prepares=1 plans=4 refreshes=0 wall=1.814801708s +interaction action=mark-space repeat=3 marks=1024->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=1.584729708s +interaction action=hover repeat=3 marks=1025->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=1.575834417s +interaction action=review-c repeat=3 marks=1025->1025 renders=3 prepares=1 plans=4 refreshes=0 wall=1.766631333s +ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 73 filtered out; finished in 37.74s + diff --git a/docs/performance/mark-resolution/expanded/lint.log b/docs/performance/mark-resolution/expanded/lint.log new file mode 100644 index 00000000..ee7838ac --- /dev/null +++ b/docs/performance/mark-resolution/expanded/lint.log @@ -0,0 +1,7 @@ + Finished `dev` profile [optimized + debuginfo] target(s) in 0.18s + Running `target/debug/xtask lint` + Checking disktree-core v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-core) + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Finished `dev` profile [optimized + debuginfo] target(s) in 2.21s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` diff --git a/docs/performance/mark-resolution/expanded/red-folders.log b/docs/performance/mark-resolution/expanded/red-folders.log new file mode 100644 index 00000000..fd240b02 --- /dev/null +++ b/docs/performance/mark-resolution/expanded/red-folders.log @@ -0,0 +1,23 @@ + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Finished `test` profile [optimized + debuginfo] target(s) in 4.21s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 1 test +test tests::folder_queue_construction_budget ... folder-queue M=128 work=16384 wall=2.888959ms +folder-queue M=1024 work=1048576 wall=177.786542ms + +thread 'tests::folder_queue_construction_budget' (404519213) panicked at crates/disktree-app/src/tests.rs:2365:5: +8x folders: 16384 -> 1048576 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace +FAILED + +failures: + +failures: + tests::folder_queue_construction_budget + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 83 filtered out; finished in 0.32s + +error: test failed, to rerun pass `-p disktree-app --bin disktree` diff --git a/docs/performance/mark-resolution/expanded/red.log b/docs/performance/mark-resolution/expanded/red.log new file mode 100644 index 00000000..81a829b1 --- /dev/null +++ b/docs/performance/mark-resolution/expanded/red.log @@ -0,0 +1,61 @@ + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Compiling disktree-core v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-core) + Finished `test` profile [optimized + debuginfo] target(s) in 7.61s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 9 tests +test argument_tests::adaptive_budget_and_fixed_override_are_explicit ... ok +test argument_tests::invalid_worker_budgets_are_rejected ... ok +test marks::tests::refresh_dimension_budget ... dimensions folders=128 M=8 D=2 R=1 work=160 wall=62.75µs +dimensions folders=1024 M=8 D=2 R=1 work=1056 wall=45µs +dimensions folders=1024 M=64 D=2 R=1 work=1280 wall=58.083µs +dimensions folders=128 M=8 D=16 R=1 work=384 wall=28.875µs +dimensions folders=128 M=8 D=2 R=8 work=1280 wall=62.834µs +ok +test marks::tests::refresh_resolution_budget ... refresh M=128 N=256 R=4 work=2560 wall=205.458µs +refresh M=1024 N=2048 R=4 work=20480 wall=1.533583ms +ok +test tests::blocked_review_status_budget ... review-status covered=false M=128 work=66048 renders=8 rows=128 per-render=8256 wall=113.90025ms +review-status covered=false M=1024 work=4198400 renders=8 rows=1024 per-render=524800 wall=1.038960833s + +thread 'tests::blocked_review_status_budget' (404491031) panicked at crates/disktree-app/src/tests.rs:2298:5: +8x status rows: 66048/8 -> 4198400/8 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace +FAILED +test tests::covered_review_status_budget ... review-status covered=true M=128 work=67072 renders=8 rows=129 per-render=8384 wall=135.896292ms +review-status covered=true M=1024 work=4206592 renders=8 rows=1025 per-render=525824 wall=1.29864975s + +thread 'tests::covered_review_status_budget' (404491108) panicked at crates/disktree-app/src/tests.rs:2298:5: +8x status rows: 67072/8 -> 4206592/8 +FAILED +test tests::marked_window_resolution_budget ... warm window M=128 prepares=8 resolution=216 tiles=1544 wall=63.308583ms +window M=128 N=256 draws=4 prepares=8 work=856 wall=64.349292ms +warm window M=1024 prepares=8 resolution=216 tiles=776 wall=342.802833ms +window M=1024 N=2048 draws=4 prepares=8 work=5336 wall=360.040792ms +ok +test tests::parent_absorption_budget ... parent-absorption M=128 work=8771 compactions=8512 wall=347.334µs +parent-absorption M=1024 work=528899 compactions=526848 wall=15.802708ms + +thread 'tests::parent_absorption_budget' (404491437) panicked at crates/disktree-app/src/tests.rs:2223:5: +8x descendants: 8771 -> 528899 +FAILED +test tests::queue_construction_budget ... queue-construction M=128 work=16384 wall=2.851667ms +queue-construction M=1024 work=1048576 wall=183.52175ms + +thread 'tests::queue_construction_budget' (404491448) panicked at crates/disktree-app/src/tests.rs:2181:5: +8x marks: 16384 -> 1048576 +FAILED + +failures: + +failures: + tests::blocked_review_status_budget + tests::covered_review_status_budget + tests::parent_absorption_budget + tests::queue_construction_budget + +test result: FAILED. 5 passed; 4 failed; 0 ignored; 0 measured; 74 filtered out; finished in 4.00s + +error: test failed, to rerun pass `-p disktree-app --bin disktree` diff --git a/docs/performance/mark-resolution/expanded/tests.log b/docs/performance/mark-resolution/expanded/tests.log new file mode 100644 index 00000000..a27e00a6 --- /dev/null +++ b/docs/performance/mark-resolution/expanded/tests.log @@ -0,0 +1,275 @@ + Finished `dev` profile [optimized + debuginfo] target(s) in 0.11s + Running `target/debug/xtask test` + Compiling disktree-core v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-core) + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Finished `test` profile [optimized + debuginfo] target(s) in 3.26s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 89 tests +test appearance::tests::a_linux_desktop_is_followed_only_if_it_states_a_preference ... ok +test argument_tests::invalid_worker_budgets_are_rejected ... ok +test marks::tests::display_path_shortens_the_home_prefix ... ok +test git::tests::summaries_say_what_would_be_lost ... ok +test marks::tests::marking_the_same_path_twice_keeps_one_entry ... ok +test marks::tests::ordered_marks_keep_exact_non_utf8_paths ... ok +test marks::tests::ordered_marks_preserve_components_case_and_outermost_ancestor ... ok +test argument_tests::adaptive_budget_and_fixed_override_are_explicit ... ok +test marks::tests::resolver_preserves_lossy_non_utf8_components ... ok +test marks::tests::toggling_marks_and_unmarks ... ok +test marks::tests::find_matches_whole_components_only ... ok +test marks::tests::refresh_re_reads_sizes_from_a_new_tree ... ok +test marks::tests::absorption_invalidates_cached_crumbs_and_keeps_missing_paths_indexed ... ok +test marks::tests::cached_crumbs_follow_every_invalidation_boundary ... ok +test marks::tests::resolver_preserves_scan_name_semantics ... ok +test palette::tests::age_buckets_cover_every_age_in_order ... ok +test palette::tests::colourful_categories_share_one_level ... ok +test palette::tests::deeper_tiles_lift_away_from_the_background ... ok +test palette::tests::every_legend_category_has_its_own_hue ... ok +test palette::tests::mix_clamps_its_parameter ... ok +test palette::tests::mixing_toward_a_grey_keeps_the_hue ... ok +test palette::tests::the_highlight_is_not_a_category_colour ... ok +test power::tests::presets_are_fixed_and_show_the_effective_cpu_limit ... ok +test power::tests::presets_that_add_no_workers_are_not_offered ... ok +test state::tests::a_transition_grows_a_tile_that_is_being_entered ... ok +test state::tests::a_transition_starts_where_the_region_was_and_ends_where_it_is ... ok +test state::tests::clamping_never_leaves_a_margin ... ok +test state::tests::directions_only_see_gaps_on_their_own_side ... ok +test argument_tests::saved_power_is_loaded_before_cli_overrides ... ok +test state::tests::projecting_and_unprojecting_are_inverses ... ok +test state::tests::zooming_keeps_the_point_under_the_cursor_still ... ok +test marks::tests::refresh_dimension_budget ... ok +test power::tests::saved_choice_survives_replacement_and_bad_data_is_reported ... ok +test marks::tests::refresh_resolution_budget ... ok +test git::tests::reads_a_real_checkout ... ok +test git::tests::a_checkout_cannot_make_git_run_its_programs ... ok +test git::tests::a_checkout_cannot_make_git_verify_a_signature_with_its_program ... ok +test git::tests::a_checkouts_own_filter_is_never_run ... ok +test tests::escape_cancels_widening_and_keeps_the_tree_on_screen ... ok +test tests::escape_in_the_delete_dialog_cancels ... ok +test tests::command_chords_are_not_read_as_plain_letters ... ok +test tests::enter_before_the_search_lands_applies_it_when_it_does ... ok +test tests::marked_interaction_timings ... ignored, manual interaction timing on synthetic temporary files +test tests::a_view_without_flags_or_marks_still_draws ... ok +test tests::a_parents_name_gets_its_own_band_above_its_children ... ok +test tests::a_permanent_deletion_asks_in_an_alert_dialog_then_removes ... ok +test tests::a_crumb_lists_its_siblings_and_jumps_sideways ... ok +test tests::enter_in_the_focused_volume_picker_scans_the_selected_root ... ok +test tests::folder_queue_construction_budget ... ok +test tests::enter_opens_the_selected_directory_at_any_depth ... ok +test tests::restart_arguments_parse_back_to_the_same_scan ... ok +test tests::after_descending_every_tile_is_inside_the_directory_drawn ... ok +test tests::both_appearances_draw ... ok +test tests::back_and_forward_retrace_where_you_have_been ... ok +test tests::dragging_the_panel_edge_resizes_it_within_its_limits ... ok +test tests::escape_cancels_the_first_scan_and_r_starts_it_again ... ok +test tests::hovering_reports_the_tile_under_the_pointer ... ok +test tests::interface_zoom_scales_the_rem_and_the_header_band ... ok +test tests::marked_tiles_follow_metric_rescan_and_mark_changes ... ok +test tests::marking_a_directory_marks_everything_inside_it ... ok +test tests::power_efficiency_menu_saves_without_discarding_the_tree ... ok +test tests::showing_a_tile_that_is_gone_says_so_instead ... ok +test tests::keys_walk_the_tree_and_mark_what_is_selected ... ok +test tests::switching_the_metric_keeps_the_directory_and_the_selection ... ok +test tests::mouse_side_buttons_go_back_and_forward ... ok +test tests::parent_absorption_budget ... ok +test tests::right_click_selects_the_tile_and_reveals_it ... ok +test tests::the_first_scan_shows_what_it_is_doing_then_the_treemap ... ok +test views::tests::review_status_keeps_non_utf8_paths_distinct ... ok +test views::tests::review_status_preserves_exact_paths_and_first_blocked_reason ... ok +test widgets::tests::ages_read_in_the_unit_a_person_would_use ... ok +test widgets::tests::sizes_split_into_number_and_unit ... ok +test tests::the_help_overlay_opens_and_closes ... ok +test tests::the_mark_key_follows_the_pointer_until_the_keyboard_moves ... ok +test tests::queue_construction_budget ... ok +test tests::the_power_menu_offers_only_what_the_cpus_can_tell_apart ... ok +test tests::the_review_screen_copies_the_list_as_an_agent_prompt ... ok +test tests::the_review_screen_switches_removal_mode ... ok +test tests::the_trash_is_the_default_when_there_is_one ... ok +test tests::the_volume_picker_is_centred_and_still_dismisses_from_outside ... ok +test tests::marked_window_resolution_budget ... ok +test tests::the_wheel_goes_into_the_directory_it_zoomed_into ... ok +test tests::the_treemap_zooms_with_the_wheel_and_resets ... ok +test tests::the_volume_picker_opens_moves_and_closes ... ok +test tests::typing_filters_live_and_enter_shows_only_the_matches ... ok +test tests::widening_reuses_the_tree_it_has_and_reads_only_the_rest ... ok +test tests::the_window_draws_a_treemap_with_tiles ... ok +test tests::blocked_review_status_budget ... ok +test tests::covered_review_status_budget ... ok + +test result: ok. 88 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 4.87s + + Running unittests src/lib.rs (target/debug/deps/disktree_core-9300e5ba20d6b25f) + +running 152 tests +test classify::tests::macos_developer_leftovers_are_reclaimable_and_its_risks_are_not ... ok +test export::tests::the_list_is_one_path_per_line ... ok +test classify::tests::steam_libraries_and_emulation_are_media_not_disposable_caches ... ok +test filter::tests::case_is_ignored_without_allocating ... ok +test classify::tests::the_legend_lists_every_named_category_once ... ok +test classify::tests::windows_caches_and_sync_folders_are_recognized ... ok +test export::tests::a_name_with_a_newline_cannot_smuggle_in_a_path ... ok +test export::tests::a_name_that_is_not_unicode_is_flagged_not_listed ... ok +test export::tests::the_prompt_lists_every_path_with_its_size_and_the_rules ... ok +test filter::tests::an_empty_needle_filters_nothing ... ok +test filter::tests::a_search_below_the_root_leaves_the_rest_alone ... ok +test filter::tests::matches_are_kept_whole_and_their_ancestors_by_what_matched ... ok +test access::tests::only_macos_has_an_answer_and_a_missing_database_is_not_a_refusal ... ok +test classify::tests::a_steam_library_on_another_drive_is_media_not_its_temp_folder ... ok +test classify::tests::sandbox_layers_and_snapshots_are_reclaimable_only_in_sandbox_state ... ok +test insights::tests::the_limit_keeps_the_largest ... ok +test insights::tests::ranks_findings_largest_first_and_skips_the_tiny ... ok +test insights::tests::documents_are_never_suggested ... ok +test insights::tests::crumbs_address_the_finding_from_the_root ... ok +test classify::tests::names_announce_their_kind_and_children_inherit_it ... ok +test classify::tests::target_is_build_output_only_beside_a_cargo_manifest ... ok +test classify::tests::an_unknown_top_level_directory_takes_its_largest_known_child ... ok +test classify::tests::caches_are_reclaimable_all_the_way_down ... ok +test removal::tests::a_directory_holding_a_system_tree_is_refused ... ok +test removal::tests::a_directory_holding_the_home_directory_is_refused ... ok +test macos::tests::a_missing_directory_is_an_error ... ok +test removal::tests::macos_always_uses_the_system_trash ... ok +test removal::tests::macos_guard_keys_fold_the_data_volume_and_case ... ok +test removal::tests::macos_guards_see_through_other_spellings ... ok +test removal::tests::macos_system_trees_are_refused_but_apps_are_not ... ok +test removal::tests::a_name_that_is_not_utf8_is_refused_before_the_trash_sees_it ... ok +test removal::tests::names_win32_would_misread_are_recognized ... ok +test macos::tests::a_listing_has_names_kinds_lengths_and_no_dot_entries ... ok +test removal::tests::nesting_keeps_component_boundaries_duplicates_and_output_order ... ok +test removal::tests::normalize_resolves_dots_without_the_filesystem ... ok +test macos::tests::names_are_text_and_open ... ok +test removal::tests::nesting_uses_guard_case_order_even_when_the_child_sorts_first ... ok +test macos::tests::every_leaf_reads_as_lstat_reads_it ... ok +test removal::tests::a_mount_below_a_target_is_caught_again_at_removal_time ... ok +test removal::tests::a_volume_is_judged_by_its_mount_where_the_kernel_names_one ... ok +test removal::tests::percent_encoding_escapes_what_the_spec_requires ... ok +test removal::tests::a_missing_target_reports_not_found ... ok +test removal::tests::a_plan_keeps_only_the_outermost_targets ... ok +test removal::tests::a_target_with_a_mount_inside_is_refused ... ok +test removal::tests::mount_points_are_recognized ... ok +test removal::tests::a_trash_info_path_is_restorable ... ok +test removal::tests::a_target_reached_through_a_link_is_refused ... ok +test removal::tests::paths_outside_the_root_are_refused ... ok +test removal::tests::permanent_removal_takes_directories_and_leaves_siblings ... ok +test removal::tests::a_removal_run_reports_every_item_and_a_total ... ok +test removal::tests::the_macos_trash_takes_a_file_and_leaves_a_linked_target ... ignored, puts a file in this Mac's real Trash +test removal::tests::home_is_found_by_its_real_path_too ... ok +test removal::tests::permanent_removal_follows_links_above_the_root ... ok +test removal::tests::permanent_removal_does_not_follow_a_link_put_on_the_way_down ... ok +test removal::tests::permanent_removal_unlinks_nested_symlinks_without_following_them ... ok +test removal::tests::permanent_removal_takes_nested_trees_and_hidden_files ... ok +test removal::tests::permanent_removal_unlinks_a_symlink_instead_of_following_it ... ok +test removal::tests::nothing_is_mounted_below_a_temp_dir ... ok +test removal::tests::read_only_files_are_removed_too ... ok +test removal::tests::sibling_prefixes_are_not_treated_as_containment ... ok +test removal::tests::a_link_put_on_the_way_down_after_planning_stops_the_worker ... ok +test removal::tests::the_mount_table_is_read_off_the_calling_thread_and_then_kept ... ok +test removal::tests::trash_names_avoid_collisions ... ok +test removal::tests::the_root_and_home_are_refused ... ok +test removal::tests::the_xdg_trash_moves_a_file_and_records_where_it_came_from ... ok +test scan::tests::a_file_root_is_rejected ... ok +test scan::tests::fixed_worker_pools_change_size_without_reinitializing_rayon ... ok +test removal::tests::this_macs_mount_table_is_read_without_proc ... ok +test scan::tests::disk_usage_is_whole_allocation_units ... ok +test scan::tests::followed_symlink_loops_do_not_hang_the_scan ... ok +test scan::tests::hardlinks_are_charged_once_by_default ... ok +test scan::tests::an_unreadable_directory_is_recorded_not_fatal ... ok +test scan::tests::a_spawned_scan_reports_progress_and_a_result ... ok +test scan::tests::a_directory_reports_its_own_bytes_separately ... ok +test scan::tests::whole_disk_smoke ... ignored, walks the whole disk +test scan::tests::children_are_ranked_largest_first ... ok +test scan_threads::tests::governor_waits_for_retirement_and_recovers_without_exceeding_target ... ok +test scan_threads::tests::inconclusive_windows_cannot_accept_a_reduction ... ok +test scan_threads::tests::increased_limit_is_not_supplied_until_jobs_are_dispatched ... ok +test scan_threads::tests::long_directory_never_becomes_a_fully_supplied_window ... ok +test scan_threads::tests::search_refines_one_reference_without_compounding_loss ... ok +test size::tests::a_value_that_rounds_up_to_the_next_unit_is_shown_in_it ... ok +test size::tests::bytes_use_binary_units_with_one_decimal_below_ten ... ok +test size::tests::counts_switch_to_metric_suffixes ... ok +test size::tests::share_bar_is_always_the_requested_width ... ok +test scan_threads::tests::real_pool_retires_at_job_boundaries_and_drains_queued_descendants ... ok +test size::tests::share_survives_a_zero_total ... ok +test size::tests::short_form_drops_the_space ... ok +test space::tests::a_bind_mount_inside_the_scan_is_left_out ... ok +test space::tests::a_home_scan_has_no_foreign_mounts_here ... ok +test space::tests::a_missing_path_reports_the_io_error ... ok +test space::tests::a_real_volume_reports_plausible_numbers ... ok +test space::tests::a_root_booted_from_a_snapshot_keeps_its_subvolumes ... ok +test space::tests::a_table_that_does_not_place_a_path_claims_nothing ... ok +test space::tests::a_volume_includes_its_subvolumes_and_nothing_else ... ok +test space::tests::a_volume_keeps_its_subvolumes_and_loses_everything_else ... ok +test space::tests::btrfs_subvolume_devices_can_differ ... ok +test space::tests::excluded_views_cannot_replace_visible_files ... ok +test space::tests::hidden_original_and_nested_mounts_are_preserved ... ok +test space::tests::macos_mount_points_keep_spaces_and_brackets ... ok +test space::tests::mountinfo_escapes_are_decoded_once ... ok +test space::tests::only_macos_skips_the_data_volume_and_in_the_roots_spelling ... ok +test space::tests::projecting_removal_cannot_exceed_the_volume ... ok +test space::tests::separate_home_disk_is_its_own_volume ... ok +test space::tests::subvolumes_are_not_repeats_but_a_second_mount_of_a_disk_is ... ok +test space::tests::the_device_is_the_longest_matching_mount ... ok +test scan::tests::file_count_metric_ranks_by_entries ... ok +test space::tests::the_home_disk_on_macos_is_the_root_and_has_a_device ... ok +test space::tests::the_top_of_a_btrfs_disk_beside_its_subvolumes_is_counted_once ... ok +test space::tests::the_whole_disk_is_the_top_of_the_home_volume ... ok +test space::tests::unrelated_tmpfs_mounts_are_not_duplicates ... ok +test space::tests::used_fraction_handles_an_empty_volume_report ... ok +test space::tests::volume_candidates_are_real_disks_not_pseudo_filesystems ... ok +test space::tests::volumes_with_least_space_come_first_and_unknowns_last ... ok +test tree::tests::a_node_stays_small ... ok +test tree::tests::aggregate_derives_totals_and_orders_children ... ok +test scan::tests::a_wider_scan_reuses_the_subtree_it_already_knows ... ok +test tree::tests::depth_counts_edges ... ok +test tree::tests::find_reports_crumbs_and_is_case_insensitive ... ok +test tree::tests::aggregate_can_rank_by_file_count ... ok +test tree::tests::identities_that_differ_only_in_their_top_bits_are_two_files ... ok +test tree::tests::largest_child_is_the_first_child_because_children_are_sorted ... ok +test tree::tests::path_of_joins_names_beneath_the_root ... ok +test tree::tests::resolve_walks_child_indices ... ok +test treemap::tests::a_leaf_never_claims_a_header ... ok +test treemap::tests::a_filtered_layout_shows_only_the_matches_at_their_size ... ok +test treemap::tests::a_subdivided_directory_keeps_a_header_for_its_own_name ... ok +test treemap::tests::a_tile_without_room_for_a_header_stays_whole ... ok +test treemap::tests::hit_returns_the_deepest_tile ... ok +test treemap::tests::layout_depth_one_stops_at_direct_children ... ok +test tree::tests::seen_charges_an_identity_once_in_either_store ... ok +test treemap::tests::layout_merges_the_child_tail_into_one_tile ... ok +test treemap::tests::squarify_fills_the_area ... ok +test treemap::tests::layout_nests_children_inside_their_parent ... ok +test space::tests::without_a_table_the_same_place_is_one_volume ... ok +test scan::tests::hidden_entries_are_included_by_default_and_excluded_on_request ... ok +test treemap::tests::squarify_keeps_aspect_ratios_reasonable ... ok +test treemap::tests::squarify_survives_degenerate_input ... ok +test treemap::tests::tile_crumbs_address_the_scanned_tree_not_the_drawn_node ... ok +test scan::tests::max_depth_stops_descending_but_keeps_direct_files ... ok +test scan::tests::symlinks_are_not_followed_by_default ... ok +test scan::tests::totals_are_summed_bottom_up ... ok +test removal::tests::system_trees_are_refused_in_a_whole_disk_scan ... ok +test removal::tests::the_directories_above_home_are_refused ... ok +test removal::tests::removal_nesting_budget ... ok +test scan::tests::cancelled_queued_jobs_release_parent_completion_tokens ... ok +test scan::tests::fixed_worker_pools_preserve_a_wide_deep_tree ... ok +test removal::tests::only_the_scanned_volumes_marks_are_projected ... ok +test removal::tests::a_failing_trash_tool_reports_its_stderr ... ok +test scan_threads::tests::controller_retires_recovers_after_search_and_cancels ... ok +test macos::tests::a_directory_larger_than_the_buffer_is_listed_whole ... ok +test removal::tests::a_trash_tool_is_called_with_the_path_after_a_separator ... ok + +test result: ok. 150 passed; 0 failed; 2 ignored; 0 measured; 0 filtered out; finished in 0.28s + + Running unittests src/main.rs (target/debug/deps/xtask-0dc2df263f51d89e) + +running 3 tests +test bundle::tests::signing_is_ad_hoc_unless_an_identity_is_given ... ok +test bundle::tests::the_plist_template_names_the_executable_and_takes_the_version ... ok +test bundle::tests::notarizing_needs_a_real_signature ... ok + +test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s + + Doc-tests disktree_core + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s + diff --git a/docs/performance/mark-resolution/expanded/wall-after.log b/docs/performance/mark-resolution/expanded/wall-after.log new file mode 100644 index 00000000..21a9e7eb --- /dev/null +++ b/docs/performance/mark-resolution/expanded/wall-after.log @@ -0,0 +1,127 @@ +REPEAT 1: sources at combined fix b71718f + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Finished `test` profile [optimized + debuginfo] target(s) in 4.24s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 9 tests +test argument_tests::adaptive_budget_and_fixed_override_are_explicit ... ok +test argument_tests::invalid_worker_budgets_are_rejected ... ok +test marks::tests::refresh_dimension_budget ... dimensions folders=128 M=8 D=2 R=1 work=160 wall=144.833µs +dimensions folders=1024 M=8 D=2 R=1 work=1056 wall=62.791µs +dimensions folders=1024 M=64 D=2 R=1 work=1280 wall=74.667µs +dimensions folders=128 M=8 D=16 R=1 work=384 wall=38.75µs +dimensions folders=128 M=8 D=2 R=8 work=1280 wall=87.5µs +ok +test marks::tests::refresh_resolution_budget ... refresh M=128 N=256 R=4 work=2560 wall=295.792µs +refresh M=1024 N=2048 R=4 work=20480 wall=1.906625ms +ok +test tests::blocked_review_status_budget ... review-status covered=false M=128 work=3072 renders=8 rows=128 per-render=384 wall=107.559125ms +review-status covered=false M=1024 work=24576 renders=8 rows=1024 per-render=3072 wall=883.20225ms +review-status covered=false M=8192 work=84736 renders=8 rows=1200 per-render=10592 wall=1.196734875s +ok +test tests::covered_review_status_budget ... review-status covered=true M=128 work=3088 renders=8 rows=129 per-render=386 wall=122.079458ms +review-status covered=true M=1024 work=24592 renders=8 rows=1025 per-render=3074 wall=997.160667ms +review-status covered=true M=8192 work=84736 renders=8 rows=1200 per-render=10592 wall=2.106200625s +ok +test tests::marked_window_resolution_budget ... warm window M=128 prepares=8 resolution=216 tiles=1544 wall=59.356875ms +window M=128 N=256 draws=4 prepares=8 work=856 wall=60.529083ms +warm window M=1024 prepares=8 resolution=216 tiles=776 wall=331.029917ms +window M=1024 N=2048 draws=4 prepares=8 work=5336 wall=335.875875ms +ok +test tests::parent_absorption_budget ... parent-absorption M=128 work=266 compactions=130 wall=58.125µs +parent-absorption M=1024 work=2058 compactions=1026 wall=467.083µs +ok +test tests::queue_construction_budget ... queue-construction M=128 work=1152 wall=542µs +queue-construction M=1024 work=9216 wall=6.311584ms +ok + +test result: ok. 9 passed; 0 failed; 0 ignored; 0 measured; 79 filtered out; finished in 6.71s + + +EXIT 0 +REPEAT 2: sources at combined fix b71718f + Finished `test` profile [optimized + debuginfo] target(s) in 0.27s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 9 tests +test argument_tests::adaptive_budget_and_fixed_override_are_explicit ... ok +test argument_tests::invalid_worker_budgets_are_rejected ... ok +test marks::tests::refresh_dimension_budget ... dimensions folders=128 M=8 D=2 R=1 work=160 wall=25.25µs +dimensions folders=1024 M=8 D=2 R=1 work=1056 wall=42.666µs +dimensions folders=1024 M=64 D=2 R=1 work=1280 wall=51.75µs +dimensions folders=128 M=8 D=16 R=1 work=384 wall=24.5µs +dimensions folders=128 M=8 D=2 R=8 work=1280 wall=56.75µs +ok +test marks::tests::refresh_resolution_budget ... refresh M=128 N=256 R=4 work=2560 wall=198.292µs +refresh M=1024 N=2048 R=4 work=20480 wall=1.479125ms +ok +test tests::blocked_review_status_budget ... review-status covered=false M=128 work=3072 renders=8 rows=128 per-render=384 wall=105.373709ms +review-status covered=false M=1024 work=24576 renders=8 rows=1024 per-render=3072 wall=883.687ms +review-status covered=false M=8192 work=84736 renders=8 rows=1200 per-render=10592 wall=1.188244s +ok +test tests::covered_review_status_budget ... review-status covered=true M=128 work=3088 renders=8 rows=129 per-render=386 wall=122.092208ms +review-status covered=true M=1024 work=24592 renders=8 rows=1025 per-render=3074 wall=1.010354417s +review-status covered=true M=8192 work=84736 renders=8 rows=1200 per-render=10592 wall=2.112680083s +ok +test tests::marked_window_resolution_budget ... warm window M=128 prepares=8 resolution=216 tiles=1544 wall=61.657666ms +window M=128 N=256 draws=4 prepares=8 work=856 wall=61.290042ms +warm window M=1024 prepares=8 resolution=216 tiles=776 wall=335.296459ms +window M=1024 N=2048 draws=4 prepares=8 work=5336 wall=333.089792ms +ok +test tests::parent_absorption_budget ... parent-absorption M=128 work=266 compactions=130 wall=57.125µs +parent-absorption M=1024 work=2058 compactions=1026 wall=481.292µs +ok +test tests::queue_construction_budget ... queue-construction M=128 work=1152 wall=547.333µs +queue-construction M=1024 work=9216 wall=6.518083ms +ok + +test result: ok. 9 passed; 0 failed; 0 ignored; 0 measured; 79 filtered out; finished in 6.70s + + +EXIT 0 +REPEAT 3: sources at combined fix b71718f + Finished `test` profile [optimized + debuginfo] target(s) in 0.26s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 9 tests +test argument_tests::adaptive_budget_and_fixed_override_are_explicit ... ok +test argument_tests::invalid_worker_budgets_are_rejected ... ok +test marks::tests::refresh_dimension_budget ... dimensions folders=128 M=8 D=2 R=1 work=160 wall=25.583µs +dimensions folders=1024 M=8 D=2 R=1 work=1056 wall=42.583µs +dimensions folders=1024 M=64 D=2 R=1 work=1280 wall=51.292µs +dimensions folders=128 M=8 D=16 R=1 work=384 wall=26.042µs +dimensions folders=128 M=8 D=2 R=8 work=1280 wall=59.083µs +ok +test marks::tests::refresh_resolution_budget ... refresh M=128 N=256 R=4 work=2560 wall=214µs +refresh M=1024 N=2048 R=4 work=20480 wall=1.552917ms +ok +test tests::blocked_review_status_budget ... review-status covered=false M=128 work=3072 renders=8 rows=128 per-render=384 wall=108.225542ms +review-status covered=false M=1024 work=24576 renders=8 rows=1024 per-render=3072 wall=886.057917ms +review-status covered=false M=8192 work=84736 renders=8 rows=1200 per-render=10592 wall=1.19339425s +ok +test tests::covered_review_status_budget ... review-status covered=true M=128 work=3088 renders=8 rows=129 per-render=386 wall=122.399375ms +review-status covered=true M=1024 work=24592 renders=8 rows=1025 per-render=3074 wall=1.009629625s +review-status covered=true M=8192 work=84736 renders=8 rows=1200 per-render=10592 wall=2.127712375s +ok +test tests::marked_window_resolution_budget ... warm window M=128 prepares=8 resolution=216 tiles=1544 wall=61.806167ms +window M=128 N=256 draws=4 prepares=8 work=856 wall=61.474458ms +warm window M=1024 prepares=8 resolution=216 tiles=776 wall=351.863667ms +window M=1024 N=2048 draws=4 prepares=8 work=5336 wall=336.533542ms +ok +test tests::parent_absorption_budget ... parent-absorption M=128 work=266 compactions=130 wall=57.75µs +parent-absorption M=1024 work=2058 compactions=1026 wall=459.042µs +ok +test tests::queue_construction_budget ... queue-construction M=128 work=1152 wall=547.75µs +queue-construction M=1024 work=9216 wall=6.406375ms +ok + +test result: ok. 9 passed; 0 failed; 0 ignored; 0 measured; 79 filtered out; finished in 6.76s + + +EXIT 0 diff --git a/docs/performance/mark-resolution/expanded/wall-before.log b/docs/performance/mark-resolution/expanded/wall-before.log new file mode 100644 index 00000000..d2c6de76 --- /dev/null +++ b/docs/performance/mark-resolution/expanded/wall-before.log @@ -0,0 +1,187 @@ +REPEAT 1: sources at red commit 57d4efd + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Finished `test` profile [optimized + debuginfo] target(s) in 6.29s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 9 tests +test argument_tests::adaptive_budget_and_fixed_override_are_explicit ... ok +test argument_tests::invalid_worker_budgets_are_rejected ... ok +test marks::tests::refresh_dimension_budget ... dimensions folders=128 M=8 D=2 R=1 work=160 wall=88.833µs +dimensions folders=1024 M=8 D=2 R=1 work=1056 wall=66.209µs +dimensions folders=1024 M=64 D=2 R=1 work=1280 wall=72.458µs +dimensions folders=128 M=8 D=16 R=1 work=384 wall=40.208µs +dimensions folders=128 M=8 D=2 R=8 work=1280 wall=96.25µs +ok +test marks::tests::refresh_resolution_budget ... refresh M=128 N=256 R=4 work=2560 wall=292.5µs +refresh M=1024 N=2048 R=4 work=20480 wall=1.89825ms +ok +test tests::blocked_review_status_budget ... review-status covered=false M=128 work=66048 renders=8 rows=128 per-render=8256 wall=111.492791ms +review-status covered=false M=1024 work=4198400 renders=8 rows=1024 per-render=524800 wall=1.003875917s + +thread 'tests::blocked_review_status_budget' (404509605) panicked at crates/disktree-app/src/tests.rs:2298:5: +8x status rows: 66048/8 -> 4198400/8 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace +FAILED +test tests::covered_review_status_budget ... review-status covered=true M=128 work=67072 renders=8 rows=129 per-render=8384 wall=122.635083ms +review-status covered=true M=1024 work=4206592 renders=8 rows=1025 per-render=525824 wall=1.110662959s + +thread 'tests::covered_review_status_budget' (404509677) panicked at crates/disktree-app/src/tests.rs:2298:5: +8x status rows: 67072/8 -> 4206592/8 +FAILED +test tests::marked_window_resolution_budget ... warm window M=128 prepares=8 resolution=216 tiles=1544 wall=60.112708ms +window M=128 N=256 draws=4 prepares=8 work=856 wall=61.191625ms +warm window M=1024 prepares=8 resolution=216 tiles=776 wall=333.839916ms +window M=1024 N=2048 draws=4 prepares=8 work=5336 wall=332.639625ms +ok +test tests::parent_absorption_budget ... parent-absorption M=128 work=8771 compactions=8512 wall=332.125µs +parent-absorption M=1024 work=528899 compactions=526848 wall=15.169208ms + +thread 'tests::parent_absorption_budget' (404509733) panicked at crates/disktree-app/src/tests.rs:2223:5: +8x descendants: 8771 -> 528899 +FAILED +test tests::queue_construction_budget ... queue-construction M=128 work=16384 wall=2.928667ms +queue-construction M=1024 work=1048576 wall=176.133125ms + +thread 'tests::queue_construction_budget' (404509745) panicked at crates/disktree-app/src/tests.rs:2181:5: +8x marks: 16384 -> 1048576 +FAILED + +failures: + +failures: + tests::blocked_review_status_budget + tests::covered_review_status_budget + tests::parent_absorption_budget + tests::queue_construction_budget + +test result: FAILED. 5 passed; 4 failed; 0 ignored; 0 measured; 74 filtered out; finished in 3.77s + +error: test failed, to rerun pass `-p disktree-app --bin disktree` + +EXIT 101 +REPEAT 2: sources at red commit 57d4efd + Finished `test` profile [optimized + debuginfo] target(s) in 0.26s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 9 tests +test argument_tests::adaptive_budget_and_fixed_override_are_explicit ... ok +test argument_tests::invalid_worker_budgets_are_rejected ... ok +test marks::tests::refresh_dimension_budget ... dimensions folders=128 M=8 D=2 R=1 work=160 wall=19.958µs +dimensions folders=1024 M=8 D=2 R=1 work=1056 wall=43.5µs +dimensions folders=1024 M=64 D=2 R=1 work=1280 wall=49.75µs +dimensions folders=128 M=8 D=16 R=1 work=384 wall=29.916µs +dimensions folders=128 M=8 D=2 R=8 work=1280 wall=59.417µs +ok +test marks::tests::refresh_resolution_budget ... refresh M=128 N=256 R=4 work=2560 wall=206.042µs +refresh M=1024 N=2048 R=4 work=20480 wall=1.547208ms +ok +test tests::blocked_review_status_budget ... review-status covered=false M=128 work=66048 renders=8 rows=128 per-render=8256 wall=113.726291ms +review-status covered=false M=1024 work=4198400 renders=8 rows=1024 per-render=524800 wall=1.030923916s + +thread 'tests::blocked_review_status_budget' (404509806) panicked at crates/disktree-app/src/tests.rs:2298:5: +8x status rows: 66048/8 -> 4198400/8 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace +FAILED +test tests::covered_review_status_budget ... review-status covered=true M=128 work=67072 renders=8 rows=129 per-render=8384 wall=123.684209ms +review-status covered=true M=1024 work=4206592 renders=8 rows=1025 per-render=525824 wall=1.122654292s + +thread 'tests::covered_review_status_budget' (404509980) panicked at crates/disktree-app/src/tests.rs:2298:5: +8x status rows: 67072/8 -> 4206592/8 +FAILED +test tests::marked_window_resolution_budget ... warm window M=128 prepares=8 resolution=216 tiles=1544 wall=60.245708ms +window M=128 N=256 draws=4 prepares=8 work=856 wall=61.801583ms +warm window M=1024 prepares=8 resolution=216 tiles=776 wall=341.867208ms +window M=1024 N=2048 draws=4 prepares=8 work=5336 wall=350.583125ms +ok +test tests::parent_absorption_budget ... parent-absorption M=128 work=8771 compactions=8512 wall=327.959µs +parent-absorption M=1024 work=528899 compactions=526848 wall=15.596208ms + +thread 'tests::parent_absorption_budget' (404510061) panicked at crates/disktree-app/src/tests.rs:2223:5: +8x descendants: 8771 -> 528899 +FAILED +test tests::queue_construction_budget ... queue-construction M=128 work=16384 wall=2.95175ms +queue-construction M=1024 work=1048576 wall=184.469666ms + +thread 'tests::queue_construction_budget' (404510074) panicked at crates/disktree-app/src/tests.rs:2181:5: +8x marks: 16384 -> 1048576 +FAILED + +failures: + +failures: + tests::blocked_review_status_budget + tests::covered_review_status_budget + tests::parent_absorption_budget + tests::queue_construction_budget + +test result: FAILED. 5 passed; 4 failed; 0 ignored; 0 measured; 74 filtered out; finished in 3.81s + +error: test failed, to rerun pass `-p disktree-app --bin disktree` + +EXIT 101 +REPEAT 3: sources at red commit 57d4efd + Finished `test` profile [optimized + debuginfo] target(s) in 0.26s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 9 tests +test argument_tests::adaptive_budget_and_fixed_override_are_explicit ... ok +test argument_tests::invalid_worker_budgets_are_rejected ... ok +test marks::tests::refresh_dimension_budget ... dimensions folders=128 M=8 D=2 R=1 work=160 wall=19.625µs +dimensions folders=1024 M=8 D=2 R=1 work=1056 wall=44.666µs +dimensions folders=1024 M=64 D=2 R=1 work=1280 wall=52.459µs +dimensions folders=128 M=8 D=16 R=1 work=384 wall=24.583µs +dimensions folders=128 M=8 D=2 R=8 work=1280 wall=61.791µs +ok +test marks::tests::refresh_resolution_budget ... refresh M=128 N=256 R=4 work=2560 wall=199.917µs +refresh M=1024 N=2048 R=4 work=20480 wall=1.529833ms +ok +test tests::blocked_review_status_budget ... review-status covered=false M=128 work=66048 renders=8 rows=128 per-render=8256 wall=108.861834ms +review-status covered=false M=1024 work=4198400 renders=8 rows=1024 per-render=524800 wall=999.468209ms + +thread 'tests::blocked_review_status_budget' (404510132) panicked at crates/disktree-app/src/tests.rs:2298:5: +8x status rows: 66048/8 -> 4198400/8 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace +FAILED +test tests::covered_review_status_budget ... review-status covered=true M=128 work=67072 renders=8 rows=129 per-render=8384 wall=124.821916ms +review-status covered=true M=1024 work=4206592 renders=8 rows=1025 per-render=525824 wall=1.110591625s + +thread 'tests::covered_review_status_budget' (404510197) panicked at crates/disktree-app/src/tests.rs:2298:5: +8x status rows: 67072/8 -> 4206592/8 +FAILED +test tests::marked_window_resolution_budget ... warm window M=128 prepares=8 resolution=216 tiles=1544 wall=59.989667ms +window M=128 N=256 draws=4 prepares=8 work=856 wall=61.309958ms +warm window M=1024 prepares=8 resolution=216 tiles=776 wall=341.035208ms +window M=1024 N=2048 draws=4 prepares=8 work=5336 wall=332.707042ms +ok +test tests::parent_absorption_budget ... parent-absorption M=128 work=8771 compactions=8512 wall=336µs +parent-absorption M=1024 work=528899 compactions=526848 wall=15.915917ms + +thread 'tests::parent_absorption_budget' (404510244) panicked at crates/disktree-app/src/tests.rs:2223:5: +8x descendants: 8771 -> 528899 +FAILED +test tests::queue_construction_budget ... queue-construction M=128 work=16384 wall=2.838333ms +queue-construction M=1024 work=1048576 wall=175.767541ms + +thread 'tests::queue_construction_budget' (404510255) panicked at crates/disktree-app/src/tests.rs:2181:5: +8x marks: 16384 -> 1048576 +FAILED + +failures: + +failures: + tests::blocked_review_status_budget + tests::covered_review_status_budget + tests::parent_absorption_budget + tests::queue_construction_budget + +test result: FAILED. 5 passed; 4 failed; 0 ignored; 0 measured; 74 filtered out; finished in 3.72s + +error: test failed, to rerun pass `-p disktree-app --bin disktree` + +EXIT 101 diff --git a/docs/performance/mark-resolution/green.log b/docs/performance/mark-resolution/green.log new file mode 100644 index 00000000..64b445ee --- /dev/null +++ b/docs/performance/mark-resolution/green.log @@ -0,0 +1,40 @@ + Finished `test` profile [optimized + debuginfo] target(s) in 0.26s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 5 tests +test argument_tests::invalid_worker_budgets_are_rejected ... ok +test argument_tests::adaptive_budget_and_fixed_override_are_explicit ... ok +dimensions folders=128 M=8 D=2 R=1 work=160 wall=30.334µs +refresh M=128 N=256 R=4 work=2560 wall=241.75µs +dimensions folders=1024 M=8 D=2 R=1 work=1056 wall=46.917µs +dimensions folders=1024 M=64 D=2 R=1 work=1280 wall=71.5µs +dimensions folders=128 M=8 D=16 R=1 work=384 wall=45µs +dimensions folders=128 M=8 D=2 R=8 work=1280 wall=88.459µs +test marks::tests::refresh_dimension_budget ... ok +refresh M=1024 N=2048 R=4 work=20480 wall=1.580625ms +test marks::tests::refresh_resolution_budget ... ok +warm window M=128 prepares=8 resolution=216 tiles=1544 wall=61.302208ms +window M=128 N=256 draws=4 prepares=8 work=856 wall=61.50175ms +warm window M=1024 prepares=8 resolution=216 tiles=776 wall=354.14925ms +window M=1024 N=2048 draws=4 prepares=8 work=5336 wall=341.058584ms +test tests::marked_window_resolution_budget ... ok + +test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 73 filtered out; finished in 0.87s + + Running unittests src/lib.rs (target/debug/deps/disktree_core-9300e5ba20d6b25f) + +running 1 test +plan M=128 work=1314 wall=2.802916ms +plan M=1024 work=15298 wall=21.911541ms +test removal::tests::removal_nesting_budget ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 151 filtered out; finished in 0.03s + + Running unittests src/main.rs (target/debug/deps/xtask-0dc2df263f51d89e) + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 3 filtered out; finished in 0.00s + diff --git a/docs/performance/mark-resolution/interactions-green.log b/docs/performance/mark-resolution/interactions-green.log new file mode 100644 index 00000000..a17c207c --- /dev/null +++ b/docs/performance/mark-resolution/interactions-green.log @@ -0,0 +1,65 @@ + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Finished `test` profile [optimized + debuginfo] target(s) in 2.78s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 1 test +test tests::marked_interaction_timings ... interaction action=mark-space repeat=1 marks=0->1 renders=3 prepares=3 plans=6 refreshes=0 wall=3.678416ms +interaction action=hover repeat=1 marks=1->1 renders=2 prepares=2 plans=4 refreshes=0 wall=2.546375ms +interaction action=review-c repeat=1 marks=1->1 renders=3 prepares=1 plans=4 refreshes=0 wall=2.183334ms +interaction action=mark-space repeat=2 marks=0->1 renders=2 prepares=2 plans=4 refreshes=0 wall=2.440541ms +interaction action=hover repeat=2 marks=1->1 renders=2 prepares=2 plans=4 refreshes=0 wall=2.752917ms +interaction action=review-c repeat=2 marks=1->1 renders=3 prepares=1 plans=4 refreshes=0 wall=2.195ms +interaction action=mark-space repeat=3 marks=0->1 renders=2 prepares=2 plans=4 refreshes=0 wall=2.512208ms +interaction action=hover repeat=3 marks=1->1 renders=2 prepares=2 plans=4 refreshes=0 wall=2.463708ms +interaction action=review-c repeat=3 marks=1->1 renders=3 prepares=1 plans=4 refreshes=0 wall=2.125291ms +interaction action=mark-space repeat=1 marks=1->2 renders=3 prepares=3 plans=6 refreshes=0 wall=3.916458ms +interaction action=hover repeat=1 marks=2->2 renders=2 prepares=2 plans=4 refreshes=0 wall=2.693916ms +interaction action=review-c repeat=1 marks=2->2 renders=3 prepares=1 plans=4 refreshes=0 wall=2.467208ms +interaction action=mark-space repeat=2 marks=1->2 renders=2 prepares=2 plans=4 refreshes=0 wall=2.570084ms +interaction action=hover repeat=2 marks=2->2 renders=2 prepares=2 plans=4 refreshes=0 wall=2.661209ms +interaction action=review-c repeat=2 marks=2->2 renders=3 prepares=1 plans=4 refreshes=0 wall=2.573834ms +interaction action=mark-space repeat=3 marks=1->2 renders=2 prepares=2 plans=4 refreshes=0 wall=2.588833ms +interaction action=hover repeat=3 marks=2->2 renders=2 prepares=2 plans=4 refreshes=0 wall=2.671125ms +interaction action=review-c repeat=3 marks=2->2 renders=3 prepares=1 plans=4 refreshes=0 wall=2.675084ms +interaction action=mark-space repeat=1 marks=8->9 renders=3 prepares=3 plans=6 refreshes=0 wall=5.180041ms +interaction action=hover repeat=1 marks=9->9 renders=2 prepares=2 plans=4 refreshes=0 wall=3.608791ms +interaction action=review-c repeat=1 marks=9->9 renders=3 prepares=1 plans=4 refreshes=0 wall=4.043208ms +interaction action=mark-space repeat=2 marks=8->9 renders=2 prepares=2 plans=4 refreshes=0 wall=3.50525ms +interaction action=hover repeat=2 marks=9->9 renders=2 prepares=2 plans=4 refreshes=0 wall=3.503375ms +interaction action=review-c repeat=2 marks=9->9 renders=3 prepares=1 plans=4 refreshes=0 wall=4.018792ms +interaction action=mark-space repeat=3 marks=8->9 renders=2 prepares=2 plans=4 refreshes=0 wall=3.820917ms +interaction action=hover repeat=3 marks=9->9 renders=2 prepares=2 plans=4 refreshes=0 wall=4.015208ms +interaction action=review-c repeat=3 marks=9->9 renders=3 prepares=1 plans=4 refreshes=0 wall=4.169958ms +interaction action=mark-space repeat=1 marks=32->33 renders=3 prepares=3 plans=6 refreshes=0 wall=7.792416ms +interaction action=hover repeat=1 marks=33->33 renders=2 prepares=2 plans=4 refreshes=0 wall=5.2135ms +interaction action=review-c repeat=1 marks=33->33 renders=3 prepares=1 plans=4 refreshes=0 wall=8.745875ms +interaction action=mark-space repeat=2 marks=32->33 renders=2 prepares=2 plans=4 refreshes=0 wall=5.241834ms +interaction action=hover repeat=2 marks=33->33 renders=2 prepares=2 plans=4 refreshes=0 wall=5.400709ms +interaction action=review-c repeat=2 marks=33->33 renders=3 prepares=1 plans=4 refreshes=0 wall=8.7555ms +interaction action=mark-space repeat=3 marks=32->33 renders=2 prepares=2 plans=4 refreshes=0 wall=5.447334ms +interaction action=hover repeat=3 marks=33->33 renders=2 prepares=2 plans=4 refreshes=0 wall=5.865541ms +interaction action=review-c repeat=3 marks=33->33 renders=3 prepares=1 plans=4 refreshes=0 wall=9.197958ms +interaction action=mark-space repeat=1 marks=128->129 renders=3 prepares=3 plans=6 refreshes=0 wall=19.085708ms +interaction action=hover repeat=1 marks=129->129 renders=2 prepares=2 plans=4 refreshes=0 wall=13.022875ms +interaction action=review-c repeat=1 marks=129->129 renders=3 prepares=1 plans=4 refreshes=0 wall=30.691375ms +interaction action=mark-space repeat=2 marks=128->129 renders=2 prepares=2 plans=4 refreshes=0 wall=14.717709ms +interaction action=hover repeat=2 marks=129->129 renders=2 prepares=2 plans=4 refreshes=0 wall=14.473875ms +interaction action=review-c repeat=2 marks=129->129 renders=3 prepares=1 plans=4 refreshes=0 wall=30.634125ms +interaction action=mark-space repeat=3 marks=128->129 renders=2 prepares=2 plans=4 refreshes=0 wall=12.734667ms +interaction action=hover repeat=3 marks=129->129 renders=2 prepares=2 plans=4 refreshes=0 wall=12.695834ms +interaction action=review-c repeat=3 marks=129->129 renders=3 prepares=1 plans=4 refreshes=0 wall=30.7185ms +interaction action=mark-space repeat=1 marks=1024->1025 renders=3 prepares=3 plans=6 refreshes=0 wall=113.33325ms +interaction action=hover repeat=1 marks=1025->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=94.280958ms +interaction action=review-c repeat=1 marks=1025->1025 renders=3 prepares=1 plans=4 refreshes=0 wall=247.047292ms +interaction action=mark-space repeat=2 marks=1024->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=76.356875ms +interaction action=hover repeat=2 marks=1025->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=74.409208ms +interaction action=review-c repeat=2 marks=1025->1025 renders=3 prepares=1 plans=4 refreshes=0 wall=242.707958ms +interaction action=mark-space repeat=3 marks=1024->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=77.313917ms +interaction action=hover repeat=3 marks=1025->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=74.570667ms +interaction action=review-c repeat=3 marks=1025->1025 renders=3 prepares=1 plans=4 refreshes=0 wall=237.816292ms +ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 78 filtered out; finished in 3.16s + diff --git a/docs/performance/mark-resolution/interactions-red.log b/docs/performance/mark-resolution/interactions-red.log new file mode 100644 index 00000000..a913f804 --- /dev/null +++ b/docs/performance/mark-resolution/interactions-red.log @@ -0,0 +1,66 @@ + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Compiling disktree-core v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-core) + Finished `test` profile [optimized + debuginfo] target(s) in 3.91s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 1 test +test tests::marked_interaction_timings ... interaction action=mark-space repeat=1 marks=0->1 renders=3 prepares=3 plans=6 refreshes=0 wall=3.866334ms +interaction action=hover repeat=1 marks=1->1 renders=2 prepares=2 plans=4 refreshes=0 wall=2.832708ms +interaction action=review-c repeat=1 marks=1->1 renders=3 prepares=1 plans=4 refreshes=0 wall=2.252292ms +interaction action=mark-space repeat=2 marks=0->1 renders=2 prepares=2 plans=4 refreshes=0 wall=2.443ms +interaction action=hover repeat=2 marks=1->1 renders=2 prepares=2 plans=4 refreshes=0 wall=2.800667ms +interaction action=review-c repeat=2 marks=1->1 renders=3 prepares=1 plans=4 refreshes=0 wall=2.211042ms +interaction action=mark-space repeat=3 marks=0->1 renders=2 prepares=2 plans=4 refreshes=0 wall=2.408125ms +interaction action=hover repeat=3 marks=1->1 renders=2 prepares=2 plans=4 refreshes=0 wall=2.487209ms +interaction action=review-c repeat=3 marks=1->1 renders=3 prepares=1 plans=4 refreshes=0 wall=2.212542ms +interaction action=mark-space repeat=1 marks=1->2 renders=3 prepares=3 plans=6 refreshes=0 wall=3.834833ms +interaction action=hover repeat=1 marks=2->2 renders=2 prepares=2 plans=4 refreshes=0 wall=2.865791ms +interaction action=review-c repeat=1 marks=2->2 renders=3 prepares=1 plans=4 refreshes=0 wall=2.445292ms +interaction action=mark-space repeat=2 marks=1->2 renders=2 prepares=2 plans=4 refreshes=0 wall=2.74825ms +interaction action=hover repeat=2 marks=2->2 renders=2 prepares=2 plans=4 refreshes=0 wall=2.735875ms +interaction action=review-c repeat=2 marks=2->2 renders=3 prepares=1 plans=4 refreshes=0 wall=2.421667ms +interaction action=mark-space repeat=3 marks=1->2 renders=2 prepares=2 plans=4 refreshes=0 wall=3.28325ms +interaction action=hover repeat=3 marks=2->2 renders=2 prepares=2 plans=4 refreshes=0 wall=2.782625ms +interaction action=review-c repeat=3 marks=2->2 renders=3 prepares=1 plans=4 refreshes=0 wall=2.733167ms +interaction action=mark-space repeat=1 marks=8->9 renders=3 prepares=3 plans=6 refreshes=0 wall=5.291709ms +interaction action=hover repeat=1 marks=9->9 renders=2 prepares=2 plans=4 refreshes=0 wall=4.145167ms +interaction action=review-c repeat=1 marks=9->9 renders=3 prepares=1 plans=4 refreshes=0 wall=4.556709ms +interaction action=mark-space repeat=2 marks=8->9 renders=2 prepares=2 plans=4 refreshes=0 wall=3.612542ms +interaction action=hover repeat=2 marks=9->9 renders=2 prepares=2 plans=4 refreshes=0 wall=3.624666ms +interaction action=review-c repeat=2 marks=9->9 renders=3 prepares=1 plans=4 refreshes=0 wall=4.150625ms +interaction action=mark-space repeat=3 marks=8->9 renders=2 prepares=2 plans=4 refreshes=0 wall=3.549459ms +interaction action=hover repeat=3 marks=9->9 renders=2 prepares=2 plans=4 refreshes=0 wall=3.6055ms +interaction action=review-c repeat=3 marks=9->9 renders=3 prepares=1 plans=4 refreshes=0 wall=4.159167ms +interaction action=mark-space repeat=1 marks=32->33 renders=3 prepares=3 plans=6 refreshes=0 wall=9.137625ms +interaction action=hover repeat=1 marks=33->33 renders=2 prepares=2 plans=4 refreshes=0 wall=6.42875ms +interaction action=review-c repeat=1 marks=33->33 renders=3 prepares=1 plans=4 refreshes=0 wall=9.801417ms +interaction action=mark-space repeat=2 marks=32->33 renders=2 prepares=2 plans=4 refreshes=0 wall=6.260209ms +interaction action=hover repeat=2 marks=33->33 renders=2 prepares=2 plans=4 refreshes=0 wall=6.274417ms +interaction action=review-c repeat=2 marks=33->33 renders=3 prepares=1 plans=4 refreshes=0 wall=9.739625ms +interaction action=mark-space repeat=3 marks=32->33 renders=2 prepares=2 plans=4 refreshes=0 wall=6.120542ms +interaction action=hover repeat=3 marks=33->33 renders=2 prepares=2 plans=4 refreshes=0 wall=6.348584ms +interaction action=review-c repeat=3 marks=33->33 renders=3 prepares=1 plans=4 refreshes=0 wall=9.569958ms +interaction action=mark-space repeat=1 marks=128->129 renders=3 prepares=3 plans=6 refreshes=0 wall=41.574ms +interaction action=hover repeat=1 marks=129->129 renders=2 prepares=2 plans=4 refreshes=0 wall=29.242583ms +interaction action=review-c repeat=1 marks=129->129 renders=3 prepares=1 plans=4 refreshes=0 wall=44.395917ms +interaction action=mark-space repeat=2 marks=128->129 renders=2 prepares=2 plans=4 refreshes=0 wall=27.956334ms +interaction action=hover repeat=2 marks=129->129 renders=2 prepares=2 plans=4 refreshes=0 wall=27.605834ms +interaction action=review-c repeat=2 marks=129->129 renders=3 prepares=1 plans=4 refreshes=0 wall=44.052416ms +interaction action=mark-space repeat=3 marks=128->129 renders=2 prepares=2 plans=4 refreshes=0 wall=29.216375ms +interaction action=hover repeat=3 marks=129->129 renders=2 prepares=2 plans=4 refreshes=0 wall=27.679958ms +interaction action=review-c repeat=3 marks=129->129 renders=3 prepares=1 plans=4 refreshes=0 wall=44.189917ms +interaction action=mark-space repeat=1 marks=1024->1025 renders=3 prepares=3 plans=6 refreshes=0 wall=1.726271166s +interaction action=hover repeat=1 marks=1025->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=1.09936375s +interaction action=review-c repeat=1 marks=1025->1025 renders=3 prepares=1 plans=4 refreshes=0 wall=1.237629458s +interaction action=mark-space repeat=2 marks=1024->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=1.154407584s +interaction action=hover repeat=2 marks=1025->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=1.109142875s +interaction action=review-c repeat=2 marks=1025->1025 renders=3 prepares=1 plans=4 refreshes=0 wall=1.229517333s +interaction action=mark-space repeat=3 marks=1024->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=1.064909416s +interaction action=hover repeat=3 marks=1025->1025 renders=2 prepares=2 plans=4 refreshes=0 wall=1.068550917s +interaction action=review-c repeat=3 marks=1025->1025 renders=3 prepares=1 plans=4 refreshes=0 wall=1.224605875s +ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 73 filtered out; finished in 26.34s + diff --git a/docs/performance/mark-resolution/interactions.md b/docs/performance/mark-resolution/interactions.md new file mode 100644 index 00000000..427e1b78 --- /dev/null +++ b/docs/performance/mark-resolution/interactions.md @@ -0,0 +1,96 @@ +# What is a mark, and when does the delay happen? + +This file preserves the first set of input measurements at the original +PR #9 fix. For the final combined scope, current validation and freshly +replayed main-versus-final inputs, see [expanded evidence](expanded/README.md). + +A **mark** is one file or directory queued for removal. Marking a directory +marks that path once, regardless of how many files it contains. For example, +marking a cache directory containing a million files is M=1, not M=1,000,000. +Marking 1,024 unrelated paths means 1,024 separate queued targets. Main has no +usage telemetry establishing that this is a frequent manual workload; it is +a large-queue stress case, also relevant to programmatic/bulk control. + +The earlier **6.60 seconds** measured **four forced window draws, which caused +eight `prepare` calls** in the GPUI harness. It was not a scan time, a single +click time, or a measured delay for every item. The ~359 ms fixed result has +the same denominator. These draws were of the Explore screen with many marks +already present; they were not the act of selecting 1,024 items. + +## Where it repeats + +- Explore calls `prepare` whenever the app renders, resolving marked paths on + main. Its Marked section and disk projection each call `app.plan()` when + those panels are shown, evaluating the entire queue again. +- Marking/unmarking, keyboard selection, zoom and pointer movement over a + tile can request another render. Pointer movement within the same hovered + tile also requests rendering because the tooltip follows the pointer. +- Opening Review calls `app.plan()` for the queue again. Review does not use + the treemap's `prepare`, but it still pays the original quadratic removal + nesting cost, plus constructing the list rows. +- `Marks::refresh` is different: it runs when a scan result arrives and when + the metric changes. It is not run by every mark action or hover. +- An unchanged idle window need not redraw. The free-space ticker checks + every 1.2 seconds outside removal, but only requests rendering if the value + changes. This is not an unconditional six-second periodic stall. + +## Individual user actions, with smaller queues + +An additional opt-in real-window test measures actual Space, pointer-move and +C inputs. The fixture exists on disk: 1,025 sibling directories, each with one +64-byte file, scanned before timing. The tree size stays fixed at 2,050 +non-root nodes while the queued count changes. The window is 1,400 by 900, +with the selection/Marked panel and disk projection visible. No files are +deleted or trashed. + +Each row seeds M folder marks, then measures adding one more folder with +Space. Hover and Review are measured with M+1 marks afterward. Values are +medians of three input repetitions in milliseconds; each cell is +**main → fixed**. Both snapshots use the same fixture and test-only counters. + +| Already queued M | Add one mark (Space) | Move pointer over a tile | Open Review (C) | +| ---: | ---: | ---: | ---: | +| 0 | 2.44 → 2.51 | 2.80 → 2.55 | 2.21 → 2.18 | +| 1 | 3.28 → 2.59 | 2.78 → 2.67 | 2.45 → 2.57 | +| 8 | 3.61 → 3.82 | 3.62 → 3.61 | 4.16 → 4.04 | +| 32 | 6.26 → 5.45 | 6.35 → 5.40 | 9.74 → 8.76 | +| 128 | 29.22 → 14.72 | 27.68 → 13.02 | 44.19 → 30.69 | +| 1,024 | 1,154.41 → 77.31 | 1,099.36 → 74.57 | 1,229.52 → 242.71 | + +For a handful of marks, these operations were already a few milliseconds on +main; this measurement does not establish a substantial common-case speedup. +At 128 marks the repeated work is more noticeable, and the large queue causes +roughly a one-second delay for ordinary interactions in this fixture. The +problem repeats while interacting with that queue, rather than being paid +once when the scan finishes. Opening a large Review list remains more costly +than hovering because it constructs many rows as well as evaluating the plan. + +The measured Space input caused two renders in repetitions 2–3, and three in +the first repetition. Hover caused two renders. Review caused three renders +(one Explore prepare plus the switch to Review). With panels visible, these +inputs evaluated four plans, or six for the first Space repetition. Framework +render scheduling can vary, so these are end-to-end harness input timings, +not a universal mapping of one physical event to one frame. + +Every timed input asserts that real rendering and removal projections ran, +and that **zero `Marks::refresh` calls** occurred. No scan is part of these +individual-action numbers. Raw output includes exact render, prepare, plan +and refresh counts: + +- [Main interaction log](interactions-red.log): main algorithms from the + red commit `5a3c92e`, with the new test/counters temporarily applied. +- [Fixed interaction log](interactions-green.log): fixed algorithms with + the identical test/counters. + +These are synthetic macOS arm64 test-profile measurements, not release-app +latency guarantees or evidence of how often users select a given queue size. +The previous deterministic N/8N budgets remain necessary to protect scaling; +this additional test is intentionally ignored by normal CI because elapsed +latency is recorded as evidence, not asserted as a portable threshold. + +Reproduce on the final branch: + +```sh +cargo test -p disktree-app marked_interaction_timings -- \ + --ignored --nocapture --test-threads=1 +``` diff --git a/docs/performance/mark-resolution/lint.log b/docs/performance/mark-resolution/lint.log new file mode 100644 index 00000000..1687dd61 --- /dev/null +++ b/docs/performance/mark-resolution/lint.log @@ -0,0 +1,6 @@ + Finished `dev` profile [optimized + debuginfo] target(s) in 0.09s + Running `target/debug/xtask lint` + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Finished `dev` profile [optimized + debuginfo] target(s) in 1.10s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` diff --git a/docs/performance/mark-resolution/red-core.log b/docs/performance/mark-resolution/red-core.log new file mode 100644 index 00000000..2227d991 --- /dev/null +++ b/docs/performance/mark-resolution/red-core.log @@ -0,0 +1,33 @@ + Compiling fastrand v2.5.0 + Compiling either v1.18.0 + Compiling log v0.4.34 + Compiling num-traits v0.2.19 + Compiling rustix v1.1.4 + Compiling once_cell v1.21.4 + Compiling errno v0.3.14 + Compiling objc2-foundation v0.3.2 + Compiling rayon v1.12.0 + Compiling trash v5.2.9 + Compiling chrono v0.4.45 + Compiling tempfile v3.27.0 + Compiling disktree-core v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-core) + Finished `test` profile [optimized + debuginfo] target(s) in 3.82s + Running unittests src/lib.rs (target/debug/deps/disktree_core-c3cb863045931ea5) + +running 1 test +plan M=128 work=9187 wall=9.931833ms +plan M=1024 work=537027 wall=390.640459ms + +thread 'removal::tests::removal_nesting_budget' (403531013) panicked at crates/disktree-core/src/removal.rs:1789:9: +8x marks: 9187 -> 537027 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace +test removal::tests::removal_nesting_budget ... FAILED + +failures: + +failures: + removal::tests::removal_nesting_budget + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 149 filtered out; finished in 0.40s + +error: test failed, to rerun pass `-p disktree-core --lib` diff --git a/docs/performance/mark-resolution/red-dimensions.log b/docs/performance/mark-resolution/red-dimensions.log new file mode 100644 index 00000000..4d93cf97 --- /dev/null +++ b/docs/performance/mark-resolution/red-dimensions.log @@ -0,0 +1,17 @@ + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Compiling disktree-core v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-core) + Finished `test` profile [optimized + debuginfo] target(s) in 5.10s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 1 test +dimensions folders=128 M=8 D=2 R=1 work=1012 wall=61.958µs +dimensions folders=1024 M=8 D=2 R=1 work=8180 wall=34.958µs +dimensions folders=1024 M=64 D=2 R=1 work=63648 wall=284.042µs +dimensions folders=128 M=8 D=16 R=1 work=1124 wall=10.666µs +dimensions folders=128 M=8 D=2 R=8 work=8096 wall=46.792µs +test marks::tests::refresh_dimension_budget ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 73 filtered out; finished in 0.00s + diff --git a/docs/performance/mark-resolution/red.log b/docs/performance/mark-resolution/red.log new file mode 100644 index 00000000..75475620 --- /dev/null +++ b/docs/performance/mark-resolution/red.log @@ -0,0 +1,32 @@ + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Finished `test` profile [optimized + debuginfo] target(s) in 5.18s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 4 tests +test argument_tests::invalid_worker_budgets_are_rejected ... ok +test argument_tests::adaptive_budget_and_fixed_override_are_explicit ... ok +refresh M=128 N=256 R=4 work=34048 wall=364µs +refresh M=1024 N=2048 R=4 work=2107392 wall=8.818542ms + +thread 'marks::tests::refresh_resolution_budget' (403532227) panicked at crates/disktree-app/src/marks.rs:208:9: +8x marks/folders: 34048 -> 2107392 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace +test marks::tests::refresh_resolution_budget ... FAILED +window M=128 N=256 draws=4 prepares=8 work=68312 wall=171.271792ms +window M=1024 N=2048 draws=4 prepares=8 work=4215000 wall=6.734163791s + +thread 'tests::marked_window_resolution_budget' (403532228) panicked at crates/disktree-app/src/tests.rs:1904:5: +8x marks/folders per frame: 68312/8 -> 4215000/8 +test tests::marked_window_resolution_budget ... FAILED + +failures: + +failures: + marks::tests::refresh_resolution_budget + tests::marked_window_resolution_budget + +test result: FAILED. 2 passed; 2 failed; 0 ignored; 0 measured; 69 filtered out; finished in 6.96s + +error: test failed, to rerun pass `-p disktree-app --bin disktree` diff --git a/docs/performance/mark-resolution/tests.log b/docs/performance/mark-resolution/tests.log new file mode 100644 index 00000000..af929fb7 --- /dev/null +++ b/docs/performance/mark-resolution/tests.log @@ -0,0 +1,265 @@ + Finished `dev` profile [optimized + debuginfo] target(s) in 0.08s + Running `target/debug/xtask test` + Compiling disktree-core v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-core) + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Finished `test` profile [optimized + debuginfo] target(s) in 4.25s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 79 tests +test appearance::tests::a_linux_desktop_is_followed_only_if_it_states_a_preference ... ok +test git::tests::summaries_say_what_would_be_lost ... ok +test argument_tests::invalid_worker_budgets_are_rejected ... ok +test marks::tests::toggling_marks_and_unmarks ... ok +test argument_tests::adaptive_budget_and_fixed_override_are_explicit ... ok +test marks::tests::display_path_shortens_the_home_prefix ... ok +test marks::tests::marking_the_same_path_twice_keeps_one_entry ... ok +test marks::tests::resolver_preserves_lossy_non_utf8_components ... ok +test palette::tests::every_legend_category_has_its_own_hue ... ok +test palette::tests::age_buckets_cover_every_age_in_order ... ok +test palette::tests::mix_clamps_its_parameter ... ok +test palette::tests::colourful_categories_share_one_level ... ok +test palette::tests::deeper_tiles_lift_away_from_the_background ... ok +test palette::tests::mixing_toward_a_grey_keeps_the_hue ... ok +test palette::tests::the_highlight_is_not_a_category_colour ... ok +test power::tests::presets_are_fixed_and_show_the_effective_cpu_limit ... ok +test power::tests::presets_that_add_no_workers_are_not_offered ... ok +test state::tests::a_transition_grows_a_tile_that_is_being_entered ... ok +test state::tests::a_transition_starts_where_the_region_was_and_ends_where_it_is ... ok +test marks::tests::refresh_re_reads_sizes_from_a_new_tree ... ok +test state::tests::clamping_never_leaves_a_margin ... ok +test marks::tests::find_matches_whole_components_only ... ok +test marks::tests::resolver_preserves_scan_name_semantics ... ok +test marks::tests::cached_crumbs_follow_every_invalidation_boundary ... ok +test state::tests::directions_only_see_gaps_on_their_own_side ... ok +test argument_tests::saved_power_is_loaded_before_cli_overrides ... ok +test state::tests::projecting_and_unprojecting_are_inverses ... ok +test state::tests::zooming_keeps_the_point_under_the_cursor_still ... ok +test marks::tests::refresh_dimension_budget ... ok +test power::tests::saved_choice_survives_replacement_and_bad_data_is_reported ... ok +test marks::tests::refresh_resolution_budget ... ok +test git::tests::reads_a_real_checkout ... ok +test git::tests::a_checkout_cannot_make_git_run_its_programs ... ok +test git::tests::a_checkout_cannot_make_git_verify_a_signature_with_its_program ... ok +test git::tests::a_checkouts_own_filter_is_never_run ... ok +test tests::command_chords_are_not_read_as_plain_letters ... ok +test tests::marked_interaction_timings ... ignored, manual interaction timing on synthetic temporary files +test tests::enter_before_the_search_lands_applies_it_when_it_does ... ok +test tests::escape_in_the_delete_dialog_cancels ... ok +test tests::a_view_without_flags_or_marks_still_draws ... ok +test tests::back_and_forward_retrace_where_you_have_been ... ok +test tests::interface_zoom_scales_the_rem_and_the_header_band ... ok +test tests::restart_arguments_parse_back_to_the_same_scan ... ok +test tests::after_descending_every_tile_is_inside_the_directory_drawn ... ok +test tests::enter_opens_the_selected_directory_at_any_depth ... ok +test tests::escape_cancels_the_first_scan_and_r_starts_it_again ... ok +test tests::enter_in_the_focused_volume_picker_scans_the_selected_root ... ok +test tests::a_permanent_deletion_asks_in_an_alert_dialog_then_removes ... ok +test tests::escape_cancels_widening_and_keeps_the_tree_on_screen ... ok +test tests::keys_walk_the_tree_and_mark_what_is_selected ... ok +test tests::a_crumb_lists_its_siblings_and_jumps_sideways ... ok +test tests::hovering_reports_the_tile_under_the_pointer ... ok +test tests::a_parents_name_gets_its_own_band_above_its_children ... ok +test tests::dragging_the_panel_edge_resizes_it_within_its_limits ... ok +test tests::both_appearances_draw ... ok +test tests::marked_tiles_follow_metric_rescan_and_mark_changes ... ok +test tests::the_help_overlay_opens_and_closes ... ok +test tests::the_review_screen_switches_removal_mode ... ok +test tests::the_review_screen_copies_the_list_as_an_agent_prompt ... ok +test tests::switching_the_metric_keeps_the_directory_and_the_selection ... ok +test widgets::tests::ages_read_in_the_unit_a_person_would_use ... ok +test widgets::tests::sizes_split_into_number_and_unit ... ok +test tests::right_click_selects_the_tile_and_reveals_it ... ok +test tests::showing_a_tile_that_is_gone_says_so_instead ... ok +test tests::power_efficiency_menu_saves_without_discarding_the_tree ... ok +test tests::mouse_side_buttons_go_back_and_forward ... ok +test tests::marking_a_directory_marks_everything_inside_it ... ok +test tests::the_first_scan_shows_what_it_is_doing_then_the_treemap ... ok +test tests::the_trash_is_the_default_when_there_is_one ... ok +test tests::the_mark_key_follows_the_pointer_until_the_keyboard_moves ... ok +test tests::the_power_menu_offers_only_what_the_cpus_can_tell_apart ... ok +test tests::the_volume_picker_is_centred_and_still_dismisses_from_outside ... ok +test tests::the_treemap_zooms_with_the_wheel_and_resets ... ok +test tests::the_volume_picker_opens_moves_and_closes ... ok +test tests::the_window_draws_a_treemap_with_tiles ... ok +test tests::the_wheel_goes_into_the_directory_it_zoomed_into ... ok +test tests::widening_reuses_the_tree_it_has_and_reads_only_the_rest ... ok +test tests::typing_filters_live_and_enter_shows_only_the_matches ... ok +test tests::marked_window_resolution_budget ... ok + +test result: ok. 78 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 1.46s + + Running unittests src/lib.rs (target/debug/deps/disktree_core-9300e5ba20d6b25f) + +running 152 tests +test classify::tests::steam_libraries_and_emulation_are_media_not_disposable_caches ... ok +test classify::tests::macos_developer_leftovers_are_reclaimable_and_its_risks_are_not ... ok +test classify::tests::windows_caches_and_sync_folders_are_recognized ... ok +test classify::tests::the_legend_lists_every_named_category_once ... ok +test filter::tests::case_is_ignored_without_allocating ... ok +test export::tests::the_list_is_one_path_per_line ... ok +test export::tests::a_name_with_a_newline_cannot_smuggle_in_a_path ... ok +test export::tests::a_name_that_is_not_unicode_is_flagged_not_listed ... ok +test export::tests::the_prompt_lists_every_path_with_its_size_and_the_rules ... ok +test access::tests::only_macos_has_an_answer_and_a_missing_database_is_not_a_refusal ... ok +test filter::tests::matches_are_kept_whole_and_their_ancestors_by_what_matched ... ok +test filter::tests::a_search_below_the_root_leaves_the_rest_alone ... ok +test classify::tests::a_steam_library_on_another_drive_is_media_not_its_temp_folder ... ok +test insights::tests::ranks_findings_largest_first_and_skips_the_tiny ... ok +test insights::tests::documents_are_never_suggested ... ok +test filter::tests::an_empty_needle_filters_nothing ... ok +test insights::tests::the_limit_keeps_the_largest ... ok +test classify::tests::an_unknown_top_level_directory_takes_its_largest_known_child ... ok +test classify::tests::caches_are_reclaimable_all_the_way_down ... ok +test insights::tests::crumbs_address_the_finding_from_the_root ... ok +test classify::tests::names_announce_their_kind_and_children_inherit_it ... ok +test classify::tests::target_is_build_output_only_beside_a_cargo_manifest ... ok +test removal::tests::a_directory_holding_a_system_tree_is_refused ... ok +test removal::tests::a_directory_holding_the_home_directory_is_refused ... ok +test classify::tests::sandbox_layers_and_snapshots_are_reclaimable_only_in_sandbox_state ... ok +test macos::tests::a_missing_directory_is_an_error ... ok +test removal::tests::macos_always_uses_the_system_trash ... ok +test removal::tests::macos_guard_keys_fold_the_data_volume_and_case ... ok +test removal::tests::macos_guards_see_through_other_spellings ... ok +test removal::tests::a_name_that_is_not_utf8_is_refused_before_the_trash_sees_it ... ok +test removal::tests::macos_system_trees_are_refused_but_apps_are_not ... ok +test removal::tests::names_win32_would_misread_are_recognized ... ok +test macos::tests::a_listing_has_names_kinds_lengths_and_no_dot_entries ... ok +test removal::tests::nesting_keeps_component_boundaries_duplicates_and_output_order ... ok +test removal::tests::normalize_resolves_dots_without_the_filesystem ... ok +test removal::tests::nesting_uses_guard_case_order_even_when_the_child_sorts_first ... ok +test macos::tests::names_are_text_and_open ... ok +test removal::tests::a_mount_below_a_target_is_caught_again_at_removal_time ... ok +test removal::tests::percent_encoding_escapes_what_the_spec_requires ... ok +test removal::tests::a_volume_is_judged_by_its_mount_where_the_kernel_names_one ... ok +test removal::tests::a_missing_target_reports_not_found ... ok +test removal::tests::a_plan_keeps_only_the_outermost_targets ... ok +test removal::tests::mount_points_are_recognized ... ok +test macos::tests::every_leaf_reads_as_lstat_reads_it ... ok +test removal::tests::a_target_with_a_mount_inside_is_refused ... ok +test removal::tests::a_trash_info_path_is_restorable ... ok +test removal::tests::paths_outside_the_root_are_refused ... ok +test removal::tests::a_target_reached_through_a_link_is_refused ... ok +test removal::tests::a_removal_run_reports_every_item_and_a_total ... ok +test removal::tests::permanent_removal_takes_directories_and_leaves_siblings ... ok +test removal::tests::the_macos_trash_takes_a_file_and_leaves_a_linked_target ... ignored, puts a file in this Mac's real Trash +test removal::tests::home_is_found_by_its_real_path_too ... ok +test removal::tests::permanent_removal_follows_links_above_the_root ... ok +test removal::tests::nothing_is_mounted_below_a_temp_dir ... ok +test removal::tests::permanent_removal_unlinks_a_symlink_instead_of_following_it ... ok +test removal::tests::permanent_removal_unlinks_nested_symlinks_without_following_them ... ok +test removal::tests::read_only_files_are_removed_too ... ok +test removal::tests::permanent_removal_takes_nested_trees_and_hidden_files ... ok +test removal::tests::permanent_removal_does_not_follow_a_link_put_on_the_way_down ... ok +test removal::tests::a_link_put_on_the_way_down_after_planning_stops_the_worker ... ok +test removal::tests::trash_names_avoid_collisions ... ok +test removal::tests::the_root_and_home_are_refused ... ok +test removal::tests::sibling_prefixes_are_not_treated_as_containment ... ok +test removal::tests::the_mount_table_is_read_off_the_calling_thread_and_then_kept ... ok +test scan::tests::a_file_root_is_rejected ... ok +test scan::tests::fixed_worker_pools_change_size_without_reinitializing_rayon ... ok +test removal::tests::the_xdg_trash_moves_a_file_and_records_where_it_came_from ... ok +test scan::tests::a_directory_reports_its_own_bytes_separately ... ok +test removal::tests::this_macs_mount_table_is_read_without_proc ... ok +test scan::tests::an_unreadable_directory_is_recorded_not_fatal ... ok +test scan::tests::disk_usage_is_whole_allocation_units ... ok +test scan::tests::children_are_ranked_largest_first ... ok +test scan::tests::a_spawned_scan_reports_progress_and_a_result ... ok +test scan::tests::whole_disk_smoke ... ignored, walks the whole disk +test scan::tests::hardlinks_are_charged_once_by_default ... ok +test scan_threads::tests::governor_waits_for_retirement_and_recovers_without_exceeding_target ... ok +test scan_threads::tests::inconclusive_windows_cannot_accept_a_reduction ... ok +test scan::tests::hidden_entries_are_included_by_default_and_excluded_on_request ... ok +test scan_threads::tests::increased_limit_is_not_supplied_until_jobs_are_dispatched ... ok +test scan_threads::tests::long_directory_never_becomes_a_fully_supplied_window ... ok +test scan::tests::followed_symlink_loops_do_not_hang_the_scan ... ok +test scan_threads::tests::search_refines_one_reference_without_compounding_loss ... ok +test size::tests::a_value_that_rounds_up_to_the_next_unit_is_shown_in_it ... ok +test size::tests::bytes_use_binary_units_with_one_decimal_below_ten ... ok +test size::tests::counts_switch_to_metric_suffixes ... ok +test size::tests::share_bar_is_always_the_requested_width ... ok +test size::tests::share_survives_a_zero_total ... ok +test size::tests::short_form_drops_the_space ... ok +test space::tests::a_home_scan_has_no_foreign_mounts_here ... ok +test space::tests::a_bind_mount_inside_the_scan_is_left_out ... ok +test scan::tests::a_wider_scan_reuses_the_subtree_it_already_knows ... ok +test space::tests::a_missing_path_reports_the_io_error ... ok +test space::tests::a_real_volume_reports_plausible_numbers ... ok +test space::tests::a_root_booted_from_a_snapshot_keeps_its_subvolumes ... ok +test space::tests::a_table_that_does_not_place_a_path_claims_nothing ... ok +test space::tests::a_volume_includes_its_subvolumes_and_nothing_else ... ok +test space::tests::a_volume_keeps_its_subvolumes_and_loses_everything_else ... ok +test scan::tests::max_depth_stops_descending_but_keeps_direct_files ... ok +test space::tests::btrfs_subvolume_devices_can_differ ... ok +test space::tests::excluded_views_cannot_replace_visible_files ... ok +test space::tests::hidden_original_and_nested_mounts_are_preserved ... ok +test scan_threads::tests::real_pool_retires_at_job_boundaries_and_drains_queued_descendants ... ok +test space::tests::macos_mount_points_keep_spaces_and_brackets ... ok +test space::tests::mountinfo_escapes_are_decoded_once ... ok +test space::tests::only_macos_skips_the_data_volume_and_in_the_roots_spelling ... ok +test space::tests::projecting_removal_cannot_exceed_the_volume ... ok +test space::tests::separate_home_disk_is_its_own_volume ... ok +test space::tests::subvolumes_are_not_repeats_but_a_second_mount_of_a_disk_is ... ok +test space::tests::the_device_is_the_longest_matching_mount ... ok +test space::tests::the_home_disk_on_macos_is_the_root_and_has_a_device ... ok +test space::tests::the_whole_disk_is_the_top_of_the_home_volume ... ok +test space::tests::the_top_of_a_btrfs_disk_beside_its_subvolumes_is_counted_once ... ok +test space::tests::unrelated_tmpfs_mounts_are_not_duplicates ... ok +test space::tests::used_fraction_handles_an_empty_volume_report ... ok +test space::tests::volumes_with_least_space_come_first_and_unknowns_last ... ok +test space::tests::volume_candidates_are_real_disks_not_pseudo_filesystems ... ok +test scan::tests::symlinks_are_not_followed_by_default ... ok +test tree::tests::a_node_stays_small ... ok +test tree::tests::depth_counts_edges ... ok +test tree::tests::aggregate_derives_totals_and_orders_children ... ok +test tree::tests::find_reports_crumbs_and_is_case_insensitive ... ok +test tree::tests::identities_that_differ_only_in_their_top_bits_are_two_files ... ok +test tree::tests::largest_child_is_the_first_child_because_children_are_sorted ... ok +test tree::tests::path_of_joins_names_beneath_the_root ... ok +test tree::tests::resolve_walks_child_indices ... ok +test tree::tests::aggregate_can_rank_by_file_count ... ok +test treemap::tests::a_leaf_never_claims_a_header ... ok +test treemap::tests::a_filtered_layout_shows_only_the_matches_at_their_size ... ok +test treemap::tests::a_tile_without_room_for_a_header_stays_whole ... ok +test treemap::tests::a_subdivided_directory_keeps_a_header_for_its_own_name ... ok +test treemap::tests::hit_returns_the_deepest_tile ... ok +test treemap::tests::layout_depth_one_stops_at_direct_children ... ok +test treemap::tests::layout_merges_the_child_tail_into_one_tile ... ok +test treemap::tests::squarify_fills_the_area ... ok +test treemap::tests::squarify_keeps_aspect_ratios_reasonable ... ok +test treemap::tests::layout_nests_children_inside_their_parent ... ok +test treemap::tests::squarify_survives_degenerate_input ... ok +test treemap::tests::tile_crumbs_address_the_scanned_tree_not_the_drawn_node ... ok +test scan::tests::totals_are_summed_bottom_up ... ok +test space::tests::without_a_table_the_same_place_is_one_volume ... ok +test tree::tests::seen_charges_an_identity_once_in_either_store ... ok +test scan::tests::file_count_metric_ranks_by_entries ... ok +test removal::tests::system_trees_are_refused_in_a_whole_disk_scan ... ok +test removal::tests::the_directories_above_home_are_refused ... ok +test removal::tests::removal_nesting_budget ... ok +test scan::tests::cancelled_queued_jobs_release_parent_completion_tokens ... ok +test removal::tests::a_failing_trash_tool_reports_its_stderr ... ok +test scan::tests::fixed_worker_pools_preserve_a_wide_deep_tree ... ok +test removal::tests::only_the_scanned_volumes_marks_are_projected ... ok +test scan_threads::tests::controller_retires_recovers_after_search_and_cancels ... ok +test macos::tests::a_directory_larger_than_the_buffer_is_listed_whole ... ok +test removal::tests::a_trash_tool_is_called_with_the_path_after_a_separator ... ok + +test result: ok. 150 passed; 0 failed; 2 ignored; 0 measured; 0 filtered out; finished in 0.20s + + Running unittests src/main.rs (target/debug/deps/xtask-0dc2df263f51d89e) + +running 3 tests +test bundle::tests::signing_is_ad_hoc_unless_an_identity_is_given ... ok +test bundle::tests::notarizing_needs_a_real_signature ... ok +test bundle::tests::the_plist_template_names_the_executable_and_takes_the_version ... ok + +test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s + + Doc-tests disktree_core + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s + diff --git a/docs/performance/mark-resolution/wall-green-repeats.log b/docs/performance/mark-resolution/wall-green-repeats.log new file mode 100644 index 00000000..ece27470 --- /dev/null +++ b/docs/performance/mark-resolution/wall-green-repeats.log @@ -0,0 +1,126 @@ + +REPEAT 1: disktree-app fixed + Compiling disktree-core v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-core) + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Finished `test` profile [optimized + debuginfo] target(s) in 5.26s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 5 tests +test argument_tests::adaptive_budget_and_fixed_override_are_explicit ... ok +test argument_tests::invalid_worker_budgets_are_rejected ... ok +test marks::tests::refresh_dimension_budget ... dimensions folders=128 M=8 D=2 R=1 work=160 wall=92.541µs +dimensions folders=1024 M=8 D=2 R=1 work=1056 wall=47.167µs +dimensions folders=1024 M=64 D=2 R=1 work=1280 wall=50.167µs +dimensions folders=128 M=8 D=16 R=1 work=384 wall=28.084µs +dimensions folders=128 M=8 D=2 R=8 work=1280 wall=57.541µs +ok +test marks::tests::refresh_resolution_budget ... refresh M=128 N=256 R=4 work=2560 wall=204.417µs +refresh M=1024 N=2048 R=4 work=20480 wall=1.528584ms +ok +test tests::marked_window_resolution_budget ... warm window M=128 prepares=8 resolution=216 tiles=1544 wall=64.363667ms +window M=128 N=256 draws=4 prepares=8 work=856 wall=66.748208ms +warm window M=1024 prepares=8 resolution=216 tiles=776 wall=347.242958ms +window M=1024 N=2048 draws=4 prepares=8 work=5336 wall=358.680958ms +ok + +test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 73 filtered out; finished in 0.91s + +EXIT 0 + +REPEAT 1: disktree-core fixed + Compiling disktree-core v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-core) + Finished `test` profile [optimized + debuginfo] target(s) in 1.68s + Running unittests src/lib.rs (target/debug/deps/disktree_core-c3cb863045931ea5) + +running 1 test +test removal::tests::removal_nesting_budget ... plan M=128 work=1314 wall=3.372625ms +plan M=1024 work=15298 wall=23.837875ms +ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 151 filtered out; finished in 0.03s + +EXIT 0 + +REPEAT 2: disktree-app fixed + Finished `test` profile [optimized + debuginfo] target(s) in 0.29s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 5 tests +test argument_tests::adaptive_budget_and_fixed_override_are_explicit ... ok +test argument_tests::invalid_worker_budgets_are_rejected ... ok +test marks::tests::refresh_dimension_budget ... dimensions folders=128 M=8 D=2 R=1 work=160 wall=23.458µs +dimensions folders=1024 M=8 D=2 R=1 work=1056 wall=44.542µs +dimensions folders=1024 M=64 D=2 R=1 work=1280 wall=56.5µs +dimensions folders=128 M=8 D=16 R=1 work=384 wall=26µs +dimensions folders=128 M=8 D=2 R=8 work=1280 wall=55.125µs +ok +test marks::tests::refresh_resolution_budget ... refresh M=128 N=256 R=4 work=2560 wall=208.667µs +refresh M=1024 N=2048 R=4 work=20480 wall=1.52875ms +ok +test tests::marked_window_resolution_budget ... warm window M=128 prepares=8 resolution=216 tiles=1544 wall=65.17375ms +window M=128 N=256 draws=4 prepares=8 work=856 wall=67.732166ms +warm window M=1024 prepares=8 resolution=216 tiles=776 wall=350.850083ms +window M=1024 N=2048 draws=4 prepares=8 work=5336 wall=356.051625ms +ok + +test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 73 filtered out; finished in 0.89s + +EXIT 0 + +REPEAT 2: disktree-core fixed + Finished `test` profile [optimized + debuginfo] target(s) in 0.10s + Running unittests src/lib.rs (target/debug/deps/disktree_core-c3cb863045931ea5) + +running 1 test +test removal::tests::removal_nesting_budget ... plan M=128 work=1314 wall=2.852625ms +plan M=1024 work=15298 wall=21.89725ms +ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 151 filtered out; finished in 0.03s + +EXIT 0 + +REPEAT 3: disktree-app fixed + Finished `test` profile [optimized + debuginfo] target(s) in 0.30s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 5 tests +test argument_tests::adaptive_budget_and_fixed_override_are_explicit ... ok +test argument_tests::invalid_worker_budgets_are_rejected ... ok +test marks::tests::refresh_dimension_budget ... dimensions folders=128 M=8 D=2 R=1 work=160 wall=23µs +dimensions folders=1024 M=8 D=2 R=1 work=1056 wall=51.5µs +dimensions folders=1024 M=64 D=2 R=1 work=1280 wall=59µs +dimensions folders=128 M=8 D=16 R=1 work=384 wall=33.667µs +dimensions folders=128 M=8 D=2 R=8 work=1280 wall=60.167µs +ok +test marks::tests::refresh_resolution_budget ... refresh M=128 N=256 R=4 work=2560 wall=198.958µs +refresh M=1024 N=2048 R=4 work=20480 wall=1.648333ms +ok +test tests::marked_window_resolution_budget ... warm window M=128 prepares=8 resolution=216 tiles=1544 wall=65.083791ms +window M=128 N=256 draws=4 prepares=8 work=856 wall=66.946292ms +warm window M=1024 prepares=8 resolution=216 tiles=776 wall=340.564ms +window M=1024 N=2048 draws=4 prepares=8 work=5336 wall=359.560417ms +ok + +test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 73 filtered out; finished in 0.89s + +EXIT 0 + +REPEAT 3: disktree-core fixed + Finished `test` profile [optimized + debuginfo] target(s) in 0.11s + Running unittests src/lib.rs (target/debug/deps/disktree_core-c3cb863045931ea5) + +running 1 test +test removal::tests::removal_nesting_budget ... plan M=128 work=1314 wall=3.403792ms +plan M=1024 work=15298 wall=23.242542ms +ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 151 filtered out; finished in 0.03s + +EXIT 0 diff --git a/docs/performance/mark-resolution/wall-red-repeats.log b/docs/performance/mark-resolution/wall-red-repeats.log new file mode 100644 index 00000000..55f720af --- /dev/null +++ b/docs/performance/mark-resolution/wall-red-repeats.log @@ -0,0 +1,174 @@ + +REPEAT 1: disktree-app baseline 5a3c92e + Compiling disktree-app v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-app) + Compiling disktree-core v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-core) + Finished `test` profile [optimized + debuginfo] target(s) in 4.81s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 4 tests +test argument_tests::adaptive_budget_and_fixed_override_are_explicit ... ok +test argument_tests::invalid_worker_budgets_are_rejected ... ok +test marks::tests::refresh_resolution_budget ... refresh M=128 N=256 R=4 work=34048 wall=457.125µs +refresh M=1024 N=2048 R=4 work=2107392 wall=11.105667ms + +thread 'marks::tests::refresh_resolution_budget' (403559694) panicked at crates/disktree-app/src/marks.rs:208:9: +8x marks/folders: 34048 -> 2107392 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace +FAILED +test tests::marked_window_resolution_budget ... window M=128 N=256 draws=4 prepares=8 work=68312 wall=159.687834ms +window M=1024 N=2048 draws=4 prepares=8 work=4215000 wall=6.601997625s + +thread 'tests::marked_window_resolution_budget' (403559695) panicked at crates/disktree-app/src/tests.rs:1904:5: +8x marks/folders per frame: 68312/8 -> 4215000/8 +FAILED + +failures: + +failures: + marks::tests::refresh_resolution_budget + tests::marked_window_resolution_budget + +test result: FAILED. 2 passed; 2 failed; 0 ignored; 0 measured; 69 filtered out; finished in 6.83s + +error: test failed, to rerun pass `-p disktree-app --bin disktree` +EXIT 101 + +REPEAT 1: disktree-core baseline 5a3c92e + Compiling disktree-core v0.11.0 (/Users/huntharo/.codex/worktrees/mv8epstr/disktree/crates/disktree-core) + Finished `test` profile [optimized + debuginfo] target(s) in 0.68s + Running unittests src/lib.rs (target/debug/deps/disktree_core-c3cb863045931ea5) + +running 1 test +test removal::tests::removal_nesting_budget ... plan M=128 work=9187 wall=11.07275ms +plan M=1024 work=537027 wall=398.130709ms + +thread 'removal::tests::removal_nesting_budget' (403560362) panicked at crates/disktree-core/src/removal.rs:1789:9: +8x marks: 9187 -> 537027 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace +FAILED + +failures: + +failures: + removal::tests::removal_nesting_budget + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 149 filtered out; finished in 0.41s + +error: test failed, to rerun pass `-p disktree-core --lib` +EXIT 101 + +REPEAT 2: disktree-app baseline 5a3c92e + Finished `test` profile [optimized + debuginfo] target(s) in 0.28s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 4 tests +test argument_tests::adaptive_budget_and_fixed_override_are_explicit ... ok +test argument_tests::invalid_worker_budgets_are_rejected ... ok +test marks::tests::refresh_resolution_budget ... refresh M=128 N=256 R=4 work=34048 wall=278.333µs +refresh M=1024 N=2048 R=4 work=2107392 wall=9.065291ms + +thread 'marks::tests::refresh_resolution_budget' (403560424) panicked at crates/disktree-app/src/marks.rs:208:9: +8x marks/folders: 34048 -> 2107392 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace +FAILED +test tests::marked_window_resolution_budget ... window M=128 N=256 draws=4 prepares=8 work=68312 wall=161.706417ms +window M=1024 N=2048 draws=4 prepares=8 work=4215000 wall=6.607910459s + +thread 'tests::marked_window_resolution_budget' (403560426) panicked at crates/disktree-app/src/tests.rs:1904:5: +8x marks/folders per frame: 68312/8 -> 4215000/8 +FAILED + +failures: + +failures: + marks::tests::refresh_resolution_budget + tests::marked_window_resolution_budget + +test result: FAILED. 2 passed; 2 failed; 0 ignored; 0 measured; 69 filtered out; finished in 6.83s + +error: test failed, to rerun pass `-p disktree-app --bin disktree` +EXIT 101 + +REPEAT 2: disktree-core baseline 5a3c92e + Finished `test` profile [optimized + debuginfo] target(s) in 0.09s + Running unittests src/lib.rs (target/debug/deps/disktree_core-c3cb863045931ea5) + +running 1 test +test removal::tests::removal_nesting_budget ... plan M=128 work=9187 wall=8.688291ms +plan M=1024 work=537027 wall=399.84275ms + +thread 'removal::tests::removal_nesting_budget' (403560664) panicked at crates/disktree-core/src/removal.rs:1789:9: +8x marks: 9187 -> 537027 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace +FAILED + +failures: + +failures: + removal::tests::removal_nesting_budget + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 149 filtered out; finished in 0.41s + +error: test failed, to rerun pass `-p disktree-core --lib` +EXIT 101 + +REPEAT 3: disktree-app baseline 5a3c92e + Finished `test` profile [optimized + debuginfo] target(s) in 0.26s +warning: the following packages contain code that will be rejected by a future version of Rust: block v0.1.6 +note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1` + Running unittests src/main.rs (target/debug/deps/disktree-be72e126ba0d25ca) + +running 4 tests +test argument_tests::adaptive_budget_and_fixed_override_are_explicit ... ok +test argument_tests::invalid_worker_budgets_are_rejected ... ok +test marks::tests::refresh_resolution_budget ... refresh M=128 N=256 R=4 work=34048 wall=263.917µs +refresh M=1024 N=2048 R=4 work=2107392 wall=7.863542ms + +thread 'marks::tests::refresh_resolution_budget' (403560714) panicked at crates/disktree-app/src/marks.rs:208:9: +8x marks/folders: 34048 -> 2107392 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace +FAILED +test tests::marked_window_resolution_budget ... window M=128 N=256 draws=4 prepares=8 work=68312 wall=155.442209ms +window M=1024 N=2048 draws=4 prepares=8 work=4215000 wall=6.564761291s + +thread 'tests::marked_window_resolution_budget' (403560715) panicked at crates/disktree-app/src/tests.rs:1904:5: +8x marks/folders per frame: 68312/8 -> 4215000/8 +FAILED + +failures: + +failures: + marks::tests::refresh_resolution_budget + tests::marked_window_resolution_budget + +test result: FAILED. 2 passed; 2 failed; 0 ignored; 0 measured; 69 filtered out; finished in 6.77s + +error: test failed, to rerun pass `-p disktree-app --bin disktree` +EXIT 101 + +REPEAT 3: disktree-core baseline 5a3c92e + Finished `test` profile [optimized + debuginfo] target(s) in 0.10s + Running unittests src/lib.rs (target/debug/deps/disktree_core-c3cb863045931ea5) + +running 1 test +test removal::tests::removal_nesting_budget ... plan M=128 work=9187 wall=8.564791ms +plan M=1024 work=537027 wall=393.824917ms + +thread 'removal::tests::removal_nesting_budget' (403560958) panicked at crates/disktree-core/src/removal.rs:1789:9: +8x marks: 9187 -> 537027 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace +FAILED + +failures: + +failures: + removal::tests::removal_nesting_budget + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 149 filtered out; finished in 0.40s + +error: test failed, to rerun pass `-p disktree-core --lib` +EXIT 101 diff --git a/docs/pr-screenshots.md b/docs/pr-screenshots.md new file mode 100644 index 00000000..6193a12c --- /dev/null +++ b/docs/pr-screenshots.md @@ -0,0 +1,139 @@ +# PR screenshots + +`AGENTS.md` asks for before/after screenshots on any PR that changes what the +window shows. This file covers making them without leaking a real disk, and +attaching them with `gh` so the links render. The procedure is the Pwr +family's; PwrGit's `docs/pr-screenshots.md` and PwrAgent's `AGENTS.md` carry +the same rules. + +## Making them + +A disk scan is private by nature: paths carry user names, project and client +names; the status bar names the volume and its free space; the source chooser +lists mounts and the SSH hosts from your config. So point the app at a tree +built for the picture, never at `~` or a real volume. + +Make them in the PwrSuiteLab headed E2E VM, never on the operator's Mac. +Launching PwrDisk on the operator's Mac and driving it with synthetic input +lands keys in whatever the operator is using; see +[AGENTS.md](../AGENTS.md#testing-on-a-desktop). Everything below runs inside +one guest job, and [headed-e2e-pwrsuitelab.md](headed-e2e-pwrsuitelab.md) +has the job's shape and an example. Without the PwrSuiteLab Control MCP, +stop and ask the operator. + +1. In the job, create a disk image with an invented name and build the tree + on it: `hdiutil create -ov -size 512m -fs APFS -volname Fixtures -attach + target/fixtures.dmg` mounts it at `/Volumes/Fixtures`. Detach it at the + end. The image is required in the lab: a tree anywhere else shows the + guest's paths, volume name and free space, which are lab details. If + `hdiutil` fails, stop and report it to the operator as a baseline issue. +2. On that image, build a contrived tree with invented names, sized so the + treemap has something to show. Sparse files do not work, because sizes + come from allocated blocks; write real bytes. + + ```sh + root=/Volumes/Fixtures/Projects + mkdir -p "$root"/{atlas/build,atlas/src,beacon/node_modules,photos/2024} + # dd, not head -c 120m: macOS's head takes no size suffix. + fill() { dd if=/dev/urandom of="$1" bs=1048576 count="$2" 2>/dev/null; } + fill "$root/atlas/build/app.bin" 120 + fill "$root/beacon/node_modules/bundle.js" 40 + fill "$root/photos/2024/IMG_0001.raw" 80 + ``` + +3. Launch `pwrdisk ` in the guest, in the background: with a path + it scans directly and skips the chooser. Wait for its window, drive the + screen under test from the job's command, and capture only the PwrDisk + window (`screencapture -o -x -l `), not the screen. Write the + images to a checkout-relative directory such as `target/lab-shots/`, list + it in the job's `artifacts`, and quit the app. +4. Fetch them with `lab_e2e_collect`; + [headed-e2e-pwrsuitelab.md](headed-e2e-pwrsuitelab.md) says where its + `artifact_directory` is. Copy each image to a short local name, such as + `./after.png`, and attach that copy; the artifact directory's own path + never goes in a PR. Never commit the copy, and delete it once the + uploaded links check out. +5. For "before", run the same job against a clean, committed worktree of + `main` (`git fetch origin main && git worktree add --detach + origin/main`), with the same tree and the same window size. Remove it + with `git worktree remove ` afterwards. + +Lab VMs start with clipboard sharing off. Images come back as collected +artifacts, never through the clipboard, and the operator is never asked to +copy one out of the guest. + +In the guest, the source chooser lists the guest's mounts and SSH config +hosts, which are lab details: never attach a guest capture of them. If the +change is to the chooser, say so in the body and ask the operator. Any other +screen that can only be shown with real data: **show the image to the +operator and wait for approval before attaching it.** Crop or redact user +names, host names, volume names and anything else that is not invented. + +Say in the PR body how each image was made ("`pwrdisk` on a contrived tree on +a disk image named Fixtures, macOS 27, in the PwrSuiteLab VM"), without the +VM's name or any other lab detail. If nothing can show the change, including +a Linux or Windows window the lab cannot show, say why and ask the operator +before merging; a missing screenshot is not optional. + +## Attaching them with `gh --attach` + +GitHub CLI 2.99+ attaches images and videos with the repeatable `--attach` +flag on `gh pr create`, `gh pr edit` and `gh pr comment`. Reference the local +path in the Markdown body and `gh` uploads the file and rewrites the link to a +`https://github.com/user-attachments/assets/...` URL in place. Unreferenced +attachments are appended at the end. Check `gh --version` first. + +Do not host images any other way: not on a side branch, a gist, or committed +to the repository. Those links break when the branch is deleted, and they put +binaries in the fork's history. + +```sh +gh pr create --repo pwrdrvr/PwrDisk \ + --title "fix(app): keep tile labels inside their tile" \ + --body-file /tmp/pr-body.md \ + --attach ./before.png \ + --attach ./after.png +``` + +```markdown +## Before +![labels before](./before.png) + +## After +![labels after](./after.png) +``` + +Alt text can follow the path after `#`, as in +`--attach './after.png#labels after'`; the `#alt` part is not matched. + +Three ways this fails silently. `gh` exits 0 in every one of them: + +* **The match is a literal string comparison.** `gh` rewrites `](path)` only + when `path` is byte-identical to what `--attach` was given, so + `--attach /tmp/shots/after.png` against `![after](./after.png)` does not + match. The upload still happens, the dead relative link stays where it was, + and a second copy is appended at the end. Use the same spelling in both + places, and keep paths short enough to retype exactly. +* **After the upload, edit the live body, never your draft.** The rewrite + exists only in the uploaded body; your local file keeps the local paths. For + every later edit, run `gh pr view --json body -q .body > ` and edit + that copy. Re-sending the draft replaces the live `user-attachments` URLs + with dead local paths. To add an image later, pass `--attach` for the new + file only: existing `user-attachments` URLs match no `--attach` path, so + `gh` leaves them alone, and attaching an uploaded image again appends a + duplicate. +* **Check the result before calling the PR done.** Finding `user-attachments` + URLs in the body is not enough; after a mismatch they are there, but in the + wrong place. Every image link in the body must be a `user-attachments` URL, + and each must fetch with HTTP 200 and the local file's byte count: + + ```sh + gh pr view --repo pwrdrvr/PwrDisk --json body -q .body \ + | grep -o '!\[[^]]*\]([^)]*)' | sed 's/.*](\(.*\))/\1/' \ + | while read -r url; do + curl -sL -o /dev/null -w "%{http_code} %{size_download} $url\n" "$url" + done + ``` + + To recover from a mismatch without uploading again, copy the URLs out of + the body and `gh pr edit --body-file` with them where you wanted them. diff --git a/docs/property-model-oracle-testing.md b/docs/property-model-oracle-testing.md new file mode 100644 index 00000000..12138754 --- /dev/null +++ b/docs/property-model-oracle-testing.md @@ -0,0 +1,165 @@ +# Property, model and oracle tests + +Most PwrDisk tests are **example tests**: build one tree, mark one path, +write down the number you expect. They check only the cases someone thought +of, and they check what the author *believed*. In this repo's history the +expected output was sometimes the bug, and the test kept it in place (table +below). + +The three ideas here let the computer choose the inputs. We use +[proptest](https://docs.rs/proptest) inside `cargo test`. + +## The three words + +**Property.** A rule that must hold for *every* input, written as code. +proptest generates hundreds of inputs. When one breaks the rule, it +*shrinks* that input to the smallest one that still fails and prints it. + +> *"Every directory a search keeps is reachable from the root through kept +> parents."* Against the code before #34, this shrank to one empty +> directory, `A/b`, searched for `b`: the count said 1 and the treemap +> showed nothing. + +**Model.** For code with state, a small stand-in that is obviously correct. +The test generates random sequences of commands, such as mark, mark anyway, +open Review, type the phrase, commit, agent preview. It runs each sequence +on the real code and on the model, and checks that they agree after every +step. + +> Rule: *no disk loses more than the limit unless the person confirmed that +> disk's share.* Against the code before #103, it shrank to four commands: +> mark 101 bytes on a USB disk anyway, open Review, type the phrase, commit. +> The USB disk lost 101 bytes of 2,000 against a 100-byte limit. Review +> asked for one share, "trash 11% of my disk", for both disks. + +**Oracle.** Whatever tells the test what the right answer is. It can be one +of three things: + +- **The filesystem itself.** Build the tree in a temp dir and compare + PwrDisk's answer with `du`, `stat`, `find`, `df` before and after a real + deletion, or `cp -c` clones and `hdiutil` disk images on macOS. +- **A slow, obviously correct version** of the function, such as a + recursive walk with an inode set, or a guard that judges by `(dev, ino)` + instead of by spelling. +- **A second code path** that must give the same answer, such as one worker + against twelve, or the canonical path against a symlink to it. Comparing + two paths is called a *differential* test. + +> *"Deleting the selection frees at least the reclaim estimate's lower +> bound."* Checked with real `cp -c` clones and `df` on an APFS image, HEAD +> promises 4 MiB, exact, and deleting frees 2 MiB. + +The three work together. A property needs an oracle to say what "correct" +means, and a model test usually uses the filesystem as its oracle. + +## What the history showed + +Each test below ran against the code from just before the fix, extracted +with `git archive` or `git show` into a scratch directory, and passed on +the fix and on `main`. "Runs" is the number of generated cases to the first +failure (min/median/max over 20 seeds). + +| Fix | Bug | Test | Found in | +| --- | --- | --- | --- | +| #76, #97 | The removal guard refused everything under `/private/tmp` (38 days, v0.10.0–v0.14.0), then allowed `/Users/` (v0.10.0–v0.16.0). Invariant 4 has had 14 fixes in under six weeks, 4 of them undoing an over-refusal an earlier fix caused. | Oracle: a guard judged by `(dev, ino)` on generated trees with links | Runs 1/1/4 and 1/3/8 | +| #103, #104 | #97 introduced both: one disk's confirmed share applied to every disk, and an agent's worker ran at 100% when the window's limit was Off. Fixed 2.5 hours later. A test asserted one share for one disk, so it could never fail. | Model: 17 kinds of command over three disks | #103 median 440 runs; #104 shrank to 5 commands | +| #92 | A removal worker that could not start left the window on Removing forever (40 days, v0.9.0–v0.16.0). #90's test asserted the silent empty-path item 53 minutes earlier. | Model on real files, with a real thread limit | Runs 1/3/10 | +| #10 | Files in a folder the scan could not read were dropped, and the root still said its totals were complete (35 days). The test checked the flag on the locked folder only. | Oracle: a slow walk, `find`, `stat` and `du` on generated trees | Runs 1/2/11; shrunk to `chmod 000 a` | +| #34 | A search matching only an empty directory counted 1 and showed nothing (37 days, eight releases). | Property with a slow oracle | Runs 2/26/117; shrunk to `A/b` | +| #5 | Two marks differing only in case both became targets, and the child was counted twice. | Differential against an O(n²) nesting check | Shrunk to `["a", "A/a"]` | +| #19 | Linking a window to earlier MCP marks moved the window's root. The test fake asserted "the fake has one tree", so it couldn't see the move. | Model with a real socket and a fake window | Runs 1/1/3 | +| #58, #29 | Clone accounting claimed more than it could measure: repeated bytes above shared bytes, and MCP saying "Frees 1.0 MiB" when deletion freed 0. | Property; oracle with `cp -c` and `df` | Median 246 runs; median 1 run | +| #70, #72 | The main window opened 48 points off a 1512-point screen, and new windows opened on the primary display, not the one in use. | Property over random display layouts | Runs 1/2/5 and 1/3/22 | +| #87 → #88 | Unbounded `git status` probes, then a cut probe that left `git-lfs` running. #88 fixed #87's cut 95 minutes later. | Model; oracle with `kill -0` | Runs 1/1/2; 5 of 5 runs | +| #31 | Mount sources printed as `My\040Share`. The mount *point* half was fixed earlier by a separate commit. | Property: decode(encode(x)) == x | Runs 1/1/3 | + +Still on `main` when this was written, found by running the same tests +against it: a scan root spelled through a symlink (`/var`, +`/Volumes/Macintosh HD`, `/tmp`) gets past the system-tree, profile and +mount guards, and crosses into a disk mounted inside it. The MCP tests +mark files under `/var/folders/…`, which the guards refuse under its real +name, `/private/var/folders/…`. They pass because of the bug. The same +run found an APFS reclaim estimate that promises 4 MiB where deleting frees +2 MiB, and marks that forget an earlier removal inside them. + +## When to write one + +- **Fixing a bug.** Write the rule the bug broke as a property or model + invariant, and confirm it fails on the pre-fix code before you fix it. + Also keep the shrunk counterexample as a plain `#[test]`, so the + regression has a name. +- **Anything that deletes, or refuses to** (`removal.rs`, + `removal_limit.rs`, `mark_guard.rs`). Write an oracle that judges by + identity: `(dev, ino)` from `stat`, the real mount table, the real home. + Generate the same directory under every spelling it can have: through a + symlink, `/tmp` and `/private/tmp`, the Data volume, a trailing `/`, + another case, NFD. The verdict must not change. +- **Sizes and totals** (`scan.rs`, `tree.rs`, `sharing.rs`, `space.rs`). + The filesystem is the oracle. Generate the shapes fixtures rarely build: + - hardlinks inside and across directories, and to a file outside the root; + - symlinks to files, to directories, in loops, and dangling; + - sparse and zero-byte files; + - APFS clones (`cp -c`), then one copy truncated, appended to or + overwritten; + - a disk image mounted inside the tree (`hdiutil` on macOS); + - deep and wide directories, and odd names: `\`, newlines, emoji, NFC + and NFD. +- **State over time:** marks across removals and rescans, the limit and + Review's confirmation, the removal run, the git probe store, the link + between `pwrdisk mcp` and the window. Write a model: a `Vec` of commands + from proptest, applied to the real code and to a few lines of plain Rust. +- **Pure logic with rules:** treemap layout, filters, `PathStyle`, size + formatting, window placement, mount table parsing. Write a property. +- **Two places answer the same question,** such as the canonical path and + a link to it, one worker and twelve, `Draft` and `Tree::build`, Review's + phrase and the worker's limit. Write a differential test that they agree. +- **Before an `assert_eq!` pins a refusal, a zero or a count,** say the + rule in words. If the rule and the output disagree, the output is the + bug. + +## How to write them + +- **Put the property beside the promise it checks,** in the module's + `#[cfg(test)] mod tests` or a `tests/` file of the crate, as the house + rules ask. `cargo xtask test` runs `cargo test --workspace`, so CI runs it + on Linux, macOS and Windows with no extra wiring. +- **proptest is a dev-dependency** of the crate that uses it: + `proptest = "1.12"` under `[dev-dependencies]`. 1.12.0 is already in + `Cargo.lock` through gpui's test support, so adding it pulls no new crate. + `licenses/about.toml` ignores dev-dependencies, so `THIRD_PARTY_LICENSES` + does not change, but the `licenses` CI job still runs because a + `Cargo.toml` changed. +- **Test code is linted.** `cargo xtask lint` runs clippy with + `--all-targets`, so pedantic lints apply to properties and generators + too. +- **Build inputs the way the filesystem does.** Generate a list of + operations (make directory, write file, hardlink, symlink, `cp -c`, + mount, mark, remove, rescan) and apply them to a `tempfile::tempdir()`, + not random structs. Don't generate states the system can't produce: + APFS never reports a clone group member with private bytes, for example. + Impossible states give false failures. +- **Test both spellings of a temp root.** macOS temp dirs live under + `/var`, a link to `/private/var`. A fixture that uses only one spelling + sees only one verdict: the MCP fixtures pass under `/var/folders` because + the guards compare spelling, and #58 moved its fixture into the checkout + to get away from `/private`. Run the property under both. +- **Take the property from a promise:** the invariant in `AGENTS.md`, a + doc comment, `docs/guide.md`, or what the user wants. Never take it from + today's output. +- **Narrow, don't weaken.** A counterexample may be a case the code handles + on purpose, such as PiB being the last unit or a hardlink whose other + name survives freeing nothing. If so, restrict the generator or add + `prop_assume!`, with a comment saying why. Don't loosen the assertion + until it passes. +- **Budget the runs.** + - Pure properties: 256 cases, and a test under about a second in debug. + - Real-filesystem oracles: 32 to 64 cases. Disk images (`hdiutil`) cost + about a second each, so gate them to macOS and keep them few. + - Raise `PROPTEST_CASES` locally when hunting. +- **Don't commit replay files.** Set `failure_persistence: None` in the + `ProptestConfig` so a failure writes no `proptest-regressions/` file. + Copy the shrunk input from the failure message into a named `#[test]`. +- **A property failure on an unrelated PR is a real bug.** Reproduce it from + the printed input and fix it or file it. Never re-run CI to get green. +- **Removal tests remove only inside their temp dir.** The guards apply to + tests too; use permanent mode so nothing reaches the real Trash. diff --git a/docs/releasing.md b/docs/releasing.md new file mode 100644 index 00000000..f4e00f91 --- /dev/null +++ b/docs/releasing.md @@ -0,0 +1,165 @@ +# Releasing + +1. Bump `version` in `[workspace.package]` of the root `Cargo.toml`, and move + `CHANGELOG.md`'s Unreleased entries under a matching `## vX.Y.Z` heading. + `cargo xtask release-check --tag vX.Y.Z` checks the two agree. +2. Verify all preparation, commit it as one `chore(release): vX.Y.Z` + commit, and push directly to `main` as a fast-forward update. Do not + open a release-prep PR. Push the `vX.Y.Z` tag on that exact commit. +3. Approve the `apple-signing` and `windows-signing` deployments in the + Actions tab when the run pauses for them. +4. The run creates a GitHub **Pre-release** with every asset once all + platforms are in. Install it from the DMG and Setup.exe, check it, then + promote it: + + ```sh + gh release edit vX.Y.Z --repo pwrdrvr/PwrDisk --latest --prerelease=false + ``` + + Installed copies on Stable · Latest, the default channel, see a release + only once it is promoted; until then it reaches Stable · Prerelease and + Beta · Prerelease. Promote suffix-free tags only. + +The changelog section is the release's notes on GitHub and the notes +Velopack keeps with the update. A tag whose version or section is missing +fails in the first job, before anything is built or signed. + +To rebuild an existing tag, run the Release workflow by hand with **Use +workflow from** set to that tag, and the same tag in the form. The signing +environments accept only `v*` tags, so a run started from a branch stops in +the first job. The release is created only when every platform is in, so a +failed run leaves nothing to clean up; a run for a tag that already has a +release fails at the end, so delete that release first. + +## What a release contains + +| Platform | Assets | +| --- | --- | +| macOS | `PwrDisk--universal.dmg` and the same file as `PwrDisk.dmg`, `PwrDisk-osx-Portable.zip`, `PwrDisk--osx-full.nupkg` (and `-delta`), `releases.osx.json`, `assets.osx.json`, `RELEASES-osx`, `PwrDisk--macos-SHA256SUMS` | +| Windows x64 | `PwrDisk-win-Setup.exe`, `PwrDisk-win.msi`, `PwrDisk-win-Portable.zip`, `PwrDisk--full.nupkg` (and `-delta`), `releases.win.json`, `assets.win.json`, `RELEASES` | +| Windows ARM64 | the same with `win-arm64` in place of `win` | +| Windows, both | `PwrDisk--windows-SHA256SUMS` | +| Linux | `pwrdisk---linux.tar.gz` and `.sha256`, for x86_64 and aarch64, and the same tarballs as `pwrdisk--linux.tar.gz` | + +Velopack's installer and portable names carry no version, and the DMG and +tarballs get unversioned copies, so links such as +`https://github.com/pwrdrvr/PwrDisk/releases/latest/download/PwrDisk-win-Setup.exe` +and `.../latest/download/PwrDisk.dmg` stay good once a release is promoted. +The README's download buttons rely on them; rename one and update it too. The `releases..json` +feeds are what installed copies read; never delete them from a release. + +## Versions + +PwrDisk's first release is 0.12.0: the fork carries on from disktree 0.11.0, +the last version it took from upstream, rather than restarting, so a version +always says which is newer. Tags follow the Pwr family's channels: a +suffix-free `vX.Y.Z` for stable releases, `-rc.N` for candidates, `-beta.N` +and `-alpha.N` for builds off `main`. Velopack compares versions as SemVer. + +A preview build for a pull request is versioned `-pr.`; see +`.github/workflows/README.md`. + +## Velopack + +Windows and macOS install and update through +[Velopack](https://docs.velopack.io), as PwrRoute does. The app runs +Velopack's startup hook first in `main` (`crates/disktree-app/src/updater.rs`) +and reads the release list from GitHub's API without a token, so the +repository must stay public for updates to work. + +The sign jobs install the `vpk` CLI with `scripts/release/install-vpk.sh`, +only from a package whose SHA-512 matches the one pinned there. Its +`VPK_VERSION` must equal the `velopack` crate's `=` pin in +`crates/disktree-app/Cargo.toml`: upgrade both, and the hash, together, then +rerun `scripts/release/velopack-notices.sh` to regenerate +`licenses/velopack.txt`, the notices for the binaries `vpk` adds +(`Update.exe`, `Setup.exe`, the stub and `UpdateMac`). Both the Windows +install and the Mac app carry that file as `VELOPACK-NOTICES.txt`. + +Linux does not use Velopack: `vpk`'s Linux output is an AppImage, and its +updater only runs from one. The tarball updates by downloading the next +release. + +To rebuild an existing tag, run the Release workflow by hand with **Use +workflow from** set to that tag, and the same tag in the form. The signing +environments accept only `v*` tags, so a run started from a branch stops +before drafting anything. + +## Signing + +Release signing uses two GitHub environments. Both accept deployments only +from `v*` tags and wait for a required reviewer, so every release run pauses +until it is approved in the Actions tab. A release without full signing +credentials fails; it never ships unsigned. + +### `apple-signing` + +Used by `macos-sign` only. `macos-prepare` builds the universal app on a +hosted runner without any credential and hands it over as an archive whose +SHA-256 travels as a job output; `macos-sign` checks both, never checks out +or builds source, and fails if any of the five secrets is missing. + +| Secret | What | +| --- | --- | +| `CSC_LINK` | the Developer ID Application `.p12`, base64 | +| `CSC_KEY_PASSWORD` | its password | +| `APPLE_API_KEY_BASE64` | an App Store Connect API key (`AuthKey_*.p8`), base64 | +| `APPLE_API_KEY_ID` | that key's ID | +| `APPLE_API_ISSUER` | its issuer ID | + +The signing identity is read from the certificate itself. Upload all five from +1Password, the same item PwrAgent and PwrRoute use: + +```sh +scripts/release/upload-csc-link-from-1password.sh --list-accounts +OP_ACCOUNT= scripts/release/upload-csc-link-from-1password.sh +``` + +`scripts/release/macos-signing.py` imports the certificate into a keychain +of the job's own and saves the API key as the notarytool profile +`pwrdisk-notary`; it restores the runner's keychain list and deletes both +afterwards, even when a later step fails. `vpk pack` signs the app with the +hardened runtime and `packaging/macos/PwrDisk.entitlements` (none), +notarizes and staples it; `macos-dmg.sh` does the same for the DMG cut from +it. The job checks the team identifier (`T44CNHC4UH`), both staples and +`spctl` before anything is uploaded. + +### `windows-signing` + +Used by `windows-sign`, which packs and signs what both Windows build jobs +(x64 on `windows-2025`, ARM64 on `windows-11-arm`) hand over, checking each +archive against the digest its build job reported. It never checks out or +builds source, and fails if any of the seven values is missing. `vpk pack` +signs `pwrdisk.exe`, `Update.exe` and the launcher, then `Setup.exe` and +the MSI, through the Artifact Signing dlib it ships. Signing uses Azure Artifact +Signing, with the same signing account and profile as PwrAgent and its own +Entra app registration; see PwrAgent's `docs/desktop-windows-signing.md` for +how those were set up. Upload all seven values from the 1Password item +"PwrDisk - Windows Azure Trusted Signing": + +```sh +OP_ACCOUNT= scripts/release/upload-azure-signing-from-1password.sh +``` + +| Variable | Value | +| --- | --- | +| `WIN_AZURE_SIGN_ENDPOINT` | `https://eus.codesigning.azure.net/` | +| `WIN_AZURE_SIGN_ACCOUNT` | `pwrdrvrsigning` | +| `WIN_AZURE_SIGN_PROFILE` | `pwrdrvr-public-trust` | +| `WIN_AZURE_SIGN_PUBLISHER_NAME` | `PwrDrvr LLC` | + +| Secret | What | +| --- | --- | +| `AZURE_TENANT_ID` | the Entra directory (tenant) ID | +| `AZURE_CLIENT_ID` | the signing app registration's client ID | +| `AZURE_CLIENT_SECRET` | its client secret; the 1Password item records when it expires | + +Every one of those files' signatures must be valid, timestamped and issued +to the publisher above, or the job fails. + +## Runners + +Every job uses standard GitHub-hosted runners, which are free for a public +repository, macOS included. Larger runners are billed even on public +repositories, so do not switch to them. Nor to self-hosted ones: this repository takes pull +requests from forks, and those must never reach a persistent machine. diff --git a/docs/sandboxer.md b/docs/sandboxer.md new file mode 100644 index 00000000..8aa83d89 --- /dev/null +++ b/docs/sandboxer.md @@ -0,0 +1,300 @@ +# Remote Linux verification with Sandboxer + +Use this procedure when the thread has Sandboxer MCP tools. Run Linux +builds, lint, tests and integration checks in the remote VM. This keeps +the Rust compile load off the local machine. Use the headless local +commands in [AGENTS.md](../AGENTS.md#commands) when Sandboxer is not +available; never `make run` or `cargo run`, which open a window. + +Sandboxer is Linux only and has no desktop. A check that needs an on-screen +macOS window, screenshots included, runs in the PwrSuiteLab VM as +[headed-e2e-pwrsuitelab.md](headed-e2e-pwrsuitelab.md) says, never on the +local desktop. + +This procedure follows PwrRoute's Sandboxer workflow. It uses committed +source, one VM per thread, a shared base snapshot and saved exit codes. +Use only the Sandboxer MCP tools. Do not use the `sbx` CLI. + +Start new VMs from `pwrdisk-base-us-east` in `us-east`. The snapshot has +the tools, dependencies and Cargo build cache from a verified commit. +This avoids repeated installation and compilation for each thread. Keep +the checkout at `~/pwrdisk/repo` to reuse that cache. Always transfer and +check out the commit under test; the snapshot's commit can be older. + +## Select a sandbox + +1. Discover the current Sandboxer tool schemas. In PwrAgent, use + `search_mcp_tools`, then `call_mcp_tool` to call a discovered tool. +2. Call `list_sandboxes`. Reuse this thread's VM. Use `resume_sandbox` if + it is stopped. Do not use a VM that belongs to another thread. +3. If a new VM is necessary, call `list_snapshots` with + `name: "pwrdisk-base-us-east"`. Then call `create_sandbox` with these + values: + + | Field | Value | + | --- | --- | + | `name` | `pwrdisk-`, with `/` replaced by `-` | + | `from` | `pwrdisk-base-us-east` | + | `noEnv` | `true` | + | `region` | `us-east` | + | `type` | `large` | + | `labels` | `{"repo": "pwrdisk"}` | + | `ttlSeconds` | `7200` | + + `noEnv` excludes the account's environment variables and secret files. + If the schema does not have this field, report the blocker. Do not + create the VM. The TTL stops the VM after two hours, even during a run. + Select a longer TTL at creation if the checks need more time. + Always set `region`; the default can select another region. + If the snapshot is missing, [build and test it](#build-or-refresh-the-base-snapshot). + Do not silently create a cold VM for each thread. +4. Pass `sandboxId` on every later call. The implicit default can refer to + another task's VM. + +The setup script supports Ubuntu with `apt`, `sudo`, Python 3 and Git. +Check `uname -m` and `/etc/os-release` before setup. Record the actual OS +and architecture in the results. Do not assume that all hosts are equal. + +## Send the source + +Commit the changes first. Verify `HEAD`, including the scripts in this +guide. Do not transfer a working tree with uncommitted changes. + +For a commit already pushed to `pwrdrvr/PwrDisk`, use the public HTTPS +remote. No GitHub token is required. In a VM started from the snapshot: + +```sh +cd ~/pwrdisk/repo +git fetch origin +git checkout --detach +``` + +Only a cold VM needs a clone: + +```sh +mkdir -p ~/pwrdisk +git clone https://github.com/pwrdrvr/PwrDisk.git ~/pwrdisk/repo +cd ~/pwrdisk/repo +git fetch origin +git checkout --detach +``` + +For an unpublished commit, use the bundle transfer below. Both methods +use `~/pwrdisk/repo`. Keep that path for later runs to reuse `target/`. +Never change the checkout while a check is running. + +### Transfer an unpublished commit + +The two transfer scripts come from PwrRoute, with PwrDisk paths and a +check that rejects uncommitted changes. They also retrieve logs and +artifacts without passing file contents through the agent's context. + +1. The base snapshot has `~/pwrdisk/bin/transfer.py`. For a cold VM, read + [transfer.py](../scripts/sandboxer/transfer.py) locally. Use the MCP + `write_file` tool to put that content at + `/home/user/pwrdisk/bin/transfer.py` in the VM. +2. Use `exec` with `detached: true` to start the server: + + ```sh + python3 ~/pwrdisk/bin/transfer.py + ``` + +3. Call `host_port` with `port: 8722` and `public: false`. Keep the + returned URL in a local shell variable named `URL`. It contains an + access token. Do not put it in a commit, PR, status report or log. +4. On the local machine, run: + + ```sh + scripts/sandboxer/transfer.sh send "$URL" + ``` + + The script uploads a Git bundle and prints the full commit SHA. +5. In a cold VM, replace `` with that value: + + ```sh + cd ~/pwrdisk + git clone files/.bundle repo + cd repo + git remote set-url origin https://github.com/pwrdrvr/PwrDisk.git + git checkout --detach + rm ../files/.bundle + ``` + + In a VM started from the base snapshot, or for later runs: + + ```sh + cd ~/pwrdisk/repo + git fetch ../files/.bundle HEAD + git checkout --detach + rm ../files/.bundle + ``` + +After a resume, check the transfer server before use. Start it again if +`curl -s -o /dev/null -w '%{http_code}' localhost:8722/probe` does not +return `404`. + +## Run the checks + +[verify.sh](../scripts/sandboxer/verify.sh) runs in the VM. Use `exec` +with `cwd: "pwrdisk/repo"`, `detached: true` and this command: + +```sh +scripts/sandboxer/verify.sh all +``` + +Save the returned `processId`. Use `command_status` with that ID and the +same `sandboxId` until the process exits. Pass the returned output offsets +to later calls. Long builds can exceed a synchronous `exec` timeout. Do +not start a second run because the first call has returned. + +| Step | Command run by `verify.sh` | +| --- | --- | +| `setup` | Install CI's GPUI libraries, build tools, OpenSSH, Bun, the pinned Rust toolchain, and both musl scanner targets; fetch locked dependencies. | +| `lint` | `cargo xtask lint` (rustfmt check and workspace clippy). | +| `test` | `cargo xtask test` (workspace tests and release-script tests). | +| `build` | `cargo xtask portable` (release app and embedded x64/ARM64 SSH helpers). | +| `e2e` | `bun scripts/test-ssh.ts` (isolated localhost SSH scans and error cases). | +| `all` | Setup, lint, test, build and E2E in that order. | + +`all` stops if setup fails. Otherwise, it runs every check even if one +fails. Its final exit code is nonzero if any check fails. The script holds +a lock to prevent concurrent runs in the same checkout. + +Run `setup` once before individual checks. In a VM started from the base, +installed tools and downloaded dependencies are reused. Repeat setup when +the toolchain or system dependencies change. Examples: + +```sh +scripts/sandboxer/verify.sh setup +scripts/sandboxer/verify.sh lint +scripts/sandboxer/verify.sh test -p disktree-core +scripts/sandboxer/verify.sh test -p disktree-app +scripts/sandboxer/verify.sh build +scripts/sandboxer/verify.sh e2e +``` + +Arguments after `test` select `cargo test --locked` instead of the full +xtask. Such a run does not include the Python release-script tests. + +The window-harness tests are in `disktree-app`. They draw frames, send +keys, confirm removal of temporary fixtures and drive the real link +socket. They run in `test`; they do not need Xvfb. The `e2e` step uses +temporary SSH keys and a localhost server. It does not use real SSH hosts. +It builds the portable app again, which is incremental after `build`. +PwrDisk has no separate desktop E2E runner. Do not substitute PwrRoute's +`cargo xtask e2e` command, and do not launch the app on the local desktop +instead; see [Mac GUI checks](headed-e2e-pwrsuitelab.md). + +## Read and report the results + +Each invocation replaces `.local/sandboxer/status`. Its first line is the +commit SHA. Each step adds ` exit= secs=` and writes +`.local/sandboxer/.log`. An `all` run ends with `all exit=<0|1>`. +The directory is ignored by Git. + +Read bounded sections of the logs: + +```sh +cat .local/sandboxer/status +tail -n 40 .local/sandboxer/lint.log +grep -nE '^test result|FAILED|panicked' .local/sandboxer/test.log | tail -n 20 +tail -n 40 .local/sandboxer/e2e.log +``` + +Report the sandbox ID, OS, architecture, commit, selected checks and exit +codes. Read a failed step's log and state the cause. A missing final +status line is an incomplete run, not a pass. The lint gate must pass. + +To retrieve a file, copy it to `~/pwrdisk/files/` in the VM. Then use the +authenticated transfer URL on the local machine: + +```sh +scripts/sandboxer/transfer.sh get "$URL" test.log /tmp/pwrdisk-test.log +``` + +The transfer server accepts single file names. Archive a directory before +download. Screenshots are not made here: they come from a contrived tree in +the PwrSuiteLab VM, and [pr-screenshots.md](pr-screenshots.md) covers making +and attaching them. + +## Build or refresh the base snapshot + +Refresh `pwrdisk-base-us-east` when `Cargo.lock`, `rust-toolchain.toml`, +the setup script or CI's system libraries change. Also refresh it when +its commit is far behind `main`. New threads must still select their own +commit; a base snapshot is a cache, not proof that a change passes. + +1. Use a builder VM owned by this thread. Create it in `us-east` with + `type: "large"`, `noEnv: true`, and `name: "pwrdisk-base-builder"`. + Start from the existing base when possible. Omit `from` only when no + base exists. A stopped, verified VM from this thread can be the builder. +2. Transfer the commit to cache, normally the latest `main`. Use the PR's + commit when the snapshot tools are first added. Check it out at + `~/pwrdisk/repo`. Run `scripts/sandboxer/verify.sh all` with a detached + `exec`. Wait for exit 0 and record every status line. Resolve failures + before publishing a base. +3. Stop any transfer server with `kill_command`. Check that no build or + test is running. Keep a copy of the transfer script outside the checkout: + + ```sh + mkdir -p ~/pwrdisk/bin ~/pwrdisk/files + cp ~/pwrdisk/repo/scripts/sandboxer/transfer.py ~/pwrdisk/bin/transfer.py + ``` + +4. Remove verification logs, transferred files and temporary test artifacts + from the builder. Keep `target/`, the Cargo registry and installed tools. + For the standard paths: + + ```sh + cd ~/pwrdisk/repo + rm -rf .local/sandboxer + find ~/pwrdisk/files -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + + git status --porcelain + git rev-parse HEAD + ``` + + Inspect `/tmp` and remove any test fixtures or logs left by this thread. + The Git status must be empty. Verify that the builder has no account + tokens or private artifacts. `noEnv` does not remove files inherited + from an earlier snapshot. +5. Call `save_snapshot` with `sandboxId`, `name: "pwrdisk-base-us-east"` + and labels `repo: pwrdisk`, `role: base`, `region: us-east`, + `commit: `. Wait for it to finish. Check `list_snapshots` for + the name, ready state and labels. Saving an existing unversioned name + replaces it; coordinate refreshes so builders do not overwrite each other. +6. Test a new VM from the saved snapshot. Pass `from: "pwrdisk-base-us-east"`, + `region: "us-east"`, `type: "large"` and `noEnv: true` to + `create_sandbox`. Check the inherited commit, clean Git status, + `target/`, both musl scanner targets and the transfer script. Run + `scripts/sandboxer/verify.sh all` there. Require exit 0 for every step. + A second run in the builder does not test snapshot restoration. +7. Record the builder commit, test VM ID and step times in the PR or task + results. Stop both VMs after the test. Delete a dedicated builder when + it is no longer needed; the named snapshot survives its deletion. + +## Scope and lifecycle + +- Linux checks do not verify macOS, Windows, another CPU architecture or + the oldest supported glibc. Keep the relevant platform CI checks. A macOS + window is checked in the [lab VM](headed-e2e-pwrsuitelab.md); for a + Windows or Linux window, ask the operator. +- `test` includes the default tests. It does not run ignored tests. The + `e2e` step selects only the ignored real SSH tests. Run mount-namespace + tests with [test-linux-mounts.sh](../scripts/test-linux-mounts.sh) only + on a host that permits unprivileged user and mount namespaces. Report + missing host permissions; do not count a skipped check as a pass. +- Setup uses the commit's `rust-toolchain.toml` and CI's library list. It + installs Bun only if Bun is absent. Record tool versions from the setup + log. Keep the package list aligned with `.github/workflows/ci.yml`. +- The wrapper disables dev/test debug info to reduce cache size. Its + cached artifacts can differ from a local build. It does not change + release profiles. +- Call `stop_sandbox` after each run. This stops compute billing and keeps + the disk for this thread's next run. Resume it instead of creating a VM. +- Attach the PR to the thread and call `watch_thread_pull_request` with + `notifyOn: ["merged", "closed"]`. PwrAgent releases VMs created by the + thread when its attached PRs merge or close. Check that the PR is + attached; report a cleanup failure. Without that integration, delete + this thread's VM with `delete_sandbox` when it is no longer needed. +- Use PwrDisk's base in `us-east`. Do not use a PwrRoute snapshot. Keep the + named base when deleting a thread's VM; it serves later threads too. diff --git a/licenses/about.hbs b/licenses/about.hbs new file mode 100644 index 00000000..c6a5b994 --- /dev/null +++ b/licenses/about.hbs @@ -0,0 +1,34 @@ +Crates +------ + +The Rust crates compiled into PwrDisk, for the platforms releases are built +for. Workspace crates (PwrDisk's own, MIT) are not listed. + +Dependency Summary +~~~~~~~~~~~~~~~~~~ +{{#each overview}} + +{{name}} ({{count}}) +{{#each indices}} +{{#with (lookup ../../licenses this)}} +{{#each used_by}} +- {{crate.name}}@{{crate.version}}{{#if crate.repository}} | {{crate.repository}}{{/if}} +{{/each}} +{{/with}} +{{/each}} +{{/each}} + +License Texts +~~~~~~~~~~~~~ +{{#each licenses}} + +{{name}} ({{id}}) +----------------------------------------------------------- + +Applies to: +{{#each used_by}} +- {{crate.name}}@{{crate.version}} +{{/each}} + +{{{text}}} +{{/each}} diff --git a/licenses/about.toml b/licenses/about.toml new file mode 100644 index 00000000..30e427db --- /dev/null +++ b/licenses/about.toml @@ -0,0 +1,37 @@ +# cargo-about's configuration, for `cargo xtask licenses` (PwrDisk's own +# crates, into THIRD_PARTY_LICENSES) and for +# scripts/release/velopack-notices.sh, which writes licenses/velopack.txt for +# the Velopack binaries vpk adds to the release. Copied from PwrRoute's +# about.toml; a license id that is not accepted here fails both, and adding +# one is a legal decision. +accepted = [ + "0BSD", + "Apache-2.0", + "Apache-2.0 WITH LLVM-exception", + "BSD-2-Clause", + "BSD-3-Clause", + "BSL-1.0", + "CC0-1.0", + "ISC", + "MIT", + "MPL-2.0", + "Unicode-3.0", + "Unlicense", + "Zlib", + "bzip2-1.0.6", +] +targets = [ + "aarch64-apple-darwin", + "x86_64-apple-darwin", + "x86_64-unknown-linux-gnu", + "aarch64-unknown-linux-gnu", + "x86_64-pc-windows-msvc", + "aarch64-pc-windows-msvc", +] +ignore-build-dependencies = true +ignore-dev-dependencies = true +ignore-transitive-dependencies = false + +# Per-crate exceptions, mirroring deny.toml's [[licenses.exceptions]]. +[webpki-roots] +accepted = ["CDLA-Permissive-2.0"] diff --git a/licenses/bundled.txt b/licenses/bundled.txt new file mode 100644 index 00000000..42dbaacd --- /dev/null +++ b/licenses/bundled.txt @@ -0,0 +1,41 @@ +Bundled Non-Cargo Components +---------------------------- + +These ship inside PwrDisk but are not crates, so cargo-about cannot list +them. Edit licenses/bundled.txt when one changes. + +- disktree, by Tobi Lütke, which PwrDisk is a fork of. MIT; its notice is + PwrDisk's own, in LICENSE. +- Velopack's native binaries, added to release packages by `vpk pack` + 1.2.161: Update.exe, Setup.exe and the launcher stub (Windows), the MSI's + velopack_wix custom-action DLL, and UpdateMac (macOS). MIT, Copyright (c) + 2021 Caelan Sayler, Copyright (c) 2024 Velopack Ltd. | https://github.com/velopack/velopack + The Rust crates compiled into them, with their license texts, are under + "Velopack's Native Binaries" below (licenses/velopack.txt, written by + scripts/release/velopack-notices.sh). + +DiskHound artifact classification rules and test corpus +----------------------------------------------------- +https://github.com/huntharo/diskhound + +MIT License + +Copyright (c) 2026 Thomas Zarebczan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/licenses/velopack.hbs b/licenses/velopack.hbs new file mode 100644 index 00000000..86cfb056 --- /dev/null +++ b/licenses/velopack.hbs @@ -0,0 +1,28 @@ +Dependency Summary +~~~~~~~~~~~~~~~~~~ +{{#each overview}} + +{{name}} ({{count}}) +{{#each indices}} +{{#with (lookup ../../licenses this)}} +{{#each used_by}} +- {{crate.name}}@{{crate.version}}{{#if crate.repository}} | {{crate.repository}}{{/if}} +{{/each}} +{{/with}} +{{/each}} +{{/each}} + +License Texts +~~~~~~~~~~~~~ +{{#each licenses}} + +{{name}} ({{id}}) +----------------------------------------------------------- + +Applies to: +{{#each used_by}} +- {{crate.name}}@{{crate.version}} +{{/each}} + +{{{text}}} +{{/each}} diff --git a/licenses/velopack.txt b/licenses/velopack.txt new file mode 100644 index 00000000..6acb427e --- /dev/null +++ b/licenses/velopack.txt @@ -0,0 +1,8591 @@ +Velopack's Native Binaries +-------------------------- + +The Rust crates compiled into Velopack 1.2.161's Update.exe, Setup.exe, +launcher stub and velopack_wix DLL (Windows x64 and ARM64) and UpdateMac +(macOS), which `vpk pack` adds to PwrDisk's release packages. +Velopack's own crates (velopack, velopack_bins, velopack_l18n, +velopack_wix) are listed too. +Generated by scripts/release/velopack-notices.sh from Velopack's Cargo.lock at +tag 1.2.161; do not edit by hand. + +Dependency Summary +~~~~~~~~~~~~~~~~~~ + +Apache License 2.0 (175) +- num_threads@0.1.7 | https://github.com/jhpratt/num_threads +- powerfmt@0.2.0 | https://github.com/jhpratt/powerfmt +- deranged@0.5.8 | https://github.com/jhpratt/deranged +- ureq-proto@0.6.4 | https://github.com/algesten/ureq-proto +- utf8_iter@1.0.4 | https://github.com/hsivonen/utf8_iter +- zeroize@1.9.0 | https://github.com/RustCrypto/utils +- rustix@1.1.5 | https://github.com/bytecodealliance/rustix +- ring@0.17.14 | https://github.com/briansmith/ring +- fast_image_resize@6.1.0 | https://github.com/cykooz/fast_image_resize +- windows-collections@0.3.2 | https://github.com/microsoft/windows-rs +- windows-core@0.62.2 | https://github.com/microsoft/windows-rs +- windows-future@0.3.2 | https://github.com/microsoft/windows-rs +- windows-implement@0.60.2 | https://github.com/microsoft/windows-rs +- windows-interface@0.59.3 | https://github.com/microsoft/windows-rs +- windows-link@0.2.1 | https://github.com/microsoft/windows-rs +- windows-numerics@0.3.1 | https://github.com/microsoft/windows-rs +- windows-result@0.4.1 | https://github.com/microsoft/windows-rs +- windows-strings@0.5.1 | https://github.com/microsoft/windows-rs +- windows-sys@0.52.0 | https://github.com/microsoft/windows-rs +- windows-sys@0.59.0 | https://github.com/microsoft/windows-rs +- windows-sys@0.61.2 | https://github.com/microsoft/windows-rs +- windows-targets@0.52.6 | https://github.com/microsoft/windows-rs +- windows-threading@0.2.1 | https://github.com/microsoft/windows-rs +- windows@0.62.2 | https://github.com/microsoft/windows-rs +- windows_aarch64_msvc@0.52.6 | https://github.com/microsoft/windows-rs +- windows_x86_64_msvc@0.52.6 | https://github.com/microsoft/windows-rs +- zopfli@0.8.3 | https://github.com/zopfli-rs/zopfli +- web-time@1.1.0 | https://github.com/daxpedda/web-time +- moxcms@0.8.1 | https://github.com/awxkee/moxcms.git +- pxfm@0.1.30 | https://github.com/awxkee/pxfm +- cvt@0.1.2 | https://github.com/marmistrz/cvt +- pretty-bytes-rust@0.3.0 | https://github.com/MrDesjardins/pretty-bytes +- self_cell@1.3.0 | https://github.com/Voultapher/self_cell +- sys-locale@0.3.2 | https://github.com/1Password/sys-locale +- ureq@3.4.2 | https://github.com/algesten/ureq +- zune-core@0.5.3 | https://github.com/etemesi254/zune-image +- zune-jpeg@0.5.15 | https://github.com/etemesi254/zune-image/tree/dev/crates/zune-jpeg +- fluent-bundle@0.16.0 | https://github.com/projectfluent/fluent-rs +- fluent-syntax@0.12.0 | https://github.com/projectfluent/fluent-rs +- fluent@0.17.0 | https://github.com/projectfluent/fluent-rs +- intl-memoizer@0.5.3 | https://github.com/projectfluent/fluent-rs +- clap@4.6.7 | https://github.com/clap-rs/clap +- clap_builder@4.6.7 | https://github.com/clap-rs/clap +- clap_derive@4.6.7 | https://github.com/clap-rs/clap +- clap_lex@1.1.1 | https://github.com/clap-rs/clap +- winapi@0.3.9 | https://github.com/retep998/winapi-rs +- anstream@1.0.0 | https://github.com/rust-cli/anstyle.git +- anstyle-parse@1.0.0 | https://github.com/rust-cli/anstyle.git +- anstyle-query@1.1.5 | https://github.com/rust-cli/anstyle.git +- anstyle-wincon@3.0.11 | https://github.com/rust-cli/anstyle.git +- anstyle@1.0.14 | https://github.com/rust-cli/anstyle.git +- colorchoice@1.0.5 | https://github.com/rust-cli/anstyle.git +- crc32fast@1.5.2 | https://github.com/srijs/rust-crc32fast +- is_terminal_polyfill@1.70.2 | https://github.com/polyfill-rs/is_terminal_polyfill +- log-panics@2.1.0 | https://github.com/sfackler/rust-log-panics +- once_cell_polyfill@1.70.2 | https://github.com/polyfill-rs/once_cell_polyfill +- typenum@1.20.1 | https://github.com/paholg/typenum +- http@1.5.0 | https://github.com/hyperium/http +- iana-time-zone@0.1.65 | https://github.com/strawlab/iana-time-zone +- rustls-pki-types@1.15.1 | https://github.com/rustls/pki-types +- memmap2@0.9.11 | https://github.com/RazrFalcon/memmap2-rs +- gif@0.14.2 | https://github.com/image-rs/image-gif +- weezl@0.1.12 | https://github.com/image-rs/weezl +- aligned@0.4.3 | https://github.com/rust-embedded-community/aligned +- as-slice@0.2.1 | https://github.com/japaric/as-slice +- base64@0.23.1 | https://github.com/marshallpierce/rust-base64 +- bitflags@2.13.2 | https://github.com/bitflags/bitflags +- bumpalo@3.20.3 | https://github.com/fitzgen/bumpalo +- cfg-if@1.0.5 | https://github.com/rust-lang/cfg-if +- core-foundation-sys@0.8.7 | https://github.com/servo/core-foundation-rs +- crossbeam-deque@0.8.8 | https://github.com/crossbeam-rs/crossbeam +- crossbeam-epoch@0.9.21 | https://github.com/crossbeam-rs/crossbeam +- crossbeam-utils@0.8.23 | https://github.com/crossbeam-rs/crossbeam +- derivative@2.2.0 | https://github.com/mcarton/rust-derivative +- displaydoc@0.2.7 | https://github.com/yaahc/displaydoc +- either@1.18.0 | https://github.com/rayon-rs/either +- equivalent@1.0.2 | https://github.com/indexmap-rs/equivalent +- errno@0.3.14 | https://github.com/lambda-fairy/rust-errno +- flate2@1.1.10 | https://github.com/rust-lang/flate2-rs +- fnv@1.0.7 | https://github.com/servo/rust-fnv +- form_urlencoded@1.2.2 | https://github.com/servo/rust-url +- glob@0.3.4 | https://github.com/rust-lang/glob +- hashbrown@0.17.1 | https://github.com/rust-lang/hashbrown +- heck@0.5.0 | https://github.com/withoutboats/heck +- httparse@1.10.1 | https://github.com/seanmonstar/httparse +- idna@1.1.0 | https://github.com/servo/rust-url/ +- idna_adapter@1.2.2 | https://github.com/hsivonen/idna_adapter +- indexmap@2.14.2 | https://github.com/indexmap-rs/indexmap +- lazy_static@1.5.0 | https://github.com/rust-lang-nursery/lazy-static.rs +- log@0.4.34 | https://github.com/rust-lang/log +- num-traits@0.2.19 | https://github.com/rust-num/num-traits +- once_cell@1.21.4 | https://github.com/matklad/once_cell +- percent-encoding@2.3.2 | https://github.com/servo/rust-url/ +- png@0.18.1 | https://github.com/image-rs/image-png +- rayon-core@1.13.0 | https://github.com/rayon-rs/rayon +- rayon@1.12.0 | https://github.com/rayon-rs/rayon +- regex-automata@0.4.18 | https://github.com/rust-lang/regex +- regex-syntax@0.8.11 | https://github.com/rust-lang/regex +- regex@1.13.1 | https://github.com/rust-lang/regex +- ring@0.17.14 | https://github.com/briansmith/ring +- rustix@1.1.5 | https://github.com/bytecodealliance/rustix +- rustls@0.23.45 | https://github.com/rustls/rustls +- smallvec@1.16.1 | https://github.com/servo/rust-smallvec +- stable_deref_trait@1.2.1 | https://github.com/storyyeller/stable_deref_trait +- syn@1.0.109 | https://github.com/dtolnay/syn +- time@0.1.45 | https://github.com/time-rs/time +- unic-langid-impl@0.9.6 | https://github.com/zbraniecki/unic-locale +- unic-langid@0.9.6 | https://github.com/zbraniecki/unic-locale +- url@2.5.8 | https://github.com/servo/rust-url +- uuid@1.26.1 | https://github.com/uuid-rs/uuid +- wait-timeout@0.2.1 | https://github.com/alexcrichton/wait-timeout +- waitpid-any@0.3.0 | https://github.com/oxalica/waitpid-any +- block-buffer@0.12.1 | https://github.com/RustCrypto/utils +- chacha20@0.10.2 | https://github.com/RustCrypto/stream-ciphers +- const-oid@0.10.2 | https://github.com/RustCrypto/formats +- cpufeatures@0.3.1 | https://github.com/RustCrypto/utils +- crypto-common@0.2.2 | https://github.com/RustCrypto/traits +- digest@0.11.3 | https://github.com/RustCrypto/traits +- hybrid-array@0.4.15 | https://github.com/RustCrypto/hybrid-array +- sha1@0.11.0 | https://github.com/RustCrypto/hashes +- sha2@0.11.0 | https://github.com/RustCrypto/hashes +- remove_dir_all@1.0.0 | https://github.com/XAMPPRocky/remove_dir_all.git +- rand_core@0.10.1 | https://github.com/rust-random/rand_core +- getrandom@0.2.17 | https://github.com/rust-random/getrandom +- getrandom@0.4.3 | https://github.com/rust-random/getrandom +- bytemuck@1.25.2 | https://github.com/Lokathor/bytemuck +- simplelog@0.12.2 | https://github.com/drakulix/simplelog.rs +- anyhow@1.0.104 | https://github.com/dtolnay/anyhow +- document-features@0.2.12 | https://github.com/slint-ui/document-features +- fdeflate@0.3.7 | https://github.com/image-rs/fdeflate +- fluent-langneg@0.13.1 | https://github.com/projectfluent/fluent-langneg-rs +- fluent-langneg@0.14.2 | https://github.com/projectfluent/fluent-langneg-rs +- fs_at@0.2.1 | https://github.com/rbtcollins/fs_at.git +- image@0.25.10 | https://github.com/image-rs/image +- intl_pluralrules@7.0.2 | https://github.com/zbraniecki/pluralrules +- itoa@1.0.18 | https://github.com/dtolnay/itoa +- libc@0.2.189 | https://github.com/rust-lang/libc +- litrs@1.0.0 | https://github.com/LukasKalbertodt/litrs +- miniz_oxide@0.8.9 | https://github.com/Frommi/miniz_oxide/tree/master/miniz_oxide +- miniz_oxide@0.9.1 | https://github.com/Frommi/miniz_oxide/tree/master/miniz_oxide +- normpath@1.5.2 | https://github.com/dylni/normpath +- num-conv@0.2.2 | https://github.com/jhpratt/num-conv +- objc2-app-kit@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-cloud-kit@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-core-data@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-core-foundation@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-core-graphics@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-core-image@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-core-text@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-core-video@0.3.2 | https://github.com/madsmtm/objc2 +- objc2-quartz-core@0.3.2 | https://github.com/madsmtm/objc2 +- oneshot@0.2.1 | https://github.com/faern/oneshot +- proc-macro2@1.0.107 | https://github.com/dtolnay/proc-macro2 +- quote@1.0.47 | https://github.com/dtolnay/quote +- rand@0.10.3 | https://github.com/rust-random/rand +- rustc-hash@2.1.3 | https://github.com/rust-lang/rustc-hash +- semver@1.0.28 | https://github.com/dtolnay/semver +- serde@1.0.229 | https://github.com/serde-rs/serde +- serde_core@1.0.229 | https://github.com/serde-rs/serde +- serde_derive@1.0.229 | https://github.com/serde-rs/serde +- serde_json@1.0.151 | https://github.com/serde-rs/json +- syn@2.0.119 | https://github.com/dtolnay/syn +- syn@3.0.6 | https://github.com/dtolnay/syn +- thiserror-impl@2.0.20 | https://github.com/dtolnay/thiserror +- thiserror@2.0.20 | https://github.com/dtolnay/thiserror +- time-core@0.1.9 | https://github.com/time-rs/time +- time-macros@0.2.32 | https://github.com/time-rs/time +- time@0.3.55 | https://github.com/time-rs/time +- type-map@0.5.1 | https://github.com/kardeiz/type-map +- typed-path@0.12.3 | https://github.com/chipsenkbeil/typed-path +- unicode-ident@1.0.26 | https://github.com/dtolnay/unicode-ident +- utf8-zero@0.8.1 | https://github.com/algesten/utf8-zero +- utf8parse@0.2.2 | https://github.com/alacritty/vte +- widestring@1.2.1 | https://github.com/VoidStarKat/widestring-rs +- chrono@0.4.45 | https://github.com/chronotope/chrono + +MIT License (36) +- winreg@0.56.0 | https://github.com/gentoo90/winreg-rs +- bytes@1.12.1 | https://github.com/tokio-rs/bytes +- synstructure@0.13.2 | https://github.com/mystor/synstructure +- synstructure@0.14.0 | https://github.com/mystor/synstructure +- velopack_bins@0.0.0-local | https://github.com/velopack/velopack +- velopack_l18n@0.0.0-local +- velopack@0.0.0-local | https://github.com/velopack/velopack +- velopack_wix@0.0.0-local | https://github.com/velopack/velopack +- xdialog@3.1.9 | https://github.com/velopack/xdialog +- fs_extra@1.3.0 | https://github.com/webdesus/fs_extra +- cfb@0.15.0 | https://github.com/mdsteele/rust-cfb +- simple-stopwatch@0.1.4 | https://github.com/huwb/rust-simple-stopwatch +- progress-streams@1.1.0 | https://github.com/pop-os/progress-streams +- strum@0.28.0 | https://github.com/Peternator7/strum +- strum_macros@0.28.0 | https://github.com/Peternator7/strum +- block2@0.6.2 | https://github.com/madsmtm/objc2 +- objc2-encode@4.1.0 | https://github.com/madsmtm/objc2 +- objc2-foundation@0.3.2 | https://github.com/madsmtm/objc2 +- objc2@0.6.4 | https://github.com/madsmtm/objc2 +- webview2-com-sys@0.39.1 | https://github.com/wravery/webview2-rs +- simd-adler32@0.3.10 | https://github.com/mcountryman/simd-adler32 +- zmij@1.0.23 | https://github.com/dtolnay/zmij +- zip@8.6.0 | https://github.com/zip-rs/zip2 +- xml@1.4.0 | https://github.com/kornelski/xml-rs +- aho-corasick@1.1.5 | https://github.com/BurntSushi/aho-corasick +- byteorder-lite@0.1.0 | https://github.com/image-rs/byteorder-lite +- memchr@2.8.3 | https://github.com/BurntSushi/memchr +- termcolor@1.4.1 | https://github.com/BurntSushi/termcolor +- walkdir@2.5.0 | https://github.com/BurntSushi/walkdir +- nix@0.29.0 | https://github.com/nix-rust/nix +- nix@0.31.3 | https://github.com/nix-rust/nix +- strsim@0.11.1 | https://github.com/rapidfuzz/strsim-rs +- color_quant@1.1.0 | https://github.com/image-rs/color_quant.git +- same-file@1.0.6 | https://github.com/BurntSushi/same-file +- winapi-util@0.1.11 | https://github.com/BurntSushi/winapi-util +- os_info@3.15.0 | https://github.com/stanislav-tkach/os_info + +Unicode License v3 (31) +- unicode-ident@1.0.26 | https://github.com/dtolnay/unicode-ident +- icu_collections@2.3.0 | https://github.com/unicode-org/icu4x +- icu_locale_core@2.3.0 | https://github.com/unicode-org/icu4x +- icu_locid@1.5.0 | https://github.com/unicode-org/icu4x +- icu_locid_transform@1.5.0 | https://github.com/unicode-org/icu4x +- icu_locid_transform_data@1.5.1 | https://github.com/unicode-org/icu4x +- icu_normalizer@2.3.0 | https://github.com/unicode-org/icu4x +- icu_normalizer_data@2.3.0 | https://github.com/unicode-org/icu4x +- icu_properties@2.3.0 | https://github.com/unicode-org/icu4x +- icu_properties_data@2.3.0 | https://github.com/unicode-org/icu4x +- icu_provider@1.5.0 | https://github.com/unicode-org/icu4x +- icu_provider@2.3.1 | https://github.com/unicode-org/icu4x +- icu_provider_macros@1.5.0 | https://github.com/unicode-org/icu4x +- litemap@0.7.5 | https://github.com/unicode-org/icu4x +- litemap@0.8.3 | https://github.com/unicode-org/icu4x +- potential_utf@0.1.6 | https://github.com/unicode-org/icu4x +- tinystr@0.7.6 | https://github.com/unicode-org/icu4x +- tinystr@0.8.4 | https://github.com/unicode-org/icu4x +- writeable@0.5.5 | https://github.com/unicode-org/icu4x +- writeable@0.6.4 | https://github.com/unicode-org/icu4x +- yoke-derive@0.7.5 | https://github.com/unicode-org/icu4x +- yoke-derive@0.8.3 | https://github.com/unicode-org/icu4x +- yoke@0.7.5 | https://github.com/unicode-org/icu4x +- yoke@0.8.3 | https://github.com/unicode-org/icu4x +- zerofrom-derive@0.1.8 | https://github.com/unicode-org/icu4x +- zerofrom@0.1.8 | https://github.com/unicode-org/icu4x +- zerotrie@0.2.5 | https://github.com/unicode-org/icu4x +- zerovec-derive@0.10.4 | https://github.com/unicode-org/icu4x +- zerovec-derive@0.11.6 | https://github.com/unicode-org/icu4x +- zerovec@0.10.4 | https://github.com/unicode-org/icu4x +- zerovec@0.11.8 | https://github.com/unicode-org/icu4x + +ISC License (19) +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- untrusted@0.9.0 | https://github.com/briansmith/untrusted +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- ring@0.17.14 | https://github.com/briansmith/ring +- libloading@0.9.0 | https://github.com/nagisa/rust_libloading/ +- rustls-webpki@0.103.15 | https://github.com/rustls/webpki + +BSD 3-Clause "New" or "Revised" License (7) +- zstd-safe@8.0.0 | https://github.com/gyscos/zstd-rs +- zstd-sys@2.1.0+zstd.1.5.7 | https://github.com/gyscos/zstd-rs +- zstd@0.14.0 | https://github.com/gyscos/zstd-rs +- zstd-sys@2.1.0+zstd.1.5.7 | https://github.com/gyscos/zstd-rs +- subtle@2.6.1 | https://github.com/dalek-cryptography/subtle +- sha1_smol@1.0.1 | https://github.com/mitsuhiko/sha1-smol +- zstd-sys@2.1.0+zstd.1.5.7 | https://github.com/gyscos/zstd-rs + +BSD Zero Clause License (1) +- adler2@2.0.1 | https://github.com/oyvindln/adler2 + +Community Data License Agreement Permissive 2.0 (1) +- webpki-roots@1.0.9 | https://github.com/rustls/webpki-roots + +zlib License (1) +- zlib-rs@0.6.8 | https://github.com/trifectatechfoundation/zlib-rs + +License Texts +~~~~~~~~~~~~~ + +BSD Zero Clause License (0BSD) +----------------------------------------------------------- + +Applies to: +- adler2@2.0.1 + +Copyright (C) Jonas Schievink + +Permission to use, copy, modify, and/or distribute this software for +any purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN +AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- num_threads@0.1.7 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2021 Jacob Pratt + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- powerfmt@0.2.0 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023 Jacob Pratt et al. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- deranged@0.5.8 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 Jacob Pratt et al. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- ureq-proto@0.6.4 +- utf8_iter@1.0.4 +- zeroize@1.9.0 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- rustix@1.1.5 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +--- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Licenses for support code +------------------------- + +Parts of the TLS test suite are under the Go license. This code is not included +in BoringSSL (i.e. libcrypto and libssl) when compiled, however, so +distributing code linked against BoringSSL does not trigger this license: + +Copyright (c) 2009 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BoringSSL uses the Chromium test infrastructure to run a continuous build, +trybots etc. The scripts which manage this, and the script for generating build +metadata, are under the Chromium license. Distributing code linked against +BoringSSL does not trigger this license. + +Copyright 2015 The Chromium Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- fast_image_resize@6.1.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright (c) 2021 Kirill Kuzminykh + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- windows-collections@0.3.2 +- windows-core@0.62.2 +- windows-future@0.3.2 +- windows-implement@0.60.2 +- windows-interface@0.59.3 +- windows-link@0.2.1 +- windows-numerics@0.3.1 +- windows-result@0.4.1 +- windows-strings@0.5.1 +- windows-sys@0.52.0 +- windows-sys@0.59.0 +- windows-sys@0.61.2 +- windows-targets@0.52.6 +- windows-threading@0.2.1 +- windows@0.62.2 +- windows_aarch64_msvc@0.52.6 +- windows_x86_64_msvc@0.52.6 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright (c) Microsoft Corporation. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- zopfli@0.8.3 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2011 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- web-time@1.1.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023 dAxpeDDa + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- moxcms@0.8.1 +- pxfm@0.1.30 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 Radzivon Bartoshyk + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- cvt@0.1.2 +- pretty-bytes-rust@0.3.0 +- self_cell@1.3.0 +- sys-locale@0.3.2 +- ureq@3.4.2 +- zune-core@0.5.3 +- zune-jpeg@0.5.15 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- fluent-bundle@0.16.0 +- fluent-syntax@0.12.0 +- fluent@0.17.0 +- intl-memoizer@0.5.3 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017 Mozilla + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- clap@4.6.7 +- clap_builder@4.6.7 +- clap_derive@4.6.7 +- clap_lex@1.1.1 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright Individual contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- winapi@0.3.9 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- anstream@1.0.0 +- anstyle-parse@1.0.0 +- anstyle-query@1.1.5 +- anstyle-wincon@3.0.11 +- anstyle@1.0.14 +- colorchoice@1.0.5 +- crc32fast@1.5.2 +- is_terminal_polyfill@1.70.2 +- log-panics@2.1.0 +- once_cell_polyfill@1.70.2 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- typenum@1.20.1 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2014 Paho Lurie-Gregg + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- http@1.5.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2017 http-rs authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- iana-time-zone@0.1.65 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2020 Andrew Straw + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- rustls-pki-types@1.15.1 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2023 Dirkjan Ochtman + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- memmap2@0.9.11 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [2015] [Dan Burkert] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- gif@0.14.2 +- weezl@0.1.12 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- aligned@0.4.3 +- as-slice@0.2.1 +- base64@0.23.1 +- bitflags@2.13.2 +- bumpalo@3.20.3 +- cfg-if@1.0.5 +- core-foundation-sys@0.8.7 +- crossbeam-deque@0.8.8 +- crossbeam-epoch@0.9.21 +- crossbeam-utils@0.8.23 +- derivative@2.2.0 +- displaydoc@0.2.7 +- either@1.18.0 +- equivalent@1.0.2 +- errno@0.3.14 +- flate2@1.1.10 +- fnv@1.0.7 +- form_urlencoded@1.2.2 +- glob@0.3.4 +- hashbrown@0.17.1 +- heck@0.5.0 +- httparse@1.10.1 +- idna@1.1.0 +- idna_adapter@1.2.2 +- indexmap@2.14.2 +- lazy_static@1.5.0 +- log@0.4.34 +- num-traits@0.2.19 +- once_cell@1.21.4 +- percent-encoding@2.3.2 +- png@0.18.1 +- rayon-core@1.13.0 +- rayon@1.12.0 +- regex-automata@0.4.18 +- regex-syntax@0.8.11 +- regex@1.13.1 +- ring@0.17.14 +- rustix@1.1.5 +- rustls@0.23.45 +- smallvec@1.16.1 +- stable_deref_trait@1.2.1 +- syn@1.0.109 +- time@0.1.45 +- unic-langid-impl@0.9.6 +- unic-langid@0.9.6 +- url@2.5.8 +- uuid@1.26.1 +- wait-timeout@0.2.1 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- waitpid-any@0.3.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- block-buffer@0.12.1 +- chacha20@0.10.2 +- const-oid@0.10.2 +- cpufeatures@0.3.1 +- crypto-common@0.2.2 +- digest@0.11.3 +- hybrid-array@0.4.15 +- sha1@0.11.0 +- sha2@0.11.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- remove_dir_all@1.0.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +Copyright 2017 Aaron Power + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- rand_core@0.10.1 + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- getrandom@0.2.17 +- getrandom@0.4.3 + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- bytemuck@1.25.2 + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + + "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- simplelog@0.12.2 + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, +and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by +the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all +other entities that control, are controlled by, or are under common +control with that entity. For the purposes of this definition, +"control" means (i) the power, direct or indirect, to cause the +direction or management of such entity, whether by contract or +otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity +exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, +including but not limited to software source code, documentation +source, and configuration files. + +"Object" form shall mean any form resulting from mechanical +transformation or translation of a Source form, including but +not limited to compiled object code, generated documentation, +and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or +Object form, made available under the License, as indicated by a +copyright notice that is included in or attached to the work +(an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object +form, that is based on (or derived from) the Work and for which the +editorial revisions, annotations, elaborations, or other modifications +represent, as a whole, an original work of authorship. For the purposes +of this License, Derivative Works shall not include works that remain +separable from, or merely link (or bind by name) to the interfaces of, +the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including +the original version of the Work and any modifications or additions +to that Work or Derivative Works thereof, that is intentionally +submitted to Licensor for inclusion in the Work by the copyright owner +or by an individual or Legal Entity authorized to submit on behalf of +the copyright owner. For the purposes of this definition, "submitted" +means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, +and issue tracking systems that are managed by, or on behalf of, the +Licensor for the purpose of discussing and improving the Work, but +excluding communication that is conspicuously marked or otherwise +designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity +on behalf of whom a Contribution has been received by Licensor and +subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the +Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +(except as stated in this section) patent license to make, have made, +use, offer to sell, sell, import, and otherwise transfer the Work, +where such license applies only to those patent claims licensable +by such Contributor that are necessarily infringed by their +Contribution(s) alone or by combination of their Contribution(s) +with the Work to which such Contribution(s) was submitted. If You +institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work +or a Contribution incorporated within the Work constitutes direct +or contributory patent infringement, then any patent licenses +granted to You under this License for that Work shall terminate +as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the +Work or Derivative Works thereof in any medium, with or without +modifications, and in Source or Object form, provided that You +meet the following conditions: + +(a) You must give any other recipients of the Work or +Derivative Works a copy of this License; and + +(b) You must cause any modified files to carry prominent notices +stating that You changed the files; and + +(c) You must retain, in the Source form of any Derivative Works +that You distribute, all copyright, patent, trademark, and +attribution notices from the Source form of the Work, +excluding those notices that do not pertain to any part of +the Derivative Works; and + +(d) If the Work includes a "NOTICE" text file as part of its +distribution, then any Derivative Works that You distribute must +include a readable copy of the attribution notices contained +within such NOTICE file, excluding those notices that do not +pertain to any part of the Derivative Works, in at least one +of the following places: within a NOTICE text file distributed +as part of the Derivative Works; within the Source form or +documentation, if provided along with the Derivative Works; or, +within a display generated by the Derivative Works, if and +wherever such third-party notices normally appear. The contents +of the NOTICE file are for informational purposes only and +do not modify the License. You may add Your own attribution +notices within Derivative Works that You distribute, alongside +or as an addendum to the NOTICE text from the Work, provided +that such additional attribution notices cannot be construed +as modifying the License. + +You may add Your own copyright statement to Your modifications and +may provide additional or different license terms and conditions +for use, reproduction, or distribution of Your modifications, or +for any such Derivative Works as a whole, provided Your use, +reproduction, and distribution of the Work otherwise complies with +the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, +any Contribution intentionally submitted for inclusion in the Work +by You to the Licensor shall be under the terms and conditions of +this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify +the terms of any separate license agreement you may have executed +with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade +names, trademarks, service marks, or product names of the Licensor, +except as required for reasonable and customary use in describing the +origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or +agreed to in writing, Licensor provides the Work (and each +Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +implied, including, without limitation, any warranties or conditions +of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A +PARTICULAR PURPOSE. You are solely responsible for determining the +appropriateness of using or redistributing the Work and assume any +risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, +whether in tort (including negligence), contract, or otherwise, +unless required by applicable law (such as deliberate and grossly +negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, +incidental, or consequential damages of any character arising as a +result of this License or out of the use or inability to use the +Work (including but not limited to damages for loss of goodwill, +work stoppage, computer failure or malfunction, or any and all +other commercial damages or losses), even if such Contributor +has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing +the Work or Derivative Works thereof, You may choose to offer, +and charge a fee for, acceptance of support, warranty, indemnity, +or other liability obligations and/or rights consistent with this +License. However, in accepting such obligations, You may act only +on Your own behalf and on Your sole responsibility, not on behalf +of any other Contributor, and only if You agree to indemnify, +defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason +of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following +boilerplate notice, with the fields enclosed by brackets "{}" +replaced with your own identifying information. (Don't include +the brackets!) The text should be enclosed in the appropriate +comment syntax for the file format. We also recommend that a +file or class name and description of purpose be included on the +same "printed page" as the copyright notice for easier +identification within third-party archives. + +Copyright {yyyy} {name of copyright owner} + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- anyhow@1.0.104 +- document-features@0.2.12 +- fdeflate@0.3.7 +- fluent-langneg@0.13.1 +- fluent-langneg@0.14.2 +- fs_at@0.2.1 +- image@0.25.10 +- intl_pluralrules@7.0.2 +- itoa@1.0.18 +- libc@0.2.189 +- litrs@1.0.0 +- miniz_oxide@0.8.9 +- miniz_oxide@0.9.1 +- normpath@1.5.2 +- num-conv@0.2.2 +- objc2-app-kit@0.3.2 +- objc2-cloud-kit@0.3.2 +- objc2-core-data@0.3.2 +- objc2-core-foundation@0.3.2 +- objc2-core-graphics@0.3.2 +- objc2-core-image@0.3.2 +- objc2-core-text@0.3.2 +- objc2-core-video@0.3.2 +- objc2-quartz-core@0.3.2 +- oneshot@0.2.1 +- proc-macro2@1.0.107 +- quote@1.0.47 +- rand@0.10.3 +- rustc-hash@2.1.3 +- semver@1.0.28 +- serde@1.0.229 +- serde_core@1.0.229 +- serde_derive@1.0.229 +- serde_json@1.0.151 +- syn@2.0.119 +- syn@3.0.6 +- thiserror-impl@2.0.20 +- thiserror@2.0.20 +- time-core@0.1.9 +- time-macros@0.2.32 +- time@0.3.55 +- type-map@0.5.1 +- typed-path@0.12.3 +- unicode-ident@1.0.26 +- utf8-zero@0.8.1 +- utf8parse@0.2.2 +- widestring@1.2.1 + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +Apache License 2.0 (Apache-2.0) +----------------------------------------------------------- + +Applies to: +- chrono@0.4.45 + +Rust-chrono is dual-licensed under The MIT License [1] and +Apache 2.0 License [2]. Copyright (c) 2014--2026, Kang Seonghoon and +contributors. + +Nota Bene: This is same as the Rust Project's own license. + + +[1]: , which is reproduced below: + +~~~~ +The MIT License (MIT) + +Copyright (c) 2014, Kang Seonghoon. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +~~~~ + + +[2]: , which is reproduced below: + +~~~~ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +~~~~ + + + +BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) +----------------------------------------------------------- + +Applies to: +- zstd-safe@8.0.0 +- zstd-sys@2.1.0+zstd.1.5.7 +- zstd@0.14.0 + +BSD 3-Clause License + +Copyright (c) 2026, Alexandre Bury + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) +----------------------------------------------------------- + +Applies to: +- zstd-sys@2.1.0+zstd.1.5.7 + +BSD License + +For Zstandard software + +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook, nor Meta, nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) +----------------------------------------------------------- + +Applies to: +- subtle@2.6.1 + +Copyright (c) 2016-2017 Isis Agora Lovecruft, Henry de Valence. All rights reserved. +Copyright (c) 2016-2024 Isis Agora Lovecruft. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) +----------------------------------------------------------- + +Applies to: +- sha1_smol@1.0.1 + +Copyright (c) . + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) +----------------------------------------------------------- + +Applies to: +- zstd-sys@2.1.0+zstd.1.5.7 + +The auto-generated bindings are under the 3-clause BSD license: + +BSD License + +For Zstandard software + +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook, nor Meta, nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +Community Data License Agreement Permissive 2.0 (CDLA-Permissive-2.0) +----------------------------------------------------------- + +Applies to: +- webpki-roots@1.0.9 + +# Community Data License Agreement - Permissive - Version 2.0 + +This is the Community Data License Agreement - Permissive, Version +2.0 (the "agreement"). Data Provider(s) and Data Recipient(s) agree +as follows: + +## 1. Provision of the Data + +1.1. A Data Recipient may use, modify, and share the Data made +available by Data Provider(s) under this agreement if that Data +Recipient follows the terms of this agreement. + +1.2. This agreement does not impose any restriction on a Data +Recipient's use, modification, or sharing of any portions of the +Data that are in the public domain or that may be used, modified, +or shared under any other legal exception or limitation. + +## 2. Conditions for Sharing Data + +2.1. A Data Recipient may share Data, with or without modifications, so +long as the Data Recipient makes available the text of this agreement +with the shared Data. + +## 3. No Restrictions on Results + +3.1. This agreement does not impose any restriction or obligations +with respect to the use, modification, or sharing of Results. + +## 4. No Warranty; Limitation of Liability + +4.1. All Data Recipients receive the Data subject to the following +terms: + +THE DATA IS PROVIDED ON AN "AS IS" BASIS, WITHOUT REPRESENTATIONS, +WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED +INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, +NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +NO DATA PROVIDER SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING +WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE DATA OR RESULTS, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +## 5. Definitions + +5.1. "Data" means the material received by a Data Recipient under +this agreement. + +5.2. "Data Provider" means any person who is the source of Data +provided under this agreement and in reliance on a Data Recipient's +agreement to its terms. + +5.3. "Data Recipient" means any person who receives Data directly +or indirectly from a Data Provider and agrees to the terms of this +agreement. + +5.4. "Results" means any outcome obtained by computational analysis +of Data, including for example machine learning models and models' +insights. + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +/* Copyright (c) 2014, Intel Corporation. + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION + * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ + +#ifndef OPENSSL_HEADER_EC_ECP_NISTZ384_H +#define OPENSSL_HEADER_EC_ECP_NISTZ384_H + +#include "../../limbs/limbs.h" + +#define P384_LIMBS (384u / LIMB_BITS) + +typedef struct { + Limb X[P384_LIMBS]; + Limb Y[P384_LIMBS]; + Limb Z[P384_LIMBS]; +} P384_POINT; + +typedef struct { + Limb X[P384_LIMBS]; + Limb Y[P384_LIMBS]; +} P384_POINT_AFFINE; + + +#endif // OPENSSL_HEADER_EC_ECP_NISTZ384_H + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2015-2016 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +//! EdDSA Signatures. + +use super::ops::ELEM_LEN; +use crate::digest; + +pub mod signing; +pub mod verification; + +/// The length of an Ed25519 public key. +pub const ED25519_PUBLIC_KEY_LEN: usize = ELEM_LEN; + +pub fn eddsa_digest(signature_r: &[u8], public_key: &[u8], msg: &[u8]) -> digest::Digest { + let mut ctx = digest::Context::new(&digest::SHA512); + ctx.update(signature_r); + ctx.update(public_key); + ctx.update(msg); + ctx.finish() +} + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- untrusted@0.9.0 + +// Copyright 2015-2016 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2015-2022 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +use crate::limb::Limb; + +#[derive(Clone, Copy)] +#[repr(transparent)] +pub struct N0([Limb; 2]); + +impl N0 { + #[cfg(feature = "alloc")] + pub(super) const LIMBS_USED: usize = 64 / crate::limb::LIMB_BITS; + + #[inline] + pub const fn precalculated(n0: u64) -> Self { + #[cfg(target_pointer_width = "64")] + { + Self([n0, 0]) + } + + #[cfg(target_pointer_width = "32")] + { + Self([n0 as Limb, (n0 >> crate::limb::LIMB_BITS) as Limb]) + } + } +} + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2015-2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +use crate::{bb, error}; + +#[deprecated( + note = "To be removed. Internal function not intended for external use with no promises regarding side channels." +)] +pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> { + bb::verify_slices_are_equal(a, b) +} + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2016 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +//! Elliptic curve operations and schemes using Curve25519. + +pub mod ed25519; + +pub mod x25519; + +mod ops; +mod scalar; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2016-2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +use crate::error::{KeyRejected, Unspecified}; + +impl From for Unspecified { + fn from(source: untrusted::EndOfInput) -> Self { + super::erase(source) + } +} + +impl From for Unspecified { + fn from(source: core::array::TryFromSliceError) -> Self { + super::erase(source) + } +} + +impl From for Unspecified { + fn from(source: KeyRejected) -> Self { + super::erase(source) + } +} + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2018 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +//! Serialization and deserialization. + +#[doc(hidden)] +pub mod der; + +#[cfg(feature = "alloc")] +mod writer; + +#[cfg(feature = "alloc")] +pub(crate) mod der_writer; + +pub(crate) mod positive; + +pub use self::positive::Positive; + +#[cfg(feature = "alloc")] +pub(crate) use self::writer::TooLongError; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2019-2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +use super::BlockLen; + +pub(super) use self::{ + sha2_32::{block_data_order_32, State32, SHA256_BLOCK_LEN}, + sha2_64::{block_data_order_64, State64, SHA512_BLOCK_LEN}, +}; + +pub(super) const CHAINING_WORDS: usize = 8; + +#[cfg(any( + all(target_arch = "aarch64", target_endian = "little"), + all(target_arch = "arm", target_endian = "little"), + target_arch = "x86_64" +))] +#[macro_use] +mod ffi; + +pub(super) mod fallback; +mod sha2_32; +mod sha2_64; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// TODO(MSRV 1.76): Replace with `core::ptr::from_mut`. +#[allow(dead_code)] +#[inline(always)] +pub fn from_mut(r: &mut T) -> *mut T { + r +} + +// TODO(MSRV 1.76): Replace with `core::ptr::from_ref`. +#[allow(dead_code)] +#[inline(always)] +pub const fn from_ref(r: &T) -> *const T { + r +} + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +//! Integration tests for non-public APIs. + +mod bits_tests; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +pub use self::{ + array::Array, + base::{IndexError, Overlapping}, + partial_block::PartialBlock, +}; + +mod array; +mod base; +mod partial_block; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +#![cfg(all(target_arch = "aarch64", target_endian = "little"))] + +pub(in super::super) mod mont; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +#![cfg(target_arch = "x86_64")] + +pub(in super::super::super) mod mont; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +mod storage; + +pub(super) use self::storage::{AlignedStorage, LIMBS_PER_CHUNK}; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +// Copyright 2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +pub(super) mod aarch64; +pub(super) mod x86_64; + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- ring@0.17.14 + +Copyright 2015-2025 Brian Smith. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- libloading@0.9.0 + +Copyright © 2015, Simonas Kazlauskas + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without +fee is hereby granted, provided that the above copyright notice and this permission notice appear +in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE +AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, +NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + + +ISC License (ISC) +----------------------------------------------------------- + +Applies to: +- rustls-webpki@0.103.15 + +Except as otherwise noted, this project is licensed under the following +(ISC-style) terms: + +Copyright 2015 Brian Smith. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +The files under third-party/chromium are licensed as described in +third-party/chromium/LICENSE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- winreg@0.56.0 + +Copyright (c) 2015 Igor Shaula + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- bytes@1.12.1 + +Copyright (c) 2018 Carl Lerche + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- synstructure@0.13.2 +- synstructure@0.14.0 + +Copyright 2016 Nika Layzell + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- velopack_bins@0.0.0-local +- velopack_l18n@0.0.0-local +- velopack@0.0.0-local +- velopack_wix@0.0.0-local + +Copyright © 2021 Caelan Sayler +Copyright © 2024 Velopack Ltd. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- xdialog@3.1.9 + +Copyright © 2024 Caelan Sayler, Velopack Ltd. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- fs_extra@1.3.0 + +MIT License + +Copyright (c) 2017 Denis Kurilenko + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- cfb@0.15.0 + +MIT License + +Copyright (c) 2017 Matthew D. Steele + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- simple-stopwatch@0.1.4 + +MIT License + +Copyright (c) 2018 Huw Bowles + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- progress-streams@1.1.0 + +MIT License + +Copyright (c) 2018 System76 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- strum@0.28.0 +- strum_macros@0.28.0 + +MIT License + +Copyright (c) 2019 Peter Glotfelty + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- block2@0.6.2 +- objc2-encode@4.1.0 +- objc2-foundation@0.3.2 +- objc2@0.6.4 +- webview2-com-sys@0.39.1 + +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- simd-adler32@0.3.10 + +MIT License + +Copyright (c) [2021] [Marvin Countryman] + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- zmij@1.0.23 + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- zip@8.6.0 + +The MIT License (MIT) + +Copyright (c) 2014 Mathijs van de Nes + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- xml@1.4.0 + +The MIT License (MIT) + +Copyright (c) 2014 Vladimir Matveev + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- aho-corasick@1.1.5 +- byteorder-lite@0.1.0 +- memchr@2.8.3 +- termcolor@1.4.1 +- walkdir@2.5.0 + +The MIT License (MIT) + +Copyright (c) 2015 Andrew Gallant + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- nix@0.29.0 +- nix@0.31.3 + +The MIT License (MIT) + +Copyright (c) 2015 Carl Lerche + nix-rust Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- strsim@0.11.1 + +The MIT License (MIT) + +Copyright (c) 2015 Danny Guo +Copyright (c) 2016 Titus Wormer +Copyright (c) 2018 Akash Kurdekar + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- color_quant@1.1.0 + +The MIT License (MIT) + +Copyright (c) 2016 PistonDevelopers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- same-file@1.0.6 +- winapi-util@0.1.11 + +The MIT License (MIT) + +Copyright (c) 2017 Andrew Gallant + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +MIT License (MIT) +----------------------------------------------------------- + +Applies to: +- os_info@3.15.0 + +The MIT License (MIT) + +Copyright (c) 2017 Stanislav Tkach + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +Unicode License v3 (Unicode-3.0) +----------------------------------------------------------- + +Applies to: +- unicode-ident@1.0.26 + +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2023 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. + + +Unicode License v3 (Unicode-3.0) +----------------------------------------------------------- + +Applies to: +- icu_collections@2.3.0 +- icu_locale_core@2.3.0 +- icu_locid@1.5.0 +- icu_locid_transform@1.5.0 +- icu_locid_transform_data@1.5.1 +- icu_normalizer@2.3.0 +- icu_normalizer_data@2.3.0 +- icu_properties@2.3.0 +- icu_properties_data@2.3.0 +- icu_provider@1.5.0 +- icu_provider@2.3.1 +- icu_provider_macros@1.5.0 +- litemap@0.7.5 +- litemap@0.8.3 +- potential_utf@0.1.6 +- tinystr@0.7.6 +- tinystr@0.8.4 +- writeable@0.5.5 +- writeable@0.6.4 +- yoke-derive@0.7.5 +- yoke-derive@0.8.3 +- yoke@0.7.5 +- yoke@0.8.3 +- zerofrom-derive@0.1.8 +- zerofrom@0.1.8 +- zerotrie@0.2.5 +- zerovec-derive@0.10.4 +- zerovec-derive@0.11.6 +- zerovec@0.10.4 +- zerovec@0.11.8 + +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 2020-2024 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. + +SPDX-License-Identifier: Unicode-3.0 + +— + +Portions of ICU4X may have been adapted from ICU4C and/or ICU4J. +ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others. + + +zlib License (Zlib) +----------------------------------------------------------- + +Applies to: +- zlib-rs@0.6.8 + +(C) 2024 Trifecta Tech Foundation + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + +3. This notice may not be removed or altered from any source distribution. + diff --git a/packaging/dmg/background.png b/packaging/dmg/background.png new file mode 100644 index 00000000..7620c0e4 Binary files /dev/null and b/packaging/dmg/background.png differ diff --git a/packaging/dmg/fonts/Geist-Bold.ttf b/packaging/dmg/fonts/Geist-Bold.ttf new file mode 100644 index 00000000..5b071f45 Binary files /dev/null and b/packaging/dmg/fonts/Geist-Bold.ttf differ diff --git a/packaging/dmg/fonts/OFL-Geist.txt b/packaging/dmg/fonts/OFL-Geist.txt new file mode 100644 index 00000000..b3e2de2a --- /dev/null +++ b/packaging/dmg/fonts/OFL-Geist.txt @@ -0,0 +1,92 @@ +Geist Sans and Geist Mono Font +(C) 2023 Vercel, made in collaboration with basement.studio + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is available with a FAQ at: http://scripts.sil.org/OFL and copied below + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION AND CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/packaging/install.sh b/packaging/install.sh index 92e1a4d5..25a5146e 100755 --- a/packaging/install.sh +++ b/packaging/install.sh @@ -1,5 +1,5 @@ #!/bin/sh -# Install a disktree release: the binary, a desktop entry and an icon. +# Install a PwrDisk release: the binary, a desktop entry and an icon. # # ./install.sh # into ~/.local, no root needed # sudo PREFIX=/usr/local ./install.sh @@ -16,24 +16,24 @@ ICONDIR=${ICONDIR:-"$PREFIX/share/icons/hicolor/scalable/apps"} VERSION=$(cat "$here/VERSION") install -d "$BINDIR" "$APPDIR" "$ICONDIR" -install -m755 "$here/disktree" "$BINDIR/disktree" -install -m644 "$here/disktree.svg" "$ICONDIR/disktree.svg" +install -m755 "$here/pwrdisk" "$BINDIR/pwrdisk" +install -m644 "$here/disktree.svg" "$ICONDIR/pwrdisk.svg" sed -e "s|@BINDIR@|$BINDIR|" -e "s|@VERSION@|$VERSION|" \ - "$here/disktree.desktop.in" > "$APPDIR/disktree.desktop" -chmod 644 "$APPDIR/disktree.desktop" + "$here/pwrdisk.desktop.in" > "$APPDIR/pwrdisk.desktop" +chmod 644 "$APPDIR/pwrdisk.desktop" if command -v update-desktop-database >/dev/null 2>&1; then update-desktop-database "$APPDIR" 2>/dev/null || true fi -echo "installed disktree $VERSION:" -echo " $BINDIR/disktree" -echo " $APPDIR/disktree.desktop" -echo " $ICONDIR/disktree.svg" -resolved=$(command -v disktree 2>/dev/null || true) -if [ -z "$resolved" ] || ! [ "$resolved" -ef "$BINDIR/disktree" ]; then +echo "installed PwrDisk $VERSION:" +echo " $BINDIR/pwrdisk" +echo " $APPDIR/pwrdisk.desktop" +echo " $ICONDIR/pwrdisk.svg" +resolved=$(command -v pwrdisk 2>/dev/null || true) +if [ -z "$resolved" ] || ! [ "$resolved" -ef "$BINDIR/pwrdisk" ]; then echo if [ -n "$resolved" ]; then - echo "warning: disktree still resolves to $resolved" + echo "warning: pwrdisk still resolves to $resolved" echo " that hides the build in $BINDIR" else echo "warning: $BINDIR is not on PATH" diff --git a/packaging/macos/AppGlyph.svg b/packaging/macos/AppGlyph.svg new file mode 100644 index 00000000..171e6b27 --- /dev/null +++ b/packaging/macos/AppGlyph.svg @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/macos/AppIcon.icon/icon.json b/packaging/macos/AppIcon.icon/icon.json new file mode 100644 index 00000000..496f6f42 --- /dev/null +++ b/packaging/macos/AppIcon.icon/icon.json @@ -0,0 +1,35 @@ +{ + "fill" : { + "solid" : "srgb:0.10196,0.10588,0.14902,1.00000" + }, + "groups" : [ + { + "name" : "Mark", + "layers" : [ + { + "name" : "glyph", + "image-name" : "glyph.png", + "fill" : "automatic", + "glass" : false, + "hidden" : false, + "blend-mode" : "normal" + } + ], + "lighting" : "individual", + "shadow" : { + "kind" : "neutral", + "opacity" : 0.5 + }, + "translucency" : { + "enabled" : false, + "value" : 0.5 + } + } + ], + "supported-platforms" : { + "circles" : [ + "watchOS" + ], + "squares" : "shared" + } +} diff --git a/packaging/macos/DockIcon-glass.png b/packaging/macos/DockIcon-glass.png new file mode 100644 index 00000000..0e205c55 Binary files /dev/null and b/packaging/macos/DockIcon-glass.png differ diff --git a/packaging/macos/DockIcon.png b/packaging/macos/DockIcon.png new file mode 100644 index 00000000..ccf997f9 Binary files /dev/null and b/packaging/macos/DockIcon.png differ diff --git a/packaging/macos/Info.plist.in b/packaging/macos/Info.plist.in index 7e87cda5..dcfcfc4a 100644 --- a/packaging/macos/Info.plist.in +++ b/packaging/macos/Info.plist.in @@ -6,15 +6,20 @@ CFBundleIdentifier - io.github.tobi.disktree + com.pwrdrvr.pwrdisk CFBundleName - disktree + PwrDisk CFBundleDisplayName - disktree + PwrDisk CFBundleExecutable - disktree + pwrdisk + CFBundleIconFile AppIcon + @ICON_CATALOG@ CFBundlePackageType APPL CFBundleInfoDictionaryVersion @@ -35,14 +40,14 @@ each of these. Full Disk Access has no prompt and no string: it is granted in System Settings, which the app links to. --> NSDesktopFolderUsageDescription - disktree measures the Desktop folder to show what is using your disk. It reads sizes and names only. + PwrDisk measures the Desktop folder to show what is using your disk. It reads sizes and names only. NSDocumentsFolderUsageDescription - disktree measures the Documents folder to show what is using your disk. It reads sizes and names only. + PwrDisk measures the Documents folder to show what is using your disk. It reads sizes and names only. NSDownloadsFolderUsageDescription - disktree measures the Downloads folder to show what is using your disk. It reads sizes and names only. + PwrDisk measures the Downloads folder to show what is using your disk. It reads sizes and names only. NSRemovableVolumesUsageDescription - disktree measures removable disks you scan to show what is using them. It reads sizes and names only. + PwrDisk measures removable disks you scan to show what is using them. It reads sizes and names only. NSNetworkVolumesUsageDescription - disktree measures network disks you scan to show what is using them. It reads sizes and names only. + PwrDisk measures network disks you scan to show what is using them. It reads sizes and names only. diff --git a/packaging/macos/PwrDisk.entitlements b/packaging/macos/PwrDisk.entitlements new file mode 100644 index 00000000..b68c8d2f --- /dev/null +++ b/packaging/macos/PwrDisk.entitlements @@ -0,0 +1,9 @@ + + + + + + diff --git a/packaging/macos/render-dock-icons.swift b/packaging/macos/render-dock-icons.swift new file mode 100644 index 00000000..5a615eaa --- /dev/null +++ b/packaging/macos/render-dock-icons.swift @@ -0,0 +1,266 @@ +#!/usr/bin/env swift + +// The Dock icon a run outside the app bundle shows, in both the looks a Mac +// can give it. `make dock-icons` runs this; the app embeds what it writes +// (`crates/disktree-app/src/dock_icon.rs`). +// +// packaging/macos/DockIcon.png AppIcon.svg as it is: the tile on +// Apple's 824-in-1024 legacy canvas, +// drawn literally by macOS 15 and +// earlier. +// packaging/macos/DockIcon-glass.png The same icon as macOS 26 draws it +// from AppIcon.icon: its own shape, +// the glass edge and the mark's shadow. +// +// macOS 26 gives Liquid Glass only to an app bundle's Icon Composer icon, +// never to an image set at runtime, and has no API to ask for it. So the +// glass is rendered here, by the system itself: AppIcon.icon is compiled with +// actool into a throwaway bundle, and what Finder and the Dock would draw for +// that bundle is read back through NSWorkspace. That draws in the icon style +// this Mac is set to, so the script refuses to run unless the Default style +// is on, and refuses on a Mac older than 26 or with an older actool. +// +// Both files are 512 px: the Dock draws at most 128 pt, twice that on a Retina +// display, and the glass render carries gradients that would make a 1024 px +// file four times the size for nothing. + +import AppKit +import Foundation + +let macosDir = URL(fileURLWithPath: #filePath).deletingLastPathComponent() +let tileSVG = macosDir.appendingPathComponent("AppIcon.svg") +let glyphSVG = macosDir.appendingPathComponent("AppGlyph.svg") +let package = macosDir.appendingPathComponent("AppIcon.icon", isDirectory: true) +let flatOut = macosDir.appendingPathComponent("DockIcon.png") +let glassOut = macosDir.appendingPathComponent("DockIcon-glass.png") + +/// The icon is rendered on the canvas the bundle's icons use, then scaled. +let canvas = 1024 +let output = 512 +/// Where the legacy tile sits on that canvas, as AppIcon.svg draws it. The +/// glass render must land there too, or the two files would not line up +/// between one macOS and the next. +let tileOrigin = 100 +let tileSize = 824 + +func fail(_ message: String) -> Never { + FileHandle.standardError.write("render-dock-icons: \(message)\n".data(using: .utf8)!) + exit(1) +} + +func run(_ executable: String, _ arguments: [String]) -> (status: Int32, output: Data) { + let process = Process() + process.executableURL = URL(fileURLWithPath: executable) + process.arguments = arguments + let pipe = Pipe() + process.standardOutput = pipe + process.standardError = pipe + do { try process.run() } catch { fail("cannot run \(executable): \(error)") } + let output = pipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + return (process.terminationStatus, output) +} + +// MARK: - Preconditions, before anything is written + +// The bundle's LSMinimumSystemVersion, which `cargo xtask bundle` compiles +// the package for too, so both compiles make the same catalog. Read from +// the template by hand: its placeholders keep it from parsing as a plist. +let plistTemplate = macosDir.appendingPathComponent("Info.plist.in") +guard let template = try? String(contentsOf: plistTemplate, encoding: .utf8), + let pattern = try? Regex( + #"LSMinimumSystemVersion\s*([^<]+)"#), + let match = template.firstMatch(of: pattern), + let version = match.output[1].substring +else { + fail("cannot read LSMinimumSystemVersion from \(plistTemplate.path)") +} +let deploymentTarget = String(version) + +let os = ProcessInfo.processInfo.operatingSystemVersion +guard os.majorVersion >= 26 else { + fail("the glass icon is drawn by macOS 26 or later; this is \(os.majorVersion).\(os.minorVersion)") +} +if NSWorkspace.shared.accessibilityDisplayShouldReduceTransparency + || NSWorkspace.shared.accessibilityDisplayShouldIncreaseContrast +{ + fail("turn off Reduce Transparency and Increase Contrast (Accessibility > Display) first: icons render with them") +} +let actoolVersion = run("/usr/bin/xcrun", ["actool", "--version"]) +guard actoolVersion.status == 0, + let plist = try? PropertyListSerialization.propertyList(from: actoolVersion.output, format: nil) as? [String: Any], + let info = plist["com.apple.actool.version"] as? [String: Any], + let short = info["short-bundle-version"] as? String, + let major = Int(short.split(separator: ".").first ?? ""), major >= 26 +else { + fail("needs Xcode 26's actool; select it with xcode-select or DEVELOPER_DIR") +} + +// MARK: - Helpers + +func rasterize(_ svg: URL, to png: URL, pixels: Int) { + // The same tool `cargo xtask bundle` draws the iconset with, so the flat + // Dock icon is the 512 px rep of the shipped AppIcon.icns, pixel for pixel. + let result = run("/usr/bin/sips", ["-s", "format", "png", "-z", "\(pixels)", "\(pixels)", svg.path, "--out", png.path]) + guard result.status == 0 else { + fail("sips could not draw \(svg.lastPathComponent):\n\(String(decoding: result.output, as: UTF8.self))") + } +} + +func bitmap(_ pixels: Int) -> NSBitmapImageRep { + guard let rep = NSBitmapImageRep( + bitmapDataPlanes: nil, pixelsWide: pixels, pixelsHigh: pixels, + bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, + colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0 + ) else { fail("cannot create a \(pixels) px bitmap") } + rep.size = NSSize(width: pixels, height: pixels) + return rep +} + +func draw(_ image: NSImage, at pixels: Int) -> NSBitmapImageRep { + let rep = bitmap(pixels) + NSGraphicsContext.saveGraphicsState() + guard let context = NSGraphicsContext(bitmapImageRep: rep) else { fail("cannot draw") } + NSGraphicsContext.current = context + context.imageInterpolation = .high + let frame = NSRect(x: 0, y: 0, width: pixels, height: pixels) + NSColor.clear.setFill() + frame.fill() + image.draw(in: frame, from: .zero, operation: .sourceOver, fraction: 1) + NSGraphicsContext.restoreGraphicsState() + return rep +} + +/// The opaque bounds, top-down: (minX, minY, maxX, maxY). +func opaqueBounds(_ rep: NSBitmapImageRep) -> (Int, Int, Int, Int) { + var minX = rep.pixelsWide, minY = rep.pixelsHigh, maxX = -1, maxY = -1 + for y in 0.. 0.5 { + minX = min(minX, x); maxX = max(maxX, x); minY = min(minY, y); maxY = max(maxY, y) + } + } + return (minX, minY, maxX, maxY) +} + +func srgb(_ rep: NSBitmapImageRep, x: Int, y: Int) -> [Int] { + guard let c = rep.colorAt(x: x, y: y)?.usingColorSpace(.sRGB) else { return [] } + return [c.redComponent, c.greenComponent, c.blueComponent, c.alphaComponent].map { Int(($0 * 255).rounded()) } +} + +func write(_ rep: NSBitmapImageRep, to url: URL) { + guard let data = rep.representation(using: .png, properties: [:]) else { fail("cannot encode \(url.lastPathComponent)") } + do { try data.write(to: url, options: .atomic) } catch { fail("cannot write \(url.path): \(error)") } + print(" \(url.lastPathComponent) (\(rep.pixelsWide) px, \(data.count) bytes)") +} + +// MARK: - The glass render + +let work = FileManager.default.temporaryDirectory + .appendingPathComponent("pwrdisk-dock-icons-\(UUID().uuidString)", isDirectory: true) +defer { try? FileManager.default.removeItem(at: work) } + +/// What macOS draws for an app that ships AppIcon.icon. +/// +/// The bundle path and identifier are new for every run: icon services caches +/// by path, and a reused path returns whatever it drew there before. The +/// bundle gets a real executable, because one without is drawn with the +/// "cannot open" badge. +func renderGlass() -> NSImage { + let fm = FileManager.default + // actool resolves `--app-icon Icon` by the package's basename: under any + // other name it exits 0 and writes no icon at all. + let icon = work.appendingPathComponent("Icon.icon", isDirectory: true) + let compiled = work.appendingPathComponent("compiled", isDirectory: true) + let bundle = work.appendingPathComponent("pwrdisk-\(UUID().uuidString).app", isDirectory: true) + let contents = bundle.appendingPathComponent("Contents", isDirectory: true) + let resources = contents.appendingPathComponent("Resources", isDirectory: true) + let executables = contents.appendingPathComponent("MacOS", isDirectory: true) + do { + try fm.createDirectory(at: work, withIntermediateDirectories: true) + try fm.copyItem(at: package, to: icon) + try fm.createDirectory(at: icon.appendingPathComponent("Assets"), withIntermediateDirectories: true) + for dir in [compiled, resources, executables] { + try fm.createDirectory(at: dir, withIntermediateDirectories: true) + } + } catch { fail("cannot stage the render bundle: \(error)") } + rasterize(glyphSVG, to: icon.appendingPathComponent("Assets/glyph.png"), pixels: canvas) + + // The invocation `cargo xtask bundle` uses, so this is the catalog the + // shipped app carries. + let compile = run("/usr/bin/xcrun", [ + "actool", icon.path, + "--compile", compiled.path, + "--output-format", "human-readable-text", + "--notices", "--warnings", + "--output-partial-info-plist", compiled.appendingPathComponent("Info.plist").path, + "--app-icon", "Icon", + "--include-all-app-icons", + "--enable-on-demand-resources", "NO", + "--development-region", "en", + "--target-device", "mac", + "--minimum-deployment-target", deploymentTarget, + "--platform", "macosx", + ]) + let catalog = compiled.appendingPathComponent("Assets.car") + guard compile.status == 0, fm.fileExists(atPath: catalog.path) else { + fail("actool did not compile AppIcon.icon:\n\(String(decoding: compile.output, as: UTF8.self))") + } + let info: [String: Any] = [ + "CFBundleExecutable": "stub", + "CFBundleIconName": "Icon", + "CFBundleIdentifier": "com.pwrdrvr.pwrdisk.dock-icon-render.\(UUID().uuidString)", + "CFBundleName": "PwrDisk", + "CFBundlePackageType": "APPL", + ] + do { + try fm.copyItem(at: catalog, to: resources.appendingPathComponent("Assets.car")) + try fm.copyItem(at: URL(fileURLWithPath: "/usr/bin/true"), to: executables.appendingPathComponent("stub")) + let plist = try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0) + try plist.write(to: contents.appendingPathComponent("Info.plist")) + } catch { fail("cannot assemble the render bundle: \(error)") } + return NSWorkspace.shared.icon(forFile: bundle.path) +} + +// MARK: - Render, check, then write + +let flatPNG = work.appendingPathComponent("flat.png") +do { try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true) } catch { fail("\(error)") } +rasterize(tileSVG, to: flatPNG, pixels: canvas) +guard let flatImage = NSImage(contentsOf: flatPNG) else { fail("cannot read the flat render") } +let flat = draw(flatImage, at: canvas) +let glass = draw(renderGlass(), at: canvas) + +// The glass tile must sit where the flat one does, within a pixel of +// antialiasing, so the Dock icon does not jump between macOS versions. +let expected = (tileOrigin, tileOrigin, tileOrigin + tileSize - 1, tileOrigin + tileSize - 1) +for (name, rep) in [("AppIcon.svg", flat), ("the glass render", glass)] { + let b = opaqueBounds(rep) + let drift = [b.0 - expected.0, b.1 - expected.1, b.2 - expected.2, b.3 - expected.3] + guard drift.allSatisfy({ abs($0) <= 1 }) else { + fail("\(name) covers \(b), not the \(expected) tile the Dock expects") + } +} + +// The Default icon style keeps the mark's own colours; Clear and Tinted +// replace them, and Dark darkens the tile. Two probes that hold whatever +// size AppGlyph.svg draws the mark at, as long as it is centred: the +// canvas centre, which is the mark's dark green block, and the tile 50 px +// in from its left edge, outside the mark and clear of the glass rim. +// Lighting shifts them a little; a style change replaces them. +for probe in [(x: 512, y: 512, label: "green block"), (x: 150, y: 512, label: "tile")] { + let authored = srgb(flat, x: probe.x, y: probe.y) + let rendered = srgb(glass, x: probe.x, y: probe.y) + guard authored.count == 4, rendered.count == 4, + zip(authored, rendered).allSatisfy({ abs($0 - $1) <= 32 }) + else { + fail("the glass \(probe.label) renders \(rendered), not \(authored): set System Settings > Appearance > Icon & widget style to Default") + } +} + +// sips at the output size, as the bundle's iconset is drawn, rather than a +// resample of the 1024 px check render. +rasterize(tileSVG, to: flatOut, pixels: output) +print(" \(flatOut.lastPathComponent) (\(output) px)") +let glassImage = NSImage(size: NSSize(width: canvas, height: canvas)) +glassImage.addRepresentation(glass) +write(draw(glassImage, at: output), to: glassOut) diff --git a/packaging/disktree.desktop.in b/packaging/pwrdisk.desktop.in similarity index 79% rename from packaging/disktree.desktop.in rename to packaging/pwrdisk.desktop.in index 4f9cfb78..561b591a 100644 --- a/packaging/disktree.desktop.in +++ b/packaging/pwrdisk.desktop.in @@ -1,17 +1,17 @@ [Desktop Entry] Type=Application Version=1.0 -Name=disktree +Name=PwrDisk GenericName=Disk space treemap Comment=Find what is using a volume, mark what should go, remove it -Exec=@BINDIR@/disktree %f -Icon=disktree +Exec=@BINDIR@/pwrdisk %f +Icon=pwrdisk Terminal=false Categories=System;Filesystem; Keywords=disk;space;usage;du;treemap;cleanup; StartupNotify=true -StartupWMClass=disktree -# Registered for directories, so a file manager can offer "Open with disktree". +StartupWMClass=pwrdisk +# Registered for directories, so a file manager can offer "Open with PwrDisk". # This adds a handler; it does not become the default. MimeType=inode/directory; Actions=disk; @@ -19,4 +19,4 @@ X-AppVersion=@VERSION@ [Desktop Action disk] Name=Scan the whole disk -Exec=@BINDIR@/disktree --disk +Exec=@BINDIR@/pwrdisk --disk diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 39cd91be..bfc42ebe 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,8 +1,8 @@ # The workspace's MSRV, pinned so rustup provisions it automatically: a fresh # clone builds on a machine whose default stable is older, instead of failing -# with cargo's `rustc ... is not supported` before anything compiles. CI pins -# the same version (see .github/workflows), and `make lint` needs clippy and -# rustfmt, so they come with it. +# with cargo's `rustc ... is not supported` before anything compiles. CI and +# releases read this channel (.github/actions/setup-rust), so bumping it here +# bumps them too. `make lint` needs clippy and rustfmt, so they come with it. [toolchain] channel = "1.97" components = ["clippy", "rustfmt"] diff --git a/scripts/a11y-atspi-read.py b/scripts/a11y-atspi-read.py new file mode 100644 index 00000000..da1e1fd4 --- /dev/null +++ b/scripts/a11y-atspi-read.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Read native AT-SPI metadata from an explicitly named fixture process. + +Run inside the same desktop/session bus as the PwrDisk process opened on a +contrived tree (`pwrdisk ROOT`). This diagnostic does not invoke actions, +synthesize input, or start a screen reader. +""" + +import argparse +import json +import time + +import pyatspi + + +def inspect(node, depth=0, remaining=None): + if remaining is None: + remaining = [5000] + if remaining[0] == 0 or depth > 32: + return + remaining[0] -= 1 + row = { + "depth": depth, + "role": node.getRoleName(), + "name": node.name, + "description": node.description, + "states": [str(state) for state in node.getState().getStates()], + "relations": [str(rel.getRelationType()) for rel in node.getRelationSet()], + } + try: + action = node.queryAction() + row["actions"] = [action.getName(index) for index in range(action.nActions)] + except NotImplementedError: + pass + try: + value = node.queryValue() + row["value"] = value.currentValue + except NotImplementedError: + pass + try: + row["text"] = node.queryText().getText(0, -1) + except NotImplementedError: + pass + print(json.dumps(row, ensure_ascii=False), flush=True) + for index in range(node.childCount): + child = node.getChildAtIndex(index) + if child is not None: + inspect(child, depth + 1, remaining) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--pid", required=True, type=int) + args = parser.parse_args() + deadline = time.monotonic() + 20 + while time.monotonic() < deadline: + desktop = pyatspi.Registry.getDesktop(0) + for app in desktop: + if app.get_process_id() == args.pid and app.childCount: + # The first window can register before its scan completes. + time.sleep(2) + inspect(app) + return + time.sleep(0.25) + raise SystemExit("No native AT-SPI application found for the supplied fixture PID") + + +if __name__ == "__main__": + main() diff --git a/scripts/a11y-fixture.py b/scripts/a11y-fixture.py new file mode 100644 index 00000000..b7317724 --- /dev/null +++ b/scripts/a11y-fixture.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Create a fresh, contrived tree for the PwrDisk accessibility audit.""" + +import argparse +import os +from pathlib import Path + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("root", type=Path) + parser.add_argument("--entries", type=int, default=128) + args = parser.parse_args() + if not 0 <= args.entries <= 100_000: + parser.error("--entries must be between 0 and 100000") + # Refuse an existing destination so reruns cannot overwrite user data. + args.root.mkdir(parents=True, exist_ok=False) + files = { + "keep/notes.txt": 4096, + "cache/build.bin": 2 * 1024 * 1024, + "cache/nested/older.bin": 1024 * 1024, + ".hidden/sample.bin": 512 * 1024, + "documents/Résumé 日本語.txt": 128 * 1024, + "documents/" + "long-name-" * 18 + ".txt": 64 * 1024, + "empty-file.txt": 0, + } + for name, count in files.items(): + path = args.root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"x" * count) + (args.root / "empty-directory").mkdir() + many = args.root / "many-small-files" + many.mkdir() + for index in range(args.entries): + (many / f"item-{index:06d}.txt").write_bytes(b"x" * 1024) + # Fixed dates make the age legend reproducible across reruns. + for path in args.root.rglob("*"): + if path.is_file(): + timestamp = 1_700_000_000 if "older" in path.name else 1_790_000_000 + os.utime(path, (timestamp, timestamp)) + print(args.root.resolve()) + print(f"{len(files) + args.entries} files; use --apparent-size") + + +if __name__ == "__main__": + main() diff --git a/scripts/ci/classify-changes.test.cjs b/scripts/ci/classify-changes.test.cjs new file mode 100644 index 00000000..0fc5ef15 --- /dev/null +++ b/scripts/ci/classify-changes.test.cjs @@ -0,0 +1,258 @@ +// Fixtures for ci.yml's "Classify Changes" job, ported from PwrRoute. +// Run with `node --test scripts/ci/classify-changes.test.cjs`; CI runs it in +// that job, and it needs no npm packages or GitHub credentials. +// +// Expensive CI skips only when every changed path, and a rename's old path, +// is one of these. Anything else, unknown paths included, runs full CI. +// +// - `docs/**` and Markdown anywhere (`.md`, any case): nothing builds or +// tests them. `README.md` is copied into release archives by release.yml, +// which is not this workflow. The exception is `CHANGELOG.md`: xtask's +// release check reads it, and so does a test of that check. So is +// `skills/**`: `pwrdisk mcp` compiles those skills in and tests them. +// - `.agents/skills/**`: agent resources, not app or CI inputs. +// - `.github/ISSUE_TEMPLATE/**`, `.github/PULL_REQUEST_TEMPLATE/**` and +// exactly `.github/dependabot.yml`. +// +// If a build, test or `include_str!` starts reading one of these, take it +// out of the allowlist first. The last test below catches the +// `include_str!` case. + +const assert = require('node:assert/strict'); +const { execFileSync } = require('node:child_process'); +const { readFileSync } = require('node:fs'); +const { dirname, join, posix, relative } = require('node:path'); +const { test } = require('node:test'); + +const root = join(__dirname, '../..'); + +// Execute the actual github-script body, so fixtures cannot drift from CI. +const workflow = readFileSync(join(root, '.github/workflows/ci.yml'), 'utf8'); +const script = workflow.match(/ script: \|\n((?: .*\n|\n)+)/)?.[1]; +assert.ok(script, 'the classifier must remain covered by these tests'); +const classify = new (async function () {}).constructor('github', 'context', 'core', script); + +async function run({ paths, files = paths?.map(filename => ({ filename, status: 'modified' })), + count = files?.length, event = 'pull_request', apiError = false, summaryError = false }) { + const outputs = {}; + const calls = []; + const summary = { + addHeading() { return this; }, + addTable() { return this; }, + addRaw() { return this; }, + async write() { if (summaryError) throw new Error('summary unavailable'); }, + }; + await classify({ + rest: { pulls: { listFiles: 'pulls.listFiles' } }, + async paginate(method, args) { + calls.push({ method, args }); + if (apiError) throw new Error('API unavailable'); + return files; + }, + }, { + eventName: event, + repo: { owner: 'pwrdrvr', repo: 'PwrDisk' }, + issue: { number: 11 }, + payload: { pull_request: { changed_files: count } }, + }, { + setOutput(name, value) { outputs[name] = value; }, + notice() {}, + summary, + }); + return { outputs, calls }; +} + +// PR #11, docs(agents): agent guidance and the PR screenshot procedure. +const agentGuidance = ['AGENTS.md', 'CLAUDE.md', 'docs/pr-screenshots.md']; + +for (const [name, paths] of [ + ['PR #11: agent guidance', agentGuidance], + ...agentGuidance.map(path => [`PR #11: ${path}`, [path]]), + ['skill files, scripts and images', [ + '.agents/skills/example/SKILL.md', + '.agents/skills/example/agents/openai.yaml', + '.agents/skills/example/scripts/check.sh', + '.agents/skills/example/assets/icon.png', + ]], + ['documentation, logs and patches under docs/', [ + 'README.md', '.github/workflows/README.md', 'crates/disktree-core/NOTES.MD', + 'docs/performance/mark-resolution/green.log', + 'docs/performance/mark-resolution/additional-audit.patch', + ]], + ['Dependabot configuration', ['.github/dependabot.yml']], + ['issue and PR templates', ['.github/ISSUE_TEMPLATE/bug_report.yml', '.github/PULL_REQUEST_TEMPLATE/custom.yml']], +]) { + test(`${name} skips expensive CI`, async () => { + assert.equal((await run({ paths })).outputs.code_impacting, 'false'); + }); +} + +for (const path of [ + 'crates/disktree-core/src/scan.rs', 'crates/disktree-app/Cargo.toml', + 'Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml', '.cargo/config.toml', + 'clippy.toml', 'rustfmt.toml', 'Makefile', 'xtask/src/main.rs', + 'assets/disktree.svg', 'assets/screenshot.png', 'packaging/macos/Info.plist.in', + 'packaging/pwrdisk.desktop.in', 'scripts/release/install-vpk.sh', + '.github/workflows/ci.yml', '.github/workflows/release.yml', + '.github/actions/setup-rust/action.yml', 'scripts/ci/classify-changes.test.cjs', 'licenses/velopack.txt', + 'LICENSE', 'CHANGELOG.md', 'skills/pwrdisk-free-space/SKILL.md', + 'skills/pwrdisk-free-space/references/macos.md', '.gitignore', '.agents/config.toml', 'unknown.yaml', +]) { + test(`${path} alone or mixed with docs runs full CI`, async () => { + for (const paths of [[path], [...agentGuidance, path]]) { + assert.equal((await run({ paths })).outputs.code_impacting, 'true'); + } + }); +} + +for (const [previous_filename, filename, full] of [ + ['docs/old.md', 'docs/new.md', false], + ['.agents/skills/old/SKILL.md', '.agents/skills/new/SKILL.md', false], + ['scripts/test-ssh.ts', 'docs/test-ssh.ts', true], + ['docs/notes.md', 'CHANGELOG.md', true], + ['README.md', 'Cargo.toml', true], +]) { + test(`rename ${previous_filename} to ${filename}`, async () => { + const result = await run({ files: [{ status: 'renamed', filename, previous_filename }] }); + assert.equal(result.outputs.code_impacting, String(full)); + }); +} + +for (const [name, input] of [ + ['empty list', { files: [] }], + ['incomplete pagination', { paths: agentGuidance, count: 101 }], + ['API 3,000-file cap', { paths: Array.from({ length: 3000 }, (_, i) => `docs/${i}.md`), count: 3001 }], + ['missing count', { paths: agentGuidance, count: null }], + ['noninteger count', { paths: agentGuidance, count: 3.5 }], + ['wrong count type', { paths: agentGuidance, count: '3' }], + ['duplicate pages', { paths: [agentGuidance[0], agentGuidance[0]] }], + ['malformed file', { files: [{}] }], + ['null file', { files: [null] }], + ['empty filename', { files: [{ filename: '' }] }], + ['invalid filename', { files: [{ filename: 42 }] }], + ['rename without old path', { files: [{ filename: 'docs/a.md', status: 'renamed' }] }], + ['invalid old path', { files: [{ filename: 'docs/a.md', previous_filename: 42 }] }], + ['empty old path', { files: [{ filename: 'docs/a.md', previous_filename: '' }] }], + ['API failure', { paths: agentGuidance, apiError: true }], +]) { + test(`${name} runs full CI`, async () => { + const { outputs } = await run(input); + assert.equal(outputs.code_impacting, 'true'); + assert.equal(outputs.licenses_impacting, 'true'); + }); +} + +test('uses the paginating API for more than one page', async () => { + const paths = Array.from({ length: 205 }, (_, i) => `docs/${i}.md`); + const result = await run({ paths }); + assert.equal(result.outputs.code_impacting, 'false'); + assert.deepEqual(result.calls, [{ method: 'pulls.listFiles', args: { + owner: 'pwrdrvr', repo: 'PwrDisk', pull_number: 11, per_page: 100, + } }]); +}); + +test('pushes always run full CI without querying PR files', async () => { + const result = await run({ paths: agentGuidance, event: 'push' }); + assert.equal(result.outputs.code_impacting, 'true'); + assert.equal(result.outputs.licenses_impacting, 'true'); + assert.equal(result.calls.length, 0); +}); + +test('license inputs and gate changes select the notice check, including renames', async () => { + for (const path of [ + 'Cargo.lock', 'Cargo.toml', 'crates/disktree-app/Cargo.toml', + 'xtask/Cargo.toml', 'licenses/about.toml', 'licenses/about.hbs', + 'licenses/bundled.txt', 'licenses/velopack.txt', 'licenses/nested/NOTES.md', + 'THIRD_PARTY_LICENSES', '.github/workflows/ci.yml', + '.github/actions/setup-rust/action.yml', + '.github/actions/setup-rust/prune.sh', 'xtask/src/licenses.rs', + ]) { + for (const status of ['modified', 'added', 'removed']) { + assert.equal((await run({ files: [{ filename: path, status }] })) + .outputs.licenses_impacting, 'true', `${status}: ${path}`); + } + for (const [previous_filename, filename] of [[path, 'docs/old.md'], ['docs/old.md', path]]) { + assert.equal((await run({ files: [{ filename, previous_filename, status: 'renamed' }] })) + .outputs.licenses_impacting, 'true', `rename: ${previous_filename} to ${filename}`); + } + } +}); + +test('unrelated changes skip the notice check even when they run full CI', async () => { + for (const paths of [agentGuidance, [ + 'crates/disktree-core/src/scan.rs', 'assets/disktree.svg', 'CHANGELOG.md', + 'docs/Cargo.toml.md', 'other/Cargo.lock', 'licenses-other/about.toml', + ]]) { + assert.equal((await run({ paths })).outputs.licenses_impacting, 'false'); + } +}); + +for (const field of ['code_impacting', 'licenses_impacting']) { + test(`${field} job output fails open after script failures or missing output`, async () => { + assert.match(workflow, /continue-on-error: true/); + const expression = workflow.match(new RegExp(`${field}: \\$\\{\\{ (.+) \\}\\}`))[1]; + const output = (outcome, value) => new Function('steps', `return (${expression});`)({ + classify: { outcome, outputs: { [field]: value } }, + }); + assert.equal(output('success', 'false'), false); + for (const [outcome, value] of [ + ['success', 'true'], ['success', undefined], ['failure', 'false'], + ['failure', undefined], ['skipped', undefined], ['cancelled', 'false'], + ]) assert.equal(output(outcome, value), true); + await assert.rejects(run({ paths: agentGuidance, summaryError: true }), /summary unavailable/); + }); +} + +test('every other job runs on classifier failure and skips only on explicit irrelevant success', () => { + const jobs = workflow.split('\njobs:\n')[1]; + const ids = [...jobs.matchAll(/^ ([a-z][\w-]*):\n/gm)].map(m => m[1]); + assert.deepEqual(ids, ['changes', 'licenses', 'check', 'check-macos', 'bundle-macos-26', 'windows', + 'other-architectures'], + 'a new job needs a decision here: gate it on the classifier or not'); + for (const id of ids.slice(1)) { + const job = workflow.match(new RegExp(`^ ${id}:\\n([\\s\\S]*?)(?=^ [a-z].*:|$(?![\\s\\S]))`, 'm'))?.[1]; + assert.ok(job, id); + assert.match(job, /^ needs: changes\n/m, `${id} must wait for the classifier`); + const expression = job.match(/ if: >-\n([\s\S]*?)(?=^ \w)/m)?.[1]; + assert.ok(expression, `${id} must have an explicit fail-safe job condition`); + const evaluate = new Function('needs', 'cancelled', `return (${expression});`); + for (const [result, output, expected] of [ + ['success', 'false', false], ['success', 'true', true], + ['success', '', true], ['failure', 'false', true], ['failure', '', true], + ['skipped', '', true], + ]) { + const field = id === 'licenses' ? 'licenses_impacting' : 'code_impacting'; + const otherField = id === 'licenses' ? 'code_impacting' : 'licenses_impacting'; + const needs = { changes: { result, outputs: { [field]: output, [otherField]: 'false' } } }; + assert.equal(evaluate(needs, () => false), expected, `${id}: ${result}/${output}`); + assert.equal(evaluate(needs, () => true), false, `${id}: cancelled`); + } + } +}); + +test('the workflow trigger has no path filters', () => { + // A path filter makes jobs vanish instead of skip, which leaves any + // required check pending forever. + assert.doesNotMatch(workflow, /^\s+paths(?:-ignore)?:/m); +}); + +test('nothing compiled in with include_str! or include_bytes! is on the allowlist', async () => { + const sources = execFileSync('git', ['ls-files', '*.rs'], { cwd: root, encoding: 'utf8' }) + .split('\n').filter(Boolean); + const included = []; + for (const source of sources) { + const text = readFileSync(join(root, source), 'utf8'); + for (const [call, literal] of text.matchAll(/include_(?:str|bytes)!\(\s*("[^"]+"\s*\))?/g)) { + // Only a plain literal can be checked here. A concat!/env! or raw + // string path would slip past, so it fails until rewritten as one. + assert.ok(literal, `${source}: \`${call}\` needs a plain string literal path`); + // Paths are relative to the including file, as rustc resolves them. + const path = relative(root, join(root, dirname(source), literal.slice(1, literal.lastIndexOf('"')))).split('\\').join(posix.sep); + included.push(path); + } + } + assert.ok(included.includes('packaging/macos/Info.plist.in'), 'the scan found xtask\'s Info.plist'); + for (const path of included) { + assert.equal((await run({ paths: [path] })).outputs.code_impacting, 'true', path); + } +}); diff --git a/scripts/ci/prune-rust-toolchains.sh b/scripts/ci/prune-rust-toolchains.sh new file mode 100755 index 00000000..1afb609a --- /dev/null +++ b/scripts/ci/prune-rust-toolchains.sh @@ -0,0 +1,33 @@ +#!/bin/sh +# Uninstall every rustup toolchain except the one rust-toolchain.toml pins, +# so the Swatinem/rust-cache key depends on that pin alone. Ported from +# PwrRoute. +# +# rust-cache hashes the version of every toolchain `rustup toolchain list` +# shows, not only the active one. GitHub's runner images ship a preinstalled +# stable whose version moves with each image rollout, and rollouts are +# gradual: two runs minutes apart can land on images with different stables +# and so compute different keys. Only main saves the cache, so a PR that +# lands on an image main has not run on yet finds nothing to restore and +# compiles cold. Turning off rust-cache's environment hash is no answer: at +# v2.9.x that input also drops the Cargo.lock hash, so main would save once +# and never follow a dependency change. +# +# Run it after the toolchain is installed and before rust-cache, from the +# workspace root, where rust-toolchain.toml decides which rustc answers. A +# toolchain whose rustc cannot be probed is left alone with a warning rather +# than failing the job. +set -eu +pinned=$(rustc -vV) +for toolchain in $(rustup toolchain list --quiet | tr -d '\r'); do + if ! probed=$(rustup run "$toolchain" rustc -vV 2>/dev/null); then + echo "::warning::could not probe toolchain $toolchain; leaving it installed" + continue + fi + if [ "$probed" = "$pinned" ]; then + echo "keeping $toolchain" + else + rustup toolchain uninstall "$toolchain" + fi +done +rustup toolchain list diff --git a/scripts/readme-chips.swift b/scripts/readme-chips.swift new file mode 100644 index 00000000..30ad4531 --- /dev/null +++ b/scripts/readme-chips.swift @@ -0,0 +1,375 @@ +#!/usr/bin/env swift + +import AppKit +import CoreText +import Foundation + +// Regenerates the README's download chips, in docs/assets/buttons/. Run +// from the repository root on a Mac: +// +// swift scripts/readme-chips.swift [path/to/Geist-Bold.ttf] +// +// This is the Pwr family's chip generator (PwrGit's +// apps/desktop/scripts/generate-readme-chips.swift) with PwrDisk's labels, +// so the chips match the sibling READMEs. Geist is not vendored here: pass +// the face from a sibling checkout to match their metrics exactly, or +// leave it out for the system bold face. +// +// Chips are deliberately theme-independent. GitHub serves README images +// unchanged in light and dark, so every chip carries its own opaque fill and +// clears contrast on white and on #0d1117 alike. + +// MARK: - Brand + +/// Everything a sibling repository has to change, in one place. +struct Brand { + let accent: NSColor + let accentTop: NSColor + let onAccent: NSColor + let surface: NSColor + let surfaceBorder: NSColor + let text: NSColor + let muted: NSColor + /// Geist Bold. Falls back to the system bold face when absent, which + /// shifts metrics slightly. + let boldFontPath: String +} + +let brand = Brand( + // deviceRGB, not calibratedRGB: the design-system tangerine is #ff8a1f and + // calibrated drifts it to #ee894a. Same pin as generate-dmg-background.swift. + accent: NSColor(deviceRed: 255 / 255.0, green: 138 / 255.0, blue: 31 / 255.0, alpha: 1), + accentTop: NSColor(deviceRed: 255 / 255.0, green: 162 / 255.0, blue: 77 / 255.0, alpha: 1), + onAccent: NSColor(deviceRed: 22 / 255.0, green: 10 / 255.0, blue: 0 / 255.0, alpha: 1), + surface: NSColor(deviceRed: 13 / 255.0, green: 13 / 255.0, blue: 13 / 255.0, alpha: 1), + surfaceBorder: NSColor(deviceRed: 247 / 255.0, green: 243 / 255.0, blue: 235 / 255.0, alpha: 0.16), + text: NSColor(deviceRed: 247 / 255.0, green: 243 / 255.0, blue: 235 / 255.0, alpha: 1), + muted: NSColor(deviceRed: 168 / 255.0, green: 160 / 255.0, blue: 148 / 255.0, alpha: 1), + boldFontPath: CommandLine.arguments.dropFirst().first ?? "" +) + +// MARK: - Chip inventory + +enum Style { + /// Tangerine fill, dark ink. Exactly one chip per README wears this. + case primary + /// Near-black fill, hairline border, light ink. + case secondary +} + +enum Family { + /// Two-line download chip: 276x64. + case download + /// One-line link chip: 200x44. + case link +} + +struct Chip { + let file: String + let family: Family + let style: Style + let title: String + /// Second line. Empty on link chips. + let subtitle: String +} + +let chips: [Chip] = [ + // One universal build: PwrDisk ships no separate Apple Silicon DMG. + Chip( + file: "download-mac.png", family: .download, style: .primary, + title: "Download for Mac", subtitle: "Universal · Intel + Apple Silicon" + ), + Chip( + file: "download-windows-x64.png", family: .download, style: .secondary, + title: "Download for Windows", subtitle: "x64 installer" + ), + Chip( + file: "download-windows-arm64.png", family: .download, style: .secondary, + title: "Download for Windows", subtitle: "ARM64 installer" + ), + // Linux ships a tarball with an install script, not distro packages. + Chip( + file: "download-linux-x64.png", family: .download, style: .secondary, + title: "Download for Linux", subtitle: "x86-64 · .tar.gz" + ), + Chip( + file: "download-linux-arm64.png", family: .download, style: .secondary, + title: "Download for Linux", subtitle: "ARM64 · .tar.gz" + ), +] + +let outputDirectory = "docs/assets/buttons" + +// MARK: - Geometry + +extension Family { + /// Logical size. PNGs are written at 2x these numbers. README.md displays + /// them slightly smaller — 250 and 180 — so three download chips still sit on + /// one row in GitHub's ~836px content column once the repo sidebar is there. + /// Rendering above 1x is what keeps them crisp at that display width. + var size: NSSize { + switch self { + case .download: return NSSize(width: 276, height: 64) + case .link: return NSSize(width: 200, height: 44) + } + } + + var cornerRadius: CGFloat { + switch self { + case .download: return 12 + case .link: return 10 + } + } +} + +let scale: CGFloat = 2 + +// MARK: - Font loading + +/// Register a font file from disk so its PostScript name resolves through +/// NSFont(name:size:). Returns the resolved PostScript name on success. +func registerFont(at path: String) -> String? { + let url = URL(fileURLWithPath: path) + guard FileManager.default.fileExists(atPath: url.path) else { return nil } + var error: Unmanaged? + guard CTFontManagerRegisterFontsForURL(url as CFURL, .process, &error) else { + if let err = error?.takeRetainedValue() { + FileHandle.standardError.write(Data("Font register failed: \(err)\n".utf8)) + } + return nil + } + guard + let descriptors = CTFontManagerCreateFontDescriptorsFromURL(url as CFURL) as? [CTFontDescriptor], + let descriptor = descriptors.first, + let psName = CTFontDescriptorCopyAttribute(descriptor, kCTFontNameAttribute) as? String + else { return nil } + return psName +} + +let geistBoldName = brand.boldFontPath.isEmpty + ? nil : registerFont(at: brand.boldFontPath) +if geistBoldName == nil && !brand.boldFontPath.isEmpty { + FileHandle.standardError.write( + Data("warning: \(brand.boldFontPath) not found — falling back to the system bold face.\n".utf8) + ) +} + +func boldFont(_ size: CGFloat) -> NSFont { + if let name = geistBoldName, let font = NSFont(name: name, size: size) { return font } + return NSFont.systemFont(ofSize: size, weight: .bold) +} + +/// Subtitles use the system medium face, as the DMG background's subtitle does. +/// Only Geist Bold is vendored, and Bold at 11px reads as a second heading +/// rather than as supporting text. +func subtitleFont(_ size: CGFloat) -> NSFont { NSFont.systemFont(ofSize: size, weight: .medium) } + +// MARK: - Lucide icons + +/// A Lucide glyph as polylines on Lucide's own 24x24 grid, y-down. +/// Coordinates are copied from the published SVG, never redrawn by hand. +struct Icon { + let polylines: [[CGPoint]] + + /// lucide `arrow-down-to-line` + static let arrowDownToLine = Icon(polylines: [ + [CGPoint(x: 12, y: 17), CGPoint(x: 12, y: 3)], + [CGPoint(x: 18, y: 11), CGPoint(x: 12, y: 17), CGPoint(x: 6, y: 11)], + [CGPoint(x: 19, y: 21), CGPoint(x: 5, y: 21)], + ]) + + /// lucide `arrow-up-right` + static let arrowUpRight = Icon(polylines: [ + [CGPoint(x: 7, y: 7), CGPoint(x: 17, y: 7), CGPoint(x: 17, y: 17)], + [CGPoint(x: 7, y: 17), CGPoint(x: 17, y: 7)], + ]) +} + +/// Stroke a Lucide glyph into `rect`, flipping y for AppKit's bottom-left origin. +func draw(icon: Icon, in rect: NSRect, color: NSColor) { + let unit = rect.width / 24 + color.setStroke() + for polyline in icon.polylines { + let path = NSBezierPath() + for (index, point) in polyline.enumerated() { + let mapped = NSPoint( + x: rect.minX + point.x * unit, + y: rect.maxY - point.y * unit + ) + if index == 0 { path.move(to: mapped) } else { path.line(to: mapped) } + } + path.lineWidth = 2 * unit + path.lineCapStyle = .round + path.lineJoinStyle = .round + path.stroke() + } +} + +// MARK: - Rendering + +var failures: [String] = [] + +func render(_ chip: Chip) -> NSBitmapImageRep { + let size = chip.family.size + guard let bitmap = NSBitmapImageRep( + bitmapDataPlanes: nil, + pixelsWide: Int(size.width * scale), + pixelsHigh: Int(size.height * scale), + bitsPerSample: 8, + samplesPerPixel: 4, + hasAlpha: true, + isPlanar: false, + colorSpaceName: .deviceRGB, + bytesPerRow: 0, + bitsPerPixel: 0 + ) else { + fatalError("Unable to create bitmap for \(chip.file)") + } + // Logical size smaller than the pixel count gives the context a 2x CTM, so + // everything below is written in logical units and lands at retina density. + bitmap.size = size + + NSGraphicsContext.saveGraphicsState() + NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmap) + + let bounds = NSRect(origin: .zero, size: size) + let radius = chip.family.cornerRadius + + switch chip.style { + case .primary: + let body = NSBezierPath(roundedRect: bounds, xRadius: radius, yRadius: radius) + body.setClip() + // A two-stop vertical wash, not a decorative gradient: it is the same + // lift the app's primary button carries, and it survives grayscale. + NSGradient(starting: brand.accentTop, ending: brand.accent)? + .draw(in: bounds, angle: -90) + case .secondary: + let body = NSBezierPath(roundedRect: bounds, xRadius: radius, yRadius: radius) + brand.surface.setFill() + body.fill() + // Inset by half the line width so the hairline lands inside the bitmap + // instead of straddling the edge and rendering at half opacity. + let border = NSBezierPath( + roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5), + xRadius: radius - 0.5, + yRadius: radius - 0.5 + ) + border.lineWidth = 1 + brand.surfaceBorder.setStroke() + border.stroke() + } + + let ink = chip.style == .primary ? brand.onAccent : brand.text + let subtleInk = chip.style == .primary + ? brand.onAccent.withAlphaComponent(0.68) + : brand.muted + let iconInk = chip.style == .primary ? brand.onAccent : brand.accent + + switch chip.family { + case .download: + let padding: CGFloat = 18 + let iconSize: CGFloat = 20 + let gutter: CGFloat = 14 + + draw( + icon: .arrowDownToLine, + in: NSRect( + x: padding, + y: (size.height - iconSize) / 2, + width: iconSize, + height: iconSize + ), + color: iconInk + ) + + let titleAttrs: [NSAttributedString.Key: Any] = [ + .font: boldFont(15), .foregroundColor: ink, + ] + let subtitleAttrs: [NSAttributedString.Key: Any] = [ + .font: subtitleFont(11), .foregroundColor: subtleInk, + ] + let titleSize = chip.title.size(withAttributes: titleAttrs) + let subtitleSize = chip.subtitle.size(withAttributes: subtitleAttrs) + + let lineGap: CGFloat = 1 + let blockHeight = titleSize.height + lineGap + subtitleSize.height + let blockBottom = ((size.height - blockHeight) / 2).rounded() + let textX = padding + iconSize + gutter + + chip.subtitle.draw(at: NSPoint(x: textX, y: blockBottom), withAttributes: subtitleAttrs) + chip.title.draw( + at: NSPoint(x: textX, y: blockBottom + subtitleSize.height + lineGap), + withAttributes: titleAttrs + ) + + let available = size.width - textX - padding + let widest = max(titleSize.width, subtitleSize.width) + if widest > available { + failures.append( + "\(chip.file): text needs \(Int(widest.rounded()))pt but the chip offers " + + "\(Int(available.rounded()))pt — widen Family.download or shorten the label" + ) + } + + case .link: + let iconSize: CGFloat = 14 + let gutter: CGFloat = 8 + let titleAttrs: [NSAttributedString.Key: Any] = [ + .font: boldFont(13), .foregroundColor: ink, + ] + let titleSize = chip.title.size(withAttributes: titleAttrs) + let groupWidth = titleSize.width + gutter + iconSize + let groupX = ((size.width - groupWidth) / 2).rounded() + + chip.title.draw( + at: NSPoint(x: groupX, y: ((size.height - titleSize.height) / 2).rounded()), + withAttributes: titleAttrs + ) + draw( + icon: .arrowUpRight, + in: NSRect( + x: groupX + titleSize.width + gutter, + y: (size.height - iconSize) / 2, + width: iconSize, + height: iconSize + ), + color: iconInk + ) + + let padding: CGFloat = 14 + if groupWidth > size.width - padding * 2 { + failures.append( + "\(chip.file): label needs \(Int(groupWidth.rounded()))pt but the chip offers " + + "\(Int((size.width - padding * 2).rounded()))pt — widen Family.link or shorten the label" + ) + } + } + + NSGraphicsContext.restoreGraphicsState() + return bitmap +} + +// MARK: - Write + +let directory = URL(fileURLWithPath: outputDirectory) +try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + +for chip in chips { + let bitmap = render(chip) + guard let data = bitmap.representation(using: .png, properties: [:]) else { + fatalError("Unable to encode \(chip.file)") + } + let url = directory.appendingPathComponent(chip.file) + do { + try data.write(to: url) + } catch { + fatalError("Unable to write \(url.path): \(error)") + } + print("\(url.path) — \(bitmap.pixelsWide)x\(bitmap.pixelsHigh)") +} + +if !failures.isEmpty { + // Clipped text is silent in a PNG. Fail loudly instead of shipping one. + FileHandle.standardError.write(Data((failures.joined(separator: "\n") + "\n").utf8)) + exit(1) +} diff --git a/scripts/release/dmg-layout.py b/scripts/release/dmg-layout.py new file mode 100644 index 00000000..66917082 --- /dev/null +++ b/scripts/release/dmg-layout.py @@ -0,0 +1,292 @@ +#!/usr/bin/env python3 +"""Write the .DS_Store that gives a mounted DMG its installer window. + + dmg-layout.py + +Finder reads a volume's window geometry, icon-view options, background picture +and per-item icon positions out of .DS_Store. Nothing in the base system +writes one: `hdiutil` only makes the filesystem, and the usual way to get the +rest is to drive Finder over AppleScript. + +This writes the file directly instead, for two reasons. + +Finder's .DS_Store embeds the ABSOLUTE PATH OF THE DISK IMAGE on the machine +that styled it, inside the background picture's alias and in a companion +bookmark record. A DMG styled that way ships the build host's home directory +and staging paths to everyone who downloads it, and a captured copy could not +be committed here at all. The alias this module writes names only the volume +and the path inside it. + +The second reason is that driving Finder needs an Apple Events grant for +whatever process runs the build. Packaging must work unattended on the +self-hosted release runner, which has no one to answer a TCC prompt. + +electron-builder reaches the same file through a downloaded `dmgbuild` binary, +which also writes a volume-relative alias. This is that step, for a repository +that does not download build tools. Format references: the Buddy allocator and +B-tree layout of .DS_Store, and Inside Macintosh's AliasRecord version 2. +""" + +# Adapted from PwrSuiteLab lab-control/scripts/dmg-layout.py. + +import os +import plistlib +import struct +import sys + +# Window and icon layout — the suite's installer geometry, shared with +# generate-dmg-background.swift, which draws the arrow between these exact +# icon centres. Coordinates are the icon CENTRE, in points, from the window's +# top-left corner. Change one file, change the other. +WINDOW_SIZE = (660, 400) +WINDOW_ORIGIN = (200, 120) +ICON_SIZE = 112 +TEXT_SIZE = 12 +BACKGROUND = ".background/background.png" +# Two icons, as in the three reference installers. Anything else in the window +# crowds the drag-to-Applications line the artwork draws. +ITEM_POSITIONS = { + "PwrDisk.app": (170, 230), + "Applications": (500, 230), +} + +# Unix epoch to the classic Mac epoch (1904-01-01), for alias date fields. +HFS_EPOCH_DELTA = 2082844800 + + +def hfs_time(seconds): + return max(0, int(seconds) + HFS_EPOCH_DELTA) & 0xFFFFFFFF + + +def pascal(text, size): + """A Pascal string padded to a fixed field width, as AliasRecord uses. + + Over-long text is trimmed a CHARACTER at a time: slicing the encoded bytes + would cut through a multi-byte sequence and leave invalid UTF-8 in the + record. + """ + raw = text.encode("utf-8") + while len(raw) > size - 1: + text = text[:-1] + raw = text.encode("utf-8") + return bytes([len(raw)]) + raw + b"\0" * (size - 1 - len(raw)) + + +def utf16_field(text): + """An alias `extra` payload: character count then UTF-16BE, no BOM.""" + encoded = text.encode("utf-16-be") + return struct.pack(">H", len(encoded) // 2) + encoded + + +def background_alias(volume, volume_name, relative_path): + """An AliasRecord version 2 for a file on the mounted volume. + + `volume` is where the image is mounted on THIS machine, and is used only to + stat the real files. Every string the record carries is built from + `volume_name` and `relative_path` instead, so the alias describes the + volume as the person who opens the DMG will see it — mounted at + /Volumes/ — and says nothing about the build host, wherever it + happened to mount the scratch image. Finder resolves the record by + catalogue node id first and falls back to those path `extra` entries. + """ + mount_point = f"/Volumes/{volume_name}" + parts = relative_path.split("/") + parent_relative, filename = "/".join(parts[:-1]), parts[-1] + target = os.path.join(volume, relative_path) + parent = os.path.dirname(target) + + target_stat, parent_stat, volume_stat = os.stat(target), os.stat(parent), os.stat(volume) + # Alias records carry 32-bit HFS+ catalogue node ids. macos-dmg.sh builds the + # scratch image with `-fs HFS+` so these always fit; say so plainly rather + # than letting struct.pack raise "argument out of range". + for label, node in (("target", target_stat.st_ino), ("parent", parent_stat.st_ino)): + if node > 0xFFFFFFFF: + raise SystemExit( + f"dmg-layout: the {label} inode {node} does not fit a 32-bit alias field — " + "the volume must be HFS+" + ) + + record = b"".join([ + struct.pack(">I", 0), # application-specific user type + struct.pack(">H", 0), # record size, patched below + struct.pack(">HH", 2, 0), # version 2, kind 0 (file) + pascal(volume_name, 28), + struct.pack(">I", hfs_time(volume_stat.st_birthtime)), + b"H+", # volume signature (HFS+) + struct.pack(">H", 4), # volume type (disk image) + struct.pack(">I", parent_stat.st_ino), + pascal(filename, 64), + struct.pack(">I", target_stat.st_ino), + struct.pack(">I", hfs_time(target_stat.st_birthtime)), + b"\0\0\0\0", # file type + b"\0\0\0\0", # file creator + struct.pack(">HH", 0xFFFF, 0xFFFF), # levels from / to: unknown + struct.pack(">I", 0), # volume attributes + struct.pack(">H", 0), # volume filesystem id + b"\0" * 10, # reserved + ]) + assert len(record) == 150, len(record) + + extras = [ + (0, os.path.basename(parent_relative).encode("utf-8")), # parent folder name + (1, struct.pack(">I", parent_stat.st_ino)), # parent folder cnid + # Carbon path: colon-separated, and the parent segment drops out when + # the target sits at the volume root. + (2, ":".join(filter(None, [volume_name, parent_relative, filename])).encode("utf-8")), + (14, utf16_field(filename)), # unicode filename + (15, utf16_field(volume_name)), # unicode volume name + (18, f"/{relative_path}".encode("utf-8")), # path within the volume + (19, mount_point.encode("utf-8")), # volume mount point + ] + for kind, payload in extras: + record += struct.pack(">hH", kind, len(payload)) + payload + if len(payload) % 2: + record += b"\0" + record += struct.pack(">hH", -1, 0) # end of extras + + return record[:4] + struct.pack(">H", len(record)) + record[6:] + + +def window_settings(): + (x, y), (width, height) = WINDOW_ORIGIN, WINDOW_SIZE + return { + "ContainerShowSidebar": False, + "ShowSidebar": False, + "ShowStatusBar": False, + "ShowTabView": False, + "ShowToolbar": False, + # The path bar is a per-viewer Finder preference, and it eats 26pt off + # the bottom of the window — enough to hide the background's own + # "Drag to Applications" line. Pin it off so every viewer sees the + # same artwork. Finder omits this key when the preference is already + # off, which is why a captured .DS_Store does not carry it. + "ShowPathbar": False, + "WindowBounds": "{{%d, %d}, {%d, %d}}" % (x, y, width, height), + } + + +def icon_view_settings(alias): + return { + "arrangeBy": "none", + # backgroundType 2 is "picture"; the colour keys are the white Finder + # falls back to and are written even when a picture is set. + "backgroundType": 2, + "backgroundColorRed": 1.0, + "backgroundColorGreen": 1.0, + "backgroundColorBlue": 1.0, + "backgroundImageAlias": alias, + "gridOffsetX": 0.0, + "gridOffsetY": 0.0, + "gridSpacing": 100.0, + "iconSize": float(ICON_SIZE), + "labelOnBottom": True, + "showIconPreview": False, + "showItemInfo": False, + "textSize": float(TEXT_SIZE), + "viewOptionsVersion": 1, + } + + +def icon_location(x, y): + """An `Iloc` blob: the icon centre, then Finder's unset-index padding.""" + return struct.pack(">II", x, y) + b"\xff\xff\xff\xff\xff\xff\x00\x00" + + +def encode_records(records): + """The B-tree leaf node holding every record, sorted the way Finder sorts. + + Keys order by filename case-insensitively, then by the four-character + structure id. A reader that binary-searches a mis-sorted node silently + misses records, so this is not cosmetic. + """ + node = struct.pack(">II", 0, len(records)) # 0 = leaf node + for name, struct_id, value in sorted(records, key=lambda r: (r[0].lower(), r[1])): + encoded = name.encode("utf-16-be") + node += struct.pack(">I", len(encoded) // 2) + encoded + node += struct_id.encode("ascii") + if isinstance(value, bytes): + node += b"blob" + struct.pack(">I", len(value)) + value + elif isinstance(value, int): + node += b"long" + struct.pack(">I", value) + elif isinstance(value, str): + code = value.encode("ascii") + if len(code) != 4: + raise ValueError(f"{name}/{struct_id}: type values must be four ASCII bytes") + node += b"type" + code + else: + raise TypeError(f"unsupported value for {name}/{struct_id}: {type(value)}") + return node + + +def encode_ds_store(node, record_count): + """Wrap the leaf node in the Buddy allocator file .DS_Store actually is. + + Three blocks, at the fixed addresses Finder itself uses, so the result is + byte-for-byte conventional: block 0 is the allocator's own root block, + block 1 the B-tree header, block 2 the single leaf page. Allocator + addresses are relative to file offset 4, and an address's low five bits + carry log2 of the block size rather than part of the offset. + """ + page = 0x1000 + if len(node) > page: + raise SystemExit(f"dmg-layout: the leaf node is {len(node)} bytes, over the {page}-byte page") + + blocks = [(0x2000, 11), (0x40, 5), (0x1000, 12)] # (address, log2 size) + root = struct.pack(">II", len(blocks), 0) + root += b"".join(struct.pack(">I", address | shift) for address, shift in blocks) + root += b"\0" * (4 * (256 - len(blocks))) # the table is padded to 256 slots + root += struct.pack(">I", 1) + bytes([4]) + b"DSDB" + struct.pack(">I", 1) + # Buddy free lists, one per power of two. Everything the three blocks do + # not occupy below 2^31 is free, which is the state Finder leaves behind. + free = {5: [0x20, 0x60], 7: [0x80], 8: [0x100], 9: [0x200], 10: [0x400], + 11: [0x800, 0x2800], 12: [0x3000]} + free.update({width: [1 << width] for width in range(14, 31)}) + for width in range(32): + addresses = free.get(width, []) + root += struct.pack(">I", len(addresses)) + root += b"".join(struct.pack(">I", address) for address in addresses) + + root_size = 0x800 + if len(root) > root_size: + raise SystemExit(f"dmg-layout: the allocator root is {len(root)} bytes, over {root_size}") + root = root.ljust(root_size, b"\0") + + header = struct.pack(">I4sIII", 1, b"Bud1", 0x2000, root_size, 0x2000) + bytes.fromhex( + "0000100c" + "00" * 12 + ) + image = bytearray(header.ljust(4 + 0x2000 + root_size, b"\0")) + # DSDB header: root node block, tree levels, total records, node count, page size. + image[4 + 0x40 : 4 + 0x40 + 20] = struct.pack(">IIIII", 2, 0, record_count, 1, page) + image[4 + 0x1000 : 4 + 0x1000 + len(node)] = node + image[4 + 0x2000 : 4 + 0x2000 + root_size] = root + return bytes(image) + + +def main(): + if len(sys.argv) not in (2, 3): + raise SystemExit("usage: dmg-layout.py [volume-name]") + volume = sys.argv[1] + # The volume name the DMG will carry, which need not be the directory the + # image is mounted on while it is being built. + volume_name = sys.argv[2] if len(sys.argv) == 3 else os.path.basename(volume.rstrip("/")) + if not os.path.isdir(volume): + raise SystemExit(f"dmg-layout: {volume} is not a mounted volume") + for name in ITEM_POSITIONS: + if not os.path.lexists(os.path.join(volume, name)): + raise SystemExit(f"dmg-layout: {volume} has no item named {name!r}") + + alias = background_alias(volume, volume_name, BACKGROUND) + records = [(".", "bwsp", plistlib.dumps(window_settings(), fmt=plistlib.FMT_BINARY)), + (".", "icvp", plistlib.dumps(icon_view_settings(alias), fmt=plistlib.FMT_BINARY)), + (".", "vSrn", 1), + (".", "vstl", "icnv")] + records += [(name, "Iloc", icon_location(*xy)) for name, xy in ITEM_POSITIONS.items()] + + destination = os.path.join(volume, ".DS_Store") + with open(destination, "wb") as handle: + handle.write(encode_ds_store(encode_records(records), len(records))) + print(f" wrote {destination} ({len(alias)}-byte background alias, {len(records)} records)") + + +if __name__ == "__main__": + main() diff --git a/scripts/release/generate-dmg-background.swift b/scripts/release/generate-dmg-background.swift new file mode 100644 index 00000000..6685f2f4 --- /dev/null +++ b/scripts/release/generate-dmg-background.swift @@ -0,0 +1,196 @@ +#!/usr/bin/env swift +// Paint the DMG window's background: the "PwrDisk" wordmark on a dark pill, +// a subtitle, and an orange arrow from the app icon to the Applications link. +// Ported from PwrSnap's apps/desktop/scripts/generate-dmg-background.swift so +// the Pwr family's installers look alike. +// +// The PNG is committed (packaging/dmg/background.png): CI does not run Swift, +// and macos-dmg.sh reads it as a file. Rerun this after changing the layout +// or the artwork, and commit the result: +// +// swift scripts/release/generate-dmg-background.swift [OUT.png] +// +// The font is the vendored Geist Bold in packaging/dmg/fonts (SIL OFL 1.1). + +import AppKit +import CoreText +import Foundation + +/// Register a font file from disk so its PostScript name becomes resolvable via +/// NSFont(name:size:). Returns the resolved PostScript name on success. +func registerFont(at url: URL) -> String? { + guard FileManager.default.fileExists(atPath: url.path) else { return nil } + var error: Unmanaged? + guard CTFontManagerRegisterFontsForURL(url as CFURL, .process, &error) else { + if let err = error?.takeRetainedValue() { + FileHandle.standardError.write(Data("Font register failed: \(err)\n".utf8)) + } + return nil + } + guard + let descriptors = CTFontManagerCreateFontDescriptorsFromURL(url as CFURL) as? [CTFontDescriptor], + let descriptor = descriptors.first, + let psName = CTFontDescriptorCopyAttribute(descriptor, kCTFontNameAttribute) as? String + else { return nil } + return psName +} + +// DMG window and icon layout — keep in sync with scripts/release/macos-dmg.sh +// (xtask's tests compare the two). +let width = 660 +let height = 400 +let iconSize = 112 +let appIconX = 170 +let applicationsX = 500 +let iconY = 230 + +// Paths resolve from this file, so the script runs from any directory. +let root = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() // scripts/release + .deletingLastPathComponent() // scripts + .deletingLastPathComponent() +let output = CommandLine.arguments.dropFirst().first.map { URL(fileURLWithPath: $0) } + ?? root.appendingPathComponent("packaging/dmg/background.png") + +let geistBoldURL = root.appendingPathComponent("packaging/dmg/fonts/Geist-Bold.ttf") +guard let geistBoldName = registerFont(at: geistBoldURL) else { + // A system-font wordmark would not match the siblings; refuse to paint one. + FileHandle.standardError.write(Data("generate-dmg-background: cannot load \(geistBoldURL.path)\n".utf8)) + exit(1) +} + +struct Color { + static let background = NSColor(calibratedRed: 0.965, green: 0.965, blue: 0.965, alpha: 1) + // Pill behind the wordmark — near-black #0a0a0a, matching the app's titlebar + // background. Pinned deviceRGB so the pixels land exactly; calibratedRGB + // drifts lighter. + static let pillBackground = NSColor(deviceRed: 10 / 255.0, green: 10 / 255.0, blue: 10 / 255.0, alpha: 1) + static let text = NSColor(calibratedRed: 0.969, green: 0.953, blue: 0.922, alpha: 1) + static let muted = NSColor(calibratedRed: 0.549, green: 0.522, blue: 0.478, alpha: 1) + // Brand tangerine — design system: #ff8a1f (rgb 255, 138, 31). Pinned in + // deviceRGB so the rendered pixels land on #ff8a1f exactly; calibratedRGB + // drifts it to #ee894a, a third orange next to the wordmark and the icon. + static let accent = NSColor(deviceRed: 255 / 255.0, green: 138 / 255.0, blue: 31 / 255.0, alpha: 1) + static let arrowShaft = NSColor(deviceRed: 255 / 255.0, green: 138 / 255.0, blue: 31 / 255.0, alpha: 1) +} + +func renderBackground() -> NSBitmapImageRep { + guard let bitmap = NSBitmapImageRep( + bitmapDataPlanes: nil, + pixelsWide: width, + pixelsHigh: height, + bitsPerSample: 8, + samplesPerPixel: 4, + hasAlpha: true, + isPlanar: false, + colorSpaceName: .deviceRGB, + bytesPerRow: 0, + bitsPerPixel: 0 + ) else { + fatalError("Unable to create bitmap") + } + bitmap.size = NSSize(width: CGFloat(width), height: CGFloat(height)) + + NSGraphicsContext.saveGraphicsState() + NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmap) + + let h = CGFloat(height) + let w = CGFloat(width) + + // Light background + Color.background.setFill() + NSRect(x: 0, y: 0, width: w, height: h).fill() + + // Dark rounded pill behind logo and subtitle + let pillWidth: CGFloat = 340 + let pillHeight: CGFloat = 100 + let pillX = (w - pillWidth) / 2 + let pillY = h - 120 + let pill = NSBezierPath( + roundedRect: NSRect(x: pillX, y: pillY, width: pillWidth, height: pillHeight), + xRadius: 16, yRadius: 16 + ) + Color.pillBackground.setFill() + pill.fill() + + // Logo: "Pwr" + "Disk" in Geist Bold, the family's display face. + guard let logoFont = NSFont(name: geistBoldName, size: 40) else { + fatalError("Geist Bold registered as \(geistBoldName) but does not resolve") + } + let logoY = pillY + pillHeight - 60 + let pwrSize = "Pwr".size(withAttributes: [.font: logoFont]) + let diskSize = "Disk".size(withAttributes: [.font: logoFont]) + let logoX = (w - pwrSize.width - diskSize.width) / 2 + + let textAttrs: [NSAttributedString.Key: Any] = [.font: logoFont, .foregroundColor: Color.text] + let accentAttrs: [NSAttributedString.Key: Any] = [.font: logoFont, .foregroundColor: Color.accent] + "Pwr".draw(at: NSPoint(x: logoX, y: logoY), withAttributes: textAttrs) + "Disk".draw(at: NSPoint(x: logoX + pwrSize.width, y: logoY), withAttributes: accentAttrs) + + // Subtitle: what the app weighs and what it gives back, in the family's + // two-noun form (PwrRoute's is "links / browsers"). + let subtitleFont = NSFont.systemFont(ofSize: 11, weight: .medium) + let subtitle = "disks / space" + let subtitleAttrs: [NSAttributedString.Key: Any] = [.font: subtitleFont, .foregroundColor: Color.muted] + let subtitleSize = subtitle.size(withAttributes: subtitleAttrs) + subtitle.draw( + at: NSPoint(x: (w - subtitleSize.width) / 2, y: pillY + 14), + withAttributes: subtitleAttrs + ) + + // Arrow — thick orange bar with chunky arrowhead + let arrowStartX = CGFloat(appIconX + iconSize / 2 + 20) + let arrowEndX = CGFloat(applicationsX - iconSize / 2 - 20) + let arrowY = h - CGFloat(iconY) + let shaftThickness: CGFloat = 18 + + // Shaft — rounded rectangle + let shaft = NSBezierPath( + roundedRect: NSRect( + x: arrowStartX, + y: arrowY - shaftThickness / 2, + width: arrowEndX - arrowStartX - 20, + height: shaftThickness + ), + xRadius: shaftThickness / 2, + yRadius: shaftThickness / 2 + ) + Color.arrowShaft.setFill() + shaft.fill() + + // Arrowhead — solid orange triangle + Color.accent.setFill() + let headHeight: CGFloat = 48 + let headWidth: CGFloat = 32 + let arrowHead = NSBezierPath() + arrowHead.move(to: NSPoint(x: arrowEndX, y: arrowY)) + arrowHead.line(to: NSPoint(x: arrowEndX - headWidth, y: arrowY + headHeight / 2)) + arrowHead.line(to: NSPoint(x: arrowEndX - headWidth, y: arrowY - headHeight / 2)) + arrowHead.close() + arrowHead.fill() + + // "Drag to Applications" hint + let instructionFont = NSFont.systemFont(ofSize: 12, weight: .medium) + let instruction = "Drag to Applications" + let instrColor = NSColor(calibratedRed: 0.45, green: 0.45, blue: 0.45, alpha: 1) + let instrAttrs: [NSAttributedString.Key: Any] = [.font: instructionFont, .foregroundColor: instrColor] + let instrSize = instruction.size(withAttributes: instrAttrs) + instruction.draw( + at: NSPoint(x: (w - instrSize.width) / 2, y: h - 366), + withAttributes: instrAttrs + ) + + NSGraphicsContext.restoreGraphicsState() + return bitmap +} + +// Single 1x PNG — no multi-resolution TIFF. +let rep = renderBackground() + +guard let pngData = rep.representation(using: .png, properties: [:]) else { + fatalError("Unable to create PNG data") +} + +try FileManager.default.createDirectory(at: output.deletingLastPathComponent(), withIntermediateDirectories: true) +try pngData.write(to: output) +print("Generated DMG background PNG (\(pngData.count / 1024) KB): \(output.path)") diff --git a/scripts/release/install-vpk.sh b/scripts/release/install-vpk.sh new file mode 100755 index 00000000..4ce2570f --- /dev/null +++ b/scripts/release/install-vpk.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# Install Velopack's vpk CLI from a SHA-512-verified package, and put it on +# PATH for the steps after this one. +# +# The release sign jobs run vpk next to the signing credentials, so it is +# installed only from the bytes pinned here, never from whatever the feed +# serves. VPK_VERSION must equal the velopack crate pin in +# crates/disktree-app/Cargo.toml; upgrade both together and take the new +# hash from NuGet's catalog (packageHash, base64) or `shasum -a 512`, then +# rerun velopack-notices.sh for the new binaries' license notices. +# +# Needs .NET 8 (actions/setup-dotnet), curl, and GITHUB_PATH / RUNNER_TEMP +# from Actions. Runs under bash on macOS and on Windows (Git Bash). +# +# usage: install-vpk.sh +set -euo pipefail + +VPK_VERSION=1.2.161 +VPK_SHA512=359f48f056f0973e1b1cf971bd67862b1dd35c21147f801d3c78541e2769a6033708a56dd5b1801c7add0630a36344b5ba892997ad2f03cf3dc00ccedbf8b19b + +temp_root=${VPK_TEMP_ROOT:-${RUNNER_TEMP:?}} +feed="$temp_root/vpk-feed" +tools="$temp_root/vpk" +mkdir -p "$feed" +package="$feed/vpk.$VPK_VERSION.nupkg" +curl -fsSL --retry 3 -o "$package" \ + "https://api.nuget.org/v3-flatcontainer/vpk/$VPK_VERSION/vpk.$VPK_VERSION.nupkg" + +# From stdin: given a Windows path, GNU sha512sum escapes its backslashes and +# prefixes the hash with "\". +if command -v sha512sum >/dev/null; then + actual=$(sha512sum < "$package" | awk '{print $1}') +else + actual=$(shasum -a 512 < "$package" | awk '{print $1}') +fi +if [ "$actual" != "$VPK_SHA512" ]; then + echo "::error::vpk $VPK_VERSION package SHA-512 mismatch: expected $VPK_SHA512, got $actual" >&2 + exit 1 +fi + +# A NuGet config whose only source is the verified package. +cat > "$feed/nuget.config" < + + + + + + +CONFIG + +dotnet tool install vpk --version "$VPK_VERSION" --tool-path "$tools" --configfile "$feed/nuget.config" + +if command -v cygpath >/dev/null; then + tools=$(cygpath -w "$tools") +fi +echo "$tools" >> "${GITHUB_PATH:?}" diff --git a/scripts/release/macos-dmg.sh b/scripts/release/macos-dmg.sh new file mode 100755 index 00000000..a3772d0d --- /dev/null +++ b/scripts/release/macos-dmg.sh @@ -0,0 +1,132 @@ +#!/usr/bin/env bash +# Put PwrDisk.app in a drag-to-install DMG laid out like the Pwr family's: +# a 660x400 window over packaging/dmg/background.png, the app at (170,230), +# an Applications link at (500,230), 112 pt icons, the app icon as the volume +# icon, and a volume named "PwrDisk -". With an identity, also +# sign the DMG, notarize it through the notarytool keychain profile +# NOTARY_PROFILE in KEYCHAIN, and staple the ticket. +# +# release.yml's macOS sign job runs this from the signing input, where there +# is no checkout and no cargo, after `vpk pack` has signed and notarized the +# app. `cargo xtask bundle` builds the same layout for local and preview +# builds. +# +# dmg-layout.py writes the image's .DS_Store directly, using PwrSuiteLab's +# unattended packaging approach. No Finder AppleEvents or Automation grant +# is needed, and background aliases contain no build-host paths. +# +# usage: macos-dmg.sh APP DMG [IDENTITY] +# +# DMG_VERSION version in the volume name; defaults to the app's +# CFBundleShortVersionString +# DMG_BACKGROUND background PNG; defaults to background.png beside this +# script, then packaging/dmg/background.png in a checkout +# DMG_VOLUME_ICON volume icon; defaults to the app's own icon, the +# .icns its Info.plist names (CFBundleIconFile) +set -euo pipefail + +if [ $# -lt 2 ] || [ $# -gt 3 ]; then + echo "usage: macos-dmg.sh APP DMG [IDENTITY]" >&2 + exit 2 +fi +app=$1 +dmg=$2 +identity=${3:-} + +here=$(cd "$(dirname "$0")" && pwd) + +# $1 if set, else the first of the other arguments that is a file. +asset() { + local name=$1 explicit=$2 candidate + shift 2 + if [ -n "$explicit" ]; then + [ -f "$explicit" ] && { printf '%s\n' "$explicit"; return 0; } + echo "macos-dmg.sh: $explicit does not exist" >&2 + return 1 + fi + for candidate in "$@"; do + [ -f "$candidate" ] && { printf '%s\n' "$candidate"; return 0; } + done + echo "macos-dmg.sh: no $name beside the script, in the checkout or in the app" >&2 + return 1 +} +background=$(asset background.png "${DMG_BACKGROUND:-}" \ + "$here/background.png" "$here/../../packaging/dmg/background.png") +plist=$app/Contents/Info.plist +# `cargo xtask bundle` draws AppIcon.icns from the SVG; the app's own copy +# is the volume icon, so there is no second file to keep in step. +icon_name=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIconFile' "$plist") +volume_icon=$(asset "${icon_name%.icns}.icns" "${DMG_VOLUME_ICON:-}" \ + "$app/Contents/Resources/${icon_name%.icns}.icns") +version=${DMG_VERSION:-$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$plist")} +executable=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleExecutable' "$plist") +read -ra archs <<<"$(lipo -archs "$app/Contents/MacOS/$executable")" +if [[ " ${archs[*]} " == *" arm64 "* && " ${archs[*]} " == *" x86_64 "* ]]; then + arch=universal +else + arch=$(IFS=-; echo "${archs[*]}") +fi +volname="PwrDisk $version-$arch" + +work=$(mktemp -d) +device= +cleanup() { + if [ -n "$device" ]; then + hdiutil detach "$device" -quiet || hdiutil detach "$device" -force -quiet || true + fi + rm -rf "$work" +} +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM + +# A read-write image sized to the app plus headroom for the background, +# the volume icon, .DS_Store and HFS+ overhead. +app_mb=$(du -sm "$app" | awk '{print $1}') +size_mb=$((app_mb + app_mb / 5 + 20)) +rw=$work/PwrDisk-rw.dmg +# -type UDIF makes a read-write image (UDRW); -format applies only to +# -srcfolder images. +hdiutil create -size "${size_mb}m" -fs HFS+ -type UDIF -volname "$volname" "$rw" + +# Mount privately: concurrent packages with the same volume name cannot collide. +mkdir "$work/mount" +attach=$(hdiutil attach -readwrite -noverify -noautoopen -nobrowse -mountpoint "$work/mount" "$rw") +device=$(awk -F'\t' '/Apple_HFS/ {sub(/[[:space:]]+$/, "", $1); print $1; exit}' <<<"$attach") +mount=$work/mount +if [ -z "$device" ] || [ ! -d "$mount" ]; then + echo "macos-dmg.sh: cannot find the attached volume in hdiutil's output:" >&2 + echo "$attach" >&2 + exit 1 +fi + +ditto "$app" "$mount/PwrDisk.app" +ln -s /Applications "$mount/Applications" +mkdir "$mount/.background" +cp "$background" "$mount/.background/background.png" + +# Preserve the complete installer layout without a GUI or TCC prompt. +python3 "$here/dmg-layout.py" "$mount" "$volname" + +# Mark the volume's custom icon after writing its layout. +cp "$volume_icon" "$mount/.VolumeIcon.icns" +if command -v SetFile >/dev/null; then + SetFile -a C "$mount" +else + xattr -wx com.apple.FinderInfo \ + "0000000000000000040000000000000000000000000000000000000000000000" "$mount" +fi + +rm -rf "$mount/.fseventsd" "$mount/.Trashes" +sync +hdiutil detach "$device" -quiet || hdiutil detach "$device" -force -quiet +device= + +rm -f "$dmg" +hdiutil convert "$rw" -format UDZO -imagekey zlib-level=9 -o "$dmg" + +if [ -n "$identity" ]; then + codesign --force --timestamp --keychain "${KEYCHAIN:?}" --sign "$identity" "$dmg" + xcrun notarytool submit "$dmg" --keychain-profile "${NOTARY_PROFILE:?}" --keychain "$KEYCHAIN" --wait + xcrun stapler staple "$dmg" +fi diff --git a/scripts/release/macos-signing.py b/scripts/release/macos-signing.py new file mode 100644 index 00000000..35be8c52 --- /dev/null +++ b/scripts/release/macos-signing.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""Job-scoped keychain lifecycle, adapted from PwrAgnt release.mjs. + +The workflow supplies a private PWRDISK_SIGNING_TEMP_DIR and runs cleanup with +always(), including cancellation. Snapshot state before creating the keychain; +restore the exact search list (including paths with spaces) before deleting it. +Never change the default keychain for signing. No credentials or subprocess +arguments containing credentials are printed, including on command failure. +""" + +import base64 +import json +import os +from pathlib import Path +import re +import signal +import subprocess +import sys +import uuid + + +def run(*args): + result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + if result.returncode: + raise RuntimeError(f"{args[0]} {args[1]} failed (exit {result.returncode})") + return result.stdout + + +def keychains(output): + # security prints one quoted path per line. Do not split on whitespace. + return [line.strip().removeprefix('"').removesuffix('"') + for line in output.splitlines() if line.strip()] + + +def cleanup(directory): + state_file = directory / "keychain-state.json" + failures = [] + try: + if state_file.exists(): + state = json.loads(state_file.read_text()) + try: + run("security", "list-keychains", "-d", "user", "-s", *state["search"]) + except RuntimeError as error: + failures.append(str(error)) + try: + current = keychains(run("security", "default-keychain", "-d", "user")) + if current != state["default"]: + run("security", "default-keychain", "-d", "user", "-s", *state["default"]) + except RuntimeError as error: + failures.append(str(error)) + keychain = directory / "signing.keychain-db" + if keychain.exists(): + try: + run("security", "delete-keychain", str(keychain)) + except RuntimeError as error: + failures.append(str(error)) + if not failures: + state_file.unlink() + finally: + for name in ("cert.p12", "AuthKey.p8"): + (directory / name).unlink(missing_ok=True) + if failures: + raise RuntimeError("; ".join(failures)) + + +def prepare(directory): + os.umask(0o077) + state = { + "search": keychains(run("security", "list-keychains", "-d", "user")), + "default": keychains(run("security", "default-keychain", "-d", "user")), + } + (directory / "keychain-state.json").write_text(json.dumps(state)) + + # Actions first sends SIGINT, then SIGTERM when cancelling a running step. + # Cleanup here covers import failures and signals; always() retries cleanup + # after a cancelled/failed later packaging step on the persistent guest. + def interrupted(signum, _frame): + raise SystemExit(128 + signum) + + signal.signal(signal.SIGINT, interrupted) + signal.signal(signal.SIGTERM, interrupted) + try: + keychain = str(directory / "signing.keychain-db") + password = str(uuid.uuid4()) + certificate = directory / "cert.p12" + certificate.write_bytes(base64.b64decode(os.environ["CSC_LINK"])) + run("security", "create-keychain", "-p", password, keychain) + run("security", "set-keychain-settings", "-lut", "21600", keychain) + run("security", "unlock-keychain", "-p", password, keychain) + run("security", "import", str(certificate), "-k", keychain, + "-P", os.environ["CSC_KEY_PASSWORD"], "-T", "/usr/bin/codesign") + run("security", "set-key-partition-list", "-S", "apple-tool:,apple:,codesign:", + "-s", "-k", password, keychain) + run("security", "list-keychains", "-d", "user", "-s", keychain, *state["search"]) + certificate.unlink() + identities = run("security", "find-identity", "-v", "-p", "codesigning", keychain) + team = re.escape(os.environ["APPLE_TEAM_ID"]) + match = re.search(r'"(Developer ID Application: [^"\r\n]+\(' + team + r'\))"', identities) + if not match: + raise RuntimeError("No Developer ID Application identity for the expected team") + api_key = directory / "AuthKey.p8" + api_key.write_bytes(base64.b64decode(os.environ["APPLE_API_KEY_BASE64"])) + run("xcrun", "notarytool", "store-credentials", "pwrdisk-notary", "--key", str(api_key), + "--key-id", os.environ["APPLE_API_KEY_ID"], "--issuer", os.environ["APPLE_API_ISSUER"], + "--keychain", keychain) + api_key.unlink() + with open(os.environ["GITHUB_OUTPUT"], "a") as output: + output.write(f"path={keychain}\nidentity={match[1]}\n") + except BaseException: + cleanup(directory) + raise + + +def main(): + directory = Path(os.environ["PWRDISK_SIGNING_TEMP_DIR"]) + if sys.argv[1:] == ["prepare"]: + prepare(directory) + elif sys.argv[1:] == ["cleanup"]: + cleanup(directory) + else: + raise RuntimeError("usage: macos-signing.py prepare|cleanup") + + +if __name__ == "__main__": + try: + main() + except Exception as error: + # No traceback: CalledProcessError/arguments must never reveal secrets. + print(f"::error::Signing keychain operation failed: {error}", file=sys.stderr) + sys.exit(1) diff --git a/scripts/release/macos_packaging_test.py b/scripts/release/macos_packaging_test.py new file mode 100644 index 00000000..b8f462b8 --- /dev/null +++ b/scripts/release/macos_packaging_test.py @@ -0,0 +1,196 @@ +"""No live credentials or keychain operations: security and xcrun are mocked.""" + +import base64 +import importlib.util +import json +import os +from pathlib import Path +import plistlib +import signal +import struct +import tempfile +import unittest +from unittest.mock import patch + + +def load(name): + spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(name + ".py")) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +signing = load("macos-signing") +layout = load("dmg-layout") + + +class SigningTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.directory = Path(self.temp.name) + self.original = ["/Users/fixture/Library/Keychains/login.keychain-db", "/tmp/Keychain With Spaces.keychain-db"] + self.search = self.original[:] + self.default = [self.original[0]] + self.calls = [] + self.failure = None + self.cancel = None + self.addCleanup(signal.signal, signal.SIGINT, signal.getsignal(signal.SIGINT)) + self.addCleanup(signal.signal, signal.SIGTERM, signal.getsignal(signal.SIGTERM)) + self.env = patch.dict(os.environ, { + "CSC_LINK": base64.b64encode(b"fixture-certificate").decode(), + "CSC_KEY_PASSWORD": "fixture-password", + "APPLE_API_KEY_BASE64": base64.b64encode(b"fixture-api-key").decode(), + "APPLE_TEAM_ID": "FIXTURETEAM", "APPLE_API_KEY_ID": "fixture-id", + "APPLE_API_ISSUER": "fixture-issuer", "GITHUB_OUTPUT": str(self.directory / "output"), + }) + self.env.start() + self.addCleanup(self.env.stop) + + def command(self, *args): + self.calls.append(args) + if args[1] == self.failure: + raise RuntimeError("fixture command failed") + if args[1] == self.cancel: + self.cancel = None + signal.raise_signal(signal.SIGTERM) + if args[1] == "create-keychain": + Path(args[-1]).touch() + if args[1] == "delete-keychain": + Path(args[-1]).unlink() + if args[1] in ("list-keychains", "default-keychain"): + attr = "search" if args[1] == "list-keychains" else "default" + if "-s" in args: + setattr(self, attr, list(args[args.index("-s") + 1:])) + return "\n".join(f' "{name}"' for name in getattr(self, attr)) + if args[1] in ("import", "notarytool"): + filename = "cert.p12" if args[1] == "import" else "AuthKey.p8" + self.assertEqual((self.directory / filename).stat().st_mode & 0o777, 0o600) + if args[1] == "find-identity": + return '1) FIXTURE "Developer ID Application: Fixture (FIXTURETEAM)"' + return "" + + def assert_clean(self): + self.assertEqual(self.search, self.original) + for name in ("cert.p12", "AuthKey.p8", "signing.keychain-db", "keychain-state.json"): + self.assertFalse((self.directory / name).exists(), name) + for call in self.calls: + if call[1] == "delete-keychain": + self.assertEqual(call[2], str(self.directory / "signing.keychain-db")) + + def test_success_restores_exact_search_list_and_preserves_default(self): + with patch.object(signing, "run", self.command): + signing.prepare(self.directory) + self.assertEqual(self.search[1:], self.original) + self.assertFalse((self.directory / "cert.p12").exists()) + signing.cleanup(self.directory) + signing.cleanup(self.directory) # workflow retry is idempotent + self.assert_clean() + self.assertFalse(any(call[1] == "default-keychain" and "-s" in call for call in self.calls)) + + def test_partial_import_failure_and_cancellation_clean_up(self): + for operation in ("create-keychain", "unlock-keychain", "import", "set-key-partition-list", "find-identity", "notarytool"): + with self.subTest(operation=operation): + self.failure = operation + with patch.object(signing, "run", self.command), self.assertRaises(RuntimeError): + signing.prepare(self.directory) + self.assert_clean() + self.failure = None + self.cancel = "notarytool" + with patch.object(signing, "run", self.command), self.assertRaises(SystemExit) as caught: + signing.prepare(self.directory) + self.assertEqual(caught.exception.code, 128 + signal.SIGTERM) + self.assert_clean() + + def test_later_packaging_failure_still_restores_default_and_search(self): + with patch.object(signing, "run", self.command): + signing.prepare(self.directory) + self.default = [str(self.directory / "signing.keychain-db")] + signing.cleanup(self.directory) # always() after a failed/cancelled pack step + self.assertEqual(self.default, [self.original[0]]) + self.assert_clean() + + def test_restore_failure_still_deletes_keychain_and_decoded_files(self): + with patch.object(signing, "run", self.command): + signing.prepare(self.directory) + (self.directory / "AuthKey.p8").write_text("fixture") + self.failure = "list-keychains" + with self.assertRaises(RuntimeError): + signing.cleanup(self.directory) + self.assertFalse((self.directory / "signing.keychain-db").exists()) + self.assertFalse((self.directory / "AuthKey.p8").exists()) + self.failure = None + signing.cleanup(self.directory) + self.assert_clean() + + def test_command_failure_does_not_print_password_or_subprocess_output(self): + with patch.object(signing.subprocess, "run") as run: + run.return_value.returncode = 1 + run.return_value.stderr = "fixture-secret" + with self.assertRaisesRegex(RuntimeError, r"^security import failed \(exit 1\)$"): + signing.run("security", "import", "-P", "fixture-secret") + + +class LayoutTests(unittest.TestCase): + def test_layout_records_round_trip_and_alias_has_no_staging_paths(self): + # Independent decoder of the leaf node, including the plist values. + alias = b"fixture-volume-relative-alias" + with tempfile.TemporaryDirectory() as directory: + volume = Path(directory) + (volume / "PwrDisk.app").mkdir() + (volume / "Applications").symlink_to("/Applications") + with patch.object(layout.sys, "argv", ["dmg-layout.py", directory, "PwrDisk Fixture"]), \ + patch.object(layout, "background_alias", return_value=alias): + layout.main() + data = (volume / ".DS_Store").read_bytes() + self.assertEqual(data[4:8], b"Bud1") + # Follow the allocator table to DSDB, then the root leaf. + allocator = struct.unpack_from(">I", data, 8)[0] + 4 + addresses = struct.unpack_from(">III", data, allocator + 8) + tree = (addresses[1] & ~31) + 4 + root, levels, count, nodes, page_size = struct.unpack_from(">IIIII", data, tree) + offset = (addresses[root] & ~31) + 4 + self.assertEqual((levels, count, nodes, page_size), (0, 6, 1, 4096)) + self.assertEqual(struct.unpack_from(">II", data, offset), (0, 6)) + offset += 8 + decoded = {} + types = {} + for _ in range(count): + chars = struct.unpack_from(">I", data, offset)[0] + offset += 4 + name = data[offset:offset + 2 * chars].decode("utf-16-be") + offset += chars * 2 + kind, value_type = struct.unpack_from(">4s4s", data, offset) + offset += 8 + types[(name, kind)] = value_type + if value_type == b"blob": + length = struct.unpack_from(">I", data, offset)[0] + offset += 4 + decoded[(name, kind)] = data[offset:offset + length] + offset += length + elif value_type == b"type": + decoded[(name, kind)] = data[offset:offset + 4] + offset += 4 + elif value_type == b"long": + decoded[(name, kind)] = struct.unpack_from(">I", data, offset)[0] + offset += 4 + else: + self.fail(f"Unexpected record type: {value_type}") + self.assertEqual(types[(".", b"vstl")], b"type") + self.assertEqual(decoded[(".", b"vstl")], b"icnv") + self.assertEqual(plistlib.loads(decoded[(".", b"bwsp")])["WindowBounds"], "{{200, 120}, {660, 400}}") + options = plistlib.loads(decoded[(".", b"icvp")]) + self.assertEqual(options["backgroundImageAlias"], alias) + self.assertEqual((options["backgroundType"], options["iconSize"]), (2, 112)) + for name, xy in (("PwrDisk.app", (170, 230)), ("Applications", (500, 230))): + self.assertEqual(struct.unpack_from(">II", decoded[(name, b"Iloc")]), xy) + fake_stat = type("Stat", (), {"st_ino": 123, "st_birthtime": 1000})() + with patch.object(layout.os, "stat", return_value=fake_stat): + alias = layout.background_alias("/Users/private/staging/mount", "PwrDisk 1.2.3-universal", layout.BACKGROUND) + self.assertNotIn(b"/Users/", alias) + self.assertIn(b"/Volumes/PwrDisk 1.2.3-universal", alias) + self.assertIn(b"/.background/background.png", alias) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/release/upload-azure-signing-from-1password.sh b/scripts/release/upload-azure-signing-from-1password.sh new file mode 100755 index 00000000..b5507883 --- /dev/null +++ b/scripts/release/upload-azure-signing-from-1password.sh @@ -0,0 +1,193 @@ +#!/usr/bin/env bash +set -euo pipefail +set +x + +repo="${GITHUB_REPOSITORY:-pwrdrvr/PwrDisk}" +environment="${GITHUB_ENVIRONMENT:-windows-signing}" +vault_name="${OP_VAULT_NAME:-PwrDrvr LLC}" +item_title="${OP_ITEM_TITLE:-PwrDisk - Windows Azure Trusted Signing}" + +# Read by release.yml's windows-sign job as vars.* (not secret). +variable_fields=( + WIN_AZURE_SIGN_PUBLISHER_NAME + WIN_AZURE_SIGN_ENDPOINT + WIN_AZURE_SIGN_ACCOUNT + WIN_AZURE_SIGN_PROFILE +) +# Read as secrets.*; the Artifact Signing dlib takes the service principal +# from these. +secret_fields=( + AZURE_TENANT_ID + AZURE_CLIENT_ID + AZURE_CLIENT_SECRET +) + +usage() { + cat >&2 <<'EOF' +Uploads PwrDisk Windows (Azure Artifact Signing) settings from 1Password to +the GitHub windows-signing environment: four environment variables and three +environment secrets. + +Usage: + scripts/release/upload-azure-signing-from-1password.sh + scripts/release/upload-azure-signing-from-1password.sh --list-accounts + +Required: + OP_ACCOUNT=<1Password account identifier> + +Use the USER ID from `op account list` when the URL or email appears more than +once. The URL is ambiguous on machines with multiple accounts on the same +1Password domain. + +The item needs one field per name, labeled exactly: + WIN_AZURE_SIGN_PUBLISHER_NAME, WIN_AZURE_SIGN_ENDPOINT, + WIN_AZURE_SIGN_ACCOUNT, WIN_AZURE_SIGN_PROFILE, + AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET + +Optional overrides: + GITHUB_REPOSITORY=pwrdrvr/PwrDisk + GITHUB_ENVIRONMENT=windows-signing + OP_VAULT_NAME="PwrDrvr LLC" + OP_ITEM_TITLE="PwrDisk - Windows Azure Trusted Signing" + +Example: + OP_ACCOUNT= scripts/release/upload-azure-signing-from-1password.sh +EOF +} + +print_accounts() { + local accounts_json + if ! accounts_json="$(op account list --format json 2>/dev/null)"; then + echo "Could not list configured 1Password accounts." >&2 + return 1 + fi + + if ! jq -e 'length > 0' <<<"$accounts_json" >/dev/null; then + echo "No configured 1Password accounts found." >&2 + return 1 + fi + + cat >&2 <<'EOF' +Configured 1Password accounts: + +NAME URL EMAIL USER ID +EOF + + while IFS=$'\t' read -r user_uuid url email; do + local account_json + local name + if account_json="$(op account get --account "$user_uuid" --format json 2>/dev/null)"; then + name="$(jq -r '.name // "(name unavailable)"' <<<"$account_json")" + else + name="(name unavailable)" + fi + printf '%s\t%s\t%s\t%s\n' "$name" "$url" "$email" "$user_uuid" >&2 + done < <(jq -r '.[] | [.user_uuid, .url, .email] | @tsv' <<<"$accounts_json") + + cat >&2 <<'EOF' + +Use the USER ID for the account that contains the configured vault. +Run again with: + OP_ACCOUNT= ./scripts/release/upload-azure-signing-from-1password.sh +EOF +} + +require_command() { + local command_name="$1" + if ! command -v "$command_name" >/dev/null 2>&1; then + echo "Missing required command: $command_name" >&2 + exit 127 + fi +} + +if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then + usage + exit 0 +fi + +if [[ "${1:-}" == "--list-accounts" ]]; then + require_command op + require_command jq + print_accounts + exit 0 +fi + +require_command jq +require_command op + +if [[ -z "${OP_ACCOUNT:-}" ]]; then + cat >&2 <<'EOF' +Set OP_ACCOUNT to the 1Password account identifier first. + +Use the USER ID column when the URL or email appears more than once. +EOF + print_accounts + exit 2 +fi + +require_command gh + +vault_id="$( + op vault list --account "$OP_ACCOUNT" --format json \ + | jq -r --arg name "$vault_name" 'first(.[] | select(.name == $name) | .id) // empty' +)" +if [[ -z "$vault_id" ]]; then + echo "Could not find vault '$vault_name' in 1Password account '$OP_ACCOUNT'." >&2 + exit 1 +fi + +item_id="$( + op item list --account "$OP_ACCOUNT" --vault "$vault_id" --format json \ + | jq -r --arg title "$item_title" 'first(.[] | select(.title == $title) | .id) // empty' +)" +if [[ -z "$item_id" ]]; then + echo "Could not find item '$item_title' in vault '$vault_name'." >&2 + exit 1 +fi + +item_json="$(op item get "$item_id" --account "$OP_ACCOUNT" --vault "$vault_id" --reveal --format json)" + +# Fields are matched by label anywhere in the item, sections included. +read_field() { + local field_name="$1" + local value + value="$( + jq -r --arg label "$field_name" \ + 'first(.fields[]? | select(.label == $label) | .value // empty) // empty' <<<"$item_json" + )" + if [[ -z "$value" ]]; then + echo "Field '$field_name' is missing or empty on item '$item_title'." >&2 + return 1 + fi + printf "%s" "$value" +} + +# Read everything before uploading anything, so a missing field leaves the +# environment as it was. +# Indexed arrays only: macOS ships bash 3.2, which has no associative arrays. +variable_values=() +for field in "${variable_fields[@]}"; do + if ! value="$(read_field "$field")"; then + exit 1 + fi + variable_values+=("$value") +done +secret_values=() +for field in "${secret_fields[@]}"; do + if ! value="$(read_field "$field")"; then + exit 1 + fi + secret_values+=("$value") +done + +for i in "${!variable_fields[@]}"; do + gh variable set "${variable_fields[$i]}" --repo "$repo" --env "$environment" --body "${variable_values[$i]}" + echo "Set variable ${variable_fields[$i]}=${variable_values[$i]} on $repo environment '$environment'." +done + +for i in "${!secret_fields[@]}"; do + printf "%s" "${secret_values[$i]}" | gh secret set "${secret_fields[$i]}" --repo "$repo" --env "$environment" + echo "Uploaded secret ${secret_fields[$i]} to $repo environment '$environment'." +done + +echo "Uploaded all Windows signing settings from 1Password item '$item_title'." diff --git a/scripts/release/upload-csc-link-from-1password.sh b/scripts/release/upload-csc-link-from-1password.sh new file mode 100755 index 00000000..32ecfefa --- /dev/null +++ b/scripts/release/upload-csc-link-from-1password.sh @@ -0,0 +1,214 @@ +#!/usr/bin/env bash +set -euo pipefail +set +x + +repo="${GITHUB_REPOSITORY:-pwrdrvr/PwrDisk}" +environment="${GITHUB_ENVIRONMENT:-apple-signing}" +vault_name="${OP_VAULT_NAME:-PwrDrvr LLC}" +item_title="${OP_ITEM_TITLE:-Apple Signing - PwrDrvr}" +p12_attachment_name="${OP_P12_ATTACHMENT_NAME:-${OP_ATTACHMENT_NAME:-PwrDrvr_DevID_Application.p12}}" +p8_attachment_name="${OP_P8_ATTACHMENT_NAME:-}" + +usage() { + cat >&2 <<'EOF' +Uploads PwrDisk Apple signing secrets from 1Password to the GitHub +apple-signing environment. + +Usage: + scripts/release/upload-csc-link-from-1password.sh + scripts/release/upload-csc-link-from-1password.sh --list-accounts + +Required: + OP_ACCOUNT=<1Password account identifier> + +Use the USER ID from `op account list` when the URL or email appears more than +once. The URL is ambiguous on machines with multiple accounts on the same +1Password domain. + +Optional overrides: + GITHUB_REPOSITORY=pwrdrvr/PwrDisk + GITHUB_ENVIRONMENT=apple-signing + OP_VAULT_NAME="PwrDrvr LLC" + OP_ITEM_TITLE="Apple Signing - PwrDrvr" + OP_P12_ATTACHMENT_NAME=PwrDrvr_DevID_Application.p12 + OP_P8_ATTACHMENT_NAME=AuthKey_XXXXXXXXXX.p8 + +Example: + OP_ACCOUNT= scripts/release/upload-csc-link-from-1password.sh +EOF +} + +print_accounts() { + local accounts_json + if ! accounts_json="$(op account list --format json 2>/dev/null)"; then + echo "Could not list configured 1Password accounts." >&2 + return 1 + fi + + if ! jq -e 'length > 0' <<<"$accounts_json" >/dev/null; then + echo "No configured 1Password accounts found." >&2 + return 1 + fi + + cat >&2 <<'EOF' +Configured 1Password accounts: + +NAME URL EMAIL USER ID +EOF + + while IFS=$'\t' read -r user_uuid url email; do + local account_json + local name + if account_json="$(op account get --account "$user_uuid" --format json 2>/dev/null)"; then + name="$(jq -r '.name // "(name unavailable)"' <<<"$account_json")" + else + name="(name unavailable)" + fi + printf '%s\t%s\t%s\t%s\n' "$name" "$url" "$email" "$user_uuid" >&2 + done < <(jq -r '.[] | [.user_uuid, .url, .email] | @tsv' <<<"$accounts_json") + + cat >&2 <<'EOF' + +Use the USER ID for the account that contains the configured vault. +Run again with: + OP_ACCOUNT= ./scripts/release/upload-csc-link-from-1password.sh +EOF +} + +require_command() { + local command_name="$1" + if ! command -v "$command_name" >/dev/null 2>&1; then + echo "Missing required command: $command_name" >&2 + exit 127 + fi +} + +if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then + usage + exit 0 +fi + +if [[ "${1:-}" == "--list-accounts" ]]; then + require_command op + require_command jq + print_accounts + exit 0 +fi + +require_command jq +require_command op + +if [[ -z "${OP_ACCOUNT:-}" ]]; then + cat >&2 <<'EOF' +Set OP_ACCOUNT to the 1Password account identifier first. + +Use the USER ID column when the URL or email appears more than once. +EOF + print_accounts + exit 2 +fi + +require_command gh +require_command base64 + +vault_id="$( + op vault list --account "$OP_ACCOUNT" --format json \ + | jq -r --arg name "$vault_name" 'first(.[] | select(.name == $name) | .id) // empty' +)" +if [[ -z "$vault_id" ]]; then + echo "Could not find vault '$vault_name' in 1Password account '$OP_ACCOUNT'." >&2 + exit 1 +fi + +item_id="$( + op item list --account "$OP_ACCOUNT" --vault "$vault_id" --format json \ + | jq -r --arg title "$item_title" 'first(.[] | select(.title == $title) | .id) // empty' +)" +if [[ -z "$item_id" ]]; then + echo "Could not find item '$item_title' in vault '$vault_name'." >&2 + exit 1 +fi + +item_json="$(op item get "$item_id" --account "$OP_ACCOUNT" --vault "$vault_id" --format json)" + +if ! jq -e --arg name "$p12_attachment_name" '.files[]? | select(.name == $name)' <<<"$item_json" >/dev/null; then + echo "Could not find attachment '$p12_attachment_name' on item '$item_title'." >&2 + exit 1 +fi + +if [[ -z "$p8_attachment_name" ]]; then + p8_attachment_name="$( + jq -r 'first(.files[]?.name | select(test("^AuthKey_[A-Za-z0-9]+\\.p8$"))) // empty' <<<"$item_json" + )" +fi +if [[ -z "$p8_attachment_name" ]]; then + echo "Could not find an AuthKey_*.p8 attachment on item '$item_title'." >&2 + echo "Set OP_P8_ATTACHMENT_NAME if the attachment has a different name." >&2 + exit 1 +fi +if ! jq -e --arg name "$p8_attachment_name" '.files[]? | select(.name == $name)' <<<"$item_json" >/dev/null; then + echo "Could not find attachment '$p8_attachment_name' on item '$item_title'." >&2 + exit 1 +fi + +tmpdir="$(mktemp -d)" +cleanup() { + rm -rf "$tmpdir" +} +trap cleanup EXIT + +read_field() { + local field_name="$1" + local value + if ! value="$(op read --account "$OP_ACCOUNT" "op://$vault_id/$item_id/$field_name")"; then + echo "Could not read field '$field_name' on item '$item_title'." >&2 + return 1 + fi + if [[ -z "$value" ]]; then + echo "Field '$field_name' is empty on item '$item_title'." >&2 + return 1 + fi + printf "%s" "$value" +} + +set_secret_from_value() { + local secret_name="$1" + local value="$2" + if [[ -z "$value" ]]; then + echo "Refusing to upload empty value for $secret_name." >&2 + exit 1 + fi + printf "%s" "$value" | gh secret set "$secret_name" --repo "$repo" --env "$environment" + echo "Uploaded $secret_name to $repo environment '$environment'." +} + +set_secret_from_attachment_base64() { + local secret_name="$1" + local attachment_name="$2" + local output_path="$tmpdir/$attachment_name" + op read --account "$OP_ACCOUNT" --out-file "$output_path" "op://$vault_id/$item_id/$attachment_name" >/dev/null + if [[ ! -s "$output_path" ]]; then + echo "Attachment '$attachment_name' downloaded as an empty file." >&2 + exit 1 + fi + base64 < "$output_path" | tr -d '\n' | gh secret set "$secret_name" --repo "$repo" --env "$environment" + echo "Uploaded $secret_name from $attachment_name to $repo environment '$environment'." +} + +if ! csc_key_password="$(read_field CSC_KEY_PASSWORD)"; then + exit 1 +fi +if ! apple_api_key_id="$(read_field APPLE_API_KEY_ID)"; then + exit 1 +fi +if ! apple_api_issuer="$(read_field APPLE_API_ISSUER)"; then + exit 1 +fi + +set_secret_from_attachment_base64 CSC_LINK "$p12_attachment_name" +set_secret_from_value CSC_KEY_PASSWORD "$csc_key_password" +set_secret_from_attachment_base64 APPLE_API_KEY_BASE64 "$p8_attachment_name" +set_secret_from_value APPLE_API_KEY_ID "$apple_api_key_id" +set_secret_from_value APPLE_API_ISSUER "$apple_api_issuer" + +echo "Uploaded all Apple signing secrets from 1Password item '$item_title'." diff --git a/scripts/release/velopack-notices.sh b/scripts/release/velopack-notices.sh new file mode 100755 index 00000000..1eeb095a --- /dev/null +++ b/scripts/release/velopack-notices.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# Write licenses/velopack.txt: the license notices for the Rust crates +# compiled into Velopack's native binaries, which `vpk pack` adds to our +# release packages (Update.exe, Setup.exe, the launcher stub and the MSI's +# velopack_wix DLL on Windows x64 and ARM64; UpdateMac on macOS). +# +# Those binaries are built from velopack/velopack's own Cargo.lock, not ours, +# so cargo-about cannot see them from this workspace. This clones Velopack at +# the vpk version pinned in install-vpk.sh, trims its workspace to the crates +# behind those binaries (src/bins, src/wix-dll and their path dependencies), +# and runs cargo-about there with licenses/about.toml and velopack.hbs. +# Trimming only drops lockfile entries; the script fails if any version moves. +# +# Rerun it whenever VPK_VERSION changes. Check the license ids it prints +# against licenses/about.toml: a new id is a legal decision. +# +# Needs git, cargo, cargo-about and perl. +# +# usage: scripts/release/velopack-notices.sh +set -euo pipefail + +repo=$(cd "$(dirname "$0")/../.." && pwd) +version=$(sed -n 's/^VPK_VERSION=//p' "$repo/scripts/release/install-vpk.sh") +[ -n "$version" ] || { echo "no VPK_VERSION in install-vpk.sh" >&2; exit 1; } + +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +git -c advice.detachedHead=false clone -q --depth 1 --branch "$version" \ + https://github.com/velopack/velopack.git "$work/velopack" +cd "$work/velopack" + +perl -0pi -e 's/members = \[.*?\]/members = ["src\/bins", "src\/l18n", "src\/lib-rust", "src\/wix-dll"]/s; s/exclude = \[.*?\]\n//s' Cargo.toml +# The workspace crates have no license file of their own; give each the +# repository's, so cargo-about quotes it rather than a blank MIT template. +for dir in src/bins src/l18n src/lib-rust src/wix-dll; do + cp LICENSE "$dir/LICENSE" +done + +packages() { awk '/^name = /{n=$3} /^version = /{print n, $3}' Cargo.lock | sort -u; } +packages > "$work/upstream.txt" +cargo metadata --format-version 1 >/dev/null +packages > "$work/trimmed.txt" +if [ -n "$(comm -13 "$work/upstream.txt" "$work/trimmed.txt")" ]; then + echo "trimming the workspace changed Cargo.lock versions:" >&2 + comm -13 "$work/upstream.txt" "$work/trimmed.txt" >&2 + exit 1 +fi + +cargo about generate -c "$repo/licenses/about.toml" "$repo/licenses/velopack.hbs" \ + --target x86_64-pc-windows-msvc --target aarch64-pc-windows-msvc \ + --target aarch64-apple-darwin --target x86_64-apple-darwin \ + --workspace --locked --fail -o "$work/crates.txt" + +{ + cat <
"$repo/licenses/velopack.txt" + +echo "wrote licenses/velopack.txt; license ids in use:" +sed -n '/^License Texts/,$p' "$repo/licenses/velopack.txt" \ + | awk '/^-{20,}$/ && prev ~ /\)$/ { sub(/.*\(/, "", prev); sub(/\)$/, "", prev); print " " prev } { prev = $0 }' \ + | sort -u diff --git a/scripts/release/vpk-pack-windows.ps1 b/scripts/release/vpk-pack-windows.ps1 new file mode 100644 index 00000000..7895c4bb --- /dev/null +++ b/scripts/release/vpk-pack-windows.ps1 @@ -0,0 +1,56 @@ +# Pack PwrDisk for Windows with vpk: Setup.exe, a per-user MSI, the +# portable zip and the update feed, for one architecture. release.yml's +# windows-sign job runs it from the signing input (with release notes and +# Azure signing); preview-build.yml runs it from the checkout (unsigned). +# One script, so the preview packs what the release packs. +# +# - -Arch x64 | arm64: vpk's --runtime (win-x64, win-arm64). Without it vpk +# defaults to x86 Setup.exe and Update.exe. +# - --channel: x64 keeps Velopack's default `win`, so its asset names +# (PwrDisk-win-Setup.exe, releases.win.json) match the rest of the Pwr +# family; arm64 is `win-arm64`, a feed of its own, so an install never +# updates to the other architecture's build. +# - --instLocation PerUser: PwrDisk installs per user, like the rest of the +# family, and needs no elevation to install or update. vpk's default +# dual-scope MSI preselects per-machine in its dialog. +# - --azureTrustedSignFile: vpk signs pwrdisk.exe, Update.exe and the stub, +# then Setup.exe and the MSI, through Azure Artifact Signing; the dlib reads +# the service principal from AZURE_TENANT_ID / AZURE_CLIENT_ID / +# AZURE_CLIENT_SECRET. +# - --icon: assets/disktree.ico, the icon pwrdisk.exe embeds, for Setup.exe, +# the MSI and the Start menu shortcut. +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)] [string]$Version, + [Parameter(Mandatory = $true)] [ValidateSet("x64", "arm64")] [string]$Arch, + [Parameter(Mandatory = $true)] [string]$PackDir, + [Parameter(Mandatory = $true)] [string]$OutputDir, + [Parameter(Mandatory = $true)] [string]$Icon, + [string]$ReleaseNotes, + [string]$AzureSignFile +) + +$ErrorActionPreference = "Stop" + +$channel = if ($Arch -eq "x64") { "win" } else { "win-$Arch" } + +$vpkArgs = @( + "--skip-updates", "pack", + "--packId", "PwrDisk", + "--packVersion", $Version, + "--runtime", "win-$Arch", + "--channel", $channel, + "--packDir", $PackDir, + "--mainExe", "pwrdisk.exe", + "--packTitle", "PwrDisk", + "--packAuthors", "PwrDrvr LLC", + "--shortcuts", "StartMenuRoot", + "--icon", $Icon, + "--msi", "--instLocation", "PerUser", + "--outputDir", $OutputDir +) +if ($ReleaseNotes) { $vpkArgs += @("--releaseNotes", $ReleaseNotes) } +if ($AzureSignFile) { $vpkArgs += @("--azureTrustedSignFile", $AzureSignFile) } + +& vpk @vpkArgs +if ($LASTEXITCODE -ne 0) { throw "vpk pack failed (exit code $LASTEXITCODE)." } diff --git a/scripts/sandboxer/transfer.py b/scripts/sandboxer/transfer.py new file mode 100755 index 00000000..a1e4717d --- /dev/null +++ b/scripts/sandboxer/transfer.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Moves files between this machine and a Sandboxer sandbox. + +Runs in the sandbox. Serves one directory over HTTP: PUT / stores a +file, GET / returns one. The Sandboxer MCP's host_port puts it behind +an HTTPS URL that carries an access token, so the laptop can `curl` a git +bundle in and a log or artifact out without either +passing through the agent's context. The procedure is in +docs/sandboxer.md. + + python3 transfer.py [DIR] [PORT] default ~/pwrdisk/files, 8722 +""" + +import http.server +import os +import re +import sys +import tempfile + +ROOT = os.path.realpath( + sys.argv[1] if len(sys.argv) > 1 + else os.path.expanduser("~/pwrdisk/files") +) +PORT = int(sys.argv[2]) if len(sys.argv) > 2 else 8722 + + +def target(path): + """The file a request names, or None for anything outside ROOT.""" + name = path.split("?", 1)[0].removeprefix("/") + if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9._-]*", name): + return None + result = os.path.join(ROOT, name) + return None if os.path.islink(result) else result + + +class Handler(http.server.BaseHTTPRequestHandler): + def do_PUT(self): + path = target(self.path) + try: + length = int(self.headers.get("Content-Length", "-1")) + except ValueError: + self.send_error(400) + return + if path is None or length < 0: + self.send_error(400) + return + # A file of its own per request, so overlapping uploads never mix. + fd, partial = tempfile.mkstemp(dir=ROOT, prefix=".partial-") + with os.fdopen(fd, "wb") as out: + remaining = length + while remaining > 0: + chunk = self.rfile.read(min(remaining, 1 << 20)) + if not chunk: + break + out.write(chunk) + remaining -= len(chunk) + if remaining: + os.remove(partial) + self.send_error(400, "short body") + return + os.replace(partial, path) + self.send_response(201) + self.send_header("Content-Length", "0") + self.end_headers() + + def do_GET(self): + path = target(self.path) + if path is None or not os.path.isfile(path): + self.send_error(404) + return + self.send_response(200) + self.send_header("Content-Length", str(os.path.getsize(path))) + self.end_headers() + with open(path, "rb") as src: + while chunk := src.read(1 << 20): + self.wfile.write(chunk) + + def log_message(self, format, *args): + # The proxy token can occur in the query. Keep it out of logs. + pass + + +os.makedirs(ROOT, exist_ok=True) +http.server.ThreadingHTTPServer(("0.0.0.0", PORT), Handler).serve_forever() diff --git a/scripts/sandboxer/transfer.sh b/scripts/sandboxer/transfer.sh new file mode 100755 index 00000000..31a31315 --- /dev/null +++ b/scripts/sandboxer/transfer.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# Runs on the laptop. Talks to scripts/sandboxer/transfer.py in a Sandboxer +# sandbox through the URL the MCP's host_port returned +# (https://?_token=). The procedure is in +# docs/sandboxer.md. +# +# scripts/sandboxer/transfer.sh send URL bundle HEAD, upload it as .bundle, +# print the sha +# scripts/sandboxer/transfer.sh get URL NAME DEST +# download ~/pwrdisk/files/NAME +# +# Git bundles include unpublished commits without a GitHub token. +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$repo_root" + +usage() { + sed -n '2,13p' "$0" >&2 + exit 2 +} + +# https://host?_token=t + name -> https://host/name?_token=t +file_url() { + local base="${1%%\?*}" query="" + [[ "$1" == *\?* ]] && query="?${1#*\?}" + printf '%s/%s%s' "${base%/}" "$2" "$query" +} + +case "${1:-}" in + send) + [[ $# -eq 2 ]] || usage + if [[ -n "$(git status --porcelain)" ]]; then + echo "uncommitted changes: the sandbox verifies HEAD, not the working tree" >&2 + exit 1 + fi + sha="$(git rev-parse HEAD)" + mkdir -p .local/sandboxer + bundle=".local/sandboxer/$sha.bundle" + trap 'rm -f "$bundle"' EXIT + git bundle create -q "$bundle" HEAD + code="$(curl -fsS --retry 3 -o /dev/null -w '%{http_code}' -T "$bundle" "$(file_url "$2" "$sha.bundle")")" + if [[ "$code" != 201 ]]; then + echo "upload answered HTTP $code, not 201" >&2 + exit 1 + fi + echo "$sha" + ;; + get) + [[ $# -eq 4 ]] || usage + [[ "$3" =~ ^[a-zA-Z0-9][a-zA-Z0-9._-]*$ ]] || usage + tmp="$(mktemp "$4.partial.XXXXXX")" + trap 'rm -f "$tmp"' EXIT + # The proxy answers a GET carrying _token with a redirect that sets an + # auth cookie: follow it with the cookie engine on, holding nothing on disk. + if ! curl -fsSL -b /dev/null --retry 3 -o "$tmp" "$(file_url "$2" "$3")"; then + rm -f "$tmp" + exit 1 + fi + mv "$tmp" "$4" + ;; + *) usage ;; +esac diff --git a/scripts/sandboxer/verify.sh b/scripts/sandboxer/verify.sh new file mode 100755 index 00000000..e4c1992d --- /dev/null +++ b/scripts/sandboxer/verify.sh @@ -0,0 +1,110 @@ +#!/usr/bin/env bash +# Run PwrDisk's Linux checks in a Sandboxer VM. See docs/sandboxer.md. +set -uo pipefail + +usage() { + echo "usage: $0 {setup|lint|test [cargo test args]|build|e2e|all}" >&2 +} + +step="${1:-}" +(( $# )) && shift +case "$step" in + setup|lint|build|e2e|all) (( $# == 0 )) || { usage; exit 2; } ;; + test) ;; + *) usage; exit 2 ;; +esac +if [[ "$(uname -s)" != Linux ]]; then + echo "run this script in the Linux sandbox; see docs/sandboxer.md" >&2 + exit 2 +fi + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$repo_root" || exit 1 +out_dir="$repo_root/.local/sandboxer" +mkdir -p "$out_dir" +# The checkout, target directory and status file belong to one run. +exec 9> "$out_dir/lock" +if ! flock -n 9; then + echo "another verification run holds $out_dir/lock" >&2 + exit 3 +fi +if [[ -n "$(git status --porcelain)" ]]; then + echo "uncommitted changes: commit before remote verification" >&2 + exit 2 +fi +export PATH="$HOME/.cargo/bin:$HOME/.bun/bin:$PATH" +export CARGO_TERM_COLOR=never +# Keep the VM's cache smaller. These profiles differ from a local build. +export CARGO_PROFILE_DEV_DEBUG=0 CARGO_PROFILE_TEST_DEBUG=0 +unset GH_TOKEN GITHUB_TOKEN DISKTREE_PROFILE_ROOT + +setup() { + # GPUI libraries match .github/workflows/ci.yml. SSH checks need Bun, + # OpenSSH and both static scanner targets used by xtask portable. + local packages=( + build-essential pkg-config curl ca-certificates git python3 unzip + util-linux openssh-client openssh-server + libxkbcommon-dev libxkbcommon-x11-dev libwayland-dev libx11-xcb-dev + libxcb1-dev libfontconfig-dev libfreetype-dev libvulkan-dev + libasound2-dev libssl-dev libzstd-dev + ) + if ! dpkg -s "${packages[@]}" > /dev/null 2>&1; then + sudo env DEBIAN_FRONTEND=noninteractive apt-get update -qq || return 1 + sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq \ + --no-install-recommends "${packages[@]}" || return 1 + fi + if ! command -v rustup > /dev/null; then + curl -fsSL https://sh.rustup.rs | sh -s -- \ + -y --profile minimal --default-toolchain none || return 1 + fi + # Read the channel and components from this commit's rust-toolchain.toml. + rustup toolchain install || return 1 + rustup target add x86_64-unknown-linux-musl \ + aarch64-unknown-linux-musl || return 1 + if ! command -v bun > /dev/null; then + curl -fsSL https://bun.sh/install | bash || return 1 + fi + # Ubuntu's sshd requires this directory even for the unprivileged test. + sudo install -d -m 0755 /run/sshd || return 1 + cargo -V && rustc -V && bun -v && cargo fetch --locked +} + +run_step() { + local name="$1" start code + shift + start="$(date +%s)" + case "$name" in + setup) setup ;; + lint) cargo xtask lint ;; + test) + if (( $# )); then + cargo test --locked "$@" + else + cargo xtask test + fi + ;; + build) cargo xtask portable ;; + e2e) bun scripts/test-ssh.ts ;; + esac > "$out_dir/$name.log" 2>&1 + code=$? + echo "$name exit=$code secs=$(($(date +%s) - start))" \ + | tee -a "$out_dir/status" + return "$code" +} + +# Tie every status file to its source. Never check out while this runs. +git rev-parse HEAD > "$out_dir/status" || exit 1 +if [[ "$step" == all ]]; then + failed=0 + if run_step setup; then + run_step lint || failed=1 + run_step test || failed=1 + run_step build || failed=1 + run_step e2e || failed=1 + else + failed=1 + fi + echo "all exit=$failed" | tee -a "$out_dir/status" + exit "$failed" +fi +run_step "$step" "$@" diff --git a/scripts/test-ssh.ts b/scripts/test-ssh.ts index 121a740c..0fb940a4 100644 --- a/scripts/test-ssh.ts +++ b/scripts/test-ssh.ts @@ -1,7 +1,7 @@ // Optional Linux integration test: isolated unprivileged OpenSSH server. // No user SSH keys/configuration or remote hosts are used or changed. // Run with: bun scripts/test-ssh.ts -import {mkdtempSync, readFileSync, writeFileSync, rmSync} from 'node:fs'; +import {existsSync, mkdtempSync, readFileSync, writeFileSync, rmSync} from 'node:fs'; import {spawn, spawnSync} from 'node:child_process'; import {tmpdir, userInfo} from 'node:os'; import {join} from 'node:path'; @@ -29,7 +29,9 @@ try { const client = join(dir,'ssh_config'); writeFileSync(join(dir,'known_hosts'), `[127.0.0.1]:${port} ${readFileSync(join(dir,'host.pub'),'utf8')}`); writeFileSync(client, `Host fixture\n HostName 127.0.0.1\n Port ${port}\n User ${userInfo().username}\n IdentityFile ${dir}/client\n IdentitiesOnly yes\n BatchMode yes\n UserKnownHostsFile ${dir}/known_hosts\n StrictHostKeyChecking yes\n ConnectTimeout 5\n`); - server = spawn('/usr/bin/sshd', ['-D','-e','-f',config], {stdio:['ignore','ignore','pipe']}); + const sshd = ['/usr/sbin/sshd', '/usr/bin/sshd'].find(existsSync); + if (!sshd) throw new Error('OpenSSH server not found; install openssh-server'); + server = spawn(sshd, ['-D','-e','-f',config], {stdio:['ignore','ignore','pipe']}); let log=''; await new Promise((resolve,reject) => { const timer = setTimeout(()=>reject(new Error('sshd startup timed out: '+log)),5000); @@ -49,7 +51,7 @@ try { for (const mode of ['ssh-plain', 'ssh']) { for (let trial=0; trial<5; trial++) run(binary, [mode,root,client,helper]); } - } else run('cargo',['test','-p','disktree-core','real_ssh_transport_','--','--ignored','--nocapture'], {...process.env,DISKTREE_TEST_SSH_CONFIG:client,DISKTREE_TEST_HELPER:join(process.cwd(),`target/${process.arch === 'arm64' ? 'aarch64' : 'x86_64'}-unknown-linux-musl/release/disktree-scan`),DISKTREE_TEST_ARCHIVE:join(process.cwd(),'target/portable/disktree')}); + } else run('cargo',['test','-p','disktree-core','real_ssh_transport_','--','--ignored','--nocapture'], {...process.env,DISKTREE_TEST_SSH_CONFIG:client,DISKTREE_TEST_HELPER:join(process.cwd(),`target/${process.arch === 'arm64' ? 'aarch64' : 'x86_64'}-unknown-linux-musl/release/disktree-scan`),DISKTREE_TEST_ARCHIVE:join(process.cwd(),'target/portable/pwrdisk')}); console.log(`${process.env.DISKTREE_PROFILE_ROOT ? 'SSH PROFILING COMPLETE' : 'REAL SSH SCAN PASSED'}. Temporary host key, client key and server will be removed.`); } finally { if (server && server.exitCode === null) { diff --git a/skills/pwrdisk-explain-usage/SKILL.md b/skills/pwrdisk-explain-usage/SKILL.md new file mode 100644 index 00000000..b264fdc2 --- /dev/null +++ b/skills/pwrdisk-explain-usage/SKILL.md @@ -0,0 +1,87 @@ +--- +name: pwrdisk-explain-usage +description: Explain where a disk's space went with PwrDisk's read-only MCP tools. Use when the user asks what is eating their disk, why it is full, or why free space disagrees with what they see. Never marks or removes anything. +license: MIT +--- + +# Explain disk usage with PwrDisk + +The user wants to understand their disk, not change it. Use only the tools +that read: `pwrdisk_status`, `pwrdisk_scan`, `pwrdisk_ls`, `pwrdisk_find`, +`pwrdisk_estimate` +and, only when the user asks to see a path, `pwrdisk_show`. Do not call +`pwrdisk_mark`, `pwrdisk_review` or `pwrdisk_remove`, and do +not run anything that deletes or changes settings. End with the +explanation; offering to free space is a question you ask, not a step you +take. + +Read the reference for the system `pwrdisk_status` names. Each says what +that system keeps outside any file scan and which read-only command shows +it: + +- macOS: `skill://pwrdisk-free-space/references/macos.md` +- Linux: `skill://pwrdisk-free-space/references/linux.md` +- Windows: `skill://pwrdisk-free-space/references/windows.md` + +## Procedure + +1. **Status.** `pwrdisk_status`: the volumes, their size and free space, + and whether a PwrDisk window is linked. With a window linked, its tree + is what you read. Status reports allocated versus apparent sizes, hidden + entry inclusion and unreadable count; retain that context without a + rescan. Browsing never moves the displayed directory. Use `pwrdisk_show` + only when the user asks to see a path or requests following. If earlier + marks are outside its root, the session keeps them and leaves the + window where it is; status explains why it is not followed. +2. **Scan the right thing.** The home directory answers "what of mine is + big" in seconds. `disk: true` answers "why is the disk full"; say first + that it walks the whole volume and can take minutes. +3. **Account for the volume.** The scan reports how much of the volume's + used space it explains. Name the rest rather than guess at it: + snapshots, other volumes in the same container, swap and hibernation, + files deleted while still open, and parts the scan could not read. Give + the read-only command from the platform reference that confirms each. +4. **Walk the big branches.** `pwrdisk_ls` largest first, a few levels + down, until each big directory has an owner: a project, a tool, an app, + the OS, or the user's own files. `pwrdisk_find` with + `reclaimable: true` totals classified cleanup candidates such as caches, + build output and verified package stores, including guard refusals; + `kind: "file"` with `min_bytes` finds the large single files. +5. **Explain.** A short table: what, where, how big, who owns it, and + whether it comes back by itself. Say plainly where PwrDisk's number + differs from another tool's and why: PwrDisk counts allocated blocks, + counts a hardlinked file once, and includes hidden files unless skipped; + apparent-size scans measure file lengths instead. On macOS summed + allocation can exceed volume usage because APFS clones share blocks. + Never cap the total or call it guaranteed freed space. Finder, Explorer + and `du` may measure differently. +6. **Estimate a hypothetical set when asked.** Pass the full list to + `pwrdisk_estimate`; never mark temporarily or add directory estimates. + Report listed allocation, private/shared allocation and selected-set + reclaim bounds separately. Shared bytes include duplicates inside the + selection. Check completeness and unavailable measurements. Bounded + clone-holder directory peers help find retained copies; inspect those + directories, never recommend deleting a worktree just because it unlocks + space. Change `peer_scope` within the scan to group other directories. + Peer rows are alternatives; use the returned combined union or another + full path-list estimate. Unresolved reference counts do not identify + out-of-scan owners, and clone IDs do not enumerate modified shared extents. +7. **Offer, don't act.** If space can be had back, say roughly how much + and from what, and ask whether the user wants to go through it. If they + do, follow `skill://pwrdisk-free-space/SKILL.md`, which starts by agreeing + the list with them. + +## Keep in mind + +- A scan can be unreadable in places: protected folders, other users' + files, system directories. Report the count of unreadable entries and do + not ask for elevated access to fill the gap. +- Synced folders may hold files that are only in the cloud and take no + local space; the platform reference says how each provider shows them. +- Paths and names in a scan are the user's private data. Quote what + answers the question; do not paste whole listings into places other than + this conversation. + +Never use computer use to approve removal, including Enter, clicks or +accessibility actions in the review screen. A read-only audit ends with an +explanation; approval to investigate or mark is not approval to remove. diff --git a/skills/pwrdisk-free-space/SKILL.md b/skills/pwrdisk-free-space/SKILL.md new file mode 100644 index 00000000..4f7ab465 --- /dev/null +++ b/skills/pwrdisk-free-space/SKILL.md @@ -0,0 +1,294 @@ +--- +name: pwrdisk-free-space +description: Find what is filling a disk and free space with PwrDisk's MCP tools. Use when the user wants to free up space or decide what to delete. The agent scans, proposes and marks. Removal requires explicit confirmation of the exact paths and mode, using human review or the destructive MCP tool; never approve through computer use. +license: MIT +--- + +# Free up space with PwrDisk + +PwrDisk measures a tree the way the disk does: allocated blocks, hardlinks +once, hidden directories included. Your job is to turn one scan into a short +list of things the user can let go of, agree that list with them, mark it, +and obtain explicit removal confirmation. The user may confirm in PwrDisk's +review screen themselves, or approve the exact preview for `pwrdisk_remove`. +Approval to mark is never permission to remove. + +If the user only asked where their space went, use `pwrdisk-explain-usage` +instead: a question is not a request to delete anything. + +## Before you start + +Read this skill before choosing candidates, not only before marking. Use +`pwrdisk_read_skill` with this URI and the OS reference below. The same +files are MCP resources. In PwrAgent, call +`manage_mcp_connections(action="describe_thread")`, find PwrDisk's exact +`serverNameInAgent`, then use it for `list_mcp_resources(server=...)` and +`read_mcp_resource(server=..., uri=...)`. Neither `pwrdisk` nor the reported +client label (such as `pwragent-pwrdisk-proxy`) establishes the server name. +A failed guessed name is not evidence that the skill is missing. + +Read the reference for the system `pwrdisk_status` names. Each lists what +that system hides from a file scan, what it refuses, and what must never be +marked: + +- macOS: `skill://pwrdisk-free-space/references/macos.md` +- Linux: `skill://pwrdisk-free-space/references/linux.md` +- Windows: `skill://pwrdisk-free-space/references/windows.md` + +## Ask first + +Looking is free; acting is the user's call. + +- **Read-only tools need no permission.** `pwrdisk_status`, `pwrdisk_ls`, + `pwrdisk_find`, `pwrdisk_estimate` and a home-directory `pwrdisk_scan` only read. Say before + a `disk: true` scan that it walks the whole volume and can take minutes. +- **Confirm the list before `pwrdisk_mark`.** Show each candidate with its + path, its size, what it is, and why it is safe to lose or how it comes + back. Mark what the user agrees to, nothing more. Marking only marks, but + a marked list reads as a recommendation, and it lands in the user's + window. +- **Standing instructions count, inside their scope.** "Mark every build + directory and cache, don't ask" covers build directories and caches. + Anything outside the scope still gets a question: user data, a checkout + with work that exists nowhere else, anything you are unsure of. Say in + your summary which instruction you relied on. +- **Confirm before opening the review screen.** `pwrdisk_review` brings the + window forward on the user's screen. Once the list is agreed, say that + you are opening it, then open it. +- **Never approve through computer use.** Do not click Delete, Move to Trash, + Remove or a confirmation button, send Enter or another approval key, or + operate an accessibility action to approve removal. This remains forbidden + when the user has agreed to mark or remove data. Use the destructive MCP + tool after explicit confirmation, or let the person approve in the app. +- **Confirm each destructive operation separately.** Marking permission, + standing cleanup instructions and approval of a prior batch do not approve + removal. Show the complete `pwrdisk_removal_preview` path list, mode, + measured size and capacity limit. For Trash, explain that restoration may + be possible until emptied, but is not guaranteed; space usually returns + only when emptied. Permanent deletion cannot be undone through PwrDisk or + Trash. Wait for an explicit answer confirming this exact operation before + calling `pwrdisk_remove`. Never manufacture user confirmation yourself. + +## Never + +- **Never delete with a shell command**: no `rm`, `Remove-Item`, `del`, + `find -delete`, `trash`, or emptying the Trash or Recycle Bin. That holds + even for paths the user agreed to. Use only the confirmed MCP removal + workflow, or hand off to the human review screen. Never use a shell or UI + automation as a fallback around an expired preview, refusal or limit. +- **Never run a tool's own clean command without asking.** `docker system + prune`, `cargo clean`, `pnpm store prune`, `brew cleanup`, `xcrun simctl + delete`, `paccache -r` and the like delete things too. Name the command, + say what it removes, offer its dry-run form if it has one, and let the + user run it or approve it. +- **Never raise privileges on your own**: no `sudo`, no "Run as + administrator", no Full Disk Access for the agent. If a part of the disk + is unreadable, say so and say what would read it. +- **Never change system settings** to win space: snapshots, swap, + hibernation, restore points, the Spotlight index. Explain them, give the + read-only command that shows them, and leave the change to the user. + +## Ground rules + +- **Separate detection from cleanup advice.** An artifact's `kind` names + what was recognized; `evidence` describes a name convention or tool + layout. `disposition: detected` is inventory, not a suggestion to remove + it. `suggested` means a relatively lower-risk candidate for review, + still subject to local edits, active owners, rebuild/reinstall costs and + the user's confirmation. Neither size nor age makes data disposable. + Use only the recognized subtree: a Cargo manifest does not establish + that all of `target`, `build` or `dist` is generated output. +- **VM data belongs to its owner app.** Disk images can contain unique + work. Review and consolidate snapshots through the VM app; never offer + individual snapshot-chain files as generic cache cleanup. For saved + memory or suspend state, suggest resuming the VM and shutting it down + normally so its owner releases the state. Checkpoints may retain memory. + These are detections, and listed bytes are not guaranteed savings. +- **Check retention before promising recovery.** On macOS call + `pwrdisk_retention` for a path on each selected volume before proposing + a recovery amount. It lists local Time Machine snapshots without changing + them; other snapshots, open files and concurrent writes remain unmeasured. + Failed, unsupported or unrecognized checks mean unknown, never zero. + Snapshot presence is a plausible retention mechanism, not proof of the + exact bytes held. Even an empty list cannot guarantee immediate recovery. + Report that uncertainty upfront, including for mostly private selections. +- **Keep five different metrics separate.** Apparent logical size is known + only if measured in that mode. An ALLOCATED scan reports allocation, + including shared/repeated clone blocks; never relabel it apparent size. + Private allocation is the scan's estimate of unshared bytes. Reclaim + bounds evaluate the whole selected union before retention. Observed + recovery is the signed before/after available-space delta on the measured + volume, which concurrent writes affect too. A negative delta is a loss of + available space, not "0 B freed". Do not subtract private from reported + allocation to explain all missing recovery. +- **Estimate before marking.** For a hypothetical path list use + `pwrdisk_estimate` without changing the cart. Evaluate the whole set; + never sum directory reclaim estimates or mark worktrees temporarily. + Allocation includes internal clone duplicates. Check bounds, scan and + metadata completeness, unavailable values and volume attribution. + Retained clone-holder directories are inspection leads, not removal + recommendations. Agree each added path separately; a larger estimated + saving does not establish that a worktree is disposable. See the macOS + reference for bounded peer discovery and unresolved references. +- **Keep browsing stationary.** `pwrdisk_ls` and `pwrdisk_find` never move + the window. Call `pwrdisk_show` only if the user asks to see a directory + or explicitly asks the window to follow along. Do not enable following + merely because you are investigating. Opening the marked list for review + is a separate, explicitly announced action. +- **Respect the capacity limit.** Settings > Safety controls the maximum + per-operation measured bytes on each volume, 5% by default, for both + Trash and permanent deletion. The app re-measures before removing anything + and refuses an operation with unknown capacity or unreadable selection. + Do not raise the setting, split a selection into batches, or retry an + ambiguous result to evade the guard. Ask the user how to proceed. + A linked window refuses a mark that would take the list past the limit, + and removal checks it again; only the person can go past it, in the + window, and agents keep the 5% default even when the window's limit is + off. Without a window, marks are checked when they reach one, so a mark + that succeeds then may still be refused. +- **The guards are not your safety net.** `pwrdisk_mark` refuses the home + directory, mount points, the scanned root, system trees and a user + profile, and says why. Anything else it will mark. You decide what to + propose. +- **Prefer the owning tool for tool-owned data.** Package stores, container + images, simulators, toolchains, game libraries and build caches have their + own clean commands. Offer them first; marking the directory is still fine + when the user wants the space now and agrees. +- **Check before proposing a checkout.** For a git repository or worktree, + run `git status --short`, `git stash list` and `git log --branches + --not --remotes --oneline`. Work that exists nowhere else is the user's + call, and you say so with the list. +- **Synced folders are not local copies.** Removing a file from iCloud + Drive, OneDrive, Dropbox or Google Drive removes it from the cloud and + from every device. Ask every time, and mention the provider's own "free up + space" or "remove download" instead. +- **Sizes are bytes on disk.** A sparse disk image or VM disk shows what it + occupies, not its nominal size. Clones and hardlinks share blocks; the + platform reference says how. +- **Trash frees nothing until it is emptied.** The review screen moves marks + to the Trash or Recycle Bin by default. Tell the user the space comes back + when they empty it. Emptying it is theirs to do. +- **Say what you cannot see.** `pwrdisk_scan` compares the scan's total with + the volume's used space. A big gap is space files do not explain: + snapshots, other volumes sharing the container, swap, deleted files still + held open. Deleting files will not fix that part. Name the likely cause + and the read-only command that confirms it; the platform reference lists + them. +- **This computer only.** The tools measure and mark the machine + `pwrdisk mcp` runs on. If `pwrdisk_status` says the window is on an SSH + host, it is not followed; ask the user to choose This computer in it. + PwrDisk does not remove files over SSH. +- **Linking keeps the window where it is.** If marks made before linking + are outside the window's root, the session keeps all of them and reports + that the window is not followed. Call `pwrdisk_scan` on a directory + containing all marked paths to move the window explicitly and hand them + over before review. If the window accepted only part of a handover, + `pwrdisk_unmark` clears the requested marks there too. A newly opened + review window starts on a directory containing all marks. Do not unmark + agreed paths to force a link. + +## Procedure + +1. **Measure the gap.** `pwrdisk_status` shows the volumes, their free + space, whether a PwrDisk window is open, and the system. When a window + is linked its tree is what every tool reads: you and the user look at + the same numbers, and a path outside its root needs a `pwrdisk_scan` + from higher up, which the window follows. Ask what the user wants: a number, or + whatever is safe. +2. **Scan.** `pwrdisk_scan` with no path scans the home directory in a few + seconds; `disk: true` scans the whole volume. With a window open it does + the scanning and shows the result. The result lists the top level, + largest first, and *worth a look*: the biggest directories that could + plausibly go. +3. **Walk and compare physical candidates.** Allocation-sorted tools show + large listings, not the largest likely savings. Pass a bounded explicit + candidate path list to `pwrdisk_rank` (`by: "private"` or + `"reclaim_lower"`) to compare scan-derived physical figures; null is + unavailable and distinct from measured zero. The returned union is not + the sum of candidate rows. Ranking establishes neither ownership nor + cleanup method; check both before proposing anything. Never delete a + worktree merely to unlock a clone group. + Continue with `pwrdisk_ls` on the largest directories, a few + levels down, until a directory clearly belongs to one project or one + tool. Leave the displayed directory unchanged. Use `pwrdisk_show` only + when the user asks to see a path or has requested following. +4. **Sweep.** `pwrdisk_find` with `reclaimable: true` lists every cache, + build directory and verified package store at once. These are cleanup + candidates, not removal eligibility or guaranteed savings. Read reported + guard refusals; never bypass them. A cache name or regenerable hatch is + insufficient permission for raw deletion. Resolve its owner and preview + owner-managed cleanup; unknown runtime/install caches need inspection. + pnpm installations include executables, global tools and `.tools`; do not + treat them as disposable stores or assume prune has directory-local scope. + `kind: "file"` with + `min_bytes` finds huge files. `older_than_days` finds what nobody has + touched. `name` matches part of a name. +5. **Classify each candidate**, in one line each: + - *regenerable*: an inspection lead, never deletion authorization; + bookkeeping-sensitive caches require their owning tool; + - *tool-owned*: stores, images, simulators, toolchains; offer the + tool's command; + - *user data*: media, downloads, archives, documents, VM disks, synced + files; the user decides each one; + - *hands-off*: anything the OS or an app owns; never propose it. +6. **Propose.** Give the user the list, grouped by class, with sizes and the + total, and anything you checked (unpushed work, a sync provider). Wait + for their answer unless a standing instruction covers it. +7. **Mark.** `pwrdisk_mark` with the agreed paths. Read the plan it + returns: what is kept back and why, what is covered by another mark, and + the projected free space, which counts only bytes on the measured + volume. Tell the user about anything kept back. +8. **Confirm removal or hand it over.** To let the person remove in the + app, announce `pwrdisk_review`, open it, and stop; never approve through + computer use. For requested MCP removal, call `pwrdisk_removal_preview` + with `owner_cleanup` for caches (otherwise explicit `trash` or + `permanent` for ordinary paths). A cache cleanup is decided per path: + the first preview lists one proposal per marked path; show every owner, + version, executable, argument list, environment override, selected path, + actual whole-cache scope, effects, limitations and recoverability, and + every unavailable reason. The user chooses `skip`, `owner` or + `delete_files` for each path; never choose for them or suggest + `delete_files` yourself. Preview again with those `decisions` (and + `delete_files_mode` when any path deletes files); its confirmation text + names each intent, and owner approval never approves deleting files. + Every mode may return preparing while inspection runs on a worker; + retry only the read-only preview. Exports contain marked paths, never + expanded owner scopes; a refused raw script is not a deletion fallback. + Cache tags/layouts on ancestors protect contained files and subtrees too. + Unknown, + unsupported, unavailable or failed owners never fall back to raw deletion. + Show every returned actual-scope path and + the consequences, and wait for explicit user confirmation. Only then call + `pwrdisk_remove` with the exact preview ID, ordered paths, mode and required + confirmation text. The preview expires after five minutes and is single + use. Any refusal, changed selection, changed scan or expiration requires + a new preview and fresh user confirmation, after checking outcome. + A cancelled MCP form describes the form, not native UI removal. If the + exact previewed selection finished or is running, do not replay it or + request another preview. Read status and reconcile failures or unreached + paths with the user. An unavailable outcome is not permission to retry. + A tool response saying the + operation started is not proof it completed; never retry it automatically. +9. **Report.** `pwrdisk_status` reports completed and failed removals and + measured freed space. Report that figure, not a projection. Trash is not + guaranteed recoverable and does not guarantee an immediate space saving. + Cache cleanup always rescans and reports each path's result (succeeded, + failed with a reason, cancelled, skipped, not reached) separately from + scope allocation and observed free-space change. Success need not + remove the cache root or free its listed allocation; APFS snapshots/clones, + hardlinks and open files can retain blocks. Never alter snapshots. + Raw removal does not rescan unless `pwrdisk_remove` is given `rescan: true`, + so the next batch can be found at once. Until a rescan, listings keep + the scan's sizes but say "removed since the scan" on what went, and + "N of it removed since the scan" on a directory that lost part of + itself; subtract that before reporting what is left. The window refuses + to mark removed paths again, so leave them out. Its removals since the scan are listed as + reported (a clone in every place), private (the scan's estimate of what + was theirs alone) and observed (the measured free-space change); report + the observed total first. Sharing figures stay the scan's until a + rescan. + +MCP removal also requires interactive confirmation from the client (form +elicitation). An agent-supplied confirmation value does not establish human +consent. If the client cannot ask the user, use human review in PwrDisk; +never approve its buttons or confirmation keys through computer use. diff --git a/skills/pwrdisk-free-space/references/linux.md b/skills/pwrdisk-free-space/references/linux.md new file mode 100644 index 00000000..056c5c7f --- /dev/null +++ b/skills/pwrdisk-free-space/references/linux.md @@ -0,0 +1,167 @@ +# PwrDisk on Linux + +What Linux keeps outside a file scan, what PwrDisk refuses, and what to +leave alone. Read with `skill://pwrdisk-free-space/SKILL.md`. + +## Reading the numbers + +- **Hardlinks are counted once.** pnpm stores, Nix, ccache and backup tools + hardlink files. Removing one name frees nothing until the last name goes; + a hardlinked tree can give back far less than its size. +- **Snapshots hold deleted data.** On btrfs (snapper, Timeshift, btrbk) and + ZFS, a snapshot keeps every block it references. Space freed while one + exists may not come back. `btrfs subvolume list /`, `snapper list` and + `zfs list -t snapshot` show them; removing one is the user's decision. +- **btrfs reports space its own way.** `df` can disagree with the sum of the + files; `btrfs filesystem usage /` gives the real allocation. +- **Deleted files still open** keep their space until the process closes + them. `lsof +L1` lists them; restarting that process frees it. +- **Swap files and the journal**: `swapon --show` and + `journalctl --disk-usage` show them. Shrinking either is a system change + (`journalctl --vacuum-size=...` needs root); give the command, do not run + it. +- **Scans stop at other filesystems.** Mounts, bind mounts and btrfs + subvolumes under the root are not counted unless the user asks for them. + +## Root discovery + +The root chooser omits mounts at or below `/proc`, `/sys` and `/dev`, +plus kernel pseudo filesystems including `binfmt_misc`, `bpf`, `efivarfs` +and `ramfs`. Discovery reads the mount table without probing candidates +or measuring their free space; an explicit scan root is still required. + +## Access + +`pwrdisk mcp` runs as the user. Root-owned directories show as unreadable; +do not use `sudo` to look inside them. Say what was unreadable and what +would read it. + +## Refused by PwrDisk + +`pwrdisk_mark` keeps these back and says why: `/bin`, `/boot`, `/dev`, +`/etc`, `/lib*`, `/proc`, `/run` (except removable media under it), `/sbin`, +`/sys`, `/usr`, `/var/lib`, `/efi`, `/nix/store`, `/gnu/store`, Homebrew's +`/home/linuxbrew/.linuxbrew`, the home directory and anything holding it, +`/home` and every account's folder in it (another user's home, +`/home/linuxbrew`; what is inside one may be proposed), the same under +`/var/home` where `/home` links there, and mount points. + +## Never propose + +- **Anything a package manager installed.** Uninstall with `pacman`, + `apt`, `dnf`, `flatpak` or `snap`, which the user runs. +- **`~/.var/app/`, `~/.local/share/`, `~/.config`**: application + data and settings. Only a specific, known cache inside them, with the app + closed. +- **Keyrings, `~/.ssh`, `~/.gnupg`, password stores**: secrets. +- **Container storage**: `~/.local/share/containers`, `/var/lib/docker`. + Use `docker system df` / `podman system df`, then the prune commands. +- **Virtual machine disks** (`*.qcow2`, `*.img` under libvirt or GNOME + Boxes): user data; ask, and remove the VM in its manager instead. +- **Synced folders** (Nextcloud, Dropbox, Syncthing, rclone mounts): + deleting there deletes on every device. + +## Usually safe, with the owning tool first + +| what | where | prefer | +| --- | --- | --- | +| user caches | `~/.cache/` | close the app; use its supported cleanup; unknown owners need inspection | +| pacman packages | `/var/cache/pacman/pkg` | `paccache -dk1`, then `paccache -rk1` (root) | +| apt and dnf packages | `/var/cache/apt`, `/var/cache/dnf` | `apt clean`, `dnf clean all` (root) | +| unused Flatpak runtimes | `/var/lib/flatpak`, `~/.local/share/flatpak` | `flatpak uninstall --unused` | +| language caches | `~/.npm/_cacache`, `~/.cargo/registry`, `~/.cache/pip`, `~/.gradle/caches` | the tool's clean command | +| pnpm store | `~/.local/share/pnpm/store` | `pnpm store prune` | +| build output | `target/`, `node_modules/`, `build/`, `dist/` | check the checkout first (see the skill) | +| Steam games | `~/.local/share/Steam/steamapps` | uninstall in Steam | + +## Trash + +PwrDisk moves marks with `trash-put`, then `gio trash`, then its own XDG +trash in `~/.local/share/Trash`; the review screen names the one it uses. +`trash-put` and `gio` put a mark on another filesystem in that +filesystem's `.Trash-`. The space returns when the user empties the +trash. With no trash at all, the review screen deletes permanently and says +so; tell the user before they confirm. + +## Confirmed removal + +Never approve a removal with computer use (clicks, keys or accessibility +actions). The user approves in the app, or explicitly confirms the exact +paths and mode from `pwrdisk_removal_preview` before the destructive +`pwrdisk_remove` call. Trash or Recycle Bin recovery may be possible until +emptied, but is not guaranteed; permanent deletion cannot be undone through +PwrDisk. Both modes use the existing removal guards and Settings > Safety's +per-operation limit, 5% of each volume's capacity by default. Never bypass a +refusal, increase the setting or split batches to evade it. A window +refuses a mark that would take the list past the limit, and marks made +without one are checked when they reach it: only the person can mark past +it, in the window. Say so, and let them decide. + +MCP removal also requires interactive confirmation from the client (form +elicitation). An agent-supplied confirmation value does not establish human +consent. If the client cannot ask the user, use human review in PwrDisk; +never approve its buttons or confirmation keys through computer use. + +Capacity checks charge a symbolic link to its containing volume, not its +destination. + +## Owner-managed caches + +A cache name or regenerable classification is an inspection lead, never +permission to delete it. Cache cleanup is decided path by path. Call +`pwrdisk_removal_preview` with `owner_cleanup` and no decisions: it returns +one proposal per marked path with its status and problem, resolved owner, +version, executable, arguments, environment overrides, configured root, full +actual scope (including unselected siblings), effects, limitations, +recoverability, and whether Delete files is offered. Show every proposal and +let the user choose for each path `skip`, `owner` (only where offered) or +`delete_files`. Never choose for them and never suggest `delete_files` +yourself; inspect unknown runtime/install caches first, since nothing says +they are disposable. Then preview again with `decisions` naming every marked +path once, and `delete_files_mode` (`trash` or `permanent`, as the user +chose) when any path uses `delete_files`. Confirmation needs that preview's +exact paths and its own text: `RUN OWNER CLEANUP`, `DELETE CACHE FILES`, +`TRASH CACHE FILES`, or both intents joined with `AND`. Owner approval never +approves deleting files. Unavailable commands do not establish absent +software. An unsupported version, failed probe, or failed or cancelled owner +command never falls back to deleting files, and never to a shell command; +deleting them instead is a new preview the user decides. + +Cache tags and owner layouts on ancestors protect contained files and +subtrees too. All removal modes may return a preparing response while +inspection runs on a worker; retry only the read-only preview. Exported +lists keep marked paths, and raw script exports cannot replace owner cleanup. + +On macOS and Linux the initial adapters cover npm packages (9–11), npm's +separate npx cache (11.2–11.x), uv (0.11.x), pip (23–26) and Cypress (13–15), +only when their installed CLI resolves the selected cache. pnpm, Homebrew, +Playwright and Puppeteer remain explicit inspection-only owners because their +full command/configuration scopes are not supported. Windows command +launchers have no execution adapter yet. Neither containers nor volumes are +cleanup scopes. + +Each path gets its own result: succeeded, failed with a reason, cancelled +(possibly part done), skipped, or not reached after Stop. A command's +success reports the owner's exit result, not guaranteed savings. +Report allocation separately from observed volume availability before/after; +other activity, hardlinks, open files, APFS clones and snapshots can retain +blocks. PwrDisk always rescans after owner cleanup, even partial failure. +Never alter snapshots to force the reported allocation to become free space. + +## Developer artifacts and virtual machines + +Artifact identity and evidence are separate from cleanup suitability. +`detected` is inventory only. `suggested` means a plausible, relatively +lower-risk candidate to review, with local edits, active tools and the +cost of reinstalling or rebuilding still to check. Name conventions are +weaker evidence than recognized tool layouts. Whole tool homes and generic +`target`, `build`, `dist`, `bin` or `obj` names do not establish disposability; +review the specific detected subtree instead. + +VM/container disk images can contain unique work. Manage snapshots in the +owner app, never by removing individual files in a snapshot chain. Saved +memory or suspend state can usually be released by resuming the VM and +shutting it down normally; checkpoints may retain it. VM data stays a +detection even inside a directory named like a cache, and its displayed +size is not a promise of recovered space. Do not run an owner's destructive +cleanup command without explicit approval for that operation. diff --git a/skills/pwrdisk-free-space/references/macos.md b/skills/pwrdisk-free-space/references/macos.md new file mode 100644 index 00000000..e64e9fbf --- /dev/null +++ b/skills/pwrdisk-free-space/references/macos.md @@ -0,0 +1,258 @@ +# PwrDisk on macOS + +What macOS keeps outside a file scan, what PwrDisk refuses, and what to +leave alone. Read with `skill://pwrdisk-free-space/SKILL.md`. + +## Reading the numbers + +Before promising recovery, call `pwrdisk_retention` for each selected +volume. This read-only, time-bounded check lists local Time Machine +snapshots. It does not quantify blocks retained from the selected paths, +list all APFS snapshots, inspect open files or predict concurrent writes. +Unknown and measured zero snapshots are distinct. Snapshot presence is +plausible evidence of retention, not proof that it explains an exact +shortfall; absence does not guarantee immediate recovery. Do not thin, +delete or alter snapshots as part of this check. Even a set with almost +all private allocation can yield no immediate available-space increase. + +An allocated scan's reported bytes are allocation, never apparent logical +size. Keep reported allocation, private allocation, whole-set reclaim +bounds and signed observed volume change separate. Logical size is a fifth +metric only when measured. Use `pwrdisk_rank` on explicit candidates to +compare private allocation or standalone reclaim lower bounds; unavailable +is null, not zero. Establish ownership and the owning tool's cleanup method +separately, and do not propose worktrees just to release clone groups. + +- **APFS clones share blocks.** Finder duplicates, `cp -c` and some package + managers make clones: two copies can cost one copy's space, and removing + one frees little or nothing. PwrDisk counts each file's allocation, so a + cloned tree can exceed the volume's used space. Listed allocation is not + guaranteed freed space; do not cap the scan total to volume usage. The + free space measured after the review is the real figure. +- **Read a row's clone split.** A row with clone blocks adds + `X private · Y shared with other APFS clones · frees ≈ Z alone`. Only the + private part goes when that entry is removed by itself; the shared part + stays while any other clone of it remains, and APFS counts clones outside + the scanned root too. A header line `APFS clones: … counted again` says + how much of the total is listed more than once. Do not present listed + bytes, or the shared part, as space a clone-backed worktree or copy will + free. A row without the clause has no clone files. +- **Use the selected-set reclaim bounds, not listed bytes.** PwrDisk + evaluates accepted marks together: a complete clone group is counted + once, while copies retained outside the selection keep shared blocks + alive. All hardlink names must be selected before their allocation can + be reclaimed. Clone groups are scoped to their physical APFS volume. + Missing metadata widens the bounds; it does not justify projecting all + listed bytes. Apparent-size scans and disabled clone measurements cannot + establish physical reclaim estimates. Linked reports use the window's + measurement context; an ongoing scan has no final estimate. + Bounds are scan-derived, before snapshots, open files and + later changes; even the lower estimate is not a guaranteed saving. +- **One container, several volumes.** The System, Data, Preboot, Recovery + and VM volumes share one APFS container's space. A whole-disk scan of + `/` explains the Data volume; the rest shows as space the scan does not + explain. `diskutil apfs list` shows each volume's use. +- **Local snapshots hold deleted data.** Time Machine and system updates + keep APFS snapshots; space freed while one exists may not come back until + it expires. `tmutil listlocalsnapshots /` lists them. Deleting one + (`tmutil deletelocalsnapshots`) is the user's decision; give the command, + do not run it. +- **"Purgeable" is not free.** Finder counts purgeable space as available; + PwrDisk and `df` do not. If the numbers disagree, that is usually why. +- **Swap and the sleep image** live on the VM volume. Leave them alone. + +## Privacy and access + +- macOS protects Desktop, Documents, Downloads, Mail, Messages, Safari, + Photos and parts of `~/Library`. A scan started by the agent runs with the + privacy grants of the app hosting the agent, such as a terminal or an + editor. It may show these folders as unreadable or make macOS prompt for + that app. +- A scan the PwrDisk window runs uses PwrDisk's own grants. If a protected + folder matters, open the window (`pwrdisk_show`) and scan from there. +- Do not ask the user to give the agent's host Full Disk Access just to + measure. Report what was unreadable and let them decide. + +## Refused by PwrDisk + +`pwrdisk_mark` keeps these back and says why: `/System`, `/Library`, +`/private`, `/cores`, `/opt/homebrew` and the other system trees, the home +directory and anything holding it, `/Users` and every account's folder in +it (`/Users/Shared`, `/Users/Guest`, another user's home; what is inside +one may be proposed), mount points, and the `.fseventsd` and +`.Spotlight-V100` stores (use `mdutil` for Spotlight, never delete either). +What is inside `/private/tmp` and `/private/var/tmp` (`/tmp` and +`/var/tmp`) may be marked, as on Linux; the two folders themselves stay +refused under `/private`, and so does `/private/var/folders`, where each +user's `$TMPDIR` and caches hold running apps' live state. Classification +is independent of removal eligibility: `pwrdisk_find` may list +`/private/tmp` as a temporary cleanup candidate and report the `/private` +guard refusal for the folder. Look inside it with `pwrdisk_ls`, propose +entries the user recognizes as their own leftovers, and leave files a +running program may still use. Do not bypass the guard. + +## Never propose + +- **Inside a library package**: the Photos Library, Music, Apple TV, iMovie, + Final Cut and Logic libraries. Removing files inside breaks the library; + the app manages its own media. +- **`~/Library/Mobile Documents`, `~/Library/CloudStorage`**: iCloud Drive + and File Provider folders (Dropbox, Google Drive, OneDrive), and legacy + Google Drive roots named `My Drive` or `My Drive ()`. Deleting a + file there deletes it in the cloud and on every device. An evicted file + takes no local space; to free space without deleting, the user chooses + "Remove Download" in Finder or turns on Optimize Mac Storage. +- **App data**: `~/Library/Containers`, `~/Library/Group Containers` and + `~/Library/Application Support` hold apps' databases and settings. Only + propose a specific, known cache inside them, with the app quit. +- **Mail and Messages attachments, Keychains, and iPhone and iPad backups** + (`~/Library/Application Support/MobileSync/Backup`): user data and + secrets. Old device backups are the user's to delete from Finder. +- **`/Applications`**: uninstall with the app's uninstaller or by dragging to + the Trash in Finder, which the user does. + +## Usually safe, with the owning tool first + +| what | where | prefer | +| --- | --- | --- | +| app cache inspection | `~/Library/Caches/` | quit the app; use its supported cleanup; unknown owners need inspection | +| Xcode build data | `~/Library/Developer/Xcode/DerivedData` | Xcode rebuilds it | +| old device support | `~/Library/Developer/Xcode/iOS DeviceSupport` | re-created when a device connects | +| simulators | `~/Library/Developer/CoreSimulator` | `xcrun simctl delete unavailable`; runtimes in Xcode › Settings › Components | +| Xcode archives | `~/Library/Developer/Xcode/Archives` | ask: needed to symbolicate shipped builds | +| Homebrew downloads | `~/Library/Caches/Homebrew` | `brew cleanup --dry-run`, then `brew cleanup` | +| Docker Desktop | `~/Library/Containers/com.docker.docker/.../Docker.raw` | never mark the disk image; `docker system df`, then prune | +| pnpm package store | `~/Library/pnpm/store/v*/files` (also older `.pnpm-store/v*/files`) | `pnpm store path` to confirm the location; `pnpm store prune` first; never treat the `pnpm` installation, executable, `global` or `.tools` as a disposable store | +| language caches | `~/.npm/_cacache`, `~/.cargo/registry`, `~/Library/Caches/pip`, `~/.gradle/caches` | the tool's clean command | + +## Trash + +Marks go to the Trash on the volume that holds them. The space returns when +the user empties the Trash; on an external disk, that disk's `.Trashes`. + +## Confirmed removal + +Never approve a removal with computer use (clicks, keys or accessibility +actions). The user approves in the app, or explicitly confirms the exact +paths and mode from `pwrdisk_removal_preview` before the destructive +`pwrdisk_remove` call. Trash or Recycle Bin recovery may be possible until +emptied, but is not guaranteed; permanent deletion cannot be undone through +PwrDisk. Both modes use the existing removal guards and Settings > Safety's +per-operation limit, 5% of each volume's capacity by default. Never bypass a +refusal, increase the setting or split batches to evade it. A window +refuses a mark that would take the list past the limit, and marks made +without one are checked when they reach it: only the person can mark past +it, in the window. Say so, and let them decide. + +MCP removal also requires interactive confirmation from the client (form +elicitation). An agent-supplied confirmation value does not establish human +consent. If the client cannot ask the user, use human review in PwrDisk; +never approve its buttons or confirmation keys through computer use. + +Capacity checks charge a symbolic link to its containing volume, not its +destination. + +## Read-only APFS path-set planning + +Use `pwrdisk_estimate` with the complete hypothetical `paths` list before +marking. It leaves the cart, scan root, displayed directory and pending +removal previews unchanged. Do not temporarily mark worktrees to measure a +set, and do not add individual directory reclaim estimates: clone groups +and hardlink names can span directories. + +`listed_bytes` counts directory allocation, even repeated clone blocks. +`shared_allocation` includes copies shared inside the selection and clone +allocation whose private size is unknown. `internal_duplicate_allocation` +reports repetitions within that whole set; neither is unique physical +usage or necessarily space retained outside it. Private allocation can +remain held by hardlink names outside the set. Reclaim bounds evaluate the +accepted union with existing guards; covered paths do not count twice. +Unavailable values are null, not measured zero. Apparent scans, disabled or +unsupported clone collection cannot supply physical bounds. Check metadata +and scan completeness, hidden filtering, depth, unreadable entries and +volume attribution. Cross-volume directory totals are not projected onto +the scanned volume's meter. + +For four full 12 GB clones, selecting three can reclaim almost nothing. +Selecting all four can unlock the shared 12 GB once. The tool returns +bounded retained clone-holder **directories** and bounds for adding each, +plus a single estimate for adding all returned peers. Individual peer +savings are alternatives, not additive. `additional` uses interval +subtraction, so modified clones can have wide additional bounds. A peer is +an inspection lead, never permission or a recommendation to remove it. +Establish ownership, uncommitted work and the user's intent before proposing +any worktree for removal. + +`peer_scope` groups peers by its direct child directories. Its default is +the selected paths' common parent; widen it within the current scan to look +elsewhere, then narrow it with another call if results are too broad. The +response bounds peer count and metadata visits and reports truncation. +Known unselected clone files are observations within the scan. Unresolved +reference counts have no owner paths; `references_not_seen_in_scan` is only +available when the relevant metadata walk and scan coverage are complete. +It does not identify external owners. Clone IDs cannot discover every +shared extent owner, especially after clones are modified. Snapshots, open +files, compression and changes after scanning can alter actual freed space; +never present these bounds as exact predictions. Trash usually frees space +only after the user empties it. + +## Owner-managed caches + +A cache name or regenerable classification is an inspection lead, never +permission to delete it. Cache cleanup is decided path by path. Call +`pwrdisk_removal_preview` with `owner_cleanup` and no decisions: it returns +one proposal per marked path with its status and problem, resolved owner, +version, executable, arguments, environment overrides, configured root, full +actual scope (including unselected siblings), effects, limitations, +recoverability, and whether Delete files is offered. Show every proposal and +let the user choose for each path `skip`, `owner` (only where offered) or +`delete_files`. Never choose for them and never suggest `delete_files` +yourself; inspect unknown runtime/install caches first, since nothing says +they are disposable. Then preview again with `decisions` naming every marked +path once, and `delete_files_mode` (`trash` or `permanent`, as the user +chose) when any path uses `delete_files`. Confirmation needs that preview's +exact paths and its own text: `RUN OWNER CLEANUP`, `DELETE CACHE FILES`, +`TRASH CACHE FILES`, or both intents joined with `AND`. Owner approval never +approves deleting files. Unavailable commands do not establish absent +software. An unsupported version, failed probe, or failed or cancelled owner +command never falls back to deleting files, and never to a shell command; +deleting them instead is a new preview the user decides. + +Cache tags and owner layouts on ancestors protect contained files and +subtrees too. All removal modes may return a preparing response while +inspection runs on a worker; retry only the read-only preview. Exported +lists keep marked paths, and raw script exports cannot replace owner cleanup. + +On macOS and Linux the initial adapters cover npm packages (9–11), npm's +separate npx cache (11.2–11.x), uv (0.11.x), pip (23–26) and Cypress (13–15), +only when their installed CLI resolves the selected cache. pnpm, Homebrew, +Playwright and Puppeteer remain explicit inspection-only owners because their +full command/configuration scopes are not supported. Windows command +launchers have no execution adapter yet. Neither containers nor volumes are +cleanup scopes. + +Each path gets its own result: succeeded, failed with a reason, cancelled +(possibly part done), skipped, or not reached after Stop. A command's +success reports the owner's exit result, not guaranteed savings. +Report allocation separately from observed volume availability before/after; +other activity, hardlinks, open files, APFS clones and snapshots can retain +blocks. PwrDisk always rescans after owner cleanup, even partial failure. +Never alter snapshots to force the reported allocation to become free space. + +## Developer artifacts and virtual machines + +Artifact identity and evidence are separate from cleanup suitability. +`detected` is inventory only. `suggested` means a plausible, relatively +lower-risk candidate to review, with local edits, active tools and the +cost of reinstalling or rebuilding still to check. Name conventions are +weaker evidence than recognized tool layouts. Whole tool homes and generic +`target`, `build`, `dist`, `bin` or `obj` names do not establish disposability; +review the specific detected subtree instead. + +VM/container disk images can contain unique work. Manage snapshots in the +owner app, never by removing individual files in a snapshot chain. Saved +memory or suspend state can usually be released by resuming the VM and +shutting it down normally; checkpoints may retain it. VM data stays a +detection even inside a directory named like a cache, and its displayed +size is not a promise of recovered space. Do not run an owner's destructive +cleanup command without explicit approval for that operation. diff --git a/skills/pwrdisk-free-space/references/windows.md b/skills/pwrdisk-free-space/references/windows.md new file mode 100644 index 00000000..bd9a4b77 --- /dev/null +++ b/skills/pwrdisk-free-space/references/windows.md @@ -0,0 +1,169 @@ +# PwrDisk on Windows + +What Windows keeps outside a file scan, what PwrDisk refuses, and what to +leave alone. Read with `skill://pwrdisk-free-space/SKILL.md`. + +## Working with the window + +On Windows `pwrdisk mcp` connects to an open PwrDisk window over a local +named pipe restricted to the current Windows account. The window is the +source of truth: scans, listings, searches and marks use its tree, and the +agent's marks appear there. `pwrdisk_show` moves its view and +`pwrdisk_review` opens its review screen; only the person confirms removal. +Without a window the agent scans and marks in its own session and can +launch a window for the handover. Agree the list before marking unless the +user gave a standing instruction. Never remove files yourself. + +When the window shows an SSH source, its paths belong to a Unix host and +use `/` on every client; backslashes and colons in names stay literal. +SSH windows answer only link identity and state requests. Switch to a local +source before using local scan, listing, marking or review tools. Windows +SSH servers are not supported. + +## Reading the numbers + +- **Sizes are allocation.** PwrDisk counts what each file occupies on disk, + which is less than its length for a compressed or sparse file and more for + a small one. +- **Cloud files take no space until downloaded.** OneDrive, iCloud for + Windows and Dropbox use placeholders; an online-only file costs nothing + locally. Deleting a synced file deletes it in the cloud and on every + device. To free local space without deleting, the user right-clicks it in + File Explorer and chooses "Free up space". +- **Space the files do not explain**: System Restore and shadow copies + (`vssadmin list shadowstorage`, from an elevated prompt), the page file, + `hiberfil.sys`, and the Recycle Bin of each drive. Changing any of these + is the user's decision in Settings or System Properties. +- **An elevated whole-drive scan** in the PwrDisk window reads the NTFS + master file table. It also counts alternate data streams, so a file's + size can be larger there than in a normal scan. The agent's scans are not + elevated; do not ask for elevation to look. + +## Refused by PwrDisk + +`pwrdisk_mark` keeps these back and says why: `Windows`, `Program Files`, +`Program Files (x86)`, `ProgramData`, `System Volume Information`, +`$Recycle.Bin`, `Recovery`, `Boot`, `bootmgr`, `pagefile.sys`, +`hiberfil.sys`, `swapfile.sys`, every user profile directly under +`C:\Users`, the home directory and anything holding it, mount points, and +names Windows would misread (trailing dots or spaces, device names such as +`NUL` or `COM1`, a colon). + +## Never propose + +- **WinSxS, the component store, and installers' caches** under Windows: + Disk Cleanup, Storage Sense or `DISM /Online /Cleanup-Image + /StartComponentCleanup`, which the user runs. +- **Installed programs**: uninstall from Settings › Apps, which the user + does. +- **`AppData\Roaming`, `AppData\Local\Packages`**: application settings and + Store apps' data. Only a specific, known cache inside `AppData\Local`, + with the app closed. +- **WSL and Docker Desktop disks** (`ext4.vhdx`, `docker_data.vhdx`): + deleting one destroys every distribution or container in it. Use + `wsl --unregister` (after `wsl --export`) or Docker's prune commands. +- **Synced folders** (`OneDrive`, `OneDrive - `, + `iCloudDrive`, `Dropbox`): see above. + +## Usually safe, with the owning tool first + +| what | where | prefer | +| --- | --- | --- | +| temp files | `%LOCALAPPDATA%\Temp` | Settings › System › Storage › Temporary files | +| app cache inspection | `%LOCALAPPDATA%\\Cache` | close the app; use its supported cleanup; unknown owners need inspection | +| browser caches | the browser's profile `Cache` folders | the browser's clear-cache setting | +| language caches | `%LOCALAPPDATA%\npm-cache`, `%USERPROFILE%\.cargo\registry`, `%LOCALAPPDATA%\pip\Cache` | the tool's clean command | +| build output | `target\`, `node_modules\`, `bin\`, `obj\` | check the checkout first (see the skill) | +| game libraries | `steamapps`, Epic and Xbox folders | uninstall in the launcher | + +## Recycle Bin + +Removal moves marks to the Recycle Bin of their drive. The space returns +when the user empties it. A network share has no Recycle Bin, so a removal +there may not be recoverable; tell the user before they mark one. + +## Confirmed removal + +Never approve a removal with computer use (clicks, keys or accessibility +actions). The user approves in the app, or explicitly confirms the exact +paths and mode from `pwrdisk_removal_preview` before the destructive +`pwrdisk_remove` call. Trash or Recycle Bin recovery may be possible until +emptied, but is not guaranteed; permanent deletion cannot be undone through +PwrDisk. Both modes use the existing removal guards and Settings > Safety's +per-operation limit, 5% of each volume's capacity by default. Never bypass a +refusal, increase the setting or split batches to evade it. A window +refuses a mark that would take the list past the limit, and marks made +without one are checked when they reach it: only the person can mark past +it, in the window. Say so, and let them decide. + +MCP removal also requires interactive confirmation from the client (form +elicitation). An agent-supplied confirmation value does not establish human +consent. If the client cannot ask the user, use human review in PwrDisk; +never approve its buttons or confirmation keys through computer use. + +Capacity checks charge a symbolic link or junction to its containing +volume, not its destination. Individual sparse and compressed files use +the same allocated size as directory scans. + +## Owner-managed caches + +A cache name or regenerable classification is an inspection lead, never +permission to delete it. Cache cleanup is decided path by path. Call +`pwrdisk_removal_preview` with `owner_cleanup` and no decisions: it returns +one proposal per marked path with its status and problem, resolved owner, +version, executable, arguments, environment overrides, configured root, full +actual scope (including unselected siblings), effects, limitations, +recoverability, and whether Delete files is offered. Show every proposal and +let the user choose for each path `skip`, `owner` (only where offered) or +`delete_files`. Never choose for them and never suggest `delete_files` +yourself; inspect unknown runtime/install caches first, since nothing says +they are disposable. Then preview again with `decisions` naming every marked +path once, and `delete_files_mode` (`trash` or `permanent`, as the user +chose) when any path uses `delete_files`. Confirmation needs that preview's +exact paths and its own text: `RUN OWNER CLEANUP`, `DELETE CACHE FILES`, +`TRASH CACHE FILES`, or both intents joined with `AND`. Owner approval never +approves deleting files. Unavailable commands do not establish absent +software. An unsupported version, failed probe, or failed or cancelled owner +command never falls back to deleting files, and never to a shell command; +deleting them instead is a new preview the user decides. + +Cache tags and owner layouts on ancestors protect contained files and +subtrees too. All removal modes may return a preparing response while +inspection runs on a worker; retry only the read-only preview. Exported +lists keep marked paths, and raw script exports cannot replace owner cleanup. + +On macOS and Linux the initial adapters cover npm packages (9–11), npm's +separate npx cache (11.2–11.x), uv (0.11.x), pip (23–26) and Cypress (13–15), +only when their installed CLI resolves the selected cache. pnpm, Homebrew, +Playwright and Puppeteer remain explicit inspection-only owners because their +full command/configuration scopes are not supported. Windows command +launchers have no execution adapter yet, and on Windows Delete files is not +offered either: it needs PwrDisk's check for programs using the path, which +runs only on macOS and Linux. A Windows cache cleanup can therefore only be +inspected and skipped. Neither containers nor volumes are cleanup scopes. + +Each path gets its own result: succeeded, failed with a reason, cancelled +(possibly part done), skipped, or not reached after Stop. A command's +success reports the owner's exit result, not guaranteed savings. +Report allocation separately from observed volume availability before/after; +other activity, hardlinks, open files, APFS clones and snapshots can retain +blocks. PwrDisk always rescans after owner cleanup, even partial failure. +Never alter snapshots to force the reported allocation to become free space. + +## Developer artifacts and virtual machines + +Artifact identity and evidence are separate from cleanup suitability. +`detected` is inventory only. `suggested` means a plausible, relatively +lower-risk candidate to review, with local edits, active tools and the +cost of reinstalling or rebuilding still to check. Name conventions are +weaker evidence than recognized tool layouts. Whole tool homes and generic +`target`, `build`, `dist`, `bin` or `obj` names do not establish disposability; +review the specific detected subtree instead. + +VM/container disk images can contain unique work. Manage snapshots in the +owner app, never by removing individual files in a snapshot chain. Saved +memory or suspend state can usually be released by resuming the VM and +shutting it down normally; checkpoints may retain it. VM data stays a +detection even inside a directory named like a cache, and its displayed +size is not a promise of recovered space. Do not run an owner's destructive +cleanup command without explicit approval for that operation. diff --git a/xtask/src/bundle.rs b/xtask/src/bundle.rs index 63e31134..6ff225df 100644 --- a/xtask/src/bundle.rs +++ b/xtask/src/bundle.rs @@ -1,23 +1,45 @@ //! `cargo xtask bundle`: the macOS app, from a release build. //! //! Plain Apple tools and nothing to install: `sips` and `iconutil` draw the -//! icon from its SVG, `codesign` signs, `ditto` zips the way Finder does +//! icon from its SVG, `actool` compiles its Icon Composer package when +//! Xcode 26's is there, `codesign` signs, `ditto` zips the way Finder does //! (keeping the signature's extended attributes), and `notarytool` and //! `stapler` notarize. Everything lands in `target/bundle/`. //! //! Signing is ad hoc unless an identity is given. An ad-hoc app runs on the //! Mac that built it; a downloaded one needs a Developer ID signature and //! notarization, or Gatekeeper stops it. +//! +//! `--universal` builds both Mac architectures and joins them with `lipo`, +//! as releases ship. `--app-only` stops at the signed app: release.yml's +//! unprivileged job hands that to the signing job, where `vpk pack` adds the +//! updater and `scripts/release/macos-dmg.sh` cuts the DMG. Without it the +//! app is also zipped and put in the same DMG, laid out by that script. +//! +//! `PWRDISK_VERSION` stamps another version than the crate's, for preview +//! builds (`0.12.0-pr.4`); Cargo.toml is left alone so `--locked` holds. use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; -const APP: &str = "disktree.app"; -const EXECUTABLE: &str = "disktree"; +const APP: &str = "PwrDisk.app"; +const EXECUTABLE: &str = "pwrdisk"; /// What the binary is built for at least; `LSMinimumSystemVersion` in /// `packaging/macos/Info.plist.in` says the same, and GPUI needs 10.15.7. const DEPLOYMENT_TARGET: &str = "11.0"; +/// What `--universal` joins, in the order `lipo` takes them. +const TARGETS: [&str; 2] = ["aarch64-apple-darwin", "x86_64-apple-darwin"]; +/// The DMG's layout, shared with release.yml's signing job. +const DMG_SCRIPT: &str = "scripts/release/macos-dmg.sh"; +/// The notices the app carries: its license, every crate compiled in +/// (also shown by Help › Third-Party Notices), and Velopack's native +/// binaries', since `vpk pack` adds `UpdateMac` to the released app. +const NOTICES: [(&str, &str); 3] = [ + ("LICENSE", "LICENSE"), + ("THIRD_PARTY_LICENSES", "THIRD_PARTY_LICENSES"), + ("licenses/velopack.txt", "VELOPACK-NOTICES.txt"), +]; /// The iconset `iconutil` expects: each point size at 1x and 2x. const ICON_SIZES: [(&str, u32); 10] = [ @@ -40,6 +62,10 @@ struct Options { /// when absent. identity: Option, notarize: bool, + /// Both architectures, joined with `lipo`. + universal: bool, + /// Stop at the signed app: no zip, no DMG. + app_only: bool, } fn parse(args: &[String]) -> Result { @@ -59,6 +85,8 @@ fn parse(args: &[String]) -> Result { options.identity = Some(identity.clone()); } "--notarize" => options.notarize = true, + "--universal" => options.universal = true, + "--app-only" => options.app_only = true, other => return Err(format!("unknown bundle option {other}")), } } @@ -67,6 +95,13 @@ fn parse(args: &[String]) -> Result { signatures only" .into()); } + // Apple notarizes an archive, and --app-only makes none; release.yml's + // signing job notarizes through vpk instead. + if options.notarize && options.app_only { + return Err( + "--notarize needs the zip and DMG that --app-only skips".into() + ); + } Ok(options) } @@ -76,23 +111,36 @@ pub fn bundle(args: &[String]) -> Result<(), String> { } let options = parse(args)?; let root = workspace_root(); - let version = env!("CARGO_PKG_VERSION"); + let version = std::env::var("PWRDISK_VERSION") + .ok() + .filter(|version| !version.trim().is_empty()) + .unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_owned()); let out = root.join("target/bundle"); let app = out.join(APP); + fs::create_dir_all(&out) + .map_err(|err| format!("cannot create {}: {err}", out.display()))?; // The target directory is named rather than inherited: a // `CARGO_TARGET_DIR` or `build.target-dir` elsewhere would put the fresh // binary there and leave a stale one here to be bundled. let target = root.join("target"); - let cargo = option_env!("CARGO").unwrap_or("cargo"); - tool( - Command::new(cargo) - .current_dir(&root) - .args(["build", "--release", "--locked", "-p", "disktree-app"]) - .arg("--target-dir") - .arg(&target) - .env("MACOSX_DEPLOYMENT_TARGET", DEPLOYMENT_TARGET), - )?; + let (built, arch) = if options.universal { + let mut lipo = Command::new("lipo"); + let joined = out.join(format!("{EXECUTABLE}-universal")); + lipo.arg("-create").arg("-output").arg(&joined); + for triple in TARGETS { + build(&root, &target, Some(triple))?; + lipo.arg(target.join(triple).join("release").join(EXECUTABLE)); + } + tool(&mut lipo)?; + (joined, "universal") + } else { + build(&root, &target, None)?; + ( + target.join("release").join(EXECUTABLE), + std::env::consts::ARCH, + ) + }; // Only ever the bundle this task made, never anything else in target/. if app.exists() { @@ -108,15 +156,28 @@ pub fn bundle(args: &[String]) -> Result<(), String> { } let binary = macos.join(EXECUTABLE); - copy(&target.join("release").join(EXECUTABLE), &binary)?; + copy(&built, &binary)?; // Local symbols only: the backtrace of a panic still names functions. tool(Command::new("strip").arg("-x").arg(&binary))?; + icon( + &root.join("packaging/macos/AppIcon.svg"), + &out, + &resources.join("AppIcon.icns"), + )?; + let catalog = icon_catalog(&root, &out, &resources)?; + let plist = fs::read_to_string(root.join("packaging/macos/Info.plist.in")) .map_err(|err| format!("cannot read the Info.plist template: {err}"))?; + for (from, to) in NOTICES { + copy(&root.join(from), &resources.join(to))?; + } write( &contents.join("Info.plist"), - &plist.replace("@VERSION@", version), + &plist.replace("@VERSION@", short_version(&version)).replace( + ICON_CATALOG_MARKER, + if catalog { ICON_CATALOG_KEYS } else { "" }, + ), )?; tool( Command::new("plutil") @@ -124,18 +185,13 @@ pub fn bundle(args: &[String]) -> Result<(), String> { .arg(contents.join("Info.plist")), )?; - icon( - &root.join("packaging/macos/AppIcon.svg"), - &out, - &resources.join("AppIcon.icns"), - )?; - sign(&app, options.identity.as_deref())?; + if options.app_only { + println!("\n{}", app.display()); + return Ok(()); + } - let zip = out.join(format!( - "disktree-{version}-{}-macos.zip", - std::env::consts::ARCH - )); + let zip = out.join(format!("pwrdisk-{version}-{arch}-macos.zip")); archive(&app, &zip)?; if options.notarize { @@ -151,10 +207,57 @@ pub fn bundle(args: &[String]) -> Result<(), String> { )?; } - println!("\n{}\n{}", app.display(), zip.display()); + let dmg = out.join(format!("PwrDisk-{version}-{arch}.dmg")); + // The script signs only through a notary keychain profile, which local + // builds do not have, so the DMG is signed and notarized here. + tool( + Command::new(root.join(DMG_SCRIPT)) + .env("DMG_VERSION", &version) + .arg(&app) + .arg(&dmg), + )?; + if let Some(identity) = &options.identity { + tool( + Command::new("codesign") + .args(["--force", "--timestamp", "--sign", identity]) + .arg(&dmg), + )?; + if options.notarize { + notarize(&dmg)?; + tool(Command::new("xcrun").args(["stapler", "staple"]).arg(&dmg))?; + } + } + + println!("\n{}\n{}\n{}", app.display(), zip.display(), dmg.display()); Ok(()) } +/// A release build of the app, for `triple` or the host. +fn build( + root: &Path, + target: &Path, + triple: Option<&str>, +) -> Result<(), String> { + let cargo = option_env!("CARGO").unwrap_or("cargo"); + let mut command = Command::new(cargo); + command + .current_dir(root) + .args(["build", "--release", "--locked", "-p", "disktree-app"]) + .arg("--target-dir") + .arg(target) + .env("MACOSX_DEPLOYMENT_TARGET", DEPLOYMENT_TARGET); + if let Some(triple) = triple { + command.args(["--target", triple]); + } + tool(&mut command) +} + +/// `0.12.0` from `0.12.0-pr.4`: `CFBundleShortVersionString` takes three +/// numbers only, and macOS compares versions by it. +fn short_version(version: &str) -> &str { + version.split(['-', '+']).next().unwrap_or(version) +} + /// `AppIcon.icns` from the SVG, through an iconset of every size. fn icon(svg: &Path, scratch: &Path, icns: &Path) -> Result<(), String> { let iconset = scratch.join("AppIcon.iconset"); @@ -186,6 +289,114 @@ fn icon(svg: &Path, scratch: &Path, icns: &Path) -> Result<(), String> { ) } +/// The token in the plist template that the catalog's keys replace. Left +/// empty without a catalog, its line keeps only its indent. +const ICON_CATALOG_MARKER: &str = "@ICON_CATALOG@"; +/// What macOS 26 reads the icon by: the name actool gave it in `Assets.car`. +const ICON_CATALOG_KEYS: &str = + "CFBundleIconName\n\tIcon"; + +/// `Assets.car` from the Icon Composer package, when Xcode 26's actool is at +/// hand; whether it was made. +/// +/// macOS 26 draws an app's icon from this catalog: its own shape, the glass +/// edge, and the Dark, Clear and Tinted looks. Handed only a legacy `.icns` +/// it normalizes that instead, and 26.6.2 has drawn a padded one on a light +/// plate. macOS 15 and earlier never open the catalog and keep reading +/// `AppIcon.icns`, which has every size they draw; actool derives an icns +/// too, but with four sizes, so it is left where it was compiled. Without +/// that actool the bundle ships the icns alone, and says so: a Mac with the +/// Command Line Tools, or an older Xcode, still builds. +fn icon_catalog( + root: &Path, + scratch: &Path, + resources: &Path, +) -> Result { + match actool_version() { + Some(major) if major >= 26 => {} + found => { + let found = found.map_or_else( + || "no actool".to_owned(), + |major| format!("actool {major}"), + ); + println!( + "note: {found}; macOS 26 will draw AppIcon.icns without \ + Liquid Glass. Xcode 26 compiles packaging/macos/AppIcon.icon." + ); + return Ok(false); + } + } + + // actool resolves `--app-icon Icon` by the package's basename: under any + // other name it exits 0 and writes no icon at all. So the package is + // copied under that name, and gets its layer drawn from the SVG there. + let package = scratch.join("Icon.icon"); + let compiled = scratch.join("AppIcon.catalog"); + for dir in [&package, &compiled] { + if dir.exists() { + fs::remove_dir_all(dir).map_err(|err| { + format!("cannot clear {}: {err}", dir.display()) + })?; + } + } + let assets = package.join("Assets"); + for dir in [&assets, &compiled] { + fs::create_dir_all(dir) + .map_err(|err| format!("cannot create {}: {err}", dir.display()))?; + } + copy( + &root.join("packaging/macos/AppIcon.icon/icon.json"), + &package.join("icon.json"), + )?; + tool( + Command::new("sips") + .args(["-s", "format", "png", "-z", "1024", "1024"]) + .arg(root.join("packaging/macos/AppGlyph.svg")) + .arg("--out") + .arg(assets.join("glyph.png")) + .stdout(Stdio::null()), + )?; + // The invocation electron-builder settled on for the same package, so + // the catalog is the one other apps on the Mac ship. + tool( + Command::new("xcrun") + .arg("actool") + .arg(&package) + .arg("--compile") + .arg(&compiled) + .args(["--output-format", "human-readable-text"]) + .args(["--notices", "--warnings"]) + .arg("--output-partial-info-plist") + .arg(compiled.join("Info.plist")) + .args(["--app-icon", "Icon", "--include-all-app-icons"]) + .args(["--enable-on-demand-resources", "NO"]) + .args(["--development-region", "en"]) + .args(["--target-device", "mac"]) + .args(["--minimum-deployment-target", DEPLOYMENT_TARGET]) + .args(["--platform", "macosx"]), + )?; + copy(&compiled.join("Assets.car"), &resources.join("Assets.car"))?; + Ok(true) +} + +/// The major version of the actool `xcrun` finds, if it finds one. +fn actool_version() -> Option { + let output = Command::new("xcrun") + .args(["actool", "--version"]) + .stdin(Stdio::null()) + .stderr(Stdio::null()) + .output() + .ok()?; + if !output.status.success() { + return None; + } + // A plist, with the version under `short-bundle-version`. + let text = String::from_utf8_lossy(&output.stdout); + let after = text.split("short-bundle-version").nth(1)?; + let value = after.split("").nth(1)?.split("").next()?; + value.split('.').next()?.parse().ok() +} + /// Sign the bundle, then check the signature holds. /// /// A real identity gets the hardened runtime and a secure timestamp, both of @@ -227,7 +438,7 @@ fn archive(app: &Path, zip: &Path) -> Result<(), String> { ) } -/// Submit `zip` and wait for Apple's verdict. +/// Submit `zip` (or a DMG) and wait for Apple's verdict. /// /// Credentials come from the environment, never the command line, so they /// stay out of shell history and CI logs: `NOTARY_PROFILE`, a keychain @@ -327,6 +538,94 @@ mod tests { ); } + #[test] + fn app_only_stops_before_notarizing() { + let options = parse(&args(&["--universal", "--app-only"])) + .expect("an unsigned universal app"); + assert!(options.universal && options.app_only); + let error = parse(&args(&[ + "--sign", + "Developer ID Application: X", + "--notarize", + "--app-only", + ])) + .expect_err("nothing to notarize"); + assert!(error.contains("--app-only"), "{error}"); + } + + #[test] + fn the_short_version_drops_a_prerelease() { + assert_eq!(short_version("0.12.0"), "0.12.0"); + assert_eq!(short_version("0.12.0-pr.4"), "0.12.0"); + assert_eq!(short_version("0.12.0-dev.7+abc"), "0.12.0"); + } + + /// dmg-layout.py places the icons and generate-dmg-background.swift + /// paints the arrow between them; the committed PNG is the window's + /// size. + #[test] + fn the_dmg_layout_matches_its_background() { + let root = workspace_root(); + let read = |path: &str| { + fs::read_to_string(root.join(path)).expect("a packaging file") + }; + let layout = read("scripts/release/dmg-layout.py"); + let swift = read("scripts/release/generate-dmg-background.swift"); + for (python, swift_name, value) in [ + ("WINDOW_SIZE = (660, 400)", "width", 660), + ("WINDOW_SIZE = (660, 400)", "height", 400), + ("ICON_SIZE = 112", "iconSize", 112), + ("\"PwrDisk.app\": (170, 230)", "appIconX", 170), + ("\"Applications\": (500, 230)", "applicationsX", 500), + ("\"PwrDisk.app\": (170, 230)", "iconY", 230), + ] { + assert!(layout.contains(python), "dmg-layout.py: no {python}"); + assert!( + swift + .lines() + .any(|line| line == format!("let {swift_name} = {value}")), + "generate-dmg-background.swift: {swift_name} is not {value}" + ); + } + let png = fs::read(root.join("packaging/dmg/background.png")) + .expect("the background"); + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "not a PNG"); + // IHDR's width and height, big-endian, at bytes 16..24. + let size = |at: usize| { + u32::from_be_bytes(png[at..at + 4].try_into().expect("4 bytes")) + }; + assert_eq!((size(16), size(20)), (660, 400)); + } + + #[cfg(unix)] + #[test] + fn the_dmg_script_parses_and_wants_two_or_three_arguments() { + let script = workspace_root().join(DMG_SCRIPT); + let syntax = Command::new("bash") + .arg("-n") + .arg(&script) + .status() + .expect("bash"); + assert!(syntax.success(), "bash -n {DMG_SCRIPT}"); + let usage = Command::new("bash") + .arg(&script) + .arg("only-one") + .output() + .expect("bash"); + assert_eq!(usage.status.code(), Some(2)); + assert!( + String::from_utf8_lossy(&usage.stderr) + .contains("usage: macos-dmg.sh") + ); + } + + #[test] + fn the_notices_the_app_carries_exist() { + for (from, _) in NOTICES { + assert!(workspace_root().join(from).is_file(), "{from}"); + } + } + #[test] fn the_plist_template_names_the_executable_and_takes_the_version() { let plist = include_str!("../../packaging/macos/Info.plist.in"); @@ -336,4 +635,28 @@ mod tests { plist.contains(&format!("{DEPLOYMENT_TARGET}")) ); } + + /// The catalog's keys go in only when the catalog does: a bundle that + /// names an icon it does not carry shows none on macOS 26. + #[test] + fn the_plist_template_takes_the_catalog_keys_from_the_bundle() { + let plist = include_str!("../../packaging/macos/Info.plist.in"); + assert!(plist.contains(ICON_CATALOG_MARKER)); + assert!(!plist.contains("CFBundleIconName")); + let without = plist.replace(ICON_CATALOG_MARKER, ""); + assert!(!without.contains(ICON_CATALOG_MARKER)); + let with = plist.replace(ICON_CATALOG_MARKER, ICON_CATALOG_KEYS); + assert!(with.contains("CFBundleIconName\n\tIcon")); + } + + /// The package names the layer the bundle draws from the SVG, and fills + /// the tile with the mark's own background. + #[test] + fn the_icon_package_is_the_glyph_on_the_marks_background() { + let manifest = + include_str!("../../packaging/macos/AppIcon.icon/icon.json"); + assert!(manifest.contains(r#""image-name" : "glyph.png""#)); + // #1a1b26, as assets/disktree.svg paints it. + assert!(manifest.contains("srgb:0.10196,0.10588,0.14902,1.00000")); + } } diff --git a/xtask/src/licenses.rs b/xtask/src/licenses.rs new file mode 100644 index 00000000..2010f7ae --- /dev/null +++ b/xtask/src/licenses.rs @@ -0,0 +1,95 @@ +//! `THIRD_PARTY_LICENSES`: what Help › Third-Party Notices shows and the +//! bundle ships. A header, the components cargo cannot see +//! (`licenses/bundled.txt`), the crates in Velopack's native binaries +//! (`licenses/velopack.txt`, from scripts/release/velopack-notices.sh), then +//! every crate PwrDisk compiles in, from cargo-about, as `PwrRoute` writes its +//! own; `--check` is the gate that it is current. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +pub fn licenses(check: bool) -> Result<(), String> { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .ok_or("xtask has no parent directory")? + .to_path_buf(); + let target = root.join("target"); + fs::create_dir_all(&target).map_err(|err| err.to_string())?; + // Written to a file, not read from stdout: under PowerShell, + // cargo-about refuses to write to a pipe. + let generated = target.join("cargo-about.txt"); + let out = Command::new("cargo") + .args([ + "about", + "generate", + "-c", + "licenses/about.toml", + "licenses/about.hbs", + "--workspace", + // --locked, not --frozen: a fresh runner has not downloaded the + // other targets' crates, whose license files this reads. + "--locked", + "--fail", + "-o", + ]) + .arg(&generated) + .current_dir(&root) + .output() + .map_err(|err| { + format!( + "cargo-about is required \ + (`cargo install --locked cargo-about`): {err}" + ) + })?; + if !out.status.success() { + return Err(format!( + "cargo about generate failed:\n{}", + String::from_utf8_lossy(&out.stderr) + )); + } + let crates = read(&generated)?; + let bundled = read(&root.join("licenses/bundled.txt"))?; + let velopack = read(&root.join("licenses/velopack.txt"))?; + let notice = normalize(&format!( + "PwrDisk Third-Party Licenses\n\ + ============================\n\ + \n\ + Generated by `cargo xtask licenses` from Cargo.lock (cargo-about),\n\ + licenses/bundled.txt and licenses/velopack.txt. Do not edit this\n\ + file by hand.\n\ + \n\ + PwrDisk's own license, which carries disktree's, is in LICENSE.\n\ + \n\ + {bundled}\n{velopack}\n{crates}" + )); + let path = root.join("THIRD_PARTY_LICENSES"); + if check { + let current = normalize(&read(&path)?); + if current != notice { + let fresh = target.join("THIRD_PARTY_LICENSES.generated"); + fs::write(&fresh, ¬ice).map_err(|err| err.to_string())?; + return Err(format!( + "THIRD_PARTY_LICENSES is out of date: run `cargo xtask \ + licenses` and commit it (fresh copy: {})", + fresh.display() + )); + } + println!("THIRD_PARTY_LICENSES is current"); + } else { + fs::write(&path, notice).map_err(|err| err.to_string())?; + println!("wrote {}", path.display()); + } + Ok(()) +} + +fn read(path: &PathBuf) -> Result { + fs::read_to_string(path) + .map_err(|err| format!("could not read {}: {err}", path.display())) +} + +/// LF line endings and exactly one trailing newline: some crates ship CRLF +/// license files. +fn normalize(text: &str) -> String { + text.replace("\r\n", "\n").trim_end().to_owned() + "\n" +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 53cd0928..592d1b44 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,4 +1,4 @@ -//! Check and packaging entry points for disktree. +//! Check and packaging entry points for PwrDisk. //! //! Each gate is reachable on its own (`cargo xtask fmt`) and through the //! aggregate CI runs (`cargo xtask lint`), mirroring how omatrack exposes every @@ -7,7 +7,9 @@ //! signal CI gives. mod bundle; +mod licenses; mod portable; +mod release; use std::process::{Command, ExitCode, Stdio}; @@ -19,12 +21,21 @@ tasks: fmt rustfmt --check over the workspace fmt-fix rustfmt in place clippy clippy --workspace --all-targets -- -D warnings - test cargo test --workspace + test cargo test --workspace, then (Unix) the release scripts' tests ci lint, then test - portable Linux: desktop executable with static x86_64/ARM64 scanners\n bundle macOS: target/bundle/disktree.app and its zip + licenses [--check] + write THIRD_PARTY_LICENSES with cargo-about, or check it is + current + portable Linux: desktop executable with static x86_64/ARM64 scanners + bundle macOS: target/bundle/PwrDisk.app, its zip and a DMG --sign IDENTITY sign with a Developer ID (default: ad hoc) --notarize notarize and staple; needs NOTARY_PROFILE, or NOTARY_KEY, NOTARY_KEY_ID and NOTARY_ISSUER + --universal both architectures, joined with lipo + --app-only stop at the signed app: no zip, no DMG + release-check --tag vX.Y.Z [--notes-file PATH] + the tag, Cargo.toml version and CHANGELOG.md agree; optionally + write that version's notes "; fn main() -> ExitCode { @@ -39,7 +50,9 @@ fn main() -> ExitCode { "test" => test(), "ci" => fmt(false).and_then(|()| clippy()).and_then(|()| test()), "bundle" => bundle::bundle(&args[1..]), + "release-check" => release::check(&args[1..]), "portable" => portable::build(), + "licenses" => licenses::licenses(args.iter().any(|a| a == "--check")), "help" | "-h" | "--help" => { println!("{USAGE}"); return ExitCode::SUCCESS; @@ -79,7 +92,26 @@ fn clippy() -> Result<(), String> { } fn test() -> Result<(), String> { - run(&["test", "--workspace"]) + run(&["test", "--workspace"])?; + // The DMG layout and the signing keychain's cleanup, with `security` + // and `xcrun` mocked: no credentials, so they run anywhere with a + // Python 3. Windows has neither the tools nor the scripts' shell. + if cfg!(unix) { + let status = Command::new("python3") + .args(["-B", "-m", "unittest", "discover", "-s"]) + .arg( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../scripts/release"), + ) + .args(["-p", "*_test.py"]) + .stdin(Stdio::null()) + .status() + .map_err(|err| format!("could not start python3: {err}"))?; + if !status.success() { + return Err("the release scripts' tests failed".into()); + } + } + Ok(()) } fn run(args: &[&str]) -> Result<(), String> { diff --git a/xtask/src/portable.rs b/xtask/src/portable.rs index b101dfb8..fe004829 100644 --- a/xtask/src/portable.rs +++ b/xtask/src/portable.rs @@ -61,10 +61,10 @@ pub fn build() -> Result<(), String> { target.join(triple).join("release/disktree-scan"), )); } - let output = target.join("portable/disktree"); + let output = target.join("portable/pwrdisk"); std::fs::create_dir_all(output.parent().unwrap()) .map_err(|e| e.to_string())?; - std::fs::copy(target.join("release/disktree"), &output) + std::fs::copy(target.join("release/pwrdisk"), &output) .map_err(|e| e.to_string())?; // strip rewrites ELF and discards overlays, so it must precede embedding. let status = Command::new("strip") diff --git a/xtask/src/release.rs b/xtask/src/release.rs new file mode 100644 index 00000000..baa08a54 --- /dev/null +++ b/xtask/src/release.rs @@ -0,0 +1,137 @@ +//! `cargo xtask release-check`: the tag, the workspace version and +//! `CHANGELOG.md` agree before anything is built or signed. +//! +//! The changelog section is the release's notes: release.yml writes it with +//! `--notes-file` for the GitHub release and for `vpk pack --releaseNotes`, +//! which Velopack shows beside an update. + +use std::fs; +use std::path::{Path, PathBuf}; + +pub fn check(args: &[String]) -> Result<(), String> { + let mut tag = std::env::var("RELEASE_TAG").ok(); + let mut notes_file = None; + let mut args = args.iter(); + while let Some(arg) = args.next() { + match arg.as_str() { + "--tag" => tag = args.next().cloned(), + "--notes-file" => notes_file = args.next().map(PathBuf::from), + other => return Err(format!("unknown argument {other}")), + } + } + let tag = tag + .filter(|tag| !tag.is_empty()) + .ok_or("needs --tag vX.Y.Z (or RELEASE_TAG)")?; + let root = root(); + let version = workspace_version(&read(&root.join("Cargo.toml"))?) + .ok_or("no version in Cargo.toml's [workspace.package]")?; + if tag != format!("v{version}") { + return Err(format!( + "tag {tag} does not match the Cargo.toml workspace version \ + {version}" + )); + } + let changelog = read(&root.join("CHANGELOG.md"))?; + let notes = changelog_section(&changelog, &version).ok_or_else(|| { + format!("CHANGELOG.md has no `## v{version}` section") + })?; + if notes.trim().is_empty() { + return Err(format!("CHANGELOG.md's `## v{version}` section is empty")); + } + if let Some(path) = notes_file { + fs::write(&path, notes) + .map_err(|err| format!("cannot write {}: {err}", path.display()))?; + } + println!("release metadata agrees for {tag}"); + Ok(()) +} + +/// The lines under `## vX.Y.Z` (or `## X.Y.Z`), up to the next `## `. +fn changelog_section(changelog: &str, version: &str) -> Option { + let mut lines = changelog.lines(); + lines.find(|line| { + line.strip_prefix("## ") + .map(|heading| heading.trim_start_matches('v')) + .and_then(|heading| heading.split_whitespace().next()) + == Some(version) + })?; + let body: Vec<&str> = + lines.take_while(|line| !line.starts_with("## ")).collect(); + Some(body.join("\n").trim().to_owned() + "\n") +} + +/// `version` under `[workspace.package]`: the one every crate inherits. +fn workspace_version(manifest: &str) -> Option { + let mut in_package = false; + for line in manifest.lines() { + let line = line.trim(); + if line.starts_with('[') { + in_package = line == "[workspace.package]"; + } else if in_package + && let Some(version) = line.strip_prefix("version = ") + { + return Some(version.trim_matches('"').to_owned()); + } + } + None +} + +fn root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .map_or_else(|| PathBuf::from("."), Path::to_path_buf) +} + +fn read(path: &Path) -> Result { + fs::read_to_string(path) + .map_err(|err| format!("cannot read {}: {err}", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + + const CHANGELOG: &str = "# Changelog\n\n## Unreleased\n\n## v0.2.0\n\n\ + - Second.\n\n## v0.1.0 - 2026-10-13\n\n- First.\n"; + + #[test] + fn finds_a_changelog_section() { + assert_eq!( + changelog_section(CHANGELOG, "0.1.0").as_deref(), + Some("- First.\n") + ); + assert_eq!( + changelog_section(CHANGELOG, "0.2.0").as_deref(), + Some("- Second.\n") + ); + assert_eq!(changelog_section(CHANGELOG, "0.3.0"), None); + } + + #[test] + fn a_prefix_is_not_a_match() { + assert_eq!(changelog_section(CHANGELOG, "0.1"), None); + } + + #[test] + fn reads_only_the_workspace_version() { + let manifest = "[package]\nversion = \"9.9.9\"\n\n\ + [workspace.package]\nversion = \"0.12.0\"\n"; + assert_eq!(workspace_version(manifest).as_deref(), Some("0.12.0")); + assert_eq!(workspace_version("[package]\nversion = \"1\"\n"), None); + } + + /// The version this checkout would release has notes to release with. + #[test] + fn this_version_has_a_changelog_section() { + let root = root(); + let version = + workspace_version(&read(&root.join("Cargo.toml")).unwrap()) + .unwrap(); + let changelog = read(&root.join("CHANGELOG.md")).unwrap(); + assert!( + changelog_section(&changelog, &version) + .is_some_and(|notes| !notes.trim().is_empty()), + "CHANGELOG.md needs a `## v{version}` section" + ); + } +}