diff --git a/.config/cargo-ci.toml b/.config/cargo-ci.toml new file mode 100644 index 000000000..93a48332f --- /dev/null +++ b/.config/cargo-ci.toml @@ -0,0 +1,37 @@ +# The Workspace gate's additions to .config/cargo-dev.toml (scripts/ci-workspace-tests.sh passes both). The gate runs +# every test of these crates, and their tests spend nearly all their time in sample and pixel loops, which run several +# times faster at opt-level 1; locally they stay at 0, so an edit to them rebuilds fast. craft-pdf (R6 hash and AES-CBC +# loops), craft-pkcs7 and craft-odf (PBKDF2 rounds, monomorphised in the crate) and craft-cms (CLUT builds) run their +# own hot loops in tests, so they take part too. +[profile.dev.package.craft-audio-dsp] +opt-level = 1 + +[profile.dev.package.craft-audio] +opt-level = 1 + +[profile.dev.package.craft-media] +opt-level = 1 + +[profile.dev.package.craft-image-codecs] +opt-level = 1 + +[profile.dev.package.craft-imaging] +opt-level = 1 + +[profile.dev.package.craft-pdf] +opt-level = 1 + +[profile.dev.package.craft-pkcs7] +opt-level = 1 + +[profile.dev.package.craft-odf] +opt-level = 1 + +[profile.dev.package.craft-cms] +opt-level = 1 + +# The runtime under every screen test: each frame of a fixture runs its pass, layout, focus and access tree. At +# opt-level 2 a suite trial runs about 40 percent fewer instructions than at 0 (Table activation 19.8 G to 11.9 G); +# opt-level 1 gives about 30 percent. Every UI crate waits for its compile, which grows by about a minute. +[profile.dev.package.craft-ui-contract] +opt-level = 2 diff --git a/.config/cargo-dev.toml b/.config/cargo-dev.toml new file mode 100644 index 000000000..cec2fbc4f --- /dev/null +++ b/.config/cargo-dev.toml @@ -0,0 +1,25 @@ +# The dev-build tuning every craft-libs test build uses: `tools/cl` passes it to each cargo command locally, and +# scripts/ci-workspace-tests.sh passes it (`--config .config/cargo-dev.toml`) to the Workspace gate's builds, so local +# and CI builds are the same. It lives here and not in Cargo.toml's `[profile]` table, which the CI cache key hashes; +# the per-crate levels Cargo.toml sets (craft-video, craft-affinity) still apply. +# +# lto off: with cargo's default, rustc runs thin-local LTO across every optimised crate's codegen units on each rebuild; +# off, a one-line edit re-optimises only the changed units. Dependencies build at opt-level 2, once per target dir and +# cache entry: egui, text shaping, hashing and codecs run in nearly every test. +# craft-theme, craft-behavior and craft-proof run in every screen-test frame or in dictionary-sized tests and are rarely +# edited, so they build at opt-level 1; every other workspace crate stays at 0, where rustc shares generic +# instantiations across crates and an edit to the runtime (craft-ui-contract) rebuilds in seconds. +[profile.dev] +lto = "off" + +[profile.dev.package."*"] +opt-level = 2 + +[profile.dev.package.craft-theme] +opt-level = 1 + +[profile.dev.package.craft-behavior] +opt-level = 1 + +[profile.dev.package.craft-proof] +opt-level = 1 diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 66897e207..01b258e23 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -69,7 +69,8 @@ workflows: '.github/workflows/menu.yml': - 'actions/checkout@v7.0.1' - 'dtolnay/rust-toolchain@stable' - '.github/workflows/nightly.yml': [] + '.github/workflows/nightly.yml': + - 'step-security/harden-runner@v2.22.4' '.github/workflows/pcraft-format.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' diff --git a/.github/workflows/crw.yml b/.github/workflows/crw.yml index 1d2b4f389..3e9b430d6 100644 --- a/.github/workflows/crw.yml +++ b/.github/workflows/crw.yml @@ -52,13 +52,22 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - name: Cache the CC0 sample files - uses: actions/cache@v6.1.0 + # Pull requests restore the entry main or next saved and never write their own: the same + # files saved once per pull request took a share of the 10 GB cache budget. + - name: Restore the CC0 sample files + id: samples + uses: actions/cache/restore@v6.1.0 with: path: ${{ runner.temp }}/crw-samples key: crw-samples-${{ hashFiles('crates/crw/tests/samples.json') }} - name: Fetch the pinned CC0 sample files (raw.pixls.us) run: python scripts/fetch-crw-samples.py "$RUNNER_TEMP/crw-samples" + - name: Save the CC0 sample files + if: github.event_name != 'pull_request' && steps.samples.outputs.cache-hit != 'true' + uses: actions/cache/save@v6.1.0 + with: + path: ${{ runner.temp }}/crw-samples + key: ${{ steps.samples.outputs.cache-primary-key }} - run: cargo test -p craft-crw --release --locked --lib -- integration::samples --nocapture env: CRAFT_CRW_SAMPLES: ${{ runner.temp }}/crw-samples diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index ed9d36127..5cc803266 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -31,4 +31,32 @@ jobs: cache-paths: .test-inputs/photocraft/corpus cache-key: photocraft-corpus cache-key-files: scripts/ci-test-inputs.sh - command: cargo nextest run --workspace --all-features --locked --profile ci + # The gate's build (the same targets and profile overrides), with every test at its full count. + command: bash scripts/ci-workspace-tests.sh full + + # The scheduled run is main's; this starts the full tests above on next too, where the gate + # runs the same fractions. It also starts one Workspace run on next a day that nothing cancels + # (pull requests run the Linux legs only, and pushes to next cancel each other's runs): next's + # macOS and Windows legs then run in full at least once a day, and its Linux leg builds from + # source and saves next's own workspace-crates cache entry, which pull requests into next + # restore. Main gets the same from workspace.yml's own scheduled runs. The only job here with + # `actions: write`; it checks out and runs nothing from the repository. + workspace-next: + name: Workspace on next + if: github.event_name == 'schedule' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + actions: write + steps: + - name: Harden runner + uses: step-security/harden-runner@v2.22.4 + with: + egress-policy: audit + - name: Start the Workspace workflow and these full tests on next + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + run: | + gh workflow run workspace.yml --repo "$REPO" --ref next + gh workflow run nightly.yml --repo "$REPO" --ref next diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index c583402a5..33106085a 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -16,19 +16,20 @@ permissions: contents: read concurrency: - # A pull request, and main, each have one group, so a newer push cancels the run it supersedes; - # the newest push's run still tests everything before it. Every other run (a release tag, a - # manual run, the scheduled run) gets a group of its own and is neither cancelled nor replaced - # while queued: a release run always finishes, and the scheduled run saves the caches. - group: workspace-${{ (github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main') && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' }} + # A pull request, main and next each have one group, so a newer push cancels the run it + # supersedes; the newest push's run still tests everything before it. Every other run (a release + # tag, a manual run, the scheduled run, nightly.yml's run on next) gets a group of its own and is + # neither cancelled nor replaced while queued: a release run always finishes, the scheduled run + # saves the caches, and next gets one complete macOS and Windows run a day. + group: workspace-${{ (github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'push' && github.ref == 'refs/heads/next') && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'push' && github.ref == 'refs/heads/next' }} jobs: # Whether this run needs the macOS and Windows legs, and which tests every leg runs - # (craft-common-actions' select-platforms). On a pull request the macOS and Windows legs run only - # when it can change platform behaviour: a crate with platform cfg code or one that depends on - # it, the build setup, or a file outside the crates. The tests are those of the crates a change - # reaches: the crates that own a changed file, the crates whose Cargo.toml declares a read of it + # (craft-common-actions' select-platforms). A pull request runs the Linux legs only, unless it + # has the full-ci label (see native-platforms); every other event runs the macOS and Windows legs + # too. The tests are those of the crates a change reaches: the crates that own a changed file, + # the crates whose Cargo.toml declares a read of it # (`[package.metadata.craft] reads`, which this job checks is complete), and every crate that # depends on those. The build setup, a crate's own Cargo.toml or a file outside the crates other # than documentation runs every test; documentation alone runs none. The full-ci label runs @@ -41,6 +42,9 @@ jobs: platform: ${{ steps.select.outputs.platform }} tests: ${{ steps.select.outputs.tests }} filter: ${{ steps.select.outputs.filter }} + audit: ${{ steps.audit.outputs.audit }} + profile: ${{ steps.audit.outputs.profile }} + deps-profile: ${{ steps.audit.outputs.deps-profile }} steps: - name: Harden runner uses: step-security/harden-runner@v2.22.4 @@ -59,14 +63,54 @@ jobs: select-os: '["windows-latest","macos-latest"]' select-tests: true label: full-ci + # Whether the selection reaches a replay-audit crate, which runs the Linux leg as a build job + # and three test shards (see `native`), and the hash of the profile overrides every test build + # passes (scripts/ci-workspace-tests.sh), which names the Workspace legs' cache entries: + # rust-cache's key does not hash these files, and an entry built with other overrides would be + # rebuilt in full on every run. Other events than a pull request check out only these files. + # The macOS and Windows legs cache dependencies only, so `deps-profile` hashes only the + # settings that reach a dependency: `[profile.dev]` and `[profile.dev.package."*"]`. Every + # other override names a workspace crate (scripts/test-workspace-tests.py), so changing one + # keeps those entries, and next's runs restore main's. + - uses: actions/checkout@v7.0.1 + if: github.event_name != 'pull_request' + with: + persist-credentials: false + sparse-checkout: | + scripts/ci-workspace-tests.sh + .config/cargo-*.toml + sparse-checkout-cone-mode: false + - id: audit + env: + CRAFT_TESTS: ${{ steps.select.outputs.tests }} + CRAFT_TEST_FILTER: ${{ steps.select.outputs.filter }} + CRAFT_TEST_SKIP: ${{ steps.select.outputs.skip }} + run: | + echo "audit=$(bash scripts/ci-workspace-tests.sh audit)" >> "$GITHUB_OUTPUT" + echo "profile=$(cat .config/cargo-dev.toml .config/cargo-ci.toml | sha256sum | cut -c1-12)" >> "$GITHUB_OUTPUT" + # An assignment, so a failure stops the step (`bash -e`) instead of naming every entry `v2-`. + deps=$(python3 -I - <<'PY' + import hashlib, json, tomllib + kept = [] + for path in (".config/cargo-dev.toml", ".config/cargo-ci.toml"): + with open(path, "rb") as file: + dev = tomllib.load(file)["profile"]["dev"] + kept.append([dev, dev.pop("package", {}).get("*", {})]) + print(hashlib.sha256(json.dumps(kept, sort_keys=True).encode()).hexdigest()[:12]) + PY + ) + echo "deps-profile=$deps" >> "$GITHUB_OUTPUT" # The Linux leg keeps the compiled workspace crates between runs (`cache-workspace-crates`): each # main run saves a rolling cache entry of its own, every run restores the newest one, and Cargo # rebuilds only the crates a change reaches. `cache-prune` keeps the newest entry. The midnight - # scheduled run builds from source (`cold-build`) and starts the entry afresh. The macOS and - # Windows legs keep a dependency-only entry: their workspace crates would not fit the 10 GB cache - # budget beside Linux's. The lint legs keep no cache (`lint-cache: false`) for the same reason; a - # cold lint leg is still shorter than its gate leg. + # scheduled run builds from source (`cold-build`) and starts the entry afresh. next has an entry + # of its own, since main's is built from different code and lockfile and a pull request into next + # rebuilt nearly everything from it (15.5 minutes): nightly.yml's daily manual run on next builds + # from source and saves it (`cache-save-on-dispatch`), and pull requests into next restore it + # before main's. The macOS and Windows legs keep a dependency-only entry: their workspace crates + # would not fit the 10 GB cache budget beside Linux's. The lint legs keep no cache + # (`lint-cache: false`) for the same reason; a cold lint leg is still shorter than its gate leg. native: name: Workspace needs: platforms @@ -74,7 +118,9 @@ jobs: with: os: '["ubuntu-latest"]' cache-workspace-crates: true - cold-build: ${{ github.event.schedule == '17 0 * * *' }} + cache-save-on-dispatch: true + cache-version: &cache-version v2-${{ needs.platforms.outputs.profile }} + cold-build: ${{ github.event.schedule == '17 0 * * *' || github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/next' }} lint-cache: false # The vendored crates are on the workspace `exclude` list, so unreached-rs has no module tree for them. unreached-rs-allow: | @@ -119,40 +165,33 @@ jobs: fi cargo clippy --workspace --all-targets --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings - command: &command | - # The tests run once, with every feature, in parallel across test binaries; nextest skips - # doctests, so `cargo test --doc` runs them. Examples are not built, except the two whose - # tests run (stubicc, h264_h264enc_bench); clippy in the lint leg covers the rest. The default-feature compile is the lint leg's - # first clippy run; the last command runs the crates whose tests check behaviour with a - # feature off, which an all-features build cannot reach. - # Every build is the whole workspace's, as on main; the filter narrows only the run. The - # doctests run for the whole workspace: `cargo test -p ` would resolve features - # over the selected crates only and rebuild the dependencies whose features differ. - if [ "$CRAFT_TESTS" = none ]; then - echo "No crate changed: no tests to run." - exit 0 - fi - cargo nextest run --workspace --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests - cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --example stubicc --example h264_h264enc_bench - # The replay audit (craft-libs#2336), on Linux: the selected UI crates' tests again, from the same build, with every - # memoized view that would replay also run for real and compared with its replay. - if [ "$RUNNER_OS" = Linux ]; then - CRAFT_UI_AUDIT_REPLAY=1 cargo nextest run --workspace --all-features --locked --profile ci -E "($CRAFT_TEST_FILTER) & (package(craft-ui-contract) | package(craft-ui-widgets) | package(craft-ui-panels) | package(craft-ui-patterns) | package(craft-ui-shell) | package(craft-ui-gallery) | package(craft-menu))" --no-tests=warn --lib --bins --tests - fi - cargo test --workspace --doc --all-features --locked - cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests + # A selection that reaches a replay-audit crate builds once in a `build` job, which writes + # three nextest archives and then runs the doctests; three shard legs run them in parallel: + # every selected test outside the replay audit's crates and craft-draw, those crates (run plainly, + # then the audit crates with the audit), and craft-image-codecs with default features. Any other selection + # (and every macOS and Windows leg) builds and runs in one leg. scripts/ci-workspace-tests.sh + # holds every step. + test-shards: ${{ needs.platforms.outputs.audit == 'true' && 3 || 0 }} + shard-archives: ${{ needs.platforms.outputs.audit == 'true' }} + archive-command: ${{ needs.platforms.outputs.audit == 'true' && 'bash scripts/ci-workspace-tests.sh archive' || '' }} + after-archive-command: bash scripts/ci-workspace-tests.sh doctest + shard-command: bash scripts/ci-workspace-tests.sh shard + command: &command bash scripts/ci-workspace-tests.sh run - # The macOS and Windows legs, when `platforms` says this run needs them, with the Linux leg's - # inputs. + # The macOS and Windows legs, with the Linux leg's inputs. They take 1.5-2 hours against the Linux + # leg's 15-40 minutes, so a pull request does not wait for them: they run after the merge, on + # every push to main and next, on main's scheduled runs and on nightly.yml's daily run on next. + # A pull request that needs them before it merges gets the full-ci label. native-platforms: name: Workspace needs: platforms - # Pushes to next run Linux only. - if: needs.platforms.outputs.platform == 'true' && github.ref != 'refs/heads/next' + if: needs.platforms.outputs.platform == 'true' && (github.event_name != 'pull_request' || contains(github.event.pull_request.labels.*.name, 'full-ci')) uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: os: '["windows-latest","macos-latest"]' lint-cache: false + # Named by the dependency settings alone (`deps-profile`), so next restores main's entries. + cache-version: v2-${{ needs.platforms.outputs.deps-profile }} timeout-minutes: *timeout tools: *tools craft-fonts-ref: *craft-fonts @@ -170,25 +209,16 @@ jobs: cache-key-files: *cache-key-files lint-command: *lint command: *command - windows-command: | - if [ "$CRAFT_TESTS" = none ]; then - echo "No crate changed: no tests to run." - exit 0 - fi - powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' - cargo nextest run --workspace --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests - cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --example stubicc --example h264_h264enc_bench - cargo test --workspace --doc --all-features --locked - cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests - # Each main run's Linux leg saves a rolling cache entry of its own (`cache-workspace-crates`), and - # every run restores only the newest. This deletes the older ones as soon as the Linux leg is - # done, instead of leaving them to the 10 GB budget's eviction, which would evict other entries - # too. The only job with `actions: write`; it checks out and runs nothing from the repository. + # Each main run's Linux leg saves a rolling cache entry of its own (`cache-workspace-crates`), as + # does the daily manual run on next, and every run restores only the newest. This deletes the + # older ones of the run's branch as soon as the Linux leg is done, instead of leaving them to the + # 10 GB budget's eviction, which would evict other entries too. The only job with + # `actions: write`; it checks out and runs nothing from the repository. cache-prune: name: cache prune needs: native - if: ${{ !cancelled() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} + if: ${{ !cancelled() && github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/next') }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -202,10 +232,11 @@ jobs: env: GH_TOKEN: ${{ github.token }} REPO: ${{ github.repository }} + REF: ${{ github.ref }} run: | set -euo pipefail # `-rust---crates-----...`, newest first. - gh cache list --repo "$REPO" --ref refs/heads/main --limit 100 --sort created_at --order desc --json id,key \ + gh cache list --repo "$REPO" --ref "$REF" --limit 100 --sort created_at --order desc --json id,key \ --jq '.[] | "\(.id) \(.key)"' > "$RUNNER_TEMP/caches" declare -A kept while read -r id key; do diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 3d1ef7749..34e0bcd6f 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -12,9 +12,10 @@ author, source and license. Library code and original assets are under the repos | `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft contributors; generated by `craft_cms::synth::coated_cmyk` | [PhotoCraft `crates/cms`](https://github.com/storytold/photocraft/tree/b3222ee8e7e6bcb4799c37f904c595f20f9baf5e/crates/cms) | CC0-1.0 | | `crates/cms/profiles/craft-coated-fogra39.icc` | craft-libs contributors; generated by `crates/cms/tests/fogra39.rs` from the FOGRA39 data below | this repository | CC0-1.0 | | `crates/ppt-binary/tests/fixtures/old-talk.pps` | DeckCraft contributors; a one-slide PowerPoint 97-2003 show built from records by `crates/ppt-binary/src/tests.rs` (`the_pps_fixture_is_a_built_presentation`, with `CRAFT_WRITE_PPT_FIXTURE=1`); no PowerPoint involved | [storytold/deckcraft#1137](https://github.com/storytold/deckcraft/pull/1137) | CC0-1.0 | -| `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | -| `crates/font-store/index/indexes/google-fonts.json.gz` (unmodified) | craft-font-index contributors; generated from the METADATA.pb files of [google/fonts](https://github.com/google/fonts) at `45e3d5269e4a17d823f6d84470bc084dc5ae46f6` | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | -| `crates/font-store/index/indexes/noto.json.gz` (unmodified) | craft-font-index contributors; generated from [notofonts/notofonts.github.io](https://github.com/notofonts/notofonts.github.io) at `93fac8abebe6c7fed0c5b7d2456d8fa484fa146c` and [noto-cjk](https://github.com/notofonts/noto-cjk) releases | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | +| `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@995ef20](https://github.com/aiongg/craft-font-index/tree/995ef2000a0159d70da245e22cfa0797a0756ae8) | Apache-2.0 | +| `crates/font-store/index/indexes/google-fonts.json.gz` (unmodified) | craft-font-index contributors; generated from the METADATA.pb files of [google/fonts](https://github.com/google/fonts) at `45e3d5269e4a17d823f6d84470bc084dc5ae46f6` | [aiongg/craft-font-index@995ef20](https://github.com/aiongg/craft-font-index/tree/995ef2000a0159d70da245e22cfa0797a0756ae8) | Apache-2.0 | +| `crates/font-store/index/indexes/noto.json.gz` (unmodified) | craft-font-index contributors; generated from [notofonts/notofonts.github.io](https://github.com/notofonts/notofonts.github.io) at `93fac8abebe6c7fed0c5b7d2456d8fa484fa146c` and [noto-cjk](https://github.com/notofonts/noto-cjk) releases | [aiongg/craft-font-index@995ef20](https://github.com/aiongg/craft-font-index/tree/995ef2000a0159d70da245e22cfa0797a0756ae8) | Apache-2.0 | +| `crates/font-manager/tests/data/preview-vectors.json` (sample sentences) | Google Fonts `lang/` contributors; texts from the Universal Declaration of Human Rights via Eric Muller's UDHR in Unicode (translations' own terms not checked); the Iroha poem is public domain | [google/fonts `lang/`](https://github.com/google/fonts/tree/45e3d5269e4a17d823f6d84470bc084dc5ae46f6/lang) at `45e3d52` | Apache-2.0 | | `crates/cms/tests/data/FOGRA39.txt` (unmodified) | Fogra | [Fogra characterisation data](https://fogra.org/en/downloads/work-tools/characterisation-data), `FOGRA39_to_FOGRA60_v2.zip` | Fogra terms: free use and redistribution, unmodified, with Fogra identified as the source; "FOGRA39" identifies the reference data only and implies no certification, approval or endorsement by Fogra (full text in [NOTICE](NOTICE)) | | `vendor/linesweeper/tests/regression/`, `vendor/linesweeper/proptest-regressions/`, the `.snap` files under `vendor/linesweeper/src/` and the path data in `vendor/linesweeper/benches/painted_dreams.rs` (all unmodified; hashes in `vendor/linesweeper/SOURCE.json`) | As published in the package, whose manifest names Joe Neeman as author and records no other source | [linesweeper 0.5.0](https://crates.io/crates/linesweeper/0.5.0) | MIT OR Apache-2.0 (the package's `license` field) | | `crates/i18n/data/collation.postcard` | Unicode, Inc. (ICU 78.1 collation data, CLDR 48.2.1); generated by `crates/i18n/data/generate-collation.sh` | [ICU](https://github.com/unicode-org/icu/releases/tag/release-78.1rc) | Unicode-3.0 | @@ -189,3 +190,13 @@ Retained XFDF source contributors (move-aware blame): Brandon Thomas, Marco Arnu `crates/media-source/src/y4m.rs` adapts the in-house [FilmCraft Y4mSource at 3f137a7e](https://github.com/storytold/filmcraft/blob/3f137a7ed420cac79b32145f5243b7f98b31f71c/crates/codecs/src/y4m.rs), MIT OR Apache-2.0. Original playback by Lloyd Nicholson ([FilmCraft #1303](https://github.com/storytold/filmcraft/pull/1303)); shared-parser integration by Dylan M. Taylor ([FilmCraft #4862](https://github.com/storytold/filmcraft/pull/4862)). The adaptation changes source/frame types and declines payloads above the shared media allocation ceiling before playback. The parser and its previous header-safety work remain in `craft-y4m` ([craft-libs #933](https://github.com/storytold/craft-libs/pull/933)). `crates/media-source/tests/it/y4m.rs` contains original repository-authored synthetic test data under MIT OR Apache-2.0: literal YUV samples and a sparse reader that reports only the length of an oversized frame. It does not use external media or decoder output. + +## Material graph runtime + +`crates/material-graph` moves the graph text format, parser, evaluator, pixel-program compiler, and tests from +[TextureCraft's SPP importer at 22a37c29](https://github.com/vangel76/texturecraft/tree/22a37c29e98d8e6fc8c5e611e22f0ab95b83243d/crates/graph) +(MIT OR Apache-2.0). [xilefenko introduced this runtime in TextureCraft](https://github.com/vangel76/texturecraft/commit/af862722be61bd7050ac782ec57a5e8938a5b017), +adapting code from [PiJellyPin's MaterialCraft](https://github.com/PiJellyPin/MaterialCraft). See the crate's +`NOTICE` for the original attribution. This extraction retains vangel76's subsequent evaluator and GPU work. +The format reference and tests are from the same TextureCraft source. The tests' numerical rule tables document +their provenance in their headers. diff --git a/Cargo.lock b/Cargo.lock index 27b9e695a..62dfc38e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1846,6 +1846,7 @@ dependencies = [ "craft-lottie", "craft-macho", "craft-markdown", + "craft-material-graph", "craft-materialx", "craft-math", "craft-mcmat", @@ -2020,6 +2021,7 @@ dependencies = [ name = "craft-android-res" version = "0.1.0" dependencies = [ + "craft-testkit", "serde", "thiserror 2.0.21", ] @@ -2075,6 +2077,9 @@ dependencies = [ [[package]] name = "craft-audio-dsp" version = "0.1.0" +dependencies = [ + "craft-testkit", +] [[package]] name = "craft-automation" @@ -2147,6 +2152,7 @@ version = "0.1.0" dependencies = [ "craft-media", "craft-media-testkit", + "craft-testkit", "craft-timeline", "craft-xml", "proptest", @@ -2169,6 +2175,7 @@ name = "craft-cfb" version = "0.1.0" dependencies = [ "craft-media-testkit", + "craft-testkit", ] [[package]] @@ -2206,6 +2213,7 @@ dependencies = [ name = "craft-cms" version = "0.1.0" dependencies = [ + "craft-testkit", "md-5 0.10.6", "moxcms", "rayon", @@ -2293,6 +2301,7 @@ dependencies = [ name = "craft-crw" version = "0.1.0" dependencies = [ + "craft-testkit", "serde", "serde_json", "sha2 0.10.9", @@ -2367,6 +2376,7 @@ dependencies = [ "craft-geom", "craft-raw", "craft-render-parity", + "craft-testkit", "proptest", "rayon", "serde", @@ -2425,6 +2435,7 @@ dependencies = [ "blake3", "craft-ecproj-format", "craft-pcraft-format", + "craft-testkit", "craft-vectorcraft-format", "flate2", "ruzstd", @@ -2480,6 +2491,7 @@ dependencies = [ "craft-math", "craft-offcrypto", "craft-opc", + "craft-testkit", "craft-wordmodel", "craft-xml", "image", @@ -2523,6 +2535,7 @@ name = "craft-drawingml" version = "0.1.0" dependencies = [ "chrono", + "craft-testkit", "craft-xml", "kurbo", "log", @@ -2619,6 +2632,7 @@ dependencies = [ name = "craft-exr" version = "0.1.0" dependencies = [ + "craft-testkit", "exr", "flate2", "half", @@ -2754,7 +2768,8 @@ dependencies = [ "epaint_default_fonts", "log", "serde", - "skrifa 0.44.0", + "serde_json", + "skrifa 0.47.0", ] [[package]] @@ -2776,6 +2791,7 @@ dependencies = [ "toml", "ureq", "write-fonts 0.54.1", + "wuff", ] [[package]] @@ -2783,6 +2799,7 @@ name = "craft-font-subset" version = "0.1.0" dependencies = [ "brotli 9.1.1", + "craft-testkit", "harfbuzz-subset-sys", "rustybuzz", "serde_json", @@ -2931,6 +2948,7 @@ dependencies = [ name = "craft-heif" version = "0.1.0" dependencies = [ + "craft-testkit", "heic-rs", "proptest", "rayon", @@ -3113,6 +3131,7 @@ dependencies = [ name = "craft-jpeg" version = "0.1.0" dependencies = [ + "craft-testkit", "jpeg-decoder", "jpeg-encoder 0.6.1", "rayon", @@ -3184,6 +3203,7 @@ dependencies = [ "craft-markdown", "craft-math", "craft-mime", + "craft-testkit", "craft-wordmodel", "proptest", ] @@ -3229,6 +3249,15 @@ dependencies = [ "craft-wordmodel", ] +[[package]] +name = "craft-material-graph" +version = "0.1.0" +dependencies = [ + "craft-testkit", + "libm", + "rayon", +] + [[package]] name = "craft-materialx" version = "0.1.0" @@ -3333,6 +3362,7 @@ name = "craft-mesh" version = "0.1.0" dependencies = [ "craft-opc", + "craft-testkit", "craft-xml", "craft-zip", "miniz_oxide 0.9.1", @@ -3380,6 +3410,7 @@ dependencies = [ "chardetng", "chrono", "craft-codepage", + "craft-testkit", "encoding_rs", "proptest", ] @@ -3451,6 +3482,7 @@ dependencies = [ name = "craft-openpgp" version = "0.1.0" dependencies = [ + "craft-testkit", "ed25519-dalek 2.2.0", "pgp", "proptest", @@ -3533,6 +3565,7 @@ dependencies = [ "chrono", "craft-stream-codecs", "craft-svg", + "craft-testkit", "flate2", "hayro", "hayro-cmap", @@ -3747,6 +3780,7 @@ dependencies = [ "craft-cms", "craft-pdf 0.1.0", "craft-plate-test", + "craft-testkit", "kurbo", "linesweeper", "thiserror 2.0.21", @@ -3790,6 +3824,7 @@ dependencies = [ name = "craft-proof" version = "0.1.0" dependencies = [ + "craft-testkit", "log", "miniz_oxide 0.9.1", "proptest", @@ -3802,6 +3837,7 @@ name = "craft-proto" version = "0.1.0" dependencies = [ "base64 0.23.1", + "craft-testkit", "log", "proptest", "zeroize", @@ -3812,6 +3848,7 @@ name = "craft-ps" version = "0.1.0" dependencies = [ "craft-eps", + "craft-testkit", "flate2", "kurbo", "miniz_oxide 0.8.9", @@ -3825,6 +3862,7 @@ name = "craft-psd" version = "0.1.0" dependencies = [ "craft-psd", + "craft-testkit", "encoding_rs", "flate2", "proptest", @@ -3838,6 +3876,7 @@ name = "craft-pst" version = "0.1.0" dependencies = [ "craft-pst", + "craft-testkit", "proptest", ] @@ -3871,6 +3910,7 @@ dependencies = [ "chrono", "craft-crw", "craft-metadata", + "craft-testkit", "craft-tiff", "jpeg-encoder 0.7.1", "jxl-oxide", @@ -3950,6 +3990,7 @@ version = "0.1.0" dependencies = [ "craft-audio", "craft-midi", + "craft-testkit", "craft-time", "craft-zip", "proptest", @@ -4091,6 +4132,7 @@ dependencies = [ name = "craft-stream-codecs" version = "0.1.0" dependencies = [ + "craft-testkit", "fax", "hayro-ccitt", "hayro-jbig2", @@ -4345,6 +4387,7 @@ name = "craft-ui-canvas" version = "0.1.0" dependencies = [ "craft-behavior", + "craft-host", "craft-i18n", "craft-keymap", "craft-theme", @@ -4352,6 +4395,7 @@ dependencies = [ "craft-ui-macros", "craft-ui-panels", "craft-ui-test-kit", + "craft-window", "egui", "serde", "serde_json", @@ -4373,6 +4417,7 @@ dependencies = [ "craft-quit", "craft-settings", "craft-svg", + "craft-testkit", "craft-theme", "craft-tracked", "craft-ui-contract", @@ -4734,6 +4779,7 @@ dependencies = [ name = "craft-xcf" version = "0.1.0" dependencies = [ + "craft-testkit", "flate2", "thiserror 2.0.21", ] @@ -4757,6 +4803,7 @@ dependencies = [ name = "craft-xfl" version = "0.1.0" dependencies = [ + "craft-testkit", "craft-xml", "miniz_oxide 0.8.9", "thiserror 2.0.21", @@ -4782,6 +4829,7 @@ dependencies = [ "craft-drawingml", "craft-opc", "craft-sheet", + "craft-testkit", "craft-xlsx", "craft-xml", "thiserror 2.0.21", @@ -4791,6 +4839,7 @@ dependencies = [ name = "craft-xml" version = "0.1.0" dependencies = [ + "craft-testkit", "quick-xml 0.41.0", "serde", "thiserror 2.0.21", @@ -5522,7 +5571,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "bytemuck", "emath", @@ -5578,7 +5627,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "ahash", "bytemuck", @@ -5613,7 +5662,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "accesskit", "ahash", @@ -5632,7 +5681,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "ahash", "bytemuck", @@ -5651,7 +5700,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5671,7 +5720,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "bytemuck", "egui", @@ -5684,7 +5733,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "eframe", "egui", @@ -5761,7 +5810,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "bytemuck", ] @@ -5834,7 +5883,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "ahash", "bytemuck", @@ -5860,7 +5909,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" [[package]] name = "equator" @@ -15192,19 +15241,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" [[patch.unused]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" diff --git a/Cargo.toml b/Cargo.toml index 9e861a40b..cc40daf56 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -170,6 +170,7 @@ craft-math = { path = "crates/math" } craft-media = { path = "crates/media", default-features = false } craft-media-source = { path = "crates/media-source" } craft-materialx = { path = "crates/materialx" } +craft-material-graph = { path = "crates/material-graph" } craft-media-testkit = { path = "crates/media-testkit" } craft-midi = { path = "crates/midi" } craft-sf2 = { path = "crates/sf2" } @@ -315,20 +316,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -egui = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +emath = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +egui = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid diff --git a/crates/aaf/src/aaf.rs b/crates/aaf/src/aaf.rs index 7ea67f4ec..f7a061ccb 100644 --- a/crates/aaf/src/aaf.rs +++ b/crates/aaf/src/aaf.rs @@ -37,6 +37,7 @@ //! name), `FilmCraft Frame Size` and `FilmCraft Audio Sample Rate` (on the composition). mod ids; +pub mod linked_audio; pub mod properties; mod read; pub(crate) mod store; diff --git a/crates/aaf/src/aaf/linked_audio.rs b/crates/aaf/src/aaf/linked_audio.rs new file mode 100644 index 000000000..7fd48f9a7 --- /dev/null +++ b/crates/aaf/src/aaf/linked_audio.rs @@ -0,0 +1,129 @@ +//! WAV/PCM FileDescriptor metadata, without loading a SourceMob or touching its locators. + +use super::ids::{cls, pid}; + +/// The two audio descriptor classes commonly attached to an external WAV source. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DescriptorKind { + /// A WAVEDescriptor (`.wav` with a RIFF header). + Wave, + /// A PCMDescriptor (raw PCM samples). + Pcm, +} + +impl DescriptorKind { + /// Classify a compound-file storage's CLSID in AAF on-disk AUID byte order + /// (little-endian GUID fields, not RFC 4122/network order). + pub fn from_auid_le(class: [u8; 16]) -> Option { + match class { + cls::WAVE_DESCRIPTOR => Some(Self::Wave), + cls::PCM_DESCRIPTOR => Some(Self::Pcm), + _ => None, + } + } +} + +/// One property from an already framed and caller-validated object. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DescriptorProperty<'a> { + /// The object has no such property. + Missing, + /// The property is stored in a form other than a plain data value. + OtherForm, + /// The property's raw value bytes. + Data(&'a [u8]), +} + +/// Why a descriptor field is unavailable. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DescriptorFieldError { + /// The descriptor has no such property. + Missing, + /// The property is stored in a form other than a plain data value. + OtherForm, + /// The value is shorter than the field's type. + Truncated, +} + +/// A lazy descriptor view over a caller's property store. This neither opens +/// the media file nor determines whether the AAF source is external. +pub struct AudioFileDescriptor { + kind: DescriptorKind, + property: F, +} + +impl<'a, F: Fn(u16) -> DescriptorProperty<'a>> AudioFileDescriptor { + /// Supply the property view for this class; the descriptor chooses AAF property IDs. + pub fn new(kind: DescriptorKind, property: F) -> Self { + Self { kind, property } + } + + /// `FileDescriptor::SampleRate` as the signed numerator and denominator on + /// the wire. The caller's rational policy (including zero) is not applied. + pub fn sample_rate(&self) -> Result<(i32, i32), DescriptorFieldError> { + let [a, b, c, d, e, f, g, h] = self.bytes(pid::SAMPLE_RATE)?; + Ok((i32::from_le_bytes([a, b, c, d]), i32::from_le_bytes([e, f, g, h]))) + } + + /// `FileDescriptor::Length` in sample-rate units, before validating clip ranges. + pub fn length(&self) -> Result { + self.bytes(pid::FILE_LENGTH).map(i64::from_le_bytes) + } + + /// `SoundDescriptor::Channels` for a PCM descriptor. A WAVEDescriptor has + /// no such declared count here; an absent PCM field is also left to the caller. + pub fn pcm_channels(&self) -> Result, DescriptorFieldError> { + if self.kind == DescriptorKind::Wave { + return Ok(None); + } + match self.bytes(pid::CHANNELS) { + Ok(bytes) => Ok(Some(u32::from_le_bytes(bytes))), + Err(DescriptorFieldError::Missing) => Ok(None), + Err(err) => Err(err), + } + } + + fn bytes(&self, pid: u16) -> Result<[u8; N], DescriptorFieldError> { + match (self.property)(pid) { + DescriptorProperty::Data(data) => data.first_chunk().copied().ok_or(DescriptorFieldError::Truncated), + DescriptorProperty::Missing => Err(DescriptorFieldError::Missing), + DescriptorProperty::OtherForm => Err(DescriptorFieldError::OtherForm), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn descriptor_class_and_little_endian_fields_are_typed() { + assert_eq!(DescriptorKind::from_auid_le([1, 1, 1, 13, 1, 1, 0, 0x48, 6, 14, 43, 52, 2, 6, 1, 1]), Some(DescriptorKind::Pcm)); + assert_eq!(DescriptorKind::from_auid_le(cls::WAVE_DESCRIPTOR), Some(DescriptorKind::Wave)); + assert_eq!(DescriptorKind::from_auid_le(cls::CDCI_DESCRIPTOR), None); + let file = AudioFileDescriptor::new(DescriptorKind::Pcm, |tag| match tag { + pid::SAMPLE_RATE => DescriptorProperty::Data(&[0x80, 0xbb, 0, 0, 1, 0, 0, 0]), + pid::FILE_LENGTH => DescriptorProperty::Data(&[2, 1, 0, 0, 0, 0, 0, 0, 99]), + pid::CHANNELS => DescriptorProperty::Data(&[2, 0, 0, 0]), + _ => DescriptorProperty::Missing, + }); + assert_eq!(file.sample_rate(), Ok((48000, 1))); + assert_eq!(file.length(), Ok(258)); + assert_eq!(file.pcm_channels(), Ok(Some(2))); + } + + #[test] + fn descriptor_fields_are_lazy_and_distinguish_missing_form_and_short_data() { + let wave = AudioFileDescriptor::new(DescriptorKind::Wave, |tag| match tag { + pid::SAMPLE_RATE => DescriptorProperty::OtherForm, + pid::FILE_LENGTH => DescriptorProperty::Data(&[0; 7]), + _ => panic!("unexpected field read"), + }); + assert_eq!(wave.pcm_channels(), Ok(None)); + assert_eq!(wave.sample_rate(), Err(DescriptorFieldError::OtherForm)); + assert_eq!(wave.length(), Err(DescriptorFieldError::Truncated)); + let pcm = AudioFileDescriptor::new(DescriptorKind::Pcm, |_| DescriptorProperty::Missing); + assert_eq!(pcm.pcm_channels(), Ok(None)); + assert_eq!(pcm.sample_rate(), Err(DescriptorFieldError::Missing)); + } +} diff --git a/crates/android-res/Cargo.toml b/crates/android-res/Cargo.toml index cc54d2513..114c4ae42 100644 --- a/crates/android-res/Cargo.toml +++ b/crates/android-res/Cargo.toml @@ -13,3 +13,6 @@ workspace = true [dependencies] serde = { workspace = true } thiserror = { workspace = true } + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/android-res/src/arsc.rs b/crates/android-res/src/arsc.rs index 79a029625..5ef10798e 100644 --- a/crates/android-res/src/arsc.rs +++ b/crates/android-res/src/arsc.rs @@ -3,7 +3,7 @@ //! orientation, SDK level…). Simple and complex (bag) entries, sparse and 16-bit offset tables. use crate::Error; -use crate::axml::{ResValue, StringPool, chunk}; +use crate::axml::{MAX_RETAINED_VALUE_BYTES, ResValue, StringPool, ValueBudget, chunk, report_partial_string_pool}; use crate::bytes::Reader; use serde::Serialize; @@ -21,14 +21,18 @@ const MAX_BAG: usize = 4096; pub struct Limits { /// Most entries decoded across all types and configurations. pub max_entries: usize, + /// Most bytes retained in formatted simple-entry and bag values. + pub max_value_bytes: usize, } impl Default for Limits { fn default() -> Self { - Limits { max_entries: 2_000_000 } + Limits { max_entries: 2_000_000, max_value_bytes: MAX_RETAINED_VALUE_BYTES } } } +const VALUE_BUDGET_WARNING: &str = "resource value budget reached; remaining values were omitted"; + #[derive(Debug, Clone, PartialEq, Serialize)] pub struct TypeInfo { pub id: u8, @@ -300,30 +304,32 @@ pub fn parse(data: &[u8], limits: Limits) -> Result { let r = Reader::new(data); let mut table = Table::default(); let mut global = StringPool::default(); + let mut value_budget = ValueBudget::new(limits.max_value_bytes); let mut pos = h; while pos < size { let Some((ct, _ch, cs)) = chunk(&r, pos) else { + table.truncated = true; table.warnings.push(format!("unreadable chunk at offset {pos}")); break; }; match ct { crate::axml::RES_STRING_POOL => match StringPool::parse(data, pos) { Ok(p) => { - if p.strings.len() < p.declared { - table.truncated = true; - table.warnings.push(format!("global string pool was capped at {} of {} strings", p.strings.len(), p.declared)); - } + report_partial_string_pool(&p, "global string pool", &mut table.truncated, &mut table.warnings); table.global_strings = p.declared; global = p; } - Err(e) => table.warnings.push(format!("global string pool: {e}")), + Err(e) => { + table.truncated = true; + table.warnings.push(format!("global string pool: {e}")); + } }, RES_PACKAGE => { if table.packages.len() >= MAX_PACKAGES { table.truncated = true; table.warnings.push("too many packages; the rest were skipped".into()); } else { - parse_package(data, pos, cs, &global, &mut table, limits); + parse_package(data, pos, cs, &global, &mut table, limits, &mut value_budget); } } _ => {} @@ -336,14 +342,16 @@ pub fn parse(data: &[u8], limits: Limits) -> Result { Ok(table) } -fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: &mut Table, limits: Limits) { +fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: &mut Table, limits: Limits, value_budget: &mut ValueBudget) { let Some(data) = pos.checked_add(cs).and_then(|end| data.get(..end)) else { + table.truncated = true; table.warnings.push("package runs past its resource table".into()); return; }; let r = Reader::new(data); let hsize = usize::from(r.u16_le(pos + 2).unwrap_or(0)); if hsize < 284 { + table.truncated = true; table.warnings.push(format!("package at offset {pos}: incomplete header")); return; } @@ -365,22 +373,17 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: return StringPool::default(); } let Some(start) = pos.checked_add(offset).filter(|&start| offset >= hsize && start < end) else { + table.truncated = true; table.warnings.push(format!("package {name}: {label} string pool is outside its payload")); return StringPool::default(); }; match StringPool::parse(data, start) { Ok(pool) => { - if pool.strings.len() < pool.declared { - table.truncated = true; - table.warnings.push(format!( - "package {name}: {label} string pool was capped at {} of {} strings", - pool.strings.len(), - pool.declared - )); - } + report_partial_string_pool(&pool, &format!("package {name}: {label} string pool"), &mut table.truncated, &mut table.warnings); pool } Err(error) => { + table.truncated = true; table.warnings.push(format!("package {name}: {label} string pool: {error}")); StringPool::default() } @@ -393,12 +396,14 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: let mut c = pos.saturating_add(hsize.max(8)); while c < end { let Some((ct, ch, sz)) = chunk(&r, c) else { + table.truncated = true; table.warnings.push(format!("package {name}: unreadable chunk at offset {c}")); break; }; // Each child was checked against its package; reads within it must also stop before // the next sibling, including fixed-width library records and bag headers. let Some(child) = data.get(..c.saturating_add(sz)) else { + table.truncated = true; table.warnings.push(format!("package {name}: child chunk runs past its package")); break; }; @@ -437,7 +442,7 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: } } } - parse_type(&r, c, (ch, sz), (cfg, locale), &p, tid, global, table, limits); + parse_type(&r, c, (ch, sz), (cfg, locale), &p, tid, global, table, limits, value_budget); } (RES_TYPE_SPEC | RES_TYPE, None) if ch >= 16 => { table.truncated = true; @@ -449,6 +454,9 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: if n > available { table.warnings.push(format!("package {name}: library records run past their chunk")); } + if n > available.min(256) { + table.truncated = true; + } for i in 0..n.min(256).min(available) { let e = c + ch + i * 260; if let Some(lid) = r.u32_le(e) { @@ -457,6 +465,7 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: } } (RES_TYPE_SPEC | RES_TYPE | RES_LIBRARY, _) => { + table.truncated = true; table.warnings.push(format!("package {name}: incomplete chunk header at offset {c}")); } _ => {} @@ -480,6 +489,7 @@ fn parse_type( global: &StringPool, table: &mut Table, limits: Limits, + value_budget: &mut ValueBudget, ) { let tid = r.u8(c + 8).unwrap_or(0); let flags = r.u8(c + 9).unwrap_or(0); @@ -493,10 +503,12 @@ fn parse_type( let mut slots: Vec<(u32, usize)> = Vec::new(); let table_bytes = if sparse || off16 { count.saturating_mul(if sparse { 4 } else { 2 }) } else { count.saturating_mul(4) }; if c.saturating_add(ch).saturating_add(table_bytes) > end { + table.truncated = true; table.warnings.push(format!("{tname} ({cfg}): entry table runs past its chunk")); return; } if count != 0 && (entries_start < ch.saturating_add(table_bytes) || entries_start > sz) { + table.truncated = true; table.warnings.push(format!("{tname} ({cfg}): invalid entry data start")); return; } @@ -517,15 +529,16 @@ fn parse_type( } } } + let mut skipped = 0usize; for (idx, o) in slots { if table.entries.len() >= limits.max_entries { table.truncated = true; - return; + break; } - let Some(e) = c.checked_add(entries_start).and_then(|x| x.checked_add(o)) else { continue }; - if e.saturating_add(8) > end { + let Some(e) = c.checked_add(entries_start).and_then(|x| x.checked_add(o)).filter(|e| e.saturating_add(8) <= end) else { + skipped += 1; continue; - } + }; let esize = usize::from(r.u16_le(e).unwrap_or(0)); let eflags = r.u16_le(e + 2).unwrap_or(0); let id = (p.id << 24) | (u32::from(type_id) << 16) | (idx & 0xffff); @@ -546,7 +559,7 @@ fn parse_type( // Compact entry: key index in the size field, type in the high byte of flags. entry.key = p.keys.get(u32::from(r.u16_le(e).unwrap_or(0))).unwrap_or("").to_string(); let v = ResValue { data_type: (eflags >> 8) as u8, data: r.u32_le(e + 4).unwrap_or(0) }; - entry.value = Some(v.format(global)); + entry.value = value_budget.take(v.format(global), &mut table.truncated, &mut table.warnings, VALUE_BUDGET_WARNING); entry.value_type = Some(v.type_name()); entry.raw = Some(v); } else { @@ -579,21 +592,30 @@ fn parse_type( } let name = r.u32_le(m).unwrap_or(0); let v = ResValue { data_type: r.u8(m + 7).unwrap_or(0), data: r.u32_le(m + 8).unwrap_or(0) }; - entry.bag.push(BagItem { name: format!("@{name:#010x}"), value: v.format(global), value_type: v.type_name() }); + let value = + value_budget.take(v.format(global), &mut table.truncated, &mut table.warnings, VALUE_BUDGET_WARNING).unwrap_or_default(); + entry.bag.push(BagItem { name: format!("@{name:#010x}"), value, value_type: v.type_name() }); m += 12; } } else { let v_at = e.saturating_add(esize.max(8)); if v_at.saturating_add(8) <= end { let v = ResValue { data_type: r.u8(v_at + 3).unwrap_or(0), data: r.u32_le(v_at + 4).unwrap_or(0) }; - entry.value = Some(v.format(global)); + entry.value = value_budget.take(v.format(global), &mut table.truncated, &mut table.warnings, VALUE_BUDGET_WARNING); entry.value_type = Some(v.type_name()); entry.raw = Some(v); + } else { + table.truncated = true; + table.warnings.push(format!("{tname} ({cfg}): incomplete value")); } } } table.entries.push(entry); } + if skipped > 0 { + table.truncated = true; + table.warnings.push(format!("{tname} ({cfg}): {skipped} entries run past their chunk")); + } } impl Table { @@ -642,6 +664,30 @@ mod tests { assert_eq!(style.config, "night-xhdpi-v21"); } + #[test] + fn skipped_type_chunks_and_entries_mark_the_table_partial() { + let bytes = fx::resources_arsc(); + // The French type chunk: RES_TYPE, an 84-byte header, and "fr" in its configuration. + let fr = (0..bytes.len() - 30).find(|&i| bytes[i..i + 4] == [0x01, 0x02, 84, 0] && &bytes[i + 28..i + 30] == b"fr").unwrap(); + let corrupt = |at: usize, value: u32| { + let mut b = bytes.clone(); + b[at..at + 4].copy_from_slice(&value.to_le_bytes()); + parse(&b, Limits::default()).unwrap() + }; + for (what, t) in [ + ("entry table past its chunk", corrupt(fr + 12, 1000)), + ("invalid entry data start", corrupt(fr + 16, 0xffff)), + ("an entry past its chunk", corrupt(fr + 84, 0x1000)), + // The second entry's header fits, but its value runs past the chunk. + ("a value past its chunk", corrupt(fr + 88, 24)), + ] { + let french = t.entries.iter().filter(|e| e.locale == "fr" && e.value.is_some()).count(); + assert!(french < 2, "{what}: the corruption should lose a French value"); + assert!(t.truncated, "{what}: lost content must mark the table partial"); + assert!(!t.warnings.is_empty(), "{what}: lost content must be reported"); + } + } + #[test] fn distinct_locale_scripts_and_variants_keep_separate_keys() { let mut cfg = [0u8; 64]; @@ -674,4 +720,162 @@ mod tests { assert_eq!(q, "es-rMX-land"); assert_eq!(l, "es-rMX"); } + + fn le_u16(v: &mut Vec, x: u16) { + v.extend_from_slice(&x.to_le_bytes()); + } + + fn le_u32(v: &mut Vec, x: u32) { + v.extend_from_slice(&x.to_le_bytes()); + } + + fn type_spec(id: u8, entries: u32) -> Vec { + let mut c = Vec::new(); + le_u16(&mut c, 0x0202); + le_u16(&mut c, 16); + le_u32(&mut c, 16 + 4 * entries); + c.push(id); + c.push(0); + le_u16(&mut c, 0); + le_u32(&mut c, entries); + for _ in 0..entries { + le_u32(&mut c, 0); + } + c + } + + fn type_chunk(id: u8, entries: &[Vec]) -> Vec { + let mut cfg = vec![0u8; 64]; + cfg[0] = 64; + let header = 20 + cfg.len(); + let start = header + 4 * entries.len(); + let mut body = Vec::new(); + let mut offs = Vec::new(); + for e in entries { + offs.push(body.len() as u32); + body.extend_from_slice(e); + } + let mut c = Vec::new(); + le_u16(&mut c, 0x0201); + le_u16(&mut c, header as u16); + le_u32(&mut c, (start + body.len()) as u32); + c.push(id); + c.push(0); + le_u16(&mut c, 0); + le_u32(&mut c, entries.len() as u32); + le_u32(&mut c, start as u32); + c.extend_from_slice(&cfg); + for o in offs { + le_u32(&mut c, o); + } + c.extend(body); + c + } + + fn table_with_entries(pool: &[&str], type_name: &str, keys: &[&str], entries: &[Vec]) -> Vec { + let global = fx::string_pool(pool, true); + let types = fx::string_pool(&[type_name], false); + let key_pool = fx::string_pool(keys, false); + let mut chunks = type_spec(1, entries.len() as u32); + chunks.extend(type_chunk(1, entries)); + let header = 288usize; + let mut pkg = Vec::new(); + le_u16(&mut pkg, 0x0200); + le_u16(&mut pkg, header as u16); + le_u32(&mut pkg, (header + types.len() + key_pool.len() + chunks.len()) as u32); + le_u32(&mut pkg, 0x7f); + pkg.extend(vec![0u8; 256]); + le_u32(&mut pkg, header as u32); + le_u32(&mut pkg, 1); + le_u32(&mut pkg, (header + types.len()) as u32); + le_u32(&mut pkg, keys.len() as u32); + le_u32(&mut pkg, 0); + pkg.extend(types); + pkg.extend(key_pool); + pkg.extend(chunks); + let mut out = Vec::new(); + le_u16(&mut out, 0x0002); + le_u16(&mut out, 12); + le_u32(&mut out, (12 + global.len() + pkg.len()) as u32); + le_u32(&mut out, 1); + out.extend(global); + out.extend(pkg); + out + } + + fn simple_string_entry(key: u32, pool_index: u32) -> Vec { + let mut e = Vec::new(); + le_u16(&mut e, 8); + le_u16(&mut e, 0); + le_u32(&mut e, key); + le_u16(&mut e, 8); + e.push(0); + e.push(0x03); + le_u32(&mut e, pool_index); + e + } + + fn compact_string_entry(key: u16, pool_index: u32) -> Vec { + let mut e = Vec::new(); + le_u16(&mut e, key); + le_u16(&mut e, 0x0308); + le_u32(&mut e, pool_index); + e + } + + fn bag_string_entry(key: u32, pool_indices: &[u32]) -> Vec { + let mut e = Vec::new(); + le_u16(&mut e, 16); + le_u16(&mut e, 1); + le_u32(&mut e, key); + le_u32(&mut e, 0); + le_u32(&mut e, pool_indices.len() as u32); + for (i, idx) in pool_indices.iter().enumerate() { + le_u32(&mut e, 0x0101_0000 + i as u32); + le_u16(&mut e, 8); + e.push(0); + e.push(0x03); + le_u32(&mut e, *idx); + } + e + } + + #[test] + fn value_budget_omits_long_copies_and_keeps_a_later_short_value() { + let long = "x".repeat(16); + let tight = Limits { max_value_bytes: 20, ..Limits::default() }; + let keys = ["a", "b", "c"]; + + let simple = + table_with_entries(&[&long, "ok"], "string", &keys, &[simple_string_entry(0, 0), simple_string_entry(1, 0), simple_string_entry(2, 1)]); + let complete = parse(&simple, Limits::default()).unwrap(); + assert!(!complete.truncated, "{:?}", complete.warnings); + assert_eq!(complete.entries.iter().map(|e| e.value.as_deref()).collect::>(), [Some(long.as_str()), Some(long.as_str()), Some("ok")]); + + let partial = parse(&simple, tight).unwrap(); + assert!(partial.truncated); + assert!(partial.warnings.iter().any(|w| w.contains("value budget")), "{:?}", partial.warnings); + assert_eq!(partial.entries.iter().map(|e| e.value.as_deref()).collect::>(), [Some(long.as_str()), None, Some("ok")]); + + let compact = table_with_entries( + &[&long, "ok"], + "string", + &keys, + &[compact_string_entry(0, 0), compact_string_entry(1, 0), compact_string_entry(2, 1)], + ); + let partial = parse(&compact, tight).unwrap(); + assert!(partial.truncated); + assert!(partial.warnings.iter().any(|w| w.contains("value budget")), "{:?}", partial.warnings); + assert_eq!(partial.entries.iter().map(|e| e.value.as_deref()).collect::>(), [Some(long.as_str()), None, Some("ok")]); + + let bag = table_with_entries(&[&long, "ok"], "style", &["theme"], &[bag_string_entry(0, &[0, 0, 1])]); + let complete = parse(&bag, Limits::default()).unwrap(); + assert!(!complete.truncated, "{:?}", complete.warnings); + assert_eq!(complete.entries[0].bag.iter().map(|i| i.value.as_str()).collect::>(), [long.as_str(), long.as_str(), "ok"]); + + let partial = parse(&bag, tight).unwrap(); + assert!(partial.truncated); + assert!(partial.warnings.iter().any(|w| w.contains("value budget")), "{:?}", partial.warnings); + assert_eq!(partial.entries[0].bag.iter().map(|i| i.value.as_str()).collect::>(), [long.as_str(), "", "ok"]); + } } diff --git a/crates/android-res/src/axml.rs b/crates/android-res/src/axml.rs index 3aea1f7ff..d45b06446 100644 --- a/crates/android-res/src/axml.rs +++ b/crates/android-res/src/axml.rs @@ -20,8 +20,10 @@ const XML_RESOURCE_MAP: u16 = 0x0180; const MAX_STRINGS: usize = 1_000_000; /// Longest string kept (characters). const MAX_STRING: usize = 64 * 1024; +/// Default budget for copied resource and XML values, and the base string-pool byte cap. +pub(crate) const MAX_RETAINED_VALUE_BYTES: usize = 64 << 20; /// Base budget for decoded string bytes; larger chunks allow at most three times their size. -const BASE_POOL_BYTES: usize = 64 << 20; +const BASE_POOL_BYTES: usize = MAX_RETAINED_VALUE_BYTES; /// Most extra UTF-8 length candidates examined across one string pool. const MAX_RECOVERY_PROBES: usize = 65_536; /// Most XML nodes decoded. @@ -54,6 +56,8 @@ pub struct StringPool { pub utf8: bool, /// Strings the pool declared (may exceed `strings.len()` when capped). pub declared: usize, + /// Entries left empty because the UTF-8 recovery probe budget ran out. + pub recovery_omitted: usize, } impl StringPool { @@ -104,12 +108,13 @@ impl StringPool { let strings_reader = Reader::new(string_bytes); let mut strings = Vec::with_capacity(count.min(MAX_STRINGS).min(65_536)); let mut bytes_left = BASE_POOL_BYTES.max(size.saturating_mul(3)); + let mut recovery_omitted = 0; for i in 0..count.min(MAX_STRINGS) { let at = r.u32_le(hdr + i * 4).ok_or_else(|| Error::Truncated("string offsets".into()))? as usize; let s = if at >= string_bytes.len() { None } else if utf8 { - utf8_string(&strings_reader, at, string_bytes.len(), recovery_left) + utf8_string(&strings_reader, at, string_bytes.len(), recovery_left, &mut recovery_omitted) } else { utf16_string(&strings_reader, at, string_bytes.len()) }; @@ -120,7 +125,7 @@ impl StringPool { bytes_left -= s.len(); strings.push(s); } - Ok(StringPool { strings, utf8, declared: count }) + Ok(StringPool { strings, utf8, declared: count, recovery_omitted }) } } @@ -134,7 +139,7 @@ fn utf8_len(r: &Reader<'_>, at: usize) -> Option<(usize, usize)> { } } -fn utf8_string(r: &Reader<'_>, at: usize, end: usize, recovery_left: &mut usize) -> Option { +fn utf8_string(r: &Reader<'_>, at: usize, end: usize, recovery_left: &mut usize, recovery_omitted: &mut usize) -> Option { let (_chars, n1) = utf8_len(r, at)?; let (mut bytes, n2) = utf8_len(r, at.checked_add(n1)?)?; let start = at.checked_add(n1 + n2)?; @@ -146,7 +151,11 @@ fn utf8_string(r: &Reader<'_>, at: usize, end: usize, recovery_left: &mut usize) } // The declared candidate costs one read per entry, already bounded by MAX_STRINGS. if bytes >= 0x8000 { - *recovery_left = recovery_left.checked_sub(1)?; + if *recovery_left == 0 { + *recovery_omitted += 1; + return None; + } + *recovery_left -= 1; } if r.u8(terminator)? == 0 { break; @@ -173,6 +182,56 @@ fn utf16_string(r: &Reader<'_>, at: usize, end: usize) -> Option { Some(String::from_utf16_lossy(&units)) } +/// Record that a string pool was capped or omitted recovery entries. +pub(crate) fn report_partial_string_pool(pool: &StringPool, prefix: &str, truncated: &mut bool, warnings: &mut Vec) { + if pool.strings.len() < pool.declared { + *truncated = true; + warnings.push(format!("{prefix} was capped at {} of {} strings", pool.strings.len(), pool.declared)); + } + if pool.recovery_omitted > 0 { + *truncated = true; + warnings.push(format!("{prefix} omitted {} strings after the UTF-8 recovery budget was exhausted", pool.recovery_omitted)); + } +} + +/// Charge `value` against a retained-byte budget. When it does not fit, report truncation once +/// and return `None`, so a later shorter value can still be kept. +pub(crate) fn retain_value( + left: &mut usize, + value: String, + truncated: &mut bool, + warned: &mut bool, + warnings: &mut Vec, + warning: &str, +) -> Option { + if value.len() > *left { + if !*warned { + warnings.push(warning.to_string()); + *warned = true; + } + *truncated = true; + None + } else { + *left -= value.len(); + Some(value) + } +} + +pub(crate) struct ValueBudget { + left: usize, + warned: bool, +} + +impl ValueBudget { + pub(crate) fn new(max_bytes: usize) -> Self { + Self { left: max_bytes, warned: false } + } + + pub(crate) fn take(&mut self, value: String, truncated: &mut bool, warnings: &mut Vec, warning: &str) -> Option { + retain_value(&mut self.left, value, truncated, &mut self.warned, warnings, warning) + } +} + /// A typed value (`Res_value`): data type and 32-bit data. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub struct ResValue { @@ -313,10 +372,10 @@ pub fn framework_attr(id: u32) -> Option<&'static str> { /// Decode a binary XML file. pub fn parse(data: &[u8]) -> Result { - parse_with_limits(data, MAX_NODES, MAX_DEPTH) + parse_with_limits(data, MAX_NODES, MAX_DEPTH, MAX_RETAINED_VALUE_BYTES) } -fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result { +fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize, max_value_bytes: usize) -> Result { let r = Reader::new(data); let (t, h, size) = chunk(&r, 0).ok_or_else(|| Error::Truncated("binary XML header".into()))?; if t != RES_XML { @@ -329,6 +388,7 @@ fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result< let mut pos = h; let mut depth = 0usize; let mut ns_stack: Vec<(String, String)> = Vec::new(); + let mut value_budget = ValueBudget::new(max_value_bytes); while pos < size { let Some((ct, ch, cs)) = chunk(&r, pos) else { doc.truncated = true; @@ -354,10 +414,7 @@ fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result< match ct { RES_STRING_POOL => match StringPool::parse(data, pos) { Ok(p) => { - if p.strings.len() < p.declared { - doc.truncated = true; - doc.warnings.push(format!("string pool was capped at {} of {} strings", p.strings.len(), p.declared)); - } + report_partial_string_pool(&p, "string pool", &mut doc.truncated, &mut doc.warnings); doc.pool = p; } Err(e) => doc.warnings.push(format!("string pool: {e}")), @@ -431,6 +488,9 @@ fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result< } else { raw.format(&doc.pool) }; + let value = value_budget + .take(value, &mut doc.truncated, &mut doc.warnings, "XML value budget reached; remaining values were omitted") + .unwrap_or_default(); attributes.push(Attribute { namespace: ans, name: aname, @@ -450,6 +510,9 @@ fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result< } XML_CDATA => { let text = r.u32_le(pos + ch).and_then(|i| doc.pool.get(i)).unwrap_or("").to_string(); + let text = value_budget + .take(text, &mut doc.truncated, &mut doc.warnings, "XML value budget reached; remaining values were omitted") + .unwrap_or_default(); doc.nodes.push(Node::Text { depth, text }); } _ => {} @@ -568,9 +631,13 @@ mod tests { #[test] fn shared_offsets_spend_a_pool_byte_budget() { - for utf8 in [true, false] { + // Each parse keeps 64 MiB of strings: the gate runs the UTF-8 pool with the appended bytes + // (the budget and the appended bytes together), nightly all four. + let full = craft_testkit::hostile::divisor() == 1; + let (encodings, appends): (&[bool], &[bool]) = if full { (&[true, false], &[false, true]) } else { (&[true], &[true]) }; + for &utf8 in encodings { let mut data = shared_ascii_pool(utf8, 8192); - for appended in [false, true] { + for &appended in appends { if appended { // Unrelated bytes after the chunk cannot buy more retained copies. data.resize(24 << 20, 0); @@ -639,6 +706,7 @@ mod tests { assert_eq!(parsed.get(1), parsed.get(0)); assert_eq!(parsed.get(2), Some("")); assert_eq!(parsed.get(3), Some("ok")); + assert_eq!(parsed.recovery_omitted, 1); } #[test] @@ -655,6 +723,7 @@ mod tests { assert_eq!(parsed.get(1).map(str::len), Some(0x8000)); assert_eq!(parsed.get(2), Some("")); assert_eq!(parsed.get(3), Some("ok")); + assert_eq!(parsed.recovery_omitted, 1); } #[test] @@ -670,6 +739,7 @@ mod tests { assert_eq!(left, remaining); assert_eq!(parsed.get(0).map(str::len), Some(length)); assert_eq!(parsed.get(1), Some("ok")); + assert_eq!(parsed.recovery_omitted, usize::from(length == 0)); } } @@ -681,10 +751,10 @@ mod tests { assert_eq!(left, 7); assert_eq!(parsed.get(0), Some("")); assert_eq!(parsed.get(1), Some("ok")); + assert_eq!(parsed.recovery_omitted, 0); } - #[test] - fn default_pool_budget_stops_repeated_recovery_before_later_long_strings() { + fn utf8_recovery_exhausted_pool() -> (Vec, usize) { let mut strings = vec![b'x'; 2 * 0x8000 + 16]; strings[..4].copy_from_slice(&[0x80, 0, 0x80, 0]); let long = append_legacy_ascii(&mut strings, 0x8000); @@ -694,13 +764,78 @@ mod tests { let repeated = MAX_RECOVERY_PROBES / 3 + 1; let mut offsets = vec![0; repeated]; offsets.extend([long, short]); - let data = pool_with_offsets(&offsets, &strings); + (pool_with_offsets(&offsets, &strings), repeated) + } + + #[test] + fn default_pool_budget_stops_repeated_recovery_before_later_long_strings() { + let (data, repeated) = utf8_recovery_exhausted_pool(); let parsed = StringPool::parse(&data, 0).unwrap(); assert_eq!(parsed.declared, repeated + 2); assert_eq!(parsed.strings.len(), repeated + 2); assert!(parsed.strings[..repeated].iter().all(String::is_empty)); assert_eq!(parsed.get(repeated as u32), Some("")); assert_eq!(parsed.get((repeated + 1) as u32), Some("ok")); + assert!(parsed.recovery_omitted > 0); + } + + #[test] + fn xml_and_resource_tables_disclose_recovery_omissions() { + let (pool, repeated) = utf8_recovery_exhausted_pool(); + let short_index = (repeated + 1) as u32; + { + let doc = parse(&pool_container(RES_XML, 8, &pool)).unwrap(); + assert!(doc.truncated); + assert!(doc.warnings.iter().any(|w| w.contains("string pool") && w.contains("UTF-8 recovery budget"))); + assert_eq!(doc.pool.get(short_index), Some("ok")); + assert!(doc.pool.recovery_omitted > 0); + } + let table = crate::arsc::parse(&pool_container(2, 12, &pool), crate::arsc::Limits::default()).unwrap(); + assert!(table.truncated); + assert!(table.warnings.iter().any(|w| w.contains("global string pool") && w.contains("UTF-8 recovery budget"))); + for (field, label) in [(268, "type"), (276, "key")] { + let mut package = pool_container(0x0200, 288, &pool); + package[8..12].copy_from_slice(&0x7fu32.to_le_bytes()); + package[field..field + 4].copy_from_slice(&288u32.to_le_bytes()); + let table = crate::arsc::parse(&pool_container(2, 12, &package), crate::arsc::Limits::default()).unwrap(); + assert!(table.truncated, "{label}"); + assert!( + table.warnings.iter().any(|w| w.contains(&format!("{label} string pool")) && w.contains("UTF-8 recovery budget")), + "{label}: {:?}", + table.warnings + ); + } + } + + #[test] + fn xml_value_budget_omits_long_copies_and_keeps_a_later_short_value() { + let long = "x".repeat(16); + let attrs = vec![ + fx::AxAttr { name: "a", res_id: None, val: fx::AxVal::Str(&long) }, + fx::AxAttr { name: "b", res_id: None, val: fx::AxVal::Str(&long) }, + fx::AxAttr { name: "c", res_id: None, val: fx::AxVal::Str("ok") }, + ]; + let bytes = fx::axml(&[fx::AxNode::Start("root", attrs), fx::AxNode::End("root")]); + let complete = parse(&bytes).unwrap(); + assert!(!complete.truncated); + let Node::Start { attributes, .. } = complete.nodes.iter().find(|n| matches!(n, Node::Start { name, .. } if name == "root")).unwrap() else { + panic!("expected the root start"); + }; + assert_eq!( + attributes.iter().map(|a| (a.name.as_str(), a.value.as_str())).collect::>(), + [("a", long.as_str()), ("b", long.as_str()), ("c", "ok")] + ); + + let partial = parse_with_limits(&bytes, MAX_NODES, MAX_DEPTH, 20).unwrap(); + assert!(partial.truncated); + assert!(partial.warnings.iter().any(|w| w.contains("value budget"))); + let Node::Start { attributes, .. } = partial.nodes.iter().find(|n| matches!(n, Node::Start { name, .. } if name == "root")).unwrap() else { + panic!("expected the root start"); + }; + assert_eq!( + attributes.iter().map(|a| (a.name.as_str(), a.value.as_str())).collect::>(), + [("a", long.as_str()), ("b", ""), ("c", "ok")] + ); } fn chunk_at(data: &[u8], kind: u16) -> usize { @@ -757,11 +892,11 @@ mod tests { #[test] fn dropping_a_close_event_marks_the_document_partial() { let bytes = fx::axml(&[fx::AxNode::Start("root", vec![]), fx::AxNode::End("root")]); - let complete = parse_with_limits(&bytes, 3, 1).unwrap(); + let complete = parse_with_limits(&bytes, 3, 1, MAX_RETAINED_VALUE_BYTES).unwrap(); assert!(!complete.truncated); assert!(matches!(complete.nodes.last(), Some(Node::End { depth: 0, .. }))); - let partial = parse_with_limits(&bytes, 2, 1).unwrap(); + let partial = parse_with_limits(&bytes, 2, 1, MAX_RETAINED_VALUE_BYTES).unwrap(); assert!(partial.truncated); assert_eq!(partial.nodes, complete.nodes[..2]); } @@ -770,19 +905,19 @@ mod tests { fn nesting_limit_keeps_an_exact_prefix_instead_of_saturating_depth() { let bytes = fx::axml(&[fx::AxNode::Start("root", vec![]), fx::AxNode::Start("child", vec![]), fx::AxNode::End("child"), fx::AxNode::End("root")]); - let complete = parse_with_limits(&bytes, 5, 2).unwrap(); + let complete = parse_with_limits(&bytes, 5, 2, MAX_RETAINED_VALUE_BYTES).unwrap(); assert!(!complete.truncated); assert!(matches!(complete.nodes[3], Node::End { depth: 1, .. })); assert!(matches!(complete.nodes[4], Node::End { depth: 0, .. })); - let partial = parse_with_limits(&bytes, 5, 1).unwrap(); + let partial = parse_with_limits(&bytes, 5, 1, MAX_RETAINED_VALUE_BYTES).unwrap(); assert!(partial.truncated); assert_eq!(partial.nodes, complete.nodes[..2]); } #[test] fn values_format() { - let p = StringPool { strings: vec!["x".into()], utf8: false, declared: 1 }; + let p = StringPool { strings: vec!["x".into()], utf8: false, declared: 1, recovery_omitted: 0 }; assert_eq!(ResValue { data_type: 0x05, data: (16 << 8) | 1 }.format(&p), "16dp"); assert_eq!(ResValue { data_type: 0x12, data: 0xffff_ffff }.format(&p), "true"); assert_eq!(ResValue { data_type: 0x1c, data: 0xff00_ff00 }.format(&p), "#ff00ff00"); diff --git a/crates/audio-dsp/Cargo.toml b/crates/audio-dsp/Cargo.toml index 5d192e9d3..46e708b73 100644 --- a/crates/audio-dsp/Cargo.toml +++ b/crates/audio-dsp/Cargo.toml @@ -12,3 +12,6 @@ workspace = true # No dependencies: planar `&mut [f32]` slices in, planar slices out. [dependencies] + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/audio-dsp/src/biquad.rs b/crates/audio-dsp/src/biquad.rs index 12d00f5a9..6b10add2b 100644 --- a/crates/audio-dsp/src/biquad.rs +++ b/crates/audio-dsp/src/biquad.rs @@ -448,7 +448,7 @@ mod tests { #[test] fn every_effect_recovers_after_one_non_finite_sample() { let mut failures = Vec::new(); - for e in crate::effects() { + for e in crate::testutil::sampled_effects() { for setting in [Setting::Default, Setting::Moved, Setting::Min] { let (l, r, _) = run_effect(e.id, setting, None); let clean = tail_rms(&l, &r); @@ -505,7 +505,7 @@ mod tests { #[test] fn nan_parameter_values_never_produce_non_finite_output() { let mut bad = Vec::new(); - for e in crate::effects() { + for e in crate::testutil::sampled_effects() { let ids: Vec<&str> = crate::create_effect(e.id, SR as f32, 2).unwrap().params().iter().map(|p| p.id).collect(); for id in ids { let mut fx = crate::create_effect(e.id, SR as f32, 2).unwrap(); @@ -525,7 +525,7 @@ mod tests { #[test] fn subnormal_input_stays_finite_and_decays() { let mut bad = Vec::new(); - for e in crate::effects() { + for e in crate::testutil::sampled_effects() { for setting in [Setting::Default, Setting::Min] { let mut fx = crate::create_effect(e.id, SR as f32, 2).unwrap(); for p in fx.params() { diff --git a/crates/audio-dsp/src/effects.rs b/crates/audio-dsp/src/effects.rs index 29c406d7a..679b7c5f9 100644 --- a/crates/audio-dsp/src/effects.rs +++ b/crates/audio-dsp/src/effects.rs @@ -234,7 +234,7 @@ mod tests { let src_l = noise(1, n, 0.7); let src_r = noise(2, n, 0.7); let change_at = 11111; - for e in effects() { + for e in crate::testutil::sampled_effects() { let run = |sizes: &mut dyn FnMut() -> usize| { let mut fx = (e.create)(SR, 2); let (mut l, mut r) = (src_l.clone(), src_r.clone()); @@ -289,8 +289,9 @@ mod tests { // One thread per effect. The tail stays 40 s long: delays, reverbs and graphic EQs still // produce output in its last second, some of it within 3x of the smallest normal f32. std::thread::scope(|scope| { - for e in effects() { + for e in crate::testutil::sampled_effects() { scope.spawn(move || { + let started = std::time::Instant::now(); for setting in [0.0f32, 1.0] { let mut fx = (e.create)(SR, 2); for p in e.params { @@ -318,6 +319,9 @@ mod tests { ); } } + if started.elapsed() > std::time::Duration::from_secs(1) { + eprintln!("DIAG extreme settings: {} took {:?}", e.id, started.elapsed()); + } }); } }); @@ -325,7 +329,7 @@ mod tests { #[test] fn reset_restores_initial_behavior() { - for e in effects() { + for e in crate::testutil::sampled_effects() { let mut fx = (e.create)(SR, 2); let x = noise(8, 6000, 0.5); let (mut a1, mut a2) = (x.clone(), x.clone()); diff --git a/crates/audio-dsp/src/effects/behavior_tests.rs b/crates/audio-dsp/src/effects/behavior_tests.rs index dee405664..0b6f05a80 100644 --- a/crates/audio-dsp/src/effects/behavior_tests.rs +++ b/crates/audio-dsp/src/effects/behavior_tests.rs @@ -429,7 +429,7 @@ fn convolution_reverb_impulses() { for (k, want_rt) in [(0usize, 0.45), (2, 1.9), (4, 1.6)] { let mut e = fx("convolution_reverb", &[("impulse", k as f32), ("mix", 100.0), ("width", 100.0)]); let lat = e.latency(); - let n = (SR * 4.0) as usize; + let n = (SR * 3.0) as usize; let mut imp = vec![0.0f32; n]; imp[0] = 1.0; let (l, r) = run(e.as_mut(), &imp, &imp); @@ -444,7 +444,7 @@ fn convolution_reverb_impulses() { } // Room size shortens the tail. let mut a = fx("convolution_reverb", &[("impulse", 2.0), ("mix", 100.0), ("room_size", 40.0)]); - let n = (SR * 3.0) as usize; + let n = (SR * 2.5) as usize; let mut imp = vec![0.0f32; n]; imp[0] = 1.0; let (l, _) = run(a.as_mut(), &imp, &imp); diff --git a/crates/audio-dsp/src/effects/stft.rs b/crates/audio-dsp/src/effects/stft.rs index 160362fc9..c4b9ed707 100644 --- a/crates/audio-dsp/src/effects/stft.rs +++ b/crates/audio-dsp/src/effects/stft.rs @@ -470,7 +470,7 @@ mod tests { use crate::AudioEffect; use crate::effects::DeNoise; const SR: f32 = 48_000.0; - let len = 512 * 940; + let len = 512 * 320; let mut rng = Rng::new(9); let a: Vec = (0..len).map(|_| 0.1 * rng.uniform()).collect(); let t = crate::testutil::sine(700.0, 0.2, SR as f64, len, 0.0); diff --git a/crates/audio-dsp/src/lib.rs b/crates/audio-dsp/src/lib.rs index b47d15fc1..59bfaa174 100644 --- a/crates/audio-dsp/src/lib.rs +++ b/crates/audio-dsp/src/lib.rs @@ -434,6 +434,12 @@ pub(crate) fn block_len(channels: &[&mut [f32]]) -> usize { #[cfg(test)] pub(crate) mod testutil { + /// Every `CRAFT_HOSTILE_DIVISOR`-th registered effect: the gate's sample of a sweep over all + /// effects; the nightly run (no divisor) covers them all. + pub fn sampled_effects() -> impl Iterator { + crate::effects().iter().step_by(craft_testkit::hostile::divisor()) + } + /// Tiny deterministic PRNG (xorshift64*) for tests. pub struct Rng(u64); impl Rng { diff --git a/crates/audio-dsp/src/loudness.rs b/crates/audio-dsp/src/loudness.rs index 9cfcd18c0..a89a22593 100644 --- a/crates/audio-dsp/src/loudness.rs +++ b/crates/audio-dsp/src/loudness.rs @@ -625,7 +625,7 @@ mod tests { fn tech3341_case1_and_2_stereo_sine() { for (sr, freq) in [(48000.0, 1000.0), (44100.0, 997.0), (96000.0, 1000.0)] { for level in [-23.0, -33.0] { - let x = segments(freq, sr, &[(20.0, level)]); + let x = segments(freq, sr, &[(6.0, level)]); let m = stereo_measure(&x, sr); assert!((m.integrated() - level).abs() < 0.1, "sr {sr} I {}", m.integrated()); assert!((m.momentary() - level).abs() < 0.1, "M {}", m.momentary()); @@ -639,7 +639,7 @@ mod tests { #[test] fn interleaved_matches_planar() { let sr = 48000.0; - let x = segments(1000.0, sr, &[(5.0, -20.0)]); + let x = segments(1000.0, sr, &[(2.0, -20.0)]); let il: Vec = x.iter().flat_map(|&v| [v, v]).collect(); let mut m = LoudnessMeter::new(sr, 2); m.process_interleaved(&il); @@ -650,12 +650,12 @@ mod tests { #[test] fn tech3341_case3_4_gating() { let sr = 48000.0; - // Case 3: -36 / -23 / -36 dBFS for 10 / 60 / 10 s → -23.0 LUFS. - let x = segments(1000.0, sr, &[(10.0, -36.0), (60.0, -23.0), (10.0, -36.0)]); + // Case 3: -36 / -23 / -36 dBFS for 3 / 18 / 3 s → -23.0 LUFS. + let x = segments(1000.0, sr, &[(3.0, -36.0), (18.0, -23.0), (3.0, -36.0)]); let m = stereo_measure(&x, sr); assert!((m.integrated() + 23.0).abs() < 0.1, "{}", m.integrated()); - // Case 4: -72 / -36 / -23 / -36 / -72 dBFS for 10/10/60/10/10 s → -23.0 LUFS. - let x = segments(1000.0, sr, &[(10.0, -72.0), (10.0, -36.0), (60.0, -23.0), (10.0, -36.0), (10.0, -72.0)]); + // Case 4: -72 / -36 / -23 / -36 / -72 dBFS for 3/3/18/3/3 s → -23.0 LUFS. + let x = segments(1000.0, sr, &[(3.0, -72.0), (3.0, -36.0), (18.0, -23.0), (3.0, -36.0), (3.0, -72.0)]); let m = stereo_measure(&x, sr); assert!((m.integrated() + 23.0).abs() < 0.1, "{}", m.integrated()); } @@ -663,7 +663,7 @@ mod tests { #[test] fn tech3341_case5_relative_gate() { let sr = 48000.0; - let x = segments(1000.0, sr, &[(20.0, -26.0), (20.1, -20.0), (20.0, -26.0)]); + let x = segments(1000.0, sr, &[(5.0, -26.0), (5.025, -20.0), (5.0, -26.0)]); let m = stereo_measure(&x, sr); assert!((m.integrated() + 23.0).abs() < 0.1, "{}", m.integrated()); } @@ -683,7 +683,8 @@ mod tests { #[test] fn tech3342_loudness_range() { - let sr = 48000.0; + // The range is level-relative, so a low rate gives the same reading for far fewer samples. + let sr = 16000.0; let cases: [(&[(f64, f64)], f64); 4] = [ (&[(20.0, -20.0), (20.0, -30.0)], 10.0), (&[(20.0, -20.0), (20.0, -15.0)], 5.0), @@ -712,15 +713,17 @@ mod tests { assert_eq!(before, 0.0); assert!((m.file_loudness_range() - s.loudness_range_lu).abs() < 1e-12); assert_eq!(m.loudness_range(), before); - // A steady program keeps a file range near 0. - let y = segments(1000.0, sr, &[(30.0, -20.0)]); - assert!(measure(&[&y, &y], sr).loudness_range_lu < 1.0); + // A steady program keeps a file range near 0. It must be long beside the 1.5 s silence tail, so it runs at a + // low rate (the range is level-relative). + let low = 16000.0; + let y = segments(1000.0, low, &[(30.0, -20.0)]); + assert!(measure(&[&y, &y], low).loudness_range_lu < 1.0); } #[test] fn log_sweep_matches_analytic_k_weighting() { let sr = 48000.0; - let secs = 20.0; + let secs = 6.0; let n = (sr * secs) as usize; let (f1, f2) = (20.0f64, 20000.0f64); let k = (f2 / f1).ln(); @@ -749,7 +752,7 @@ mod tests { #[test] fn surround_weights() { let sr = 48000.0; - let x = segments(1000.0, sr, &[(10.0, -30.0)]); + let x = segments(1000.0, sr, &[(2.0, -30.0)]); let z = vec![0.0f32; x.len()]; // Signal only in Ls of a 5.1 layout → +1.5 dB weighting vs. front channel. let mut front = LoudnessMeter::new(sr, 6); @@ -767,7 +770,7 @@ mod tests { #[test] fn surround_weights_follow_speaker_positions() { let sr = 48000.0; - let x = segments(1000.0, sr, &[(10.0, -30.0)]); + let x = segments(1000.0, sr, &[(2.0, -30.0)]); let z = vec![0.0f32; x.len()]; let only = |n: usize, ch: usize| { let mut m = LoudnessMeter::new(sr, n); @@ -776,7 +779,8 @@ mod tests { m.integrated() }; let front = only(8, 0); - assert!((only(8, 4) - front).abs() < 0.01, "back {}", only(8, 4) - front); + let back = only(8, 4) - front; + assert!(back.abs() < 0.01, "back {back}"); assert!((only(8, 6) - front - 10.0 * 1.41f64.log10()).abs() < 0.01); assert_eq!(only(8, 3), f64::NEG_INFINITY); assert_eq!(default_channel_weights(12), vec![1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.41, 1.41, 1.0, 1.0, 1.0, 1.0]); @@ -864,14 +868,14 @@ mod tests { assert_eq!((m.sample_rate(), m.channels()), (f64::from(crate::FALLBACK_SAMPLE_RATE), 1)); assert_eq!(LoudnessMeter::new(48_000.0, usize::MAX).channels(), crate::MAX_CHANNELS); let sr = 48_000.0; - let mut x = segments(1000.0, sr, &[(5.0, -23.0)]); + let mut x = segments(1000.0, sr, &[(2.0, -23.0)]); x[1000] = f32::NAN; x[2000] = f32::INFINITY; let m = stereo_measure(&x, sr); assert!((m.integrated() + 23.0).abs() < 0.1, "I {}", m.integrated()); assert!(m.true_peak().is_finite() && m.momentary().is_finite()); // A NaN or negative weight leaves its channel out instead of poisoning the sum. - let x = segments(1000.0, sr, &[(5.0, -23.0)]); + let x = segments(1000.0, sr, &[(2.0, -23.0)]); let mut m = LoudnessMeter::new(sr, 3); m.set_channel_weights(&[1.0, f64::NAN, -2.0]); m.process(&[&x, &x, &x]); @@ -883,12 +887,12 @@ mod tests { #[test] fn reset_clears_everything() { let sr = 48000.0; - let x = segments(1000.0, sr, &[(5.0, -20.0)]); + let x = segments(1000.0, sr, &[(2.0, -20.0)]); let mut m = stereo_measure(&x, sr); m.reset(); assert_eq!(m.integrated(), f64::NEG_INFINITY); assert_eq!(m.true_peak(), 0.0); - let x = segments(1000.0, sr, &[(5.0, -30.0)]); + let x = segments(1000.0, sr, &[(2.0, -30.0)]); m.process(&[&x, &x]); assert!((m.integrated() + 30.0).abs() < 0.1); } @@ -942,7 +946,7 @@ mod tests { assert_eq!(normalize_gain_db_peak_limited(-30.0, -23.0, -10.0, -1.0), 7.0); // Applying the gain lands on target. let sr = 48000.0; - let x = segments(1000.0, sr, &[(10.0, -31.3)]); + let x = segments(1000.0, sr, &[(4.0, -31.3)]); let m = stereo_measure(&x, sr); let g = 10f64.powf(normalize_gain_db(m.integrated(), -16.0) / 20.0) as f32; let y: Vec = x.iter().map(|v| v * g).collect(); diff --git a/crates/audio-dsp/src/resample.rs b/crates/audio-dsp/src/resample.rs index 150eba11c..12b566470 100644 --- a/crates/audio-dsp/src/resample.rs +++ b/crates/audio-dsp/src/resample.rs @@ -418,13 +418,16 @@ mod tests { /// returns `MAX_RESAMPLE_BLOCK` frames. #[test] fn source_held_and_block_length_are_bounded() { + // At this ratio a pull holds about 42 output frames' worth of source, so 64 frames take two pulls; each output + // frame pulls 1,536 source frames of 64 channels, so nightly runs a longer block. + let frames = if craft_testkit::hostile::divisor() == 1 { 1_024 } else { 64 }; let mut r = StreamResampler::new(1_536_000, 1_000); let mut widest = 0; - let out = r.process(0, 1_024, |_, frames| { + let out = r.process(0, frames, |_, frames| { widest = widest.max(frames); vec![vec![0.5; frames]; 64] }); - assert_eq!((out.len(), out[0].len()), (64, 1_024)); + assert_eq!((out.len(), out[0].len()), (64, frames)); assert!(widest <= MAX_RESAMPLE_HELD / 64, "{widest}"); assert!(r.held.iter().map(Vec::len).sum::() <= MAX_RESAMPLE_HELD); let mut r = StreamResampler::new(48_000, 48_000); diff --git a/crates/audio-dsp/src/sync.rs b/crates/audio-dsp/src/sync.rs index 56416ef87..d117ecba3 100644 --- a/crates/audio-dsp/src/sync.rs +++ b/crates/audio-dsp/src/sync.rs @@ -454,11 +454,11 @@ mod tests { #[test] fn pure_delay_exact_both_signs() { let sr = 48_000; - let s = speechy(sr as f64, 12.0, 1); - for delay in [0i64, 1, 7, 12_345, 96_001, -4_321, -50_000] { + let s = speechy(sr as f64, 6.0, 1); + for delay in [0i64, 1, 7, 12_345, -4_321, -50_000] { // b = s shifted: b[n] = s[n + delay] let b: Vec = - (0..400_000i64).map(|n| if n + delay >= 0 && ((n + delay) as usize) < s.len() { s[(n + delay) as usize] } else { 0.0 }).collect(); + (0..200_000i64).map(|n| if n + delay >= 0 && ((n + delay) as usize) < s.len() { s[(n + delay) as usize] } else { 0.0 }).collect(); let r = find_offset(&s, &b, sr, &SyncOptions::default()).unwrap(); assert_eq!(r.lag, delay, "{r:?}"); assert!(r.reliable(), "{r:?}"); @@ -471,8 +471,8 @@ mod tests { #[test] fn multi_mic_offsets_within_one_sample() { let sr = 48_000u32; - let src = speechy(sr as f64, 30.0, 7); - let len = 30 * sr as usize; + let src = speechy(sr as f64, 12.0, 7); + let len = 12 * sr as usize; // mic k records src delayed by d_k: mic_k[n] = src[n - d_k] let cases: [(f64, f32, Option, f32); 4] = [(0.0, 1.0, None, 40.0), (2_345.0, 0.1, None, 25.0), (-31_337.4, 3.0, Some(0.3), 10.0), (150_000.6, 0.5, None, 3.0)]; @@ -551,7 +551,7 @@ mod tests { #[test] fn max_lag_limits_the_search() { let sr = 48_000; - let s = speechy(sr as f64, 10.0, 5); + let s = speechy(sr as f64, 5.0, 5); let b: Vec = s[48_000..].to_vec(); let r = find_offset(&s, &b, sr, &SyncOptions { max_lag: Some(60_000), ..Default::default() }).unwrap(); assert_eq!(r.lag, 48_000); @@ -560,7 +560,7 @@ mod tests { // Non-finite samples count as silence (also in the refinement's window search). let mut t = s.clone(); t[1_000] = f32::NAN; - t[300_000] = f32::INFINITY; + t[200_000] = f32::INFINITY; let r = find_offset(&t, &b, sr, &SyncOptions::default()).unwrap(); assert_eq!(r.lag, 48_000); assert!(r.confidence.is_finite() && r.lag_fine.is_finite(), "{r:?}"); @@ -586,15 +586,15 @@ mod tests { assert!(r.reliable(), "{r:?}"); } - /// A coarse budget that asks for more than [`MAX_DECIMATION`] still scales the coarse lag by - /// the factor applied: 2 × 9 M samples at 8 kHz with a 4,096-sample budget asks for 4,395. + /// A decimation factor asked for beyond [`MAX_DECIMATION`] still scales the coarse lag by the + /// factor applied. A sample rate of 2,048,001 Hz against a 500 Hz coarse rate asks for 4,097. #[test] fn a_coarse_factor_above_the_cap_still_finds_the_lag() { - let sr = 8_000; - let s = speechy(sr as f64, 2_300.0, 9); - let lag = 400_000usize; + let sr = 2_048_001; + let s = speechy(sr as f64, 0.8, 9); + let lag = 100_000usize; let b: Vec = s[lag..].to_vec(); - let opts = SyncOptions { max_coarse_samples: 4_096, ..Default::default() }; + let opts = SyncOptions { coarse_rate: 500, ..Default::default() }; let r = find_offset(&s, &b, sr, &opts).unwrap(); assert_eq!(r.lag, lag as i64, "{r:?}"); } @@ -623,11 +623,11 @@ mod tests { let sr = 48_000u32; let delay = 112_560i64; for seed in [1, 3, 7] { - let src = speechy(sr as f64, 24.0, seed); + let src = speechy(sr as f64, 10.0, seed); let scratch = scratch_track(&src, sr, 100 + seed); for sign in [1.0f32, -1.0] { // b[n] = scratch[n + delay] - let b: Vec = (0..16 * sr as i64).map(|n| sign * scratch.get((n + delay) as usize).copied().unwrap_or(0.0)).collect(); + let b: Vec = (0..7 * sr as i64).map(|n| sign * scratch.get((n + delay) as usize).copied().unwrap_or(0.0)).collect(); let r = find_offset(&src, &b, sr, &SyncOptions::default()).unwrap(); assert_eq!(r.inverted, sign < 0.0, "seed {seed}, sign {sign}: {r:?}"); // the filters delay the scratch track by a few samples diff --git a/crates/audio/src/aac/sbr/mod.rs b/crates/audio/src/aac/sbr/mod.rs index 752cd03a0..d3c18b0e3 100644 --- a/crates/audio/src/aac/sbr/mod.rs +++ b/crates/audio/src/aac/sbr/mod.rs @@ -493,7 +493,8 @@ mod tests { }; let mut e = Element::new(1, RATE); let mut pair = Element::new(2, RATE); - for i in 0..600 { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs 1/N of the rounds. + for i in 0..600usize.div_ceil(craft_media_testkit::hostile::divisor()) { let mut data = good.clone(); for _ in 0..1 + next() % 6 { let bit = next() as usize % (8 * data.len()); diff --git a/crates/audio/src/ac3/encoder/tests.rs b/crates/audio/src/ac3/encoder/tests.rs index 27b232db9..a60efb768 100644 --- a/crates/audio/src/ac3/encoder/tests.rs +++ b/crates/audio/src/ac3/encoder/tests.rs @@ -105,8 +105,14 @@ fn dec3_describes_dependent_rear_pair_and_aggregate_rate() -> Result<(), Box Result<(), Box> { - for rate in [32000, 44100, 48000] { - for bitrate in super::super::BITRATES { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs every N-th bit rate, from a different offset for + // each sample rate, so the rates together still reach every bit rate. + let step = craft_media_testkit::hostile::divisor(); + for (ri, rate) in [32000, 44100, 48000].into_iter().enumerate() { + for (bi, bitrate) in super::super::BITRATES.into_iter().enumerate() { + if !(bi + ri).is_multiple_of(step) { + continue; + } for mode in [CodingMode::Mono, CodingMode::ThreeFrontTwoSurround] { let cfg = Config { codec: Codec::Ac3, sample_rate: rate, bitrate_kbps: bitrate, mode, lfe: mode == CodingMode::ThreeFrontTwoSurround }; diff --git a/crates/audio/tests/codecs/aac/robustness.rs b/crates/audio/tests/codecs/aac/robustness.rs index 2f97f2ae6..e3e622ce3 100644 --- a/crates/audio/tests/codecs/aac/robustness.rs +++ b/crates/audio/tests/codecs/aac/robustness.rs @@ -28,7 +28,8 @@ fn mutated_access_units_never_panic() { let mut errors = 0usize; for (asc, aus) in corpus() { let mut dec = Decoder::new(&asc).unwrap(); - for round in 0..3000 { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs 1/N of the rounds. + for round in 0..3000usize.div_ceil(craft_media_testkit::hostile::divisor()) { let mut au = aus[rand(aus.len())].clone(); match round % 6 { 0 => { diff --git a/crates/audio/tests/codecs/opus/robustness.rs b/crates/audio/tests/codecs/opus/robustness.rs index 781b76701..9ae1e83ea 100644 --- a/crates/audio/tests/codecs/opus/robustness.rs +++ b/crates/audio/tests/codecs/opus/robustness.rs @@ -26,7 +26,8 @@ fn random_garbage_never_panics() { for channels in 1..=2 { let mut dec = StreamDecoder::new(rate, channels).unwrap(); let mut out = Vec::new(); - for i in 0..3000 { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs 1/N of the packets. + for i in 0..3000usize.div_ceil(craft_media_testkit::hostile::divisor()) { let len = (rng.next() % 400) as usize; let mut pkt: Vec = (0..len).map(|_| rng.next() as u8).collect(); if let Some(t) = pkt.first_mut() { @@ -52,7 +53,7 @@ fn multistream_garbage_never_panics() { h.extend([1, 6, 0x38, 0x01, 0x80, 0xBB, 0, 0, 0, 0, 1, 4, 2, 0, 4, 1, 2, 3, 5]); let mut dec = Decoder::new(&h).unwrap(); let mut rng = Rng(42); - for _ in 0..2000 { + for _ in 0..2000usize.div_ceil(craft_media_testkit::hostile::divisor()) { let len = (rng.next() % 600) as usize; let pkt: Vec = (0..len).map(|_| rng.next() as u8).collect(); if let Ok(out) = dec.decode(Some(&pkt)) { diff --git a/crates/audio/tests/codecs/opusenc/modes.rs b/crates/audio/tests/codecs/opusenc/modes.rs index 263858560..a48ad2d44 100644 --- a/crates/audio/tests/codecs/opusenc/modes.rs +++ b/crates/audio/tests/codecs/opusenc/modes.rs @@ -49,12 +49,14 @@ fn band_edge(bw: Bandwidth) -> f64 { } const LEN: usize = 96_000; +/// The length of the sweeps over many encodes: one second. +const SHORT: usize = 48_000; #[test] fn every_mode_and_bandwidth_decodes() { - let sp = speech(LEN + 40_000, 11); - let left = sp[..LEN].to_vec(); - let right: Vec = sp[40_000..].iter().map(|v| v * 0.6).collect(); + let sp = speech(SHORT + 20_000, 11); + let left = sp[..SHORT].to_vec(); + let right: Vec = sp[20_000..].iter().map(|v| v * 0.6).collect(); for (mode, bw, config, rate) in [ (Mode::Silk, Bandwidth::Narrowband, 1u8, 8_000u32), (Mode::Silk, Bandwidth::Mediumband, 5, 11_000), @@ -149,8 +151,8 @@ fn silk_music_quality() { #[test] fn bitrate_tracking() { - let sp = speech(LEN, 13); - let mu = music(LEN); + let sp = speech(SHORT, 13); + let mu = music(SHORT); for (name, x) in [("speech", &sp), ("music", &mu)] { for (mode, bw, rate) in [ (Mode::Silk, Bandwidth::Narrowband, 6_000u32), @@ -178,10 +180,10 @@ fn bitrate_tracking() { #[test] fn stereo_silk_and_hybrid() { - let sp = speech(LEN + 40_000, 21); - let a = sp[..LEN].to_vec(); - let b: Vec = sp[40_000..].iter().map(|v| v * 0.7).collect(); - let mu = music(LEN); + let sp = speech(SHORT + 20_000, 21); + let a = sp[..SHORT].to_vec(); + let b: Vec = sp[20_000..].iter().map(|v| v * 0.7).collect(); + let mu = music(SHORT); let cases: Vec<(&str, Vec, Vec)> = vec![ ("dual mono", a.clone(), a.clone()), ("panned", a.iter().map(|v| v * 0.9).collect(), a.iter().map(|v| v * 0.35).collect()), diff --git a/crates/audio/tests/flac_decode.rs b/crates/audio/tests/flac_decode.rs index d25237251..214898c23 100644 --- a/crates/audio/tests/flac_decode.rs +++ b/crates/audio/tests/flac_decode.rs @@ -132,15 +132,17 @@ fn track_decoder_uses_streaminfo_layout_and_packet_length() { #[test] fn hostile_input_is_an_error_not_a_panic() { - let src = signal(2, 6000, 16, 11); + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs every N-th cut and flipped byte. + let step = craft_media_testkit::hostile::divisor(); + let src = signal(2, 3500, 16, 11); let file = encode(&src, 44_100, 16, 1152, 5); - for n in 0..file.len().min(3000) { + for n in (0..file.len().min(3000)).step_by(step) { let _ = decode(&file[..n]); } // A cut file is truncated, not silently shorter. assert!(decode(&file[..file.len() - 5]).is_err()); // Every bit flip in the first frames is caught by a CRC or another check, never a panic. - for i in 0..file.len().min(2500) { + for i in (0..file.len().min(2500)).step_by(step) { for bit in 0..8 { let mut c = file.clone(); c[i] ^= 1 << bit; diff --git a/crates/audio/tests/vorbis_decode_hostile.rs b/crates/audio/tests/vorbis_decode_hostile.rs index fba004e10..4bbccfe46 100644 --- a/crates/audio/tests/vorbis_decode_hostile.rs +++ b/crates/audio/tests/vorbis_decode_hostile.rs @@ -57,7 +57,8 @@ fn damaged_headers_never_panic() { let mut seed = 99u32; for which in [0usize, 2] { let len = p.headers[which].len(); - for _ in 0..800 { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs 1/N of the mutations. + for _ in 0..800usize.div_ceil(craft_media_testkit::hostile::divisor()) { let mut h = p.headers.clone(); for _ in 0..1 + xorshift(&mut seed) % 3 { let at = xorshift(&mut seed) as usize % len; diff --git a/crates/automation/src/actions/file.rs b/crates/automation/src/actions/file.rs index 845fd82a0..3553932c9 100644 --- a/crates/automation/src/actions/file.rs +++ b/crates/automation/src/actions/file.rs @@ -22,6 +22,12 @@ pub struct ActionsFile { /// Sets that hold no action. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub sets: Vec, + /// Every set name in display order, empty sets included. Written only when loading `actions` + /// and `sets` would not give this order (the actions' sets in order of first appearance, then + /// the empty sets), so files in that natural order, PhotoCraft's included, save unchanged. + /// Files without it load in the natural order. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub set_order: Vec, /// The folder occurrences a PhotoCraft file carried; empty for every other file. #[serde(skip)] pub(super) occurrences: FileOccurrences, @@ -55,6 +61,8 @@ struct RawFile { #[serde(default)] sets: Vec, #[serde(default)] + set_order: Vec, + #[serde(default)] set_rows: Vec, } @@ -71,7 +79,7 @@ impl From for ActionsFile { let (actions, occurrences): (Vec, Vec) = raw.actions.into_iter().map(|raw| (raw.action, raw.occurrence)).unzip(); let empty = raw.set_rows.is_empty() && occurrences.iter().all(|occurrence| *occurrence == ActionOccurrence::default()); let occurrences = if empty { FileOccurrences::default() } else { FileOccurrences { set_rows: raw.set_rows, actions: occurrences } }; - ActionsFile { version: raw.version, actions, sets: raw.sets, occurrences } + ActionsFile { version: raw.version, actions, sets: raw.sets, set_order: raw.set_order, occurrences } } } @@ -117,7 +125,7 @@ impl ActionsFile { /// A file of version [`VERSION`](Self::VERSION) with `actions` and the empty `sets`. pub fn new(actions: Vec, sets: Vec) -> Self { - ActionsFile { version: Self::VERSION, actions, sets, occurrences: FileOccurrences::default() } + ActionsFile { version: Self::VERSION, actions, sets, set_order: Vec::new(), occurrences: FileOccurrences::default() } } /// Reads a file's JSON text. diff --git a/crates/automation/src/actions/list.rs b/crates/automation/src/actions/list.rs index 4828bcb13..ce533f746 100644 --- a/crates/automation/src/actions/list.rs +++ b/crates/automation/src/actions/list.rs @@ -576,12 +576,13 @@ impl ActionList { /// actions sharing a name, the file's shortcut owner keeps the name. The stored ids come back /// in [`MergedFile::ids`]. pub fn merge_file(&mut self, file: ActionsFile, replace: bool, mut calls: impl FnMut(&mut ActionStep, &[(String, String)])) -> MergedFile { - let ActionsFile { mut actions, sets, occurrences, .. } = file; + let ActionsFile { mut actions, sets, set_order, occurrences, .. } = file; if replace { let named: BTreeSet<&str> = actions .iter() .filter_map(|action| action.set.as_deref()) .chain(sets.iter().map(String::as_str)) + .chain(set_order.iter().map(String::as_str)) .chain(occurrences.set_rows.iter().map(String::as_str)) .collect(); self.actions.retain(|action| !action.set.as_deref().is_some_and(|set| named.contains(set))); @@ -596,6 +597,9 @@ impl ActionList { for (&i, name) in order.iter().zip(claimed) { given[i] = name; } + for set in &set_order { + self.record_set(set); + } let mut merged = MergedFile::default(); let ids = file_ids(&occurrences.actions); for (index, (mut action, name)) in actions.into_iter().zip(given).enumerate() { @@ -757,10 +761,20 @@ impl ActionList { self.touch(); } - /// The list as a file (version [`ActionsFile::VERSION`]; the empty sets in `sets`). + /// The list as a file (version [`ActionsFile::VERSION`]; the empty sets in `sets`, the set order in `set_order` when it is not the natural one). pub fn to_file(&self) -> ActionsFile { let empty = self.sets().into_iter().filter(|set| !self.actions.iter().any(|action| action.set.as_deref() == Some(*set))); - ActionsFile::new(self.actions.clone(), empty.map(str::to_owned).collect()) + let mut file = ActionsFile::new(self.actions.clone(), empty.map(str::to_owned).collect()); + let mut natural: Vec<&str> = Vec::new(); + for set in self.actions.iter().filter_map(|action| action.set.as_deref()).chain(file.sets.iter().map(String::as_str)) { + if !natural.contains(&set) { + natural.push(set); + } + } + if natural != self.sets() { + file.set_order = self.sets().into_iter().map(str::to_owned).collect(); + } + file } /// Puts `set` at the end of the set order when the order lacks it. diff --git a/crates/automation/src/actions/tests.rs b/crates/automation/src/actions/tests.rs index 7bea5df8c..2ae7845e9 100644 --- a/crates/automation/src/actions/tests.rs +++ b/crates/automation/src/actions/tests.rs @@ -80,6 +80,22 @@ fn action_list_file_round_trip_keeps_pc_json() { assert_eq!(back.sets, ["Empty"]); assert_eq!(ActionList::from_file(back).sets(), ["S", "Empty"]); } +// An empty set made before filled ones keeps its place through a save; a file of the older layout +// (empty sets in `sets`, no `set_order`) loads with its filled sets first. +#[trial] +fn set_order_survives_the_file() { + let mut list = ActionList::new(); + list.new_set("A").unwrap(); + list.new_set("B").unwrap(); + list.new_set("C").unwrap(); + list.push(Action { set: Some("B".into()), ..action("X", &[]) }).unwrap(); + list.push(Action { set: Some("C".into()), ..action("Y", &[]) }).unwrap(); + let back = ActionList::from_file(ActionsFile::from_json(&list.to_file().to_json().unwrap()).unwrap()); + assert_eq!(back.sets(), ["A", "B", "C"]); + + let old = r#"{"version":1,"actions":[{"name":"X","steps":[],"set":"F"}],"sets":["E"]}"#; + assert_eq!(ActionList::from_file(ActionsFile::from_json(old).unwrap()).sets(), ["F", "E"]); +} // A file that repeats a name keeps a later action's own name: `Foo, Foo, Foo 2` renames the repeat // (`Foo 3`), never the real `Foo 2`; a merge does the same against the names already in the list. #[trial] diff --git a/crates/automation/src/client_tests.rs b/crates/automation/src/client_tests.rs index 4718057ea..46687dae3 100644 --- a/crates/automation/src/client_tests.rs +++ b/crates/automation/src/client_tests.rs @@ -10,12 +10,18 @@ use super::*; const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; +/// Writes `reply` and its newline in one write. `writeln!` on a bare stream writes in pieces, so the client can see +/// part of a line and close the connection before the rest is sent. +fn say(out: &mut impl std::io::Write, reply: serde_json::Value) -> std::io::Result<()> { + out.write_all(format!("{reply}\n").as_bytes()) +} + // call returns Ok(result) for ok replies and Err(error) otherwise. // A stale reply left by a timed-out call is skipped, and a transport failure closes the client. #[trial] fn replies_are_matched_by_id() { - use std::io::{BufRead, Write}; + use std::io::BufRead; let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); let server = std::thread::spawn(move || { @@ -24,11 +30,11 @@ fn replies_are_matched_by_id() { let mut out = stream; let mut line = String::new(); reader.read_line(&mut line).unwrap(); - writeln!(out, "{}", json!({"id": 1, "ok": true})).unwrap(); + say(&mut out, json!({"id": 1, "ok": true})).unwrap(); line.clear(); reader.read_line(&mut line).unwrap(); - writeln!(out, "{}", json!({"id": 99, "ok": true, "result": "stale"})).unwrap(); - writeln!(out, "{}", json!({"id": 2, "ok": true, "result": "fresh"})).unwrap(); + say(&mut out, json!({"id": 99, "ok": true, "result": "stale"})).unwrap(); + say(&mut out, json!({"id": 2, "ok": true, "result": "fresh"})).unwrap(); // Closing the connection ends the third call. }); let mut client = ControlClient::connect(addr, TOKEN).unwrap(); @@ -42,7 +48,7 @@ fn replies_are_matched_by_id() { // later call. #[trial] fn a_cancelled_call_stops_waiting_and_closes_the_connection() { - use std::io::{BufRead, Write}; + use std::io::BufRead; let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); let (done, wait) = std::sync::mpsc::channel::<()>(); @@ -52,12 +58,12 @@ fn a_cancelled_call_stops_waiting_and_closes_the_connection() { let mut out = stream; let mut line = String::new(); reader.read_line(&mut line).unwrap(); - writeln!(out, "{}", json!({"id": 1, "ok": true})).unwrap(); + say(&mut out, json!({"id": 1, "ok": true})).unwrap(); // The call is read and never answered while the client waits. line.clear(); reader.read_line(&mut line).unwrap(); wait.recv().unwrap(); - writeln!(out, "{}", json!({"id": 2, "ok": true, "result": "late"})).ok(); + say(&mut out, json!({"id": 2, "ok": true, "result": "late"})).ok(); }); let mut client = ControlClient::connect(addr, TOKEN).unwrap(); let asked = std::cell::Cell::new(0); @@ -86,9 +92,9 @@ fn an_unasked_line_makes_the_connection_unusable_before_sending() { let mut out = stream; let mut line = String::new(); reader.read_line(&mut line).unwrap(); - writeln!(out, "{}", json!({"id": 1, "ok": true})).unwrap(); + say(&mut out, json!({"id": 1, "ok": true})).unwrap(); wait.recv().unwrap(); - writeln!(out, "{}", json!({"id": null, "ok": false, "error": "idle connection closed"})).unwrap(); + say(&mut out, json!({"id": null, "ok": false, "error": "idle connection closed"})).unwrap(); out.flush().unwrap(); // The client's close shows as an end of input or, with the unread line, a reset. line.clear(); @@ -118,7 +124,7 @@ fn a_refusal_waiting_at_sign_in_is_the_reason_connect_gives() { let (stream, _) = listener.accept().unwrap(); let mut reader = std::io::BufReader::new(stream.try_clone().unwrap()); let mut out = stream; - writeln!(out, "{}", json!({"id": null, "ok": false, "error": "connection limit reached"})).unwrap(); + say(&mut out, json!({"id": null, "ok": false, "error": "connection limit reached"})).unwrap(); out.flush().unwrap(); let mut line = String::new(); reader.read_line(&mut line).ok().filter(|&read| read > 0).map(|_| line) diff --git a/crates/behavior/src/cursor.rs b/crates/behavior/src/cursor.rs index 3b6a67f78..2d69e7ff7 100644 --- a/crates/behavior/src/cursor.rs +++ b/crates/behavior/src/cursor.rs @@ -208,13 +208,15 @@ pub enum PaintedCursor { end: bool, }, /// A pointer with the tool's icon below and right of it: a crosshair (Perspective Crop), or an arrow with its tip - /// on the hotspot (Paint Bucket, Ruler). + /// on the hotspot (Paint Bucket, Ruler, the lassos). #[non_exhaustive] PointerTool { /// The pointer the icon rides beside. pointer: PointerGlyph, /// The icon. icon: IconId, + /// A mark at the icon's lower right. + badge: Option, }, /// No cursor at all. Hidden, @@ -294,7 +296,12 @@ impl PaintedCursor { /// `pointer` with the tool's icon below and right of it. pub const fn pointer_tool(pointer: PointerGlyph, icon: IconId) -> Self { - PaintedCursor::PointerTool { pointer, icon } + PaintedCursor::PointerTool { pointer, icon, badge: None } + } + + /// `pointer` with the tool's icon below and right of it, and `badge` at the icon's lower right. + pub const fn pointer_tool_badged(pointer: PointerGlyph, icon: IconId, badge: Option) -> Self { + PaintedCursor::PointerTool { pointer, icon, badge } } /// A system cursor with a mark. diff --git a/crates/behavior/src/dock/arrange.rs b/crates/behavior/src/dock/arrange.rs index ec2bc27d8..7984ce449 100644 --- a/crates/behavior/src/dock/arrange.rs +++ b/crates/behavior/src/dock/arrange.rs @@ -4,15 +4,16 @@ use emath::{Rect, vec2}; /// One Window › Arrange entry. The n-up entries split the document area into that many -/// cells and put one document group in each, and Tile one cell per document; the rest act on -/// windows and views. Saved under the command names (`"twoUpVertical"`, `"tile"`). +/// cells and put one document group in each, and Tile All and Tile one cell per document; the +/// rest act on windows and views. Saved under the command names (`"twoUpVertical"`, `"tile"`). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum Arrangement { - /// Tiles every document window across the document area, side by side. + /// One cell per document across the document area, side by side, floating windows docked + /// first. TileAllVertically, - /// Tiles every document window across the document area, stacked. + /// One cell per document across the document area, stacked, floating windows docked first. TileAllHorizontally, /// Two cells, side by side. TwoUpVertical, diff --git a/crates/behavior/src/dock/windows.rs b/crates/behavior/src/dock/windows.rs index 47246507b..64d3a81b5 100644 --- a/crates/behavior/src/dock/windows.rs +++ b/crates/behavior/src/dock/windows.rs @@ -33,7 +33,7 @@ pub struct DocumentWindows { /// The floating groups, each with its window rect. #[serde(with = "floating_serde")] pub floating: Vec<(DocumentGroup, Rect)>, - /// The n-up or Tile arrangement the document area shows: set by Window › Arrange, cleared by + /// The n-up, Tile All or Tile arrangement the document area shows: set by Window › Arrange, cleared by /// Consolidate and by floating a document. #[serde(default)] pub arrangement: Option, diff --git a/crates/behavior/src/press.rs b/crates/behavior/src/press.rs index 50269615f..227098fa3 100644 --- a/crates/behavior/src/press.rs +++ b/crates/behavior/src/press.rs @@ -78,12 +78,14 @@ pub struct PressStart { pub time: f64, /// 1 for a single press, 2 for a double press, and so on. pub clicks: u32, + /// The press went down on another target, which handed it to this one ([`PressMachine::take_over`]). + pub handed: bool, } impl PressStart { /// A press of `button` at `origin`. pub const fn new(origin: Pos2, button: PointerButton, time: f64, clicks: u32) -> Self { - PressStart { origin, button, time, clicks } + PressStart { origin, button, time, clicks, handed: false } } } @@ -629,8 +631,9 @@ impl PressMachine { } /// Takes over a press whose button is down and went down elsewhere, as a drag of `target` from `start`: the next - /// pass reports `DragStart`, and later ones the press's own `Drag`, `Release` or `Cancel` from their input. A - /// press this machine holds already stays as it is. + /// pass reports `DragStart`, and later ones the press's own `Drag`, `Release` or `Cancel` from their input, each + /// with a start that says it was handed over ([`PressStart::handed`]). A press this machine holds already stays as + /// it is. // PLAN: the sheet's Files table has no row for this file; the handover of a held press (decision q346) needs the // machine to open a press that did not begin on it, which only the machine can build. pub fn take_over(&mut self, target: T, sense: Sense, start: PressStart) { @@ -640,7 +643,7 @@ impl PressMachine { self.open = Some(Open { target, sense: sense - Sense::CLICK, - start, + start: PressStart { handed: true, ..start }, dragging: true, abandoned: false, left: false, diff --git a/crates/captions/Cargo.toml b/crates/captions/Cargo.toml index 1136f55f9..4a4e27520 100644 --- a/crates/captions/Cargo.toml +++ b/crates/captions/Cargo.toml @@ -21,6 +21,7 @@ craft-xml = { workspace = true } thiserror = { workspace = true } [dev-dependencies] +craft-testkit = { workspace = true } proptest = { workspace = true } # A second XML reader for the tests: checks of written TTML, and the comparison in tests/it/ttml_xml_views.rs. roxmltree = "0.21" diff --git a/crates/captions/tests/it/limits.rs b/crates/captions/tests/it/limits.rs index 3b908fa06..8a7c14ba6 100644 --- a/crates/captions/tests/it/limits.rs +++ b/crates/captions/tests/it/limits.rs @@ -18,7 +18,10 @@ fn input_over_the_size_limit_is_refused() { for format in Format::ALL { assert_eq!(parse(&big, format), Err(Error::TooLarge(MAX_INPUT)), "{format:?}"); } - assert!(parse(big.get(..MAX_INPUT).unwrap(), Format::Srt).is_ok()); + // Reading 64 MiB at the limit takes seconds: nightly only. + if craft_testkit::hostile::divisor() == 1 { + assert!(parse(big.get(..MAX_INPUT).unwrap(), Format::Srt).is_ok()); + } } /// TTML is read without entity expansion: a document type with entities defines nothing. @@ -35,7 +38,8 @@ fn mutated_files_never_panic() { for format in Format::ALL { let bytes = write(&doc(), format, WriteOptions::default()); // every byte of a text file, and the header and first blocks of the (sparse) binary one - for i in 0..bytes.len().min(2048) { + // The gate runs every divisor-th byte; nightly runs every one. + for i in (0..bytes.len().min(2048)).step_by(craft_testkit::hostile::divisor()) { for v in [0u8, 0x20, 0x3c, 0x7f, 0xff] { let mut m = bytes.clone(); if let Some(b) = m.get_mut(i) { diff --git a/crates/cfb/Cargo.toml b/crates/cfb/Cargo.toml index e2684da0b..853038aae 100644 --- a/crates/cfb/Cargo.toml +++ b/crates/cfb/Cargo.toml @@ -13,4 +13,5 @@ workspace = true [dependencies] [dev-dependencies] +craft-testkit = { workspace = true } craft-media-testkit = { workspace = true } diff --git a/crates/cfb/src/tests/ported.rs b/crates/cfb/src/tests/ported.rs index f49f9f6c0..476daebe3 100644 --- a/crates/cfb/src/tests/ported.rs +++ b/crates/cfb/src/tests/ported.rs @@ -557,7 +557,8 @@ fn truncation_at_every_length_never_panics() { #[test] fn every_single_bit_flip_never_panics_or_hangs() { for (mut file, _) in small_samples() { - for bit in 0..file.len() * 8 { + // The gate flips every divisor-th bit; nightly flips each one. + for bit in (0..file.len() * 8).step_by(craft_testkit::hostile::divisor()) { file[bit / 8] ^= 1 << (bit % 8); exercise(&file, None); file[bit / 8] ^= 1 << (bit % 8); diff --git a/crates/cms/Cargo.toml b/crates/cms/Cargo.toml index 51fb2aab7..c876e4d42 100644 --- a/crates/cms/Cargo.toml +++ b/crates/cms/Cargo.toml @@ -20,4 +20,5 @@ md5 = { workspace = true } rayon = { workspace = true } [dev-dependencies] +craft-testkit = { workspace = true } moxcms = "0.8" diff --git a/crates/cms/src/black_tests.rs b/crates/cms/src/black_tests.rs index 8752cdaa2..2d4864a99 100644 --- a/crates/cms/src/black_tests.rs +++ b/crates/cms/src/black_tests.rs @@ -70,10 +70,12 @@ fn the_destination_black_matches_the_source_lightness() { for intent in [Intent::RelativeColorimetric, Intent::Perceptual] { for bpc in [true, false] { let o = TransformOptions { intent, bpc, ..opts() }; - for (src, dst) in [(coated(), fogra()), (fogra(), coated())] { + // Both directions for one setting; the other settings in the forward one. + let directions = if intent == Intent::RelativeColorimetric && bpc { 2 } else { 1 }; + for (src, dst) in [(coated(), fogra()), (fogra(), coated())].into_iter().take(directions) { let bp = BlackPreserving::new(src, dst, o).unwrap(); let dst_black = lightness(dst, o, [0.0, 0.0, 0.0, 1.0]); - for k in [0.1f32, 0.3, 0.5, 0.7, 0.9, 1.0] { + for k in [0.1f32, 0.5, 0.9, 1.0] { let want = lightness(src, o, [0.0, 0.0, 0.0, k]); if want <= dst_black { assert_eq!(bp.map_k(k), 1.0, "darker than the destination's black clamps to K = 1"); diff --git a/crates/cms/tests/cms.rs b/crates/cms/tests/cms.rs index bf6934d9a..00b9b3b7a 100644 --- a/crates/cms/tests/cms.rs +++ b/crates/cms/tests/cms.rs @@ -115,7 +115,9 @@ fn white_is_exact_on_every_path() { let none = [0.0f32; 4]; for cmyk in [Builtin::CoatedCmyk, Builtin::CoatedFogra39] { for intent in [Intent::Perceptual, Intent::RelativeColorimetric, Intent::Saturation] { - for bpc in [false, true] { + // The gate runs black point compensation on; nightly both. + let bpcs: &[bool] = if craft_testkit::hostile::divisor() > 1 { &[true] } else { &[false, true] }; + for &bpc in bpcs { for precise_float in [false, true] { let opts = TransformOptions { intent, bpc, precise_float }; let at = format!("{cmyk:?} {opts:?}"); diff --git a/crates/color-ui/tests/it/picker.rs b/crates/color-ui/tests/it/picker.rs index bc44235a8..7a00b133e 100644 --- a/crates/color-ui/tests/it/picker.rs +++ b/crates/color-ui/tests/it/picker.rs @@ -299,7 +299,10 @@ fn the_full_picker_keeps_photoshops_arrangement_in_every_room_density_and_theme( for look in LOOKS { let wide = full_picker(600.0, look, 2); let parts = FullParts::of(&wide, 2); - the_arrangement_holds_in_other_rooms(look, &wide, &parts); + // The rooms are compared in one look, the widest: each look's own arrangement is checked below. + if look == ROOMS_LOOK { + the_arrangement_holds_in_other_rooms(look, &wide, &parts); + } the_area_strip_and_compare_block_stand_as_in_photoshop(look, &parts); the_field_groups_stand_under_the_compare_block(look, &parts); the_hex_field_and_the_rows_under_the_area_stand_as_in_photoshop(look, &parts); @@ -313,6 +316,9 @@ fn the_full_picker_keeps_photoshops_arrangement_in_every_room_density_and_theme( type Look = (Size, &'static str); +/// The look the other rooms are compared in: the comfortable density is the widest, so a narrow room presses it most. +const ROOMS_LOOK: Look = (Size::Comfortable, "craft.studio"); + /// Wider and narrower rooms leave the arrangement alone, and the warnings move no other part. fn the_arrangement_holds_in_other_rooms(look: Look, wide: &Fixture, parts: &FullParts) { assert_eq!(&FullParts::of(&full_picker(1200.0, look, 2), 2), parts, "{look:?}: the same arrangement in a room 1200 wide"); diff --git a/crates/color-ui/tests/it/sampling.rs b/crates/color-ui/tests/it/sampling.rs index bdf5aec72..53ce25aa9 100644 --- a/crates/color-ui/tests/it/sampling.rs +++ b/crates/color-ui/tests/it/sampling.rs @@ -202,9 +202,11 @@ fn an_invalid_capture_ends_the_pick_with_a_status() { assert!(pick.take_status(&words).is_some(), "and says why"); assert!(pick.take_status(&words).is_none(), "once"); - // A valid profile of another colour space: a CMYK monitor profile is not an RGB profile. + // A valid profile of another colour space: a CMYK monitor profile is not an RGB profile. The smallest grids make + // it as valid as the default coated profile, which takes far longer to build. let mut odd = monitor([0, 0], [4, 4], 1); - odd.icc_profile = Some(craft_cms::synth::coated_cmyk().expect("the synthetic CMYK profile").to_bytes()); + let params = craft_cms::synth::CmykParams { grid_a2b: 2, grid_b2a: 2, ..craft_cms::synth::CmykParams::default() }; + odd.icc_profile = Some(craft_cms::synth::cmyk_profile(¶ms).expect("the synthetic CMYK profile").to_bytes()); let mut pick = ScreenPick::new(); pick.start("a"); pick.tick_with(&ctx, 1, &|| images(vec![odd.clone()])); diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index 5d93b4ee6..3cae59522 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -109,6 +109,7 @@ craft-kra = { workspace = true, optional = true } craft-latex = { workspace = true, optional = true } craft-lottie = { workspace = true, optional = true } craft-markdown = { workspace = true, optional = true } +craft-material-graph = { workspace = true, optional = true } craft-materialx = { workspace = true, optional = true } craft-math = { workspace = true, optional = true } craft-mesh = { workspace = true, optional = true } @@ -609,6 +610,8 @@ macho-serde = ["macho", "craft-macho/serde"] markdown = ["dep:craft-markdown"] +material-graph = ["dep:craft-material-graph"] + materialx = ["dep:craft-materialx"] math = ["dep:craft-math"] diff --git a/crates/craft/src/egui_fork.rs b/crates/craft/src/egui_fork.rs index 3890d7981..b8535c5c1 100644 --- a/crates/craft/src/egui_fork.rs +++ b/crates/craft/src/egui_fork.rs @@ -3,7 +3,7 @@ /// The egui fork the library is built and tested with. Apps patch egui to exactly this. pub const GIT: &str = "https://github.com/storytold/egui.git"; /// The commit of [`GIT`]. -pub const REV: &str = "f5025284445ea19c35f746d96fc0b75468b3f560"; +pub const REV: &str = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec"; /// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]). pub const PACKAGES: &[&str] = &[ diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index 5eba7a44d..caeb7d526 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -221,6 +221,8 @@ pub use craft_lottie as lottie; pub use craft_macho as macho; #[cfg(feature = "markdown")] pub use craft_markdown as markdown; +#[cfg(feature = "material-graph")] +pub use craft_material_graph as material_graph; #[cfg(feature = "materialx")] pub use craft_materialx as materialx; #[cfg(feature = "math")] diff --git a/crates/crw/Cargo.toml b/crates/crw/Cargo.toml index e44839e70..9c58c6834 100644 --- a/crates/crw/Cargo.toml +++ b/crates/crw/Cargo.toml @@ -15,6 +15,7 @@ workspace = true thiserror = { workspace = true } [dev-dependencies] +craft-testkit = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } # Pinned digests of the decoded CC0 sample files (tests/samples.rs); not a product dependency. diff --git a/crates/crw/tests/robust.rs b/crates/crw/tests/robust.rs index b12df3a8d..8368ceb3d 100644 --- a/crates/crw/tests/robust.rs +++ b/crates/crw/tests/robust.rs @@ -61,11 +61,13 @@ fn crw() -> Vec { #[test] fn every_truncation_and_single_byte_mutation_survives() { let good = crw(); - for n in 0..good.len() { + // The gate runs every divisor-th position; nightly runs all. + let step = craft_testkit::hostile::divisor(); + for n in (0..good.len()).step_by(step) { let _ = header(&good[..n], &Limits::default()); let _ = decode(&good[..n], &Limits::default()); } - for i in 0..good.len() { + for i in (0..good.len()).step_by(step) { let mut bad = good.clone(); bad[i] ^= 0xa5; let _ = decode(&bad, &Limits::default()); diff --git a/crates/develop/Cargo.toml b/crates/develop/Cargo.toml index 19335b990..c271ad26b 100644 --- a/crates/develop/Cargo.toml +++ b/crates/develop/Cargo.toml @@ -24,4 +24,5 @@ rayon = { workspace = true } [dev-dependencies] craft-render-parity = { workspace = true } +craft-testkit = { workspace = true } proptest = { workspace = true } diff --git a/crates/develop/src/camera_raw/local_tone.rs b/crates/develop/src/camera_raw/local_tone.rs index 33f825b66..8751a2a63 100644 --- a/crates/develop/src/camera_raw/local_tone.rs +++ b/crates/develop/src/camera_raw/local_tone.rs @@ -652,7 +652,7 @@ mod tests { apply(&mut px, n, n, 70.0, -60.0, SRGB); [px[(n / 8) * n + n / 8][0], px[(3 * n / 4) * n + 3 * n / 4][0]] }; - let (a, b) = (at(96), at(384)); + let (a, b) = (at(64), at(256)); assert!((a[0] - b[0]).abs() < 0.02 && (a[1] - b[1]).abs() < 0.02, "{a:?} {b:?}"); } } diff --git a/crates/develop/src/camera_raw/mod.rs b/crates/develop/src/camera_raw/mod.rs index 0119fa1a0..feaff7b4f 100644 --- a/crates/develop/src/camera_raw/mod.rs +++ b/crates/develop/src/camera_raw/mod.rs @@ -67,10 +67,10 @@ mod whites_blacks; pub use local_tone::{LocalTone, ToneKind, TonePass}; pub use per_pixel::{ - CURVE_LUT, Grade, Grain, PerPixel, Vignette, VignetteStyle, WB_STEPS, WhitesBlacks, WhitesBlacksModel, per_pixel, spatial, white_black_points, - whites_blacks_model, + CURVE_LUT, Grade, Grain, PerPixel, Vignette, VignetteStyle, WB_STEPS, WhitesBlacks, WhitesBlacksModel, per_pixel, spatial, spatial_tone, + white_black_points, whites_blacks_model, }; -pub use spatial::{Clarity, Dehaze, Texture}; +pub use spatial::{Clarity, Dehaze, Detail, Texture}; /// How the pixels encode light: the sRGB curve (gamma 0) or a pure power law (ProPhoto's 1.8, /// Adobe RGB's 2.2). The tone controls work on light, so the document's own curve decodes it. @@ -243,6 +243,7 @@ fn box_mean(v: &[f32], w: usize, h: usize, r: usize) -> Vec { } /// Approximate Gaussian (three box passes). +#[cfg(test)] fn gauss(v: &[f32], w: usize, h: usize, sigma: f32) -> Vec { box_means(v, w, h, &spatial::gauss_radii(sigma)) } @@ -484,7 +485,6 @@ pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: & if px.is_empty() || p.is_identity() { return; } - let ps = inputs.pixel_scale.clamp(0.01, 1.0); // 1. White balance + exposure in linear light. if let Some(g) = per_pixel::gains(p) { par_rows(px, w, 1, |_, row| { @@ -629,8 +629,8 @@ pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: & }); } // 8. Detail. - if p.noise_luminance > 0.0 || p.noise_color > 0.0 || p.sharpen_amount > 0.0 { - detail(px, w, h, p, ps); + if let Some(d) = Detail::new(p, inputs) { + detail(px, w, h, &d); } // 9. Effects. if p.vignette_amount != 0.0 { @@ -843,54 +843,41 @@ fn sharpening_detail(detail: f32) -> f32 { detail / 100.0 } -fn detail(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, ps: f32) { - // The controls' documented 0..=100 range: raw values drive the filter radii below. - let [nl, nld, nc, ncd] = [p.noise_luminance, p.noise_luminance_detail, p.noise_color, p.noise_color_detail].map(|v| v.clamp(0.0, 100.0)); +fn detail(px: &mut [[f32; 4]], w: usize, h: usize, d: &Detail) { // Work in Y + chroma (BT.709 luma, B−Y, R−Y). let mut y: Vec = px.iter().map(|q| luma([q[0], q[1], q[2]])).collect(); let mut cb: Vec = px.iter().zip(&y).map(|(q, l)| q[2] - l).collect(); let mut cr: Vec = px.iter().zip(&y).map(|(q, l)| q[0] - l).collect(); - if nl > 0.0 { - let n = nl / 100.0; - let r = ((1.0 + 3.0 * n) * ps).round().max(1.0) as usize; - let smooth = guided(&y, &y, w, h, r, (n * 0.06).powi(2) + 1e-6); - let keep = nld / 100.0 * 0.5; + if let Some(n) = &d.luminance { + let smooth = guided(&y, &y, w, h, n.radius, n.eps); for i in 0..w * h { - y[i] = smooth[i] + (y[i] - smooth[i]) * keep; + y[i] = smooth[i] + (y[i] - smooth[i]) * n.keep; } } - if nc > 0.0 { - let sigma = (nc / 100.0 * 6.0 * ps).max(0.3); - let (bcb, bcr) = (gauss(&cb, w, h, sigma), gauss(&cr, w, h, sigma)); - let keep = ncd / 100.0 * 0.3; + if let Some(c) = &d.color { + let (bcb, bcr) = (box_means(&cb, w, h, &c.radii), box_means(&cr, w, h, &c.radii)); for i in 0..w * h { - cb[i] = bcb[i] + (cb[i] - bcb[i]) * keep; - cr[i] = bcr[i] + (cr[i] - bcr[i]) * keep; + cb[i] = bcb[i] + (cb[i] - bcb[i]) * c.keep; + cr[i] = bcr[i] + (cr[i] - bcr[i]) * c.keep; } } - if p.sharpen_amount > 0.0 { - let sigma = (p.sharpen_radius.clamp(0.5, 3.0) * ps).max(0.3); - let blur = gauss(&y, w, h, sigma); + if let Some(s) = &d.sharpen { + let blur = box_means(&y, w, h, &s.radii); // Masking: an edge mask from the gradient of a smoothed luminance. - let mask: Option> = (p.sharpen_masking > 0.0).then(|| { - let s = gauss(&y, w, h, 1.0 * ps.max(0.5)); - let t = p.sharpen_masking / 100.0 * 0.08; + let mask: Option> = s.mask.as_ref().map(|(radii, [e0, e1])| { + let s = box_means(&y, w, h, radii); util::par_map(w * h, |i| { let (x, yy) = (i % w, i / w); let gx = s[yy * w + (x + 1).min(w - 1)] - s[yy * w + x.saturating_sub(1)]; let gy = s[(yy + 1).min(h - 1) * w + x] - s[yy.saturating_sub(1) * w + x]; - smoothstep(t * 0.5, t + 1e-4, gx.hypot(gy)) + smoothstep(*e0, *e1, gx.hypot(gy)) }) }); - let amt = p.sharpen_amount / 100.0 * 1.2; - let det = sharpening_detail(p.sharpen_detail); for i in 0..w * h { - let hp = y[i] - blur[i]; // Low Detail damps large (halo-producing) differences. - let limit = 0.03 + det * 0.3; - let hp = hp.clamp(-limit, limit) * (0.5 + 0.5 * det); + let hp = (y[i] - blur[i]).clamp(-s.limit, s.limit) * s.scale; let m = mask.as_ref().map_or(1.0, |m| m[i]); - y[i] += amt * hp * m; + y[i] += s.amount * hp * m; } } for i in 0..w * h { @@ -1204,6 +1191,23 @@ mod tests { assert!(per_pixel(&cr! { exposure: 0.5}, 2, 2, false, None).is_some()); } + #[test] + fn detail_reaches_the_per_pixel_stages_after_measured_whites_and_blacks() { + // Detail runs after Whites and Blacks, so another implementation can take its parameters + // and still measure the points on the per-pixel image. + let sharpened = cr! { sharpen_amount: 60.0, noise_luminance: 30.0, whites: 20.0}; + let stages = per_pixel(&sharpened, 8, 8, false, Some((0.05, 0.9))).expect("Detail alone stays on the per-pixel stages"); + assert_eq!(stages.detail, Detail::new(&sharpened, &DevelopInputs::default())); + assert!(stages.detail.is_some() && stages.whites_blacks.is_some() && stages.measure_whites_blacks.is_none()); + let px = vec![[0.4f32, 0.5, 0.6, 1.0]; 64]; + assert!(white_black_points(&px, 8, 8, &sharpened, &DevelopInputs::default()).is_some()); + // A stage before Whites and Blacks still leaves the measuring to whatever runs it. + let clarified = cr!(sharpened.clone() => clarity: 30.0); + assert!(white_black_points(&px, 8, 8, &clarified, &DevelopInputs::default()).is_none()); + assert!(per_pixel(&clarified, 8, 8, false, None).is_some_and(|s| s.measure_whites_blacks.is_some())); + assert!(spatial(&sharpened) && !spatial_tone(&sharpened) && spatial_tone(&clarified)); + } + #[test] fn calibration_turns_primaries_keeps_neutrals_and_tints_shadows() { let w = calibration_weights(0.0); diff --git a/crates/develop/src/camera_raw/per_pixel.rs b/crates/develop/src/camera_raw/per_pixel.rs index 9273036bc..d4b1eacd1 100644 --- a/crates/develop/src/camera_raw/per_pixel.rs +++ b/crates/develop/src/camera_raw/per_pixel.rs @@ -1,11 +1,11 @@ //! Develop's stages resolved for one image: every constant and table the per-pixel ones use, so //! another implementation of them (the GPU preview, `photocraft_gpu::CameraRawDevelop`) runs the //! same maths. [`develop`](super::develop) builds its own constants with the same functions. -//! The spatial stages other than Detail come as their parameters: Dehaze, Clarity and Texture -//! (see [`spatial`](super::spatial)), Shadows and Highlights as a [`LocalTone`]. +//! The spatial stages come as their parameters: Dehaze, Clarity, Texture and Detail (see +//! [`spatial`](super::spatial)), Shadows and Highlights as a [`LocalTone`]. use super::local_tone::{LocalTone, WORK_SIDE}; -use super::spatial::{Clarity, Dehaze, Texture}; +use super::spatial::{Clarity, Dehaze, Detail, Texture}; use super::types::VignetteStyle as StoredStyle; use super::{ CameraRaw, DevelopInputs, Encoding, Wheel, calibration_neutral, curve_lut, grade_neutral, hsl_neutral, hsv_to_rgb, is_linear, luma, @@ -177,7 +177,7 @@ pub struct PerPixel { /// 3b. Whites and Blacks, in the document's encoding. pub whites_blacks: Option, /// 3b. Whites and Blacks to measure the image's points for (the sliders, −100 … 100), when a - /// spatial stage is set: the points then depend on its output, so whatever runs it + /// spatial stage before them is set (any but Detail): the points then depend on its output, so whatever runs it /// measures them and picks the curves from [`whites_blacks_model`]. `whites_blacks` is /// then `None`. pub measure_whites_blacks: Option<[f32; 2]>, @@ -193,6 +193,8 @@ pub struct PerPixel { pub hsl: Option<[[f32; 8]; 3]>, /// 7. Color Grading. pub grade: Option, + /// 8. Detail: noise reduction and sharpening. + pub detail: Option, /// 9. Vignette. pub vignette: Option, /// 9. Grain. @@ -204,20 +206,22 @@ pub struct PerPixel { /// Whether developing needs a stage that reads neighbouring pixels: Dehaze, Shadows and /// Highlights, Texture, Clarity, sharpening or noise reduction. pub fn spatial(p: &CameraRaw) -> bool { - p.dehaze != 0.0 || [p.highlights, p.shadows, p.texture, p.clarity].iter().any(|v| *v != 0.0) || detail_on(p) + spatial_tone(p) || p.sharpen_amount > 0.0 || p.noise_luminance > 0.0 || p.noise_color > 0.0 } -/// Whether developing needs Detail: sharpening or noise reduction. -fn detail_on(p: &CameraRaw) -> bool { - p.sharpen_amount > 0.0 || p.noise_luminance > 0.0 || p.noise_color > 0.0 +/// Whether a stage before Whites and Blacks reads neighbouring pixels: Dehaze, Shadows and +/// Highlights, Texture or Clarity (all of [`spatial`] but Detail). The image's points then +/// depend on its output. +pub fn spatial_tone(p: &CameraRaw) -> bool { + p.dehaze != 0.0 || [p.highlights, p.shadows, p.texture, p.clarity].iter().any(|v| *v != 0.0) } /// The image's black and white points that Whites and Blacks adapt to, for `px` (`w × h`, /// display-encoded) developed per pixel with `p`: what [`develop`](super::develop) measures /// after white balance and Contrast. `None` when Whites and Blacks are 0 or `p` needs a -/// spatial stage. +/// spatial stage before them ([`spatial_tone`]; Detail comes after). pub fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: &DevelopInputs) -> Option<(f32, f32)> { - if (p.whites == 0.0 && p.blacks == 0.0) || spatial(p) || px.len() != w.saturating_mul(h) { + if (p.whites == 0.0 && p.blacks == 0.0) || spatial_tone(p) || px.len() != w.saturating_mul(h) { return None; } let enc = Encoding::of(inputs.encoding_gamma); @@ -228,14 +232,14 @@ pub fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, p: &CameraRaw, in })) } -/// Develop's stages for settings without Detail or Calibration, on a `w × h` image; `points` are -/// the image's [`white_black_points`]. `None` when `p` needs Detail or Calibration (these stages -/// run neither), Shadows or Highlights on a frame wider than the filter's working copy (the +/// Develop's stages for settings without Calibration, on a `w × h` image; `points` are the image's +/// [`white_black_points`]. `None` when `p` needs Calibration (these stages don't run it), Shadows +/// or Highlights on a frame wider than the filter's working copy (the /// develop then filters a reduced copy) or only 2 pixels on its short side, or Whites or Blacks /// without a spatial stage and without `points`. The points themselves leave Calibration out, so a /// caller may cache them across Calibration changes. pub fn per_pixel(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize, float: bool, points: Option<(f32, f32)>) -> Option { - if detail_on(p) || !calibration_neutral(p) { + if !calibration_neutral(p) { return None; } // The develop leaves frames under 2 pixels on a side alone. @@ -277,6 +281,7 @@ pub fn per_pixel(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize, floa point: [pts(&p.point_curve), pts(&p.point_curve_red), pts(&p.point_curve_green), pts(&p.point_curve_blue)], hsl: (!hsl_neutral(p)).then_some([p.hsl_hue, p.hsl_sat, p.hsl_lum]), grade: (!grade_neutral(p)).then(|| Grade::new(p)), + detail: Detail::new(p, inputs), vignette: (p.vignette_amount != 0.0).then(|| Vignette::new(w, h, p)), grain: (p.grain_amount > 0.0).then(|| Grain::new(p, inputs)), clamp: !float && !identity, diff --git a/crates/develop/src/camera_raw/spatial.rs b/crates/develop/src/camera_raw/spatial.rs index a7b17347f..a74ea7a05 100644 --- a/crates/develop/src/camera_raw/spatial.rs +++ b/crates/develop/src/camera_raw/spatial.rs @@ -1,6 +1,6 @@ #![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))] -//! Dehaze, Clarity and Texture resolved for one frame: the sizes, radii and constants their +//! Dehaze, Clarity, Texture and Detail resolved for one frame: the sizes, radii and constants their //! filters use, so another implementation of them (the GPU preview, //! `photocraft_gpu::CameraRawDevelop`) runs the same filters. [`develop`](super::develop) builds //! its own from the same constructors. @@ -13,6 +13,9 @@ //! J. Sun, *Fast Guided Filter*, arXiv 2015), weighted toward the midtones. //! - **Texture** raises its difference from a Gaussian blur (three box passes), limited to //! ±[`TEXTURE_LIMIT`]. +//! - **Detail** works on BT.709 luminance and two chroma planes: a guided filter of the luminance +//! by itself for luminance noise, a Gaussian of the chroma for colour noise, then an unsharp +//! mask of the luminance, optionally weighted by its smoothed gradient. use super::{CameraRaw, DevelopInputs}; @@ -144,6 +147,80 @@ impl Texture { } } +/// Detail (noise reduction, then sharpening) on BT.709 luminance Y and the chroma B − Y, R − Y, +/// resolved for one frame. Each part is `None` when it is off. +#[derive(Clone, Debug, PartialEq)] +pub struct Detail { + pub luminance: Option, + pub color: Option, + pub sharpen: Option, +} + +/// Luminance noise reduction: a guided filter of Y by itself, with some of the detail kept. +#[derive(Clone, Debug, PartialEq)] +pub struct LuminanceNoise { + /// The guided filter's radius. + pub radius: usize, + /// Its regularisation. + pub eps: f32, + /// The share of Y's difference from the filter that stays. + pub keep: f32, +} + +/// Colour noise reduction: a Gaussian of both chroma planes, with some of the detail kept. +#[derive(Clone, Debug, PartialEq)] +pub struct ColorNoise { + /// The Gaussian's box radii, in order. + pub radii: Vec, + /// The share of the chroma's difference from the blur that stays. + pub keep: f32, +} + +/// Sharpening: Y plus `amount` times its difference from a Gaussian (after noise reduction), +/// clamped to ±`limit` and scaled by `scale`, optionally weighted by an edge mask. +#[derive(Clone, Debug, PartialEq)] +pub struct Sharpen { + /// The Gaussian's box radii, in order. + pub radii: Vec, + pub amount: f32, + pub limit: f32, + pub scale: f32, + /// Masking: the box radii of another Gaussian of Y, and the smoothstep edges its gradient's + /// length is weighed between. + pub mask: Option<(Vec, [f32; 2])>, +} + +impl Detail { + /// Detail for `p` at the job's pixel scale; `None` when sharpening and both noise reductions + /// are off. + pub fn new(p: &CameraRaw, inputs: &DevelopInputs) -> Option { + let ps = inputs.pixel_scale.clamp(0.01, 1.0); + // The controls' documented 0..=100 range: raw values drive the filter radii below. + let [nl, nld, nc, ncd] = [p.noise_luminance, p.noise_luminance_detail, p.noise_color, p.noise_color_detail].map(|v| v.clamp(0.0, 100.0)); + let luminance = (nl > 0.0).then(|| { + let n = nl / 100.0; + LuminanceNoise { radius: ((1.0 + 3.0 * n) * ps).round().max(1.0) as usize, eps: (n * 0.06).powi(2) + 1e-6, keep: nld / 100.0 * 0.5 } + }); + let color = (nc > 0.0).then(|| ColorNoise { radii: gauss_radii((nc / 100.0 * 6.0 * ps).max(0.3)), keep: ncd / 100.0 * 0.3 }); + let sharpen = (p.sharpen_amount > 0.0).then(|| { + let det = super::sharpening_detail(p.sharpen_detail); + // Masking: an edge mask from the gradient of a smoothed luminance. + let mask = (p.sharpen_masking > 0.0).then(|| { + let t = p.sharpen_masking / 100.0 * 0.08; + (gauss_radii(1.0 * ps.max(0.5)), [t * 0.5, t + 1e-4]) + }); + Sharpen { + radii: gauss_radii((p.sharpen_radius.clamp(0.5, 3.0) * ps).max(0.3)), + amount: p.sharpen_amount / 100.0 * 1.2, + limit: 0.03 + det * 0.3, + scale: 0.5 + 0.5 * det, + mask, + } + }); + (luminance.is_some() || color.is_some() || sharpen.is_some()).then_some(Detail { luminance, color, sharpen }) + } +} + /// The box radii of develop's Gaussian of `sigma`: none below 0.3. pub(crate) fn gauss_radii(sigma: f32) -> Vec { if sigma < 0.3 { @@ -189,6 +266,31 @@ mod tests { ); } + #[test] + fn detail_parts_follow_their_sliders_and_shrink_on_a_proxy() { + let full = DevelopInputs::default(); + let scale = |pixel_scale| DevelopInputs { pixel_scale, ..full }; + assert!(Detail::new(&CameraRaw::default(), &full).is_none()); + // Each part is on only when its own slider is. + let parts = |p: &CameraRaw| Detail::new(p, &full).map(|d| (d.luminance.is_some(), d.color.is_some(), d.sharpen.is_some())); + assert_eq!(parts(&cr! { noise_luminance: 40.0}), Some((true, false, false))); + assert_eq!(parts(&cr! { noise_color: 40.0}), Some((false, true, false))); + assert_eq!(parts(&cr! { sharpen_amount: 40.0}), Some((false, false, true))); + let masked = |m| Detail::new(&cr! { sharpen_amount: 40.0, sharpen_masking: m}, &full).and_then(|d| d.sharpen).map(|s| s.mask.is_some()); + assert_eq!((masked(0.0), masked(50.0)), (Some(false), Some(true))); + // Out-of-range noise sliders act as their ends. + assert_eq!(Detail::new(&cr! { noise_luminance: 1e30}, &full), Detail::new(&cr! { noise_luminance: 100.0}, &full)); + // On the dialog's proxy the filters are no wider than at full size. + let p = cr! { noise_luminance: 80.0, noise_color: 80.0, sharpen_amount: 80.0, sharpen_radius: 3.0, sharpen_masking: 50.0}; + let (big, small) = (Detail::new(&p, &full).unwrap(), Detail::new(&p, &scale(0.143)).unwrap()); + let reach = |r: &[usize]| r.iter().sum::(); + let (bl, sl) = (big.luminance.unwrap(), small.luminance.unwrap()); + assert!(sl.radius < bl.radius); + assert!(reach(&small.color.unwrap().radii) < reach(&big.color.unwrap().radii)); + let (bs, ss) = (big.sharpen.unwrap(), small.sharpen.unwrap()); + assert!(reach(&ss.radii) < reach(&bs.radii) && reach(&ss.mask.unwrap().0) <= reach(&bs.mask.unwrap().0)); + } + #[test] fn dehaze_cells_average_blocks_after_white_balance_and_refuse_a_wrong_size() { let d = Dehaze::new(&cr! { dehaze: 10.0}, 3, 1).unwrap(); diff --git a/crates/develop/src/inpaint.rs b/crates/develop/src/inpaint.rs index 7393ef4f3..c3ac0a9e1 100644 --- a/crates/develop/src/inpaint.rs +++ b/crates/develop/src/inpaint.rs @@ -116,7 +116,10 @@ mod tests { assert!(matches!(complete_with(w, h, 1, &img, &hole, &p, &count), Ok(Some(_)))); let total = polls.load(Ordering::Relaxed); assert!(total > 8, "the scene polls in the workers too: {total}"); - for nth in 0..total { + // Cancelling at the first, a quarter, the middle, three quarters and the last polls, workers' polls included. + let mut picks = vec![0, 1, 2, total / 4, total / 2, 3 * total / 4, total - 3, total - 2, total - 1]; + picks.dedup(); + for nth in picks { let polls = AtomicUsize::new(0); let once = || polls.fetch_add(1, Ordering::Relaxed) == nth; assert_eq!(complete_with(w, h, 1, &img, &hole, &p, &once), Err(Cancelled), "poll {nth} of {total}"); diff --git a/crates/develop/src/sensor/highlight/tests.rs b/crates/develop/src/sensor/highlight/tests.rs index 3386e5d73..7d2f6c05b 100644 --- a/crates/develop/src/sensor/highlight/tests.rs +++ b/crates/develop/src/sensor/highlight/tests.rs @@ -163,8 +163,13 @@ fn rebuilt_ramp_is_continuous_from_the_first_clip_to_the_last() { /// background surrounds it. #[test] fn thin_line_without_reliable_colour_is_continuous_where_it_clips() { - for height in [32usize, 512, 1024] { - for width in [1usize, 4, 16] { + // The gate runs a one-row line in 32 rows and a four-row line in 512; nightly every pair, up to 1024 rows. + let full = craft_testkit::hostile::divisor() == 1; + for (h, height) in [32usize, 512, 1024].into_iter().enumerate() { + for (w, width) in [1usize, 4, 16].into_iter().enumerate() { + if !full && (w != h || h > 1) { + continue; + } let top = (height - width) / 2; let (row, first) = rebuilt_ramp(top..top + width, height); assert_continuous(&row, first, 0.002, &format!("{width} rows of {height}")); diff --git a/crates/develop/src/sensor/mod.rs b/crates/develop/src/sensor/mod.rs index f7f20ab0a..4174ecbdd 100644 --- a/crates/develop/src/sensor/mod.rs +++ b/crates/develop/src/sensor/mod.rs @@ -168,7 +168,7 @@ impl RawDevelopExt for RawImage { fn develop_balanced_masked(&self, method: Method, wb: [f32; 3], clip: f32) -> Result<(Rgb32f, Option>)> { let n = self.normalized()?; - let mask = clip_mask(self, &n, method, clip); + let mask = raw_clip_mask(self, &n, method, clip); Ok((develop_full(self, n, method, Some(wb)), mask)) } @@ -253,17 +253,34 @@ fn scale_mosaic(n: &mut Normalized, method: Method, gains: [f32; 3]) -> bool { true } -fn clip_mask(raw: &RawImage, n: &Normalized, method: Method, clip: f32) -> Option> { +fn raw_clip_mask(raw: &RawImage, n: &Normalized, method: Method, clip: f32) -> Option> { + let crop = raw.develop_crop(n.width, n.height); + if !raw.opcodes.list3.is_empty() || stretched_height(crop.height, raw.pixel_aspect) != crop.height { + return None; + } + clip_mask(n, crop, method, clip) +} + +/// The [`highlight::reconstruct_masked`] mask for the output of [`demosaic()`] with `method` on the single-plane CFA +/// mosaic `n`, cropped to `crop` (one entry per pixel of `crop`, row-major). `n` holds sensor values normalised so +/// that 1.0 is white and before white balance; samples at or above `clip` count as clipped. Use it when the mosaic +/// is demosaicked by the caller (for example white-balanced first) rather than through [`RawDevelopExt`]. +/// `None` when nothing is clipped, `n` is not a single-plane RGB CFA mosaic, `crop` does not fit inside it, or `clip` +/// is not a positive finite level. +pub fn clip_mask(n: &Normalized, crop: Rect, method: Method, clip: f32) -> Option> { use highlight::{CLIPPED_BITS, FROM_CLIPPED_BITS}; // This radius covers samples read directly by the directional interpolators. Estimates // that build on interpolated green can depend on samples farther away. const REACH: usize = 2; - let cfa = n.cfa.as_ref().filter(|_| n.cpp == 1)?; + let cfa = n.cfa.as_ref().filter(|c| n.cpp == 1 && cfa_valid(c) && c.pattern.iter().all(|&p| p <= 2))?; let (w, h) = (n.width, n.height); - let crop = raw.develop_crop(w, h); - if !clip.is_finite() || clip <= 0.0 || !raw.opcodes.list3.is_empty() || stretched_height(crop.height, raw.pixel_aspect) != crop.height { + let fits = crop.width > 0 + && crop.height > 0 + && crop.x.checked_add(crop.width).is_some_and(|r| r <= w) + && crop.y.checked_add(crop.height).is_some_and(|b| b <= h); + if !clip.is_finite() || clip <= 0.0 || !fits || w.checked_mul(h) != Some(n.data.len()) { return None; } let is_clipped = |v: &f32| *v >= clip; diff --git a/crates/develop/src/sensor/opcodes.rs b/crates/develop/src/sensor/opcodes.rs index 0ef3cefa0..218ef7d8d 100644 --- a/crates/develop/src/sensor/opcodes.rs +++ b/crates/develop/src/sensor/opcodes.rs @@ -100,6 +100,12 @@ fn op_cost(op: &Opcode, w: usize, h: usize, cpp: usize) -> usize { } pub fn apply_list(list: &[Opcode], buf: &mut [f32], w: usize, h: usize, cpp: usize, cfa: Option<&Cfa>, scale: f32) { + apply_list_capped(list, buf, w, h, cpp, cfa, scale, MAX_BAD_PIXELS); +} + +/// [`apply_list`] with each bad-pixel opcode repairing at most `max_bad_pixels` pixels. +#[allow(clippy::too_many_arguments)] +fn apply_list_capped(list: &[Opcode], buf: &mut [f32], w: usize, h: usize, cpp: usize, cfa: Option<&Cfa>, scale: f32, max_bad_pixels: usize) { let mut budget = w.saturating_mul(h).saturating_mul(cpp).max(1).saturating_mul(MAX_LIST_PASSES); for op in list { let cost = op_cost(op, w, h, cpp); @@ -175,17 +181,17 @@ pub fn apply_list(list: &[Opcode], buf: &mut [f32], w: usize, h: usize, cpp: usi Opcode::FixBadPixelsConstant { constant, .. } => { let c = (*constant as f64 / 65535.0 * scale as f64) as f32; let bad: Vec<(usize, usize)> = - (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).filter(|&(x, y)| cpp == 1 && buf[y * w + x] == c).take(MAX_BAD_PIXELS).collect(); + (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).filter(|&(x, y)| cpp == 1 && buf[y * w + x] == c).take(max_bad_pixels).collect(); fix_pixels(buf, w, h, cpp, cfa, &bad); } Opcode::FixBadPixelsList { points, rects, .. } => { let mut bad: Vec<(usize, usize)> = - points.iter().map(|&(r, c)| (c as usize, r as usize)).filter(|&(x, y)| x < w && y < h).take(MAX_BAD_PIXELS).collect(); + points.iter().map(|&(r, c)| (c as usize, r as usize)).filter(|&(x, y)| x < w && y < h).take(max_bad_pixels).collect(); 'rects: for r in rects { let [t, l, b, rr] = r.map(|v| v as usize); for y in t..b.min(h) { for x in l..rr.min(w) { - if bad.len() >= MAX_BAD_PIXELS { + if bad.len() >= max_bad_pixels { break 'rects; } bad.push((x, y)); diff --git a/crates/develop/src/sensor/opcodes/tests.rs b/crates/develop/src/sensor/opcodes/tests.rs index c97b81eea..44a45bdda 100644 --- a/crates/develop/src/sensor/opcodes/tests.rs +++ b/crates/develop/src/sensor/opcodes/tests.rs @@ -117,15 +117,15 @@ fn map_table_raw_scale_and_bad_pixels() { /// A mosaic equal to the bad-pixel constant, or one rectangle over the whole image, used to list every pixel as /// bad: w × h entries (plus a set of them), tens of GB at the decoder's size limit. Here the rows between a good -/// first row (500) and a good last row (900) are bad: 2052 rows of 2048 pixels, four rows more than the 1 << 22 -/// cap. Row 1, within the cap, is repaired from the first row; the second-last row, past the cap, must be left -/// as it is (uncapped, it was rewritten from the last row). +/// first row (500) and a good last row (900) are bad: 8 rows of 64 pixels, four rows more than the cap of 256 the +/// test passes. Row 1, within the cap, is repaired from the first row; the second-last row, past the cap, must be +/// left as it is (uncapped, it was rewritten from the last row). fn assert_bad_pixels_capped(op: Opcode) { - let (w, h) = (2048, 2054); + let (w, h) = (64, 10); let mut buf = vec![0.0f32; w * h]; buf[..w].fill(500.0); buf[(h - 1) * w..].fill(900.0); - apply_list(&[op], &mut buf, w, h, 1, None, 65535.0); + apply_list_capped(&[op], &mut buf, w, h, 1, None, 65535.0, 256); assert!(buf[w..2 * w].iter().all(|&v| v == 500.0), "row 1 (within the cap) not repaired: {:?}", &buf[w..w + 4]); let past = &buf[(h - 2) * w..(h - 1) * w]; assert!(past.iter().all(|&v| v == 0.0), "a row past the cap was rewritten: {:?}", &past[..4]); @@ -139,7 +139,7 @@ fn bad_pixels_constant_is_capped() { #[test] fn bad_pixels_list_is_capped_inside_a_rectangle() { // top, left, bottom, right: every row but the first and the last - assert_bad_pixels_capped(Opcode::FixBadPixelsList { bayer_phase: 0, points: vec![], rects: vec![[1, 0, 2053, 2048]] }); + assert_bad_pixels_capped(Opcode::FixBadPixelsList { bayer_phase: 0, points: vec![], rects: vec![[1, 0, 9, 64]] }); } #[test] diff --git a/crates/develop/src/tests_crystal.rs b/crates/develop/src/tests_crystal.rs index 672a598c5..a01ca4dc1 100644 --- a/crates/develop/src/tests_crystal.rs +++ b/crates/develop/src/tests_crystal.rs @@ -103,9 +103,9 @@ fn reference_render_has_unit_variance_and_no_mean() { fn small_render_is_the_downscaled_reference() { for (size, rough) in [(0.0, 50.0), (25.0, 50.0), (100.0, 50.0), (25.0, 0.0), (25.0, 100.0)] { let t = tile_of(size, rough); - for k in [2usize, 4, 8] { - let full = patch(&t, REF_LONG, 120 * k, 0); - let n = 120; + for k in [2usize, 8] { + let n = 32; + let full = patch(&t, REF_LONG, n * k, 0); let down: Vec = (0..n * n) .map(|q| { let (x, y) = (q % n, q / n); @@ -120,6 +120,7 @@ fn small_render_is_the_downscaled_reference() { .collect(); let small = patch(&t, REF_LONG / k as f64, n, 0); let worst = down.iter().zip(&small).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); + eprintln!("DIAG downscale size {size} roughness {rough} 1/{k}: worst {worst} (limit 2e-3)"); assert!(worst < 2e-3, "size {size} roughness {rough} 1/{k}: differs by {worst}"); } } @@ -129,7 +130,7 @@ fn small_render_is_the_downscaled_reference() { fn strength_matches_the_target_at_mid_grey() { for (a, s, r) in [(50.0, 25.0, 50.0), (25.0, 25.0, 50.0), (50.0, 0.0, 50.0), (50.0, 100.0, 50.0), (50.0, 25.0, 0.0)] { let g = CrystalGrain::new(&Grain { amount: a, size: s, roughness: r, seed: 3 }, REF_LONG).expect("grain"); - let n = 500; + let n = 200; let lum: Vec = (0..n * n) .map(|k| { let (x, y) = ((k % n) as f32 + 0.5, (k / n) as f32 + 0.5); @@ -138,6 +139,7 @@ fn strength_matches_the_target_at_mid_grey() { }) .collect(); let want = strength_levels(a, s, r); + eprintln!("DIAG strength {a}/{s}/{r}: deviation {:.4} (limit 0.06)", std(&lum) / want - 1.0); assert!((std(&lum) / want - 1.0).abs() < 0.06, "{a}/{s}/{r}: {} levels, want {want}", std(&lum)); } } @@ -153,7 +155,7 @@ fn tones_keep_their_mean() { for (amount, size, levels) in cases { let g = CrystalGrain::new(&Grain { amount, size, roughness: 50.0, seed: 3 }, REF_LONG).expect("grain"); for &level in levels { - let n = 400; + let n = 256; let mut sum = 0.0f64; for k in 0..n * n { let (x, y) = ((k % n) as f32 + 0.5, (k / n) as f32 + 0.5); @@ -388,7 +390,9 @@ fn a_drag_takes_the_last_tile_while_the_next_is_drawn() { let (seed, fresh) = (0x0d4a_0001, 0x0d4a_0002); let (a, b) = (CrystalLook::new(30.0, 50.0), CrystalLook::new(31.0, 50.0)); let exact = |look: CrystalLook, seed: u32| patch(&CrystalTile::new(look, seed).expect("tile"), REF_LONG, 32, 0); + let drawing = std::time::Instant::now(); let first = tile(a, seed, true).expect("tile"); + eprintln!("DIAG crystal tile at size 30: {:?}", drawing.elapsed()); assert_eq!(first.look, a); let stand_in = tile(b, seed, false).expect("tile"); assert_eq!(stand_in.look, a, "the draft waited for its tile"); @@ -402,8 +406,9 @@ fn a_drag_takes_the_last_tile_while_the_next_is_drawn() { assert!(std::time::Instant::now() < deadline, "the background tile never arrived"); std::thread::sleep(std::time::Duration::from_millis(5)); }; - assert_eq!(patch(&drawn, REF_LONG, 32, 0), exact(b, seed)); - assert_eq!(patch(&tile(b, seed, true).expect("tile"), REF_LONG, 32, 0), exact(b, seed)); + let exact_b = exact(b, seed); + assert_eq!(patch(&drawn, REF_LONG, 32, 0), exact_b); + assert_eq!(patch(&tile(b, seed, true).expect("tile"), REF_LONG, 32, 0), exact_b); // nothing drawn for this seed: nothing to stand in, the draft draws it assert_eq!(patch(&tile(a, fresh, false).expect("tile"), REF_LONG, 32, 0), exact(a, fresh)); } @@ -440,8 +445,10 @@ fn a_waiting_render_gets_the_tile_the_cache_evicted() { keep(&OWN, key, drawn.clone()); // other renders' tiles push it out of the cache before the waiter wakes // (each its own tile: a waiter that took another key's would fail the check below) + // (one tile of another seed under every key: a different `Arc` from the drawn one, drawn once) + let other_tile = Arc::new(CrystalTile::new(look, seed + 1).expect("tile")); for other in 1..=CACHE as u32 { - keep(&OWN, key_of(look, seed + other), Arc::new(CrystalTile::new(look, seed + other).expect("tile"))); + keep(&OWN, key_of(look, seed + other), other_tile.clone()); } assert!(cached(&OWN, key).is_none(), "the tile is still cached"); drop(marker); @@ -474,7 +481,8 @@ fn renders_that_miss_a_tile_together_draw_it_once() { static OWN: Cache = Mutex::new(Vec::new()); const N: usize = 8; // the first render's draw waits for the other seven to miss the tile too - const SEEDS: u32 = 40; + // (each seed is a full trial, as the draw is held until the others wait, so a few are enough) + const SEEDS: u32 = 2; HOLDS.lock().unwrap_or_else(PoisonError::into_inner).push((std::ptr::from_ref(&OWN) as usize, N - 1, SEEDS as usize)); let look = CrystalLook::new(0.0, 50.0); for seed in 0x0d4a_1000..0x0d4a_1000 + SEEDS { @@ -499,7 +507,8 @@ fn renders_that_miss_a_tile_together_draw_it_once() { fn width_matches_lightroom_classic() { let lrc = [(0.0, 50.0, 0.5), (25.0, 50.0, 1.13), (100.0, 50.0, 3.38), (25.0, 0.0, 0.86), (25.0, 100.0, 1.54)]; for (s, r, want) in lrc { - let got = half_width(&patch(&tile_of(s, r), REF_LONG, 360, 0), 360); + let got = half_width(&patch(&tile_of(s, r), REF_LONG, 256, 0), 256); + eprintln!("DIAG width size {s} roughness {r}: {got:.3} want {want} (limit 10 percent)"); assert!((got / want - 1.0).abs() < 0.1, "size {s} roughness {r}: width {got:.3}, want {want}"); } } diff --git a/crates/develop/tests/it/balanced.rs b/crates/develop/tests/it/balanced.rs index 4c8584304..b0d2ca95b 100644 --- a/crates/develop/tests/it/balanced.rs +++ b/crates/develop/tests/it/balanced.rs @@ -1,7 +1,7 @@ //! Original synthetic RAW scenes from storytold/lightcraft#1463, generated in these tests. use craft_develop::raster::Rgb32f; -use craft_develop::sensor::{Method, RawDevelopExt, highlight}; +use craft_develop::sensor::{self, Method, RawDevelopExt, highlight}; use craft_raw::opcodes::{Opcode, OpcodeLists}; use craft_raw::{BlackLevel, Cfa, ColorData, Orientation, RawData, RawFormat, RawImage, Rect}; @@ -355,6 +355,30 @@ fn the_clip_mask_marks_the_colours_interpolated_from_clipped_samples() { assert!(raw.develop_balanced_masked(Method::Ahd, DAYLIGHT, CLIP).unwrap().1.is_none()); } +#[test] +fn a_caller_demosaicking_its_own_mosaic_gets_the_same_clip_mask() { + let (w, h) = (40usize, 30usize); + let light = photograph(w, h, |x, y| if (x - 18.0).powi(2) + (y - 14.0).powi(2) < 49.0 { 6.0 } else { 0.4 }); + let mut cases = layouts(); + cases.push(("RGGB bilinear".into(), Cfa::bayer("RGGB").unwrap(), Method::Bilinear)); + for (name, cfa, method) in cases { + let mut raw = raw_of(w, h, &cfa, DAYLIGHT, |x, y| [light[y * w + x]; 3]); + raw.crop = Rect::new(2, 1, 33, 27); + let (_, expected) = raw.develop_balanced_masked(method, DAYLIGHT, CLIP).unwrap(); + let n = raw.normalized().unwrap(); + let crop = raw.develop_crop(n.width, n.height); + assert_eq!(sensor::clip_mask(&n, crop, method, CLIP), expected, "{name}"); + assert!(expected.is_some(), "{name}: clipped samples"); + let outside = Rect::new(crop.x + 1, crop.y, n.width - crop.x, crop.height); + assert!(sensor::clip_mask(&n, outside, method, CLIP).is_none(), "{name}: a crop past the mosaic"); + let mut four_colour = n.clone(); + four_colour.cfa.as_mut().unwrap().pattern[0] = 3; + assert!(sensor::clip_mask(&four_colour, crop, method, CLIP).is_none(), "{name}: a colour index past blue"); + let huge = sensor::Normalized { width: usize::MAX, height: 2, data: Vec::new(), ..n.clone() }; + assert!(sensor::clip_mask(&huge, Rect::new(0, 0, 1, 1), method, CLIP).is_none(), "{name}: dimensions past usize"); + } +} + #[test] fn ppg_clip_mask_marks_same_colour_dependencies() { let cfa = Cfa::bayer("RGGB").unwrap(); @@ -528,7 +552,9 @@ fn coloured_highlights_keep_their_brightness_at_the_edges() { let tubes = [([1.0f32, 0.15, 0.1], 3.5f32), ([1.0, 0.85, 0.15], 2.6), ([0.25, 1.0, 0.4], 2.0)]; let scenes = suns.map(|(tint, level)| (tint, level, true)).into_iter().chain(tubes.map(|(tint, level)| (tint, level, false))); let lum = |p: [f32; 3]| 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]; - for (tint, level, sun) in scenes { + // The gate develops every divisor-th (scene, layout) pair, a different layout per scene; nightly all of them. + let divisor = craft_testkit::hostile::divisor(); + for (scene_index, (tint, level, sun)) in scenes.enumerate() { let scene_name = if sun { "sun" } else { "tube" }; let scene = |x: f32, y: f32| { if sun { @@ -548,7 +574,10 @@ fn coloured_highlights_keep_their_brightness_at_the_edges() { }) }); let truth = |x: usize, y: usize| -> [f32; 3] { std::array::from_fn(|c| lights[c][y * w + x]) }; - for (name, cfa, method) in layouts() { + for (layout_index, (name, cfa, method)) in layouts().into_iter().enumerate() { + if !(scene_index + layout_index).is_multiple_of(divisor) { + continue; + } let raw = raw_of(w, h, &cfa, DAYLIGHT, truth); let (mut img, mask) = raw.develop_balanced_masked(method, DAYLIGHT, CLIP).unwrap(); let mut by_value = img.clone(); diff --git a/crates/dialogs/src/ui/chooser/tests.rs b/crates/dialogs/src/ui/chooser/tests.rs index 9b92f573f..0e38060c3 100644 --- a/crates/dialogs/src/ui/chooser/tests.rs +++ b/crates/dialogs/src/ui/chooser/tests.rs @@ -117,7 +117,7 @@ fn saved(path: impl AsRef) -> Option> { // `a_selected_folder_never_replaces_the_typed_save_name` and `a_removed_selected_file_keeps_its_exact_save_path`, with // `~` and "not found". The extension is the service's policy now, so the chooser answers the name as typed. #[trial] -fn the_chooser_lists_and_accepts_like_a_file_panel() { +fn a_typed_folder_is_entered_and_a_new_name_is_saved_as_typed() { // A typed folder is entered and its name used up; a new name is answered as typed. let mut save = Chooser::open(PickRequest::save("document").directory("/d")); save.type_name("drafts"); @@ -126,7 +126,10 @@ fn the_chooser_lists_and_accepts_like_a_file_panel() { save.type_name("chapter"); save.click("Save"); assert_eq!(save.answer(), saved("/d/drafts/chapter"), "a new name is saved to as typed"); +} +#[trial] +fn a_listed_file_is_replaced_only_after_the_question() { // A listed file is replaced only after the question, asked once. let mut replace = Chooser::open(PickRequest::save("document").directory("/d/drafts")); replace.type_name("old.docx"); @@ -134,7 +137,10 @@ fn the_chooser_lists_and_accepts_like_a_file_panel() { assert_eq!(replace.answer(), None, "the chooser asks before replacing"); replace.click("Replace"); assert_eq!(replace.answer(), saved("/d/drafts/old.docx")); +} +#[trial] +fn a_selected_file_keeps_its_exact_name_for_open_and_for_the_save_question() { // A selected file keeps its exact name, leading space and all, for Open and for Save's question. let mut open = Chooser::open(PickRequest::open("document").directory("/d")); open.click(" report.docx"); @@ -147,7 +153,10 @@ fn the_chooser_lists_and_accepts_like_a_file_panel() { assert_eq!(save.answer(), None, "Save asks before replacing the selected file"); save.click("Replace"); assert_eq!(save.answer(), saved("/d/ report.docx")); +} +#[trial] +fn a_removed_selected_file_keeps_its_exact_save_path() { // A selected file removed meanwhile still names the exact path, and nothing is asked. let mut removed = Chooser::open(PickRequest::save("document").file_name("Draft.docx").directory("/d")); removed.click(" report.docx"); @@ -155,7 +164,10 @@ fn the_chooser_lists_and_accepts_like_a_file_panel() { removed.refocus(); removed.click("Save"); assert_eq!(removed.answer(), saved("/d/ report.docx"), "the removed selection keeps its path, not `report.docx`"); +} +#[trial] +fn a_selected_folder_is_entered_and_never_becomes_the_save_name() { // A selected folder is entered and never becomes the save name; once it is gone, the typed name is saved to. let mut folder = Chooser::open(PickRequest::save("document").file_name("chapter.docx").directory("/d")); folder.click("Chapters"); @@ -168,13 +180,19 @@ fn the_chooser_lists_and_accepts_like_a_file_panel() { gone.refocus(); gone.click("Save"); assert_eq!(gone.answer(), saved("/d/chapter.docx"), "the removed folder is not saved over as `Chapters.docx`"); +} +#[trial] +fn the_home_root_and_a_typed_path_elsewhere_open() { // `~` is the Home root; a typed path elsewhere is listed, then opened. let mut home = Chooser::open(PickRequest::open("document").directory("/d")); home.type_name("~/Letters/aunt.txt"); home.click("Open"); assert_eq!(home.answer(), picked("/home/u/Letters/aunt.txt")); +} +#[trial] +fn a_missing_name_on_open_is_refused_and_said() { // A missing name on Open is refused and said. let mut missing = Chooser::open(PickRequest::open("document").directory("/d")); missing.type_name("missing.docx"); diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index decaff8db..dd3d2459d 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -29,3 +29,6 @@ thiserror = { workspace = true } # `pcraft-pixels`: PhotoCraft's tiles are zstd frames named by the BLAKE3 hash of their samples. blake3 = { version = "1.8", default-features = false, features = ["pure"], optional = true } ruzstd = { version = "0.9", default-features = false, features = ["std"], optional = true } + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/doc/tests/hostile.rs b/crates/doc/tests/hostile.rs index 33f93d69f..4c8aa5797 100644 --- a/crates/doc/tests/hostile.rs +++ b/crates/doc/tests/hostile.rs @@ -82,7 +82,7 @@ impl Rng { fn seeded_mutations_never_panic() { let mut rng = Rng(0x5eed); for s in samples() { - for _ in 0..1500 { + for _ in 0..1500 / craft_testkit::hostile::divisor() { let mut d = s.clone(); for _ in 0..1 + rng.below(4) { let at = rng.below(d.len()); diff --git a/crates/doc/tests/pixels.rs b/crates/doc/tests/pixels.rs index aa2f02f21..de2687b45 100644 --- a/crates/doc/tests/pixels.rs +++ b/crates/doc/tests/pixels.rs @@ -120,7 +120,8 @@ fn every_truncation_and_flipped_byte_is_an_error_not_a_panic() { let m = surface("Grayscale", "U8", false, &[255], &[(0, 0, &hash(&mask_tile))]); let file = bundle(3, 2, "Rgb", &[layer(&raster(&s), Some(&m))], &[&tile, &mask_tile]); assert!(read(&file, &[0]).mask.is_some()); - for n in 0..file.len() { + // The gate runs every divisor-th truncation and flip; nightly runs every one. + for n in (0..file.len()).step_by(craft_testkit::hostile::divisor()) { let _ = pcraft_layer_rgba(&file[..n], &[0], &Limits::default()); let mut flipped = file.clone(); flipped[n] ^= 0xff; diff --git a/crates/docx/Cargo.toml b/crates/docx/Cargo.toml index ed84356e0..0ffedf2aa 100644 --- a/crates/docx/Cargo.toml +++ b/crates/docx/Cargo.toml @@ -28,6 +28,7 @@ zeroize = "1" [dev-dependencies] craft-cfb = { workspace = true } +craft-testkit = { workspace = true } craft-opc = { workspace = true, features = ["test-support"] } craft-wordmodel = { workspace = true, features = ["test-support"] } image = { version = "0.25", default-features = false, features = ["png"] } diff --git a/crates/docx/src/read/chart/tests.rs b/crates/docx/src/read/chart/tests.rs index 1aeab5235..ea338016e 100644 --- a/crates/docx/src/read/chart/tests.rs +++ b/crates/docx/src/read/chart/tests.rs @@ -230,11 +230,12 @@ fn hostile_radar_charts_never_panic() { let small = chart_items(&space(&format!("{}", ser(0, "S", None, &["a", "b", "c"], &["1", "2", "3"]))), &theme(), 20.0, 20.0); let _ = small; - // Caps: thousands of categories and series stay bounded. - let cats: Vec = (0..5000).map(|i| format!("c{i}")).collect(); + // Caps: three times as many categories and series as are drawn stay bounded. + let n = 3 * MAX_SPOKES; + let cats: Vec = (0..n).map(|i| format!("c{i}")).collect(); let refs: Vec<&str> = cats.iter().map(String::as_str).collect(); - let vals = vec!["1"; 5000]; - let many: Vec = (0..300).map(|i| ser(i, "S", None, &refs, &vals)).collect(); + let vals = vec!["1"; n]; + let many: Vec = (0..3 * MAX_RADAR_SERIES).map(|i| ser(i, "S", None, &refs, &vals)).collect(); let items = radar_chart("marker", &many); let polygons = items.iter().filter(|it| matches!(it, GraphicItem::Path { stroke: Some(c), .. } if *c != GRID)).count(); assert!(polygons <= MAX_RADAR_SERIES, "{polygons}"); diff --git a/crates/docx/tests/it/comment_save_cost.rs b/crates/docx/tests/it/comment_save_cost.rs index 2bcd5fb86..88902400b 100644 --- a/crates/docx/tests/it/comment_save_cost.rs +++ b/crates/docx/tests/it/comment_save_cost.rs @@ -29,8 +29,8 @@ fn cpu_cost(mut f: impl FnMut()) -> f64 { #[test] fn many_comments_save_without_quadratic_id_searches() { for imported in [true, false] { - let small = comments(4_000, imported); - let big = comments(32_000, imported); + let small = comments(1_000, imported); + let big = comments(8_000, imported); let save = |d: &Document| drop(std::hint::black_box(craft_docx::write(d).unwrap())); save(&small); save(&big); @@ -39,7 +39,7 @@ fn many_comments_save_without_quadratic_id_searches() { // use elapsed time; retry ratios far from linear before declaring a regression. for _ in 0..3 { let (mut s, mut b) = (f64::INFINITY, f64::INFINITY); - for _ in 0..3 { + for _ in 0..2 { s = s.min(cpu_cost(|| (0..8).for_each(|_| save(&small))) / 8.0); b = b.min(cpu_cost(|| save(&big))); } diff --git a/crates/docx/tests/it/content_control_save_cost.rs b/crates/docx/tests/it/content_control_save_cost.rs index 9b96aeb7b..768f00ede 100644 --- a/crates/docx/tests/it/content_control_save_cost.rs +++ b/crates/docx/tests/it/content_control_save_cost.rs @@ -59,7 +59,7 @@ fn cost_ratio(scale: usize, mut small: impl FnMut(), mut big: impl FnMut()) -> ( big(); let mut small_scaled = || (0..scale).for_each(|_| small()); let (mut t1, mut tk) = (f64::INFINITY, f64::INFINITY); - for _ in 0..5 { + for _ in 0..3 { let a = Instant::now(); small_scaled(); t1 = t1.min(a.elapsed().as_secs_f64() / scale as f64); @@ -76,8 +76,8 @@ fn cost_ratio(scale: usize, mut small: impl FnMut(), mut big: impl FnMut()) -> ( #[test] fn a_document_with_many_inline_content_controls_saves_in_linear_time() { let scale = 4; - let small = inline_controls(8_000); - let big = inline_controls(8_000 * scale); + let small = inline_controls(2_000); + let big = inline_controls(2_000 * scale); let (t1, tk, ratio) = cost_ratio( scale, || { @@ -96,8 +96,8 @@ fn a_document_with_many_inline_content_controls_saves_in_linear_time() { #[test] fn a_document_with_many_block_content_controls_saves_in_linear_time() { let scale = 4; - let small = block_controls(8_000); - let big = block_controls(8_000 * scale); + let small = block_controls(2_000); + let big = block_controls(2_000 * scale); let (t1, tk, ratio) = cost_ratio( scale, || { diff --git a/crates/docx/tests/it/element_budget.rs b/crates/docx/tests/it/element_budget.rs index 6b220ae7c..d18e2762a 100644 --- a/crates/docx/tests/it/element_budget.rs +++ b/crates/docx/tests/it/element_budget.rs @@ -9,6 +9,11 @@ const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingm #[test] fn a_file_of_element_budget_parts_still_reads() { + // 18M elements: nightly only. `the_xml_element_budget_is_package_wide` (in `package.rs`) proves + // the package-wide budget with a small one at the gate. + if craft_testkit::hostile::divisor() > 1 { + return; + } // Nine chart parts of 2M elements each: 18M over the package's 16M budget. The later // parts are skipped with a warning instead of built, and the file still reads. Before // the budget, every part's whole tree was parsed and the chart trees stayed cached for diff --git a/crates/docx/tests/it/malformed.rs b/crates/docx/tests/it/malformed.rs index b1c5b8f17..fc65b8e2d 100644 --- a/crates/docx/tests/it/malformed.rs +++ b/crates/docx/tests/it/malformed.rs @@ -179,7 +179,8 @@ fn many_fields_and_huge_attribute_values() { /// limit error, or the extras are dropped and the text survives (#3702, WC-06). #[test] fn millions_of_attributes_on_one_paragraph_are_capped() { - let attrs: String = (0..2_000_000).map(|i| format!(" a{i}=\"\"")).collect(); + // The gate reads a fraction of the attributes; nightly all of them. + let attrs: String = (0..2_000_000 / craft_testkit::hostile::divisor()).map(|i| format!(" a{i}=\"\"")).collect(); let x = format!("kept"); // Only the read is timed: deflating the test input in a debug build is not what is bounded. let z = doc_zip(x.as_bytes()); @@ -253,7 +254,7 @@ fn malformed_or_hostile_bibliography_never_panics() { fn hostile_bibliography_source_count_is_capped() { let doc = format!("body"); let mut sources = String::from(r#""#); - for i in 0..60_000 { + for i in 0..(60_000 / craft_testkit::hostile::divisor()).max(10_500) { sources.push_str(&format!("T{i}Title {i}")); // Untagged duplicates all collapse into one source. sources.push_str("Same"); @@ -313,11 +314,13 @@ fn compound(info: &[u8], package: &[u8]) -> Vec { proptest! { // Each case that parses runs the 50,000-spin key derivation, so fewer cases. - #![proptest_config(ProptestConfig { cases: 48, ..ProptestConfig::default() })] + #![proptest_config(ProptestConfig { cases: (48 / craft_testkit::hostile::divisor() as u32).max(6), ..ProptestConfig::default() })] #[test] fn mutated_standard_encryption_never_panics(ops in proptest::collection::vec((0u8..3, any::(), any::(), any::()), 1..8)) { - let (mut info, mut package) = standard_streams(); + // Encrypting runs the key derivation too: once for every case. + static STREAMS: std::sync::OnceLock<(Vec, Vec)> = std::sync::OnceLock::new(); + let (mut info, mut package) = STREAMS.get_or_init(standard_streams).clone(); for (k, idx, byte, in_package) in ops { let x = if in_package { &mut package } else { &mut info }; let at = idx.index(x.len() + 1); diff --git a/crates/docx/tests/it/word_xml.rs b/crates/docx/tests/it/word_xml.rs index 31c022aa0..2571facb2 100644 --- a/crates/docx/tests/it/word_xml.rs +++ b/crates/docx/tests/it/word_xml.rs @@ -268,6 +268,10 @@ fn flat_opc_limits_count_what_is_not_kept() { assert!(limited(&r#"AA=="#.repeat(20_000))); assert!(limited(&"".repeat(20_000))); // A part nothing reads, one element over what the XML tree reader takes in a part (8 000 000). + // Millions of elements: nightly only; the checks above prove the same counting at the gate. + if craft_testkit::hostile::divisor() > 1 { + return; + } assert!(limited(&format!(r#"{}"#, "".repeat(8_000_000)))); } diff --git a/crates/draw/src/ui/pen/bezier/mod.rs b/crates/draw/src/ui/pen/bezier/mod.rs index be40e447a..a480816dc 100644 --- a/crates/draw/src/ui/pen/bezier/mod.rs +++ b/crates/draw/src/ui/pen/bezier/mod.rs @@ -212,6 +212,8 @@ enum Target { knot: KnotRef, side: HandleSide, from: Point, + /// The handle's anchor at the press: ⇧ turns the handle about it. + anchor: Point, }, /// A curved segment, grabbed at `t` where it passes `from`. Bend { @@ -635,7 +637,8 @@ impl<'a> BezierOverlay<'a> { let knot_at = |path: u64, knot: KnotRef| Self::path(paths, path).and_then(|p| p.knot(knot)); match (self.tool, hit) { (_, BezierHit::Handle { path, knot, side }) if self.tool != BezierTool::Curvature => { - Target::Handle { path, knot, side, from: knot_at(path, knot).map_or(Point::ZERO, |k| k.handle(side)) } + let at = knot_at(path, knot); + Target::Handle { path, knot, side, from: at.map_or(Point::ZERO, |k| k.handle(side)), anchor: at.map_or(Point::ZERO, |k| k.anchor) } } (BezierTool::Curvature, BezierHit::Anchor { path, knot }) => { self.report.select = Some(self.selecting(path, vec![knot], None)); @@ -728,8 +731,10 @@ impl<'a> BezierOverlay<'a> { Target::Anchors { path, anchors, from } => { PathEdit::MoveAnchors { path: *path, anchors: anchors.clone(), by: snapped(*from + locked(delta)) - *from } } - &Target::Handle { path, knot, side, from } => { - PathEdit::MoveHandle { path, knot, side, to: snapped(from + delta), alone: tool == BezierTool::Convert || mods.alt } + &Target::Handle { path, knot, side, from, anchor } => { + // ⇧ turns the handle to the nearest 45° about its anchor, as the Pen's pull does. + let to = if mods.shift { handle_45(anchor, from + delta) } else { snapped(from + delta) }; + PathEdit::MoveHandle { path, knot, side, to, alone: tool == BezierTool::Convert || mods.alt } } &Target::Bend { path, segment, t, from } => PathEdit::BendSegment { path, segment, t, by: snapped(from + delta) - from }, &Target::Convert { path, knot } => PathEdit::Convert { path, knot, out: Some(snapped(view.to_doc(pointer))) }, diff --git a/crates/draw/src/ui/transform/session_overlay.rs b/crates/draw/src/ui/transform/session_overlay.rs index de65d190e..f5414abac 100644 --- a/crates/draw/src/ui/transform/session_overlay.rs +++ b/crates/draw/src/ui/transform/session_overlay.rs @@ -160,6 +160,7 @@ impl<'a, W: TransformWarp> TransformOverlay<'a, W> { .reference_point(session.reference_point()) .reach(self.reach) .rotate_zone(self.rotate_zone) + .own_context_menu(self.reach == TransformReach::Box) .id_source(self.id); if let Some(mods) = self.mods { tbox = tbox.mods(mods); diff --git a/crates/draw/src/ui/transform/transform_box.rs b/crates/draw/src/ui/transform/transform_box.rs index c5605959c..837fe4dee 100644 --- a/crates/draw/src/ui/transform/transform_box.rs +++ b/crates/draw/src/ui/transform/transform_box.rs @@ -509,6 +509,10 @@ pub struct TransformBox<'a> { /// and an open drag's Escape still cancels the drag. #[prop] session_commit: bool, + /// The caller hangs a context menu of its own on the box (`Menu::context` over its response): every part takes the + /// right click, so it does not reach the tool under the box. + #[prop] + own_context_menu: bool, /// Whether this pass holds a drag of the reference point, so the hidden point is drawn while it moves. pivot_held: bool, /// Whether this pass holds a drag that began, so a live line's box shows as it scales. @@ -538,6 +542,7 @@ impl<'a> TransformBox<'a> { reach: TransformReach::Box, color: None, session_commit: true, + own_context_menu: false, pivot_held: false, dragging: false, report: Report::default(), @@ -1098,11 +1103,11 @@ fn paint_frame(draw: &Draw<'_>, style: &TransformBoxStyle, line: StrokeColor, co /// The move reach outside the box whose corners are `quad` on the screen: every point within `points` of its border, /// as a strip along each side and a round sector outside each corner (PhotoCraft's type move reach measures the /// distance to the nearest side, pc-prod-e76 type_transform.rs:156-196). -fn declare_ring(cx: &mut PartsCx<'_, TransformBox<'_>>, quad: &[Pos2; 4], points: f32) { +fn declare_ring(cx: &mut PartsCx<'_, TransformBox<'_>>, quad: &[Pos2; 4], points: f32, context: Sense) { let outward = outward_normals(quad); let mut declare = |part: usize, shape: Vec| { cx.part(MOVE_RING.at(part as u64), HitShape::Polygon(shape)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside) | context) .priority(HitPriority::new(HitLevel::Body, RING_SUB)) .pointer_only(MOVE_BY_KEY); }; @@ -1250,9 +1255,10 @@ impl Component for TransformBox<'_> { let style = cx.style; let screen = on_screen(&space.view, &state); let quad: [Pos2; 4] = screen.quad.map(pos); + let context = if self.own_context_menu { Sense::CONTEXT_CLICK } else { Sense::empty() }; if self.move_only().is_some() { if let Some(points) = self.ring_reach() { - declare_ring(cx, &quad, points); + declare_ring(cx, &quad, points, context); } return; } @@ -1279,13 +1285,13 @@ impl Component for TransformBox<'_> { ) } }; - cx.part(BOX.at(part.index()), shape).sense(sense | slop_sense(part)).priority(priority).focus_shape(focus).focusable(); + cx.part(BOX.at(part.index()), shape).sense(sense | slop_sense(part) | context).priority(priority).focus_shape(focus).focusable(); any = true; } if let Some(line) = self.line { for (end, at) in line.free_ends() { cx.part(LINE_END.at(end.index()), HitShape::circle(space.view.to_screen(at), style.handle_reach)) - .sense(Sense::DRAG | Sense::CLICK) + .sense(Sense::DRAG | Sense::CLICK | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(LINE_END_BY_KEY); } @@ -1299,7 +1305,7 @@ impl Component for TransformBox<'_> { let band = if self.rules.edge_band > 0.0 { edge_band(&quad, side, self.rules.edge_band) } else { side_band(&quad, side, style.side_band) }; cx.part(EDGE.at(u64::from(k)), band) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Edge(k))) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Edge(k)) | context) .priority(HitPriority::new(HitLevel::Handle, EDGE_SUB)) .pointer_only(EDGE_BY_KEY); } @@ -1309,7 +1315,7 @@ impl Component for TransformBox<'_> { for (end, side) in [(0u64, corner), (1, (corner + 3) % 4)] { let Some(reach) = corner_reach(&quad, side, corner, style.side_band) else { continue }; cx.part(CORNER_REACH.at(2 * u64::from(k) + end), reach) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Corner(k))) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Corner(k)) | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(CORNER_BY_KEY); } @@ -1317,7 +1323,7 @@ impl Component for TransformBox<'_> { if self.declares_centre() { let centre = quad.iter().fold(Vec2::ZERO, |sum, corner| sum + corner.to_vec2()) / 4.0; cx.part(CENTRE.at(0), HitShape::circle(centre.to_pos2(), style.hit)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside) | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(MOVE_BY_KEY); } @@ -1328,7 +1334,7 @@ impl Component for TransformBox<'_> { RotateZone::Outside | RotateZone::Border { .. } if self.rules.allows(BoxPart::Outside) => { for (corner, region) in outside_regions(&quad, rect).into_iter().enumerate() { cx.part(OUTSIDE.at(corner as u64), HitShape::Polygon(region)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context) .priority(HitPriority::new(HitLevel::Background, 0)) .pointer_only(ROTATE_BY_KEY); } @@ -1336,7 +1342,7 @@ impl Component for TransformBox<'_> { RotateZone::Band if self.rules.allows(BoxPart::Outside) => { for (corner, ring) in band_rings(&screen, style).into_iter().enumerate() { cx.part(OUTSIDE.at(corner as u64), HitShape::Polygon(ring)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context) .priority(HitPriority::new(HitLevel::Body, 0)) .pointer_only(ROTATE_BY_KEY); } @@ -1347,7 +1353,7 @@ impl Component for TransformBox<'_> { if self.has_knob() { let (knob, _) = knob_at(&quad, rect, style); cx.part(KNOB.at(0), HitShape::circle(knob, style.handle_reach)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(ROTATE_BY_KEY); } @@ -1355,7 +1361,7 @@ impl Component for TransformBox<'_> { RotateZone::Handle if self.rules.allows(BoxPart::Outside) => { let (_, knob) = rotate_handle(&quad, style.rotate_stem); cx.part(ROTATE_HANDLE.at(0), HitShape::circle(knob, style.handle_reach)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(ROTATE_BY_KEY); } diff --git a/crates/draw/src/ui/transform/transform_fields.rs b/crates/draw/src/ui/transform/transform_fields.rs index cfc007bbf..d6e039acf 100644 --- a/crates/draw/src/ui/transform/transform_fields.rs +++ b/crates/draw/src/ui/transform/transform_fields.rs @@ -16,8 +16,8 @@ use craft_behavior::{ColumnWidth, EditEvent, EditEvents, GestureId, IconId, Mixe use craft_ui::buttons::ToggleButton; use craft_ui::canvas::CanvasRulers; use craft_ui::contract::{ - Bind, BodyCx, Entry, FieldLayout, GlyphLabel, LabelKind, LabelPress, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, SideLabel, - Sizing, + Bind, BodyCx, Bracket, Entry, FieldLayout, GlyphLabel, LabelKind, LabelPress, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, + SideLabel, Sizing, }; use craft_ui::display::Divider; use craft_ui::form::{Field, FieldGroup}; @@ -135,7 +135,8 @@ pub enum FieldArrangement { /// W, the link and H on the first row, then X and Y. #[default] SizeFirst, - /// X and W on the first row, Y and H on the second, the link after them: Tab runs X, W, Y, H. + /// X and W on the first row, Y and H on the second, the link beside them centred across the two rows: Tab runs X, + /// W, Y, H. PositionFirst, } @@ -224,7 +225,8 @@ impl Outcome for TransformFieldsOutput { /// - **Panel form** (the default): two field columns that fill the width, the link's column between them: W, the /// link and H on one row, X and Y on the next, the angle, then the H and V skews; the compact reference point, when /// shown, leads the first row. [`groups`](Self::groups) leaves out the rows of hidden groups. With -/// [`FieldArrangement::PositionFirst`] the grid is X and W, then Y and H, with the link after them. +/// [`FieldArrangement::PositionFirst`] the grid is X and W, then Y and H, with the link beside it, centred across +/// the two rows. /// - **Bar form** ([`bar`](Self::bar)): the compact reference point, then captioned fields in Photoshop's order with a /// divider between the groups, the Δ toggle between X and Y, the interpolation select last. /// [`groups`](Self::groups) narrows the strip. @@ -437,10 +439,10 @@ struct Cells<'a> { const FIELD_COLUMNS: [ColumnWidth; 3] = [ColumnWidth::fill(1.0), ColumnWidth::Content, ColumnWidth::fill(1.0)]; /// The panel form's columns with the reference point before them. const REFERENCE_COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content, ColumnWidth::fill(1.0), ColumnWidth::Content, ColumnWidth::fill(1.0)]; -/// The position-first panel form's columns: two fields, then the link's column. -const POSITION_COLUMNS: [ColumnWidth; 3] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; +/// The position-first panel form's columns: two fields that share the width. +const PAIR_COLUMNS: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0)]; /// The position-first panel form's columns with the reference point before them. -const POSITION_REFERENCE_COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content, ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; +const REFERENCE_PAIR_COLUMNS: [ColumnWidth; 3] = [ColumnWidth::Content, ColumnWidth::fill(1.0), ColumnWidth::fill(1.0)]; /// Which form the cells show in. #[derive(Clone, Copy, PartialEq, Eq)] @@ -690,43 +692,39 @@ impl Cells<'_> { }); } - /// The position-first grid of [`rows`](Self::rows): X and W, Y and H with the link after them, the angle, then the - /// skews; two field columns and the link's column, the reference point, when shown, in a column before them. + /// The position-first form of [`rows`](Self::rows): X and W, then Y and H, in a grid beside the link, which stands + /// centred across their two rows; the reference point, when shown, leads the grid's first row in a column of its + /// own. The angle and the skews follow in a grid of their own. fn position_first(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>, pass: &mut Pass) { let groups = self.groups; - let columns: &'static [ColumnWidth] = if groups.reference { &POSITION_REFERENCE_COLUMNS } else { &POSITION_COLUMNS }; - Grid::new(columns).id_salt("fields").fill_width().show(ui, |ui, _| { - let mut first = true; - let pair = [(groups.position, TransformField::X, TransformField::Y), (groups.size, TransformField::W, TransformField::H)]; - if groups.position || groups.size || groups.reference { - self.lead(ui, cx, pass, &mut first); - for (shown, top, _) in pair { - self.field_or_empty(ui, cx, pass, shown, top); - } + if groups.position || groups.size || groups.reference { + let columns: &'static [ColumnWidth] = if groups.reference { &REFERENCE_PAIR_COLUMNS } else { &PAIR_COLUMNS }; + Row::new().bracket(Bracket::Unlinked).fill_width().show(ui, |ui, _| { + Grid::new(columns).id_salt("fields").fill_width().show(ui, |ui, _| { + let mut first = true; + let rows = if groups.position || groups.size { 2 } else { 1 }; + for row in [[TransformField::X, TransformField::W], [TransformField::Y, TransformField::H]].into_iter().take(rows) { + self.lead(ui, cx, pass, &mut first); + self.field_or_empty(ui, cx, pass, groups.position, row[0]); + self.field_or_empty(ui, cx, pass, groups.size, row[1]); + } + }); if groups.size { self.link(ui); - } else { - empty(ui); } - } - if groups.position || groups.size { - self.lead(ui, cx, pass, &mut first); - for (shown, _, bottom) in pair { - self.field_or_empty(ui, cx, pass, shown, bottom); - } - empty(ui); - } + }); + } + if !(groups.angle || groups.skew) { + return; + } + Grid::new(&PAIR_COLUMNS).id_salt("turns").fill_width().show(ui, |ui, _| { if groups.angle { - self.lead(ui, cx, pass, &mut first); self.field(ui, cx, pass, TransformField::Angle, Form::Panel); empty(ui); - empty(ui); } if groups.skew { - self.lead(ui, cx, pass, &mut first); self.field(ui, cx, pass, TransformField::SkewH, Form::Panel); self.field(ui, cx, pass, TransformField::SkewV, Form::Panel); - empty(ui); } }); } diff --git a/crates/draw/tests/it/bezier.rs b/crates/draw/tests/it/bezier.rs index 65b671f93..aa17f1914 100644 --- a/crates/draw/tests/it/bezier.rs +++ b/crates/draw/tests/it/bezier.rs @@ -739,6 +739,33 @@ fn shift_keeps_an_anchor_drag_on_the_axis_or_the_diagonal() { } } +// ⇧ during a handle drag turns the handle to the nearest 45° about its anchor, also when pressed mid-drag: about 20° +// lands on the axis, about 40° on the diagonal, and photocraft#15760's measured (-78, +140) on (-78, +78); without ⇧ +// the handle follows the pointer. +#[trial] +fn shift_locks_a_handle_drag_to_the_nearest_45_degrees() { + let anchor = p(260.0, 60.0); + let cases = + [(p(360.0, 96.0), p(360.0, 60.0)), (p(340.0, 127.0), p(327.0, 127.0)), (anchor + Vec2::new(-78.0, 140.0), anchor + Vec2::new(-78.0, 78.0))]; + for (shift, (target, locked)) in cases.iter().flat_map(|c| [(true, *c), (false, *c)]) { + let mut h = two_paths(); + h.update(|st| st.selection = sel(1, &[(0, 2)])); + let handle = h.screen(p(290.0, 100.0)); + let to = h.screen(target); + h.press_at(handle); + h.move_to(handle + (to - handle) * 0.5); + if shift { + h.fixture.hold(egui::Modifiers::SHIFT); + } + h.move_to(to); + let Some(PathEdit::MoveHandle { to: got, .. }) = h.last_change() else { panic!("a handle move: {:?}", h.last_change()) }; + h.release_at(to); + h.fixture.hold(egui::Modifiers::NONE); + let want = if shift { locked } else { target }; + assert!(got.distance(want) < 1e-3, "shift {shift}: {target:?} gives {got:?}, wants {want:?}"); + } +} + // Delete Anchor with only some subpaths' anchors shown (#12769): a click on a hidden anchor deletes nothing and // edits nothing, selects that anchor and shows only its subpath; the next click on it deletes it. #[trial] diff --git a/crates/draw/tests/it/transform_box.rs b/crates/draw/tests/it/transform_box.rs index 0fbf30cc6..e8b32bb82 100644 --- a/crates/draw/tests/it/transform_box.rs +++ b/crates/draw/tests/it/transform_box.rs @@ -1070,20 +1070,28 @@ fn a_jittery_double_click_inside_applies_with_no_move_committed() { assert_eq!(h.host.borrow().applied, 1, "the double click applies"); } -/// A secondary click on the session's box opens the mode menu (its rows are on the page); with the menu closed again, a -/// secondary click away from the box opens none. +/// A secondary click on the session's box opens the mode menu (its rows are on the page) and is the box's alone: the +/// tool host under it asks for no menu of its own. With the menu closed again, a secondary click away from the box +/// opens none. #[trial] fn a_secondary_click_on_the_box_opens_the_mode_menu() { + use craft_draw::ui::transform::TransformTool; + use craft_ui::canvas::{ToolHost, tool_pass}; let session = TransformSession::<()>::new(RECT); let settings = TransformSettings::default(); let view = Rc::new(RefCell::new(CanvasView::new(egui::Rect::NOTHING, Point::ZERO, 1.0))); - let shown_view = Rc::clone(&view); + let host_asked = Rc::new(Cell::new(false)); + let (shown_view, asked) = (Rc::clone(&view), Rc::clone(&host_asked)); let mut fixture = Fixture::new(move |ui| { let room = ui.available_rect_before_wrap(); let at = CanvasView::new(room, Point::new(f64::from(room.width()) / 2.0, f64::from(room.height()) / 2.0), 1.0); *shown_view.borrow_mut() = at; Canvas::new("Document").view(at).show(ui, |ui, body| { - TransformOverlay::new("Free Transform", &session, &settings).show_at(ui, body.rect); + let shown = TransformOverlay::new("Free Transform", &session, &settings).show_at(ui, body.rect); + if let Some(pass) = tool_pass(&body.env) { + let mut tool = TransformTool::new(&session, shown.snapped.clone()); + asked.set(asked.get() || ToolHost::new().run(ui, &pass, &mut tool).context.is_some()); + } }); }); fixture.settle(); @@ -1098,8 +1106,10 @@ fn a_secondary_click_on_the_box_opens_the_mode_menu() { right_click(&mut fixture, screen(Point::new(1000.0, 1000.0))); assert!(fixture.by_label("Distort").is_none(), "a secondary click away from the box opens no mode menu"); + host_asked.set(false); right_click(&mut fixture, screen(Point::new(200.0, 150.0))); assert!(fixture.by_label("Distort").is_some(), "a secondary click on the box opens the mode menu"); + assert!(!host_asked.get(), "the tool host under the box asks for no menu"); } /// A drag from inside snaps the moved box's edges, not the pointer: the right edge lands on the guide at 310 while the diff --git a/crates/draw/tests/it/transform_fields.rs b/crates/draw/tests/it/transform_fields.rs index 7a7341445..b83456aa9 100644 --- a/crates/draw/tests/it/transform_fields.rs +++ b/crates/draw/tests/it/transform_fields.rs @@ -4,7 +4,7 @@ use craft_behavior::geometry::quad::BoxState; use craft_behavior::kurbo::{Point, Rect, Size}; use craft_behavior::{EditEvent, Mixed, RulerUnits}; -use craft_draw::ui::transform::{SizeUnit, TransformField, TransformFields, TransformGroups, TransformRow, TransformSource}; +use craft_draw::ui::transform::{FieldArrangement, SizeUnit, TransformField, TransformFields, TransformGroups, TransformRow, TransformSource}; use craft_ui::canvas::{CanvasRulers, RulerText}; use craft_ui::contract::Bind; use craft_ui::runtime::env::UnitKind; @@ -286,3 +286,44 @@ fn a_start_box_that_moves_with_a_scrub_keeps_the_scrub_running() { assert!(events.iter().any(|event| matches!(event, EditEvent::Commit { .. })), "the release committed it: {events:?}"); assert!(row.state.quad[0].distance(row.state.quad[1]) > START.width(), "the scrub widened the box: {row:?}"); } + +/// The position-first panel form stands the reference point before the X and W, Y and H rows and the link after them +/// centred across the rows, both clear of every field, in a wide room, a narrow one and a host sized from its content. +#[trial] +fn the_position_first_link_stands_between_the_width_and_height_rows() { + use craft_ui::contract::ShowContainer as _; + for (width, content) in [(260.0, false), (400.0, false), (400.0, true)] { + let mut row = TransformRow::new(BoxState::from_rect(START), 0.0); + let mut linked = true; + let mut fixture = Fixture::new(move |ui| { + let mut show = |ui: &mut egui::Ui| { + TransformFields::new("Transform", Bind::bound(&mut row), START, Bind::bound(&mut linked)) + .arrangement(FieldArrangement::PositionFirst) + .show(ui) + }; + if content { + craft_ui::layout_components::Stack::new().show(ui, |ui, _| show(ui)); + } else { + show(ui); + } + }); + fixture.room(egui::vec2(width, 400.0)).settle(); + let rect = |label: &str| fixture.by_label(label).unwrap_or_else(|| panic!("the fields show {label}")).rect; + let link = rect("Maintain aspect ratio"); + let reference = rect("Reference point"); + let fields = ["X position", "Width", "Y position", "Height"].map(rect); + let dump = format!("in {width} (content: {content}): reference {reference:?}, link {link:?}, fields {fields:?}"); + assert!( + fields.iter().all(|field| !field.intersects(link) && !field.intersects(reference)), + "no field overlaps the link or the point: {dump}" + ); + let [x, w, _, h] = fields; + assert!( + reference.right() <= x.left() && w.right() <= link.left() && link.right() <= width, + "point, fields, link in order, inside the room: {dump}" + ); + assert!(h.top() >= w.bottom(), "H is under W: {dump}"); + let middle = (w.top() + h.bottom()) / 2.0; + assert!((link.center().y - middle).abs() <= 1.0, "the link is centred across the two rows: {dump}"); + } +} diff --git a/crates/drawingml/Cargo.toml b/crates/drawingml/Cargo.toml index 9a8fe2f9a..46a6c596f 100644 --- a/crates/drawingml/Cargo.toml +++ b/crates/drawingml/Cargo.toml @@ -18,4 +18,5 @@ log = "0.4" serde = { workspace = true } [dev-dependencies] +craft-testkit = { workspace = true } serde_json = { workspace = true } diff --git a/crates/drawingml/src/chart.rs b/crates/drawingml/src/chart.rs index 1dd92177a..91321e351 100644 --- a/crates/drawingml/src/chart.rs +++ b/crates/drawingml/src/chart.rs @@ -1762,8 +1762,8 @@ mod chartex_tests { #[test] fn large_box_hierarchy_and_stacked_charts_take_linear_work() { - // 50,000 distinct categories in one series: grouped through a map, one pass. - let n = 50_000; + // 5,000 distinct categories in one series: grouped through a map, one pass. + let n = 5_000; let mut c = Chart::sample(ChartType::BoxWhisker); c.series.truncate(1); c.categories = (0..n).map(|i| format!("g{i}")).collect(); @@ -1771,12 +1771,13 @@ mod chartex_tests { let (groups, stats) = c.box_groups(); assert_eq!((groups.len(), stats[0].len()), (n, n)); assert!(stats[0].iter().all(Option::is_some)); - // 2,000 series cap the groups so the result stays within MAX_BOX_CELLS. - c.series = vec![c.series[0].clone(); 2000]; + // Enough series to cap the groups so the result stays within MAX_BOX_CELLS. + let series = MAX_BOX_CELLS / n * 2; + c.series = vec![c.series[0].clone(); series]; let (groups, stats) = c.box_groups(); - assert_eq!(groups.len(), MAX_BOX_CELLS / 2000); + assert_eq!(groups.len(), MAX_BOX_CELLS / series); assert!(stats.iter().all(|s| s.len() == groups.len())); - // One long outer label over 50,000 leaves is shared, not copied per leaf. + // One long outer label over 5,000 leaves is shared, not copied per leaf. let mut t = Chart::sample(ChartType::Treemap); t.series.truncate(1); t.categories = (0..n).map(|i| format!("c{i}")).collect(); diff --git a/crates/drawingml/src/table.rs b/crates/drawingml/src/table.rs index b5d83d530..dd6c90d03 100644 --- a/crates/drawingml/src/table.rs +++ b/crates/drawingml/src/table.rs @@ -342,30 +342,42 @@ impl Table { } /// Whether [`Table::normalize`] would drop rows or columns to fit [`MAX_CELLS`]. pub fn over_cap(&self) -> bool { - let n = self.cols.len(); - n > MAX_CELLS || self.rows.len() > (MAX_CELLS / n.max(1)).max(1) + self.over(MAX_CELLS) } /// What [`Table::normalize`] would leave of this table, cloning only the rows and cells that /// survive (an oversized table is not copied whole first). pub fn normalized(&self) -> Table { - let n = self.cols.len().min(MAX_CELLS); - let keep = (MAX_CELLS / n.max(1)).max(1); - let rows = self.rows.iter().take(keep).map(|r| Row { height: r.height, cells: r.cells.iter().take(n).cloned().collect() }).collect(); - let mut t = Table { cols: self.cols[..n].to_vec(), rows, background: self.background.clone(), style: self.style.clone(), ..*self }; - t.normalize(); - if self.over_cap() { - t.clip_spans(); - } - t + self.normalized_within(MAX_CELLS) } /// Make every row have exactly `cols.len()` cells (repair after loading). A grid over /// [`MAX_CELLS`] loses its last rows (and columns) first, so a file naming many rows and many /// columns but few cells cannot make this allocate their product. pub fn normalize(&mut self) { - let truncated = self.over_cap(); - self.cols.truncate(MAX_CELLS); + self.normalize_within(MAX_CELLS); + } + /// [`Table::over_cap`] for a cap of `max` cells. + fn over(&self, max: usize) -> bool { let n = self.cols.len(); - self.rows.truncate((MAX_CELLS / n.max(1)).max(1)); + n > max || self.rows.len() > (max / n.max(1)).max(1) + } + /// [`Table::normalized`] for a cap of `max` cells. + fn normalized_within(&self, max: usize) -> Table { + let n = self.cols.len().min(max); + let keep = (max / n.max(1)).max(1); + let rows = self.rows.iter().take(keep).map(|r| Row { height: r.height, cells: r.cells.iter().take(n).cloned().collect() }).collect(); + let mut t = Table { cols: self.cols[..n].to_vec(), rows, background: self.background.clone(), style: self.style.clone(), ..*self }; + t.normalize_within(max); + if self.over(max) { + t.clip_spans(); + } + t + } + /// [`Table::normalize`] for a cap of `max` cells. + fn normalize_within(&mut self, max: usize) { + let truncated = self.over(max); + self.cols.truncate(max); + let n = self.cols.len(); + self.rows.truncate((max / n.max(1)).max(1)); for r in &mut self.rows { r.cells.resize_with(n, || Cell::new("")); for c in &mut r.cells { @@ -741,18 +753,27 @@ mod tests { #[test] fn normalize_caps_a_sparse_grid_at_max_cells() { - let mut t = Table { cols: vec![10.0; 1000], rows: vec![Row::default(); 1000], ..Default::default() }; - t.normalize(); - assert_eq!(t.cols.len(), 1000); - assert_eq!(t.rows.len(), MAX_CELLS / 1000); - assert!(t.rows.iter().all(|r| r.cells.len() == 1000)); - let mut t = Table { cols: vec![1.0; MAX_CELLS + 5], rows: vec![Row::default(); 3], ..Default::default() }; - t.normalize(); - assert_eq!((t.cols.len(), t.rows.len()), (MAX_CELLS, 1)); - let wide = Table { cols: vec![10.0; 1000], rows: vec![Row { height: 1.0, cells: vec![Cell::new("x"); 1500] }; 150], ..Default::default() }; - let mut n = wide.clone(); - n.normalize(); - assert_eq!(wide.normalized(), n); + // At a cap 100 times smaller; nightly also at MAX_CELLS. + let full = craft_testkit::hostile::divisor() == 1; + for max in [MAX_CELLS / 100].into_iter().chain(full.then_some(MAX_CELLS)) { + let cols = max / 100; + let mut t = Table { cols: vec![10.0; cols], rows: vec![Row::default(); 1000], ..Default::default() }; + t.normalize_within(max); + assert_eq!(t.cols.len(), cols); + assert_eq!(t.rows.len(), max / cols); + assert!(t.rows.iter().all(|r| r.cells.len() == cols)); + let mut t = Table { cols: vec![1.0; max + 5], rows: vec![Row::default(); 3], ..Default::default() }; + t.normalize_within(max); + assert_eq!((t.cols.len(), t.rows.len()), (max, 1)); + let wide = Table { + cols: vec![10.0; cols], + rows: vec![Row { height: 1.0, cells: vec![Cell::new("x"); cols + cols / 10] }; max / cols + 1], + ..Default::default() + }; + let mut n = wide.clone(); + n.normalize_within(max); + assert_eq!(wide.normalized_within(max), n); + } let mut t = Table::new(4, 4, 400.0, 30.0); t.normalize(); assert_eq!((t.n_rows(), t.n_cols()), (4, 4)); diff --git a/crates/exr/Cargo.toml b/crates/exr/Cargo.toml index 7221a6858..28a1649b8 100644 --- a/crates/exr/Cargo.toml +++ b/crates/exr/Cargo.toml @@ -24,3 +24,6 @@ half = { version = "2", optional = true } thiserror = { workspace = true, optional = true } # zlib for scanline payloads and deep ZIPS chunks, which the `exr` crate does not read. flate2 = { version = "1", default-features = false, features = ["rust_backend"], optional = true } + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/exr/src/decode_tests.rs b/crates/exr/src/decode_tests.rs index 61f207a16..32fefa029 100644 --- a/crates/exr/src/decode_tests.rs +++ b/crates/exr/src/decode_tests.rs @@ -243,11 +243,13 @@ fn hostile_files_never_panic() { (5, 3), ); let limits = Limits { max_bytes: 1 << 24, ..Limits::default() }; - for n in 0..good.len() { + // The gate runs every divisor-th truncation and byte; nightly runs every one. + let step = craft_testkit::hostile::divisor(); + for n in (0..good.len()).step_by(step) { let _ = parts(&good[..n], &limits); let _ = decode_part(&good[..n], 1, &all, &limits); } - for i in 0..good.len() { + for i in (0..good.len()).step_by(step) { for v in [0u8, 1, 0x7F, 0xFF] { let mut b = good.clone(); b[i] = v; diff --git a/crates/exr/src/seek_tests.rs b/crates/exr/src/seek_tests.rs index 010492235..0f48fdb38 100644 --- a/crates/exr/src/seek_tests.rs +++ b/crates/exr/src/seek_tests.rs @@ -354,12 +354,13 @@ fn hostile_files_are_refused_and_never_panic() { let channels: Vec<(usize, usize)> = (0..index.parts().len()).flat_map(|p| channels_of(&index, p)).collect(); let _ = read_planes(&mut Cursor::new(data), &index, &Request::new(&channels, 1 << 24), &never); }; - // Every truncation. - for n in 0..bytes.len() { + // Every truncation (at the gate every divisor-th one, as for the flipped bytes). + let step = craft_testkit::hostile::divisor(); + for n in (0..bytes.len()).step_by(step) { try_read(&bytes[..n]); } // A flipped byte at every position (headers, tables and chunks). - for at in 0..bytes.len() { + for at in (0..bytes.len()).step_by(step) { let mut broken = bytes.clone(); broken[at] ^= 0xFF; try_read(&broken); @@ -1413,11 +1414,11 @@ fn groups_must_be_slots_of_one_part_each_in_one_group() { #[test] fn the_estimate_covers_what_the_read_does() { // A flat colour in ZIP16 (decodes to far more than it reads), lines of a ramp, and tiles. - let (w, h) = (1024usize, 600usize); + let (w, h) = (256usize, 160usize); let list = vec![AnyChannel::new("R", FlatSamples::F32(vec![0.25; w * h])), AnyChannel::new("G", FlatSamples::F32(vec![0.5; w * h]))]; let encoding = Encoding { compression: Compression::ZIP16, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing }; let flat = file(vec![Layer::new((w, h), LayerAttributes::default(), encoding, AnyChannels::sort(list.into()))], (w, h)); - let ramp = file(vec![layer(None, (0, 0), (1024, 600), &["R", "G"], false, Compression::Uncompressed)], (1024, 600)); + let ramp = file(vec![layer(None, (0, 0), (256, 160), &["R", "G"], false, Compression::Uncompressed)], (256, 160)); let tiled = file(vec![layer(None, (0, 0), (300, 200), &["R", "G", "B"], true, Compression::PIZ)], (300, 200)); for bytes in [&flat, &ramp, &tiled] { let index = indexed(bytes); diff --git a/crates/font-manager/Cargo.toml b/crates/font-manager/Cargo.toml index e3fd1e677..fbaa41999 100644 --- a/crates/font-manager/Cargo.toml +++ b/crates/font-manager/Cargo.toml @@ -46,7 +46,7 @@ craft-theme = { workspace = true, optional = true } serde = { workspace = true, optional = true } log = { version = "0.4", optional = true } # Variation axes and named instances of a face (`axes`), on every feature set. -skrifa = { version = "0.44", default-features = false, features = ["std"] } +skrifa = { version = "0.47", default-features = false, features = ["std"] } [build-dependencies] # The Arabic sample story's face, from the craft fonts set when `CRAFT_FONTS_DIR` names one. @@ -54,6 +54,8 @@ craft-fonts-build = { workspace = true } [dev-dependencies] craft-font-manager = { path = ".", features = ["suite"] } +# The shared preview test vectors. +serde_json = { workspace = true } [[test]] name = "it" diff --git a/crates/font-manager/README.md b/crates/font-manager/README.md index ba54bbce7..5c4fd076f 100644 --- a/crates/font-manager/README.md +++ b/crates/font-manager/README.md @@ -10,7 +10,7 @@ Fonts tab; the standalone app | `filter` | always | Search over the index: family names ignoring case and accents, category, language (English name, autonym or id) and script | | `index` | always | The pinned built-in indexes (Google Fonts and Noto) compiled into [`craft-font-store`](../font-store/README.md) (`bundled`), each family's source (`source_label`: its name and whether it is curated), and the categories | | `installed` | always | The installed fonts [`craft-font-catalog`](../font-catalog/README.md) sees, grouped by family and source | -| `store` | always | `Installer`, what the interface needs from the font store: the download consent, install, remove, downloads for a preview, the indexes (`indexes`, `fetch_indexes`) and the sources the user added (`user_sources`, `add_user_source`, `remove_user_source`). `SuiteStore` is craft-font-store's store (native only), `FakeStore` a stand-in for tests, `NoStore` one for when the store folder is unknown | +| `store` | always | `Installer`, what the interface needs from the font store: the download consent, install, remove, downloads for a preview, the indexes (`indexes`, `fetch_indexes`) and the sources the user added (`user_sources`, `add_user_source`, `remove_user_source`). `SuiteStore` is craft-font-store's store (native only), `FakeStore` a stand-in for tests, `NoStore` one for when the store folder is unknown. What the preview pool (craft-font-store's `preview`) reads is the `PreviewStore` part | | `FontsPanel` | `ui` | The whole interface as one egui panel | | `glyphs` | `ui` | `GlyphsPanel`: the character grid of a face with categories, zoom and Recently Used; the app supplies the glyphs through `GlyphSource`, which also reports when it is ready and when its faces change. Sizes are the `glyphs.*` tokens | | `missing` | `ui` | `document_fonts`, `missing_font_warnings` and `MissingFontsDialog`: which fonts a document names are not installed, and a replacement for each | diff --git a/crates/font-manager/src/picker.rs b/crates/font-manager/src/picker.rs index 887faf69c..6e3856bb5 100644 --- a/crates/font-manager/src/picker.rs +++ b/crates/font-manager/src/picker.rs @@ -19,7 +19,7 @@ use craft_host::Section; use craft_theme::variant::Tone; use craft_ui::buttons::{ControlPlace, IconButton}; use craft_ui::contract::{ - Access, Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, + Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, Styled as _, WordSetCx as _, step_stop, }; use craft_ui::controls::disclosure::{DisclosureGlyph, DropdownArrow}; @@ -59,8 +59,6 @@ craft_ui::words! { /// The name of the preview banner, with `{family}` for the family it shows. preview_of: template "fontPicker.previewOf" = "Font preview: {family}"; no_match: "fontPicker.noMatch" = "No fonts match"; - /// The family field's label when the selection has several families. - mixed: "fontPicker.mixed" = "Mixed"; /// The name of a row's star, with `{row}` for the row's label. favorite: template "fontPicker.favorite" = "Favorite {row}"; list: "fontPicker.list" = "Fonts"; @@ -531,7 +529,7 @@ const TEXT: PartKey = PartKey::new("text"); const CHEVRON: PartKey = PartKey::new("chevron"); /// The mark before the chevron of a shown font that is not installed; its tooltip is the note. const WARNING: PartKey = PartKey::new("missing"); -const WARNING_ICON: &str = "warning"; +const WARNING_ICON: &str = "warning_filled"; /// The popup the chevron and Alt+Down toggle. const POPUP: &str = "list"; /// The Show Similar part at the end of a family row, in the `Chips` layout. @@ -732,6 +730,24 @@ pub struct FontPicker<'a> { host_picked: Option, } +/// How many times a closed [`FontPicker`] built its stop list on `ctx`, for regression trials. +#[cfg(feature = "screen-testing")] +#[derive(Clone, Copy, Default)] +struct StopBuilds(u64); + +/// Where the stop-build count lives in the context's memory. +#[cfg(feature = "screen-testing")] +fn stop_builds_id() -> egui::Id { + craft_ui::runtime::memory::global("font_picker_stop_builds", ()) +} + +/// How many times a closed [`FontPicker`] built its stop list on `ctx`. +#[doc(hidden)] +#[cfg(feature = "screen-testing")] +pub fn stop_builds(ctx: &egui::Context) -> u64 { + craft_ui::runtime::memory::with_session::(ctx, stop_builds_id(), |builds| builds.0) +} + impl<'a> FontPicker<'a> { /// A picker named `label` over the family `family` of `catalog`. pub fn new(label: impl Into