Merge next into feat/unit-text

This commit is contained in:
dotCooCoo committed 2026-11-24 19:22:42 -08:00
commit cdcd0c7c4d
544 files changed
+43656 -1613

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
# 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
+25
View File
@@ -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
+2 -1
View File
@@ -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'
+11 -2
View File
@@ -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
+29 -1
View File
@@ -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
+88 -57
View File
@@ -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 <selected>` 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, those crates (run plainly, then 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
# `<version>-rust-<profile>-<job>-crates-<os>-<arch>-<run>-<attempt>-...`, 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
+14 -3
View File
@@ -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.
Generated
+64 -15
View File
@@ -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=a87d00caaec947ea781657c6ff410c9838016d18#a87d00caaec947ea781657c6ff410c9838016d18"
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=a87d00caaec947ea781657c6ff410c9838016d18#a87d00caaec947ea781657c6ff410c9838016d18"
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=a87d00caaec947ea781657c6ff410c9838016d18#a87d00caaec947ea781657c6ff410c9838016d18"
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=a87d00caaec947ea781657c6ff410c9838016d18#a87d00caaec947ea781657c6ff410c9838016d18"
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=a87d00caaec947ea781657c6ff410c9838016d18#a87d00caaec947ea781657c6ff410c9838016d18"
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=a87d00caaec947ea781657c6ff410c9838016d18#a87d00caaec947ea781657c6ff410c9838016d18"
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=a87d00caaec947ea781657c6ff410c9838016d18#a87d00caaec947ea781657c6ff410c9838016d18"
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=a87d00caaec947ea781657c6ff410c9838016d18#a87d00caaec947ea781657c6ff410c9838016d18"
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=a87d00caaec947ea781657c6ff410c9838016d18#a87d00caaec947ea781657c6ff410c9838016d18"
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=a87d00caaec947ea781657c6ff410c9838016d18#a87d00caaec947ea781657c6ff410c9838016d18"
[[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=a87d00caaec947ea781657c6ff410c9838016d18#a87d00caaec947ea781657c6ff410c9838016d18"
[[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=a87d00caaec947ea781657c6ff410c9838016d18#a87d00caaec947ea781657c6ff410c9838016d18"
[[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=a87d00caaec947ea781657c6ff410c9838016d18#a87d00caaec947ea781657c6ff410c9838016d18"
[[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=a87d00caaec947ea781657c6ff410c9838016d18#a87d00caaec947ea781657c6ff410c9838016d18"
+15 -14
View File
@@ -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 = "a87d00caaec947ea781657c6ff410c9838016d18" }
emath = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
egui = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
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
+1
View File
@@ -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;
+129
View File
@@ -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<Self> {
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<F> {
kind: DescriptorKind,
property: F,
}
impl<'a, F: Fn(u16) -> DescriptorProperty<'a>> AudioFileDescriptor<F> {
/// 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<i64, DescriptorFieldError> {
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<Option<u32>, 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<const N: usize>(&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));
}
}
+3
View File
@@ -13,3 +13,6 @@ workspace = true
[dependencies]
serde = { workspace = true }
thiserror = { workspace = true }
[dev-dependencies]
craft-testkit = { workspace = true }
+229 -25
View File
@@ -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<Table, Error> {
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<Table, Error> {
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<u8>, x: u16) {
v.extend_from_slice(&x.to_le_bytes());
}
fn le_u32(v: &mut Vec<u8>, x: u32) {
v.extend_from_slice(&x.to_le_bytes());
}
fn type_spec(id: u8, entries: u32) -> Vec<u8> {
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<u8>]) -> Vec<u8> {
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<u8>]) -> Vec<u8> {
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<u8> {
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<u8> {
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<u8> {
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::<Vec<_>>(), [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::<Vec<_>>(), [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::<Vec<_>>(), [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::<Vec<_>>(), [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::<Vec<_>>(), [long.as_str(), "", "ok"]);
}
}
+156 -21
View File
@@ -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<String> {
fn utf8_string(r: &Reader<'_>, at: usize, end: usize, recovery_left: &mut usize, recovery_omitted: &mut usize) -> Option<String> {
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<String> {
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<String>) {
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<String>,
warning: &str,
) -> Option<String> {
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<String>, warning: &str) -> Option<String> {
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<Document, Error> {
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<Document, Error> {
fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize, max_value_bytes: usize) -> Result<Document, Error> {
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<u8>, 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::<Vec<_>>(),
[("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::<Vec<_>>(),
[("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");
+3
View File
@@ -12,3 +12,6 @@ workspace = true
# No dependencies: planar `&mut [f32]` slices in, planar slices out.
[dependencies]
[dev-dependencies]
craft-testkit = { workspace = true }
+3 -3
View File
@@ -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() {
+7 -3
View File
@@ -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());
@@ -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);
+1 -1
View File
@@ -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<f32> = (0..len).map(|_| 0.1 * rng.uniform()).collect();
let t = crate::testutil::sine(700.0, 0.2, SR as f64, len, 0.0);
+6
View File
@@ -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<Item = &'static crate::effects::EffectInfo> {
crate::effects().iter().step_by(craft_testkit::hostile::divisor())
}
/// Tiny deterministic PRNG (xorshift64*) for tests.
pub struct Rng(u64);
impl Rng {
+24 -20
View File
@@ -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<f32> = 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<f32> = x.iter().map(|v| v * g).collect();
+5 -2
View File
@@ -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::<usize>() <= MAX_RESAMPLE_HELD);
let mut r = StreamResampler::new(48_000, 48_000);
+15 -15
View File
@@ -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<f32> =
(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>, 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<f32> = 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<f32> = 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<f32> = (0..16 * sr as i64).map(|n| sign * scratch.get((n + delay) as usize).copied().unwrap_or(0.0)).collect();
let b: Vec<f32> = (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
+2 -1
View File
@@ -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());
+8 -2
View File
@@ -105,8 +105,14 @@ fn dec3_describes_dependent_rear_pair_and_aggregate_rate() -> Result<(), Box<dyn
#[test]
fn actual_decoder_positions_satisfy_all_three_ac3_bit_budgets() -> Result<(), Box<dyn std::error::Error>> {
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 };
+2 -1
View File
@@ -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 => {
+3 -2
View File
@@ -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<u8> = (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<u8> = (0..len).map(|_| rng.next() as u8).collect();
if let Ok(out) = dec.decode(Some(&pkt)) {
+11 -9
View File
@@ -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<f32> = 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<f32> = 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<f32> = 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<f32> = sp[20_000..].iter().map(|v| v * 0.7).collect();
let mu = music(SHORT);
let cases: Vec<(&str, Vec<f32>, Vec<f32>)> = vec![
("dual mono", a.clone(), a.clone()),
("panned", a.iter().map(|v| v * 0.9).collect(), a.iter().map(|v| v * 0.35).collect()),
+5 -3
View File
@@ -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;
+2 -1
View File
@@ -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;
+16 -10
View File
@@ -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)
+9 -2
View File
@@ -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<CursorBadge>,
},
/// 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<CursorBadge>) -> Self {
PaintedCursor::PointerTool { pointer, icon, badge }
}
/// A system cursor with a mark.
+7 -4
View File
@@ -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<T: Copy> PressMachine<T> {
}
/// 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<T: Copy> PressMachine<T> {
self.open = Some(Open {
target,
sense: sense - Sense::CLICK,
start,
start: PressStart { handed: true, ..start },
dragging: true,
abandoned: false,
left: false,
+1
View File
@@ -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"
+6 -2
View File
@@ -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) {
+1
View File
@@ -13,4 +13,5 @@ workspace = true
[dependencies]
[dev-dependencies]
craft-testkit = { workspace = true }
craft-media-testkit = { workspace = true }
+2 -1
View File
@@ -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);
+1
View File
@@ -20,4 +20,5 @@ md5 = { workspace = true }
rayon = { workspace = true }
[dev-dependencies]
craft-testkit = { workspace = true }
moxcms = "0.8"
+4 -2
View File
@@ -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");
+3 -1
View File
@@ -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:?}");
+7 -1
View File
@@ -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");
+4 -2
View File
@@ -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(&params).expect("the synthetic CMYK profile").to_bytes());
let mut pick = ScreenPick::new();
pick.start("a");
pick.tick_with(&ctx, 1, &|| images(vec![odd.clone()]));
+3
View File
@@ -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"]
+1 -1
View File
@@ -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 = "a87d00caaec947ea781657c6ff410c9838016d18";
/// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]).
pub const PACKAGES: &[&str] = &[
+2
View File
@@ -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")]
+1
View File
@@ -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.
+4 -2
View File
@@ -61,11 +61,13 @@ fn crw() -> Vec<u8> {
#[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());
+1
View File
@@ -24,4 +24,5 @@ rayon = { workspace = true }
[dev-dependencies]
craft-render-parity = { workspace = true }
craft-testkit = { workspace = true }
proptest = { workspace = true }
+1 -1
View File
@@ -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:?}");
}
}
+38 -34
View File
@@ -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<f32> {
}
/// Approximate Gaussian (three box passes).
#[cfg(test)]
fn gauss(v: &[f32], w: usize, h: usize, sigma: f32) -> Vec<f32> {
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<f32> = px.iter().map(|q| luma([q[0], q[1], q[2]])).collect();
let mut cb: Vec<f32> = px.iter().zip(&y).map(|(q, l)| q[2] - l).collect();
let mut cr: Vec<f32> = 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<Vec<f32>> = (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<Vec<f32>> = 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);
+19 -14
View File
@@ -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<WhitesBlacks>,
/// 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<Grade>,
/// 8. Detail: noise reduction and sharpening.
pub detail: Option<Detail>,
/// 9. Vignette.
pub vignette: Option<Vignette>,
/// 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<PerPixel> {
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,
+103 -1
View File
@@ -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<LuminanceNoise>,
pub color: Option<ColorNoise>,
pub sharpen: Option<Sharpen>,
}
/// 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<usize>,
/// 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<usize>,
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<usize>, [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<Self> {
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<usize> {
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::<usize>();
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();
+4 -1
View File
@@ -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}");
+7 -2
View File
@@ -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}"));
+22 -5
View File
@@ -168,7 +168,7 @@ impl RawDevelopExt for RawImage {
fn develop_balanced_masked(&self, method: Method, wb: [f32; 3], clip: f32) -> Result<(Rgb32f, Option<Vec<u8>>)> {
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<Vec<u8>> {
fn raw_clip_mask(raw: &RawImage, n: &Normalized, method: Method, clip: f32) -> Option<Vec<u8>> {
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<Vec<u8>> {
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;
+9 -3
View File
@@ -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));
+6 -6
View File
@@ -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]
+19 -10
View File
@@ -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<f32> = (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<f32> = (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}");
}
}
+32 -3
View File
@@ -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();
+19 -1
View File
@@ -117,7 +117,7 @@ fn saved(path: impl AsRef<Path>) -> Option<DialogResult<Answer>> {
// `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");
+3
View File
@@ -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 }
+1 -1
View File
@@ -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());
+2 -1
View File
@@ -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;
+1
View File
@@ -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"] }
+5 -4
View File
@@ -230,11 +230,12 @@ fn hostile_radar_charts_never_panic() {
let small =
chart_items(&space(&format!("<c:radarChart>{}</c:radarChart>", 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<String> = (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<String> = (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<String> = (0..300).map(|i| ser(i, "S", None, &refs, &vals)).collect();
let vals = vec!["1"; n];
let many: Vec<String> = (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}");
+3 -3
View File
@@ -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)));
}
@@ -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,
|| {
+5
View File
@@ -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
+7 -4
View File
@@ -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!("<w:document {W_NS}><w:body><w:p{attrs}><w:r><w:t>kept</w:t></w:r></w:p></w:body></w:document>");
// 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!("<w:document {W_NS}><w:body><w:p><w:r><w:t>body</w:t></w:r></w:p></w:body></w:document>");
let mut sources = String::from(r#"<b:Sources xmlns:b="http://schemas.openxmlformats.org/officeDocument/2006/bibliography" StyleName="MLA">"#);
for i in 0..60_000 {
for i in 0..(60_000 / craft_testkit::hostile::divisor()).max(10_500) {
sources.push_str(&format!("<b:Source><b:Tag>T{i}</b:Tag><b:Title>Title {i}</b:Title></b:Source>"));
// Untagged duplicates all collapse into one source.
sources.push_str("<b:Source><b:Title>Same</b:Title></b:Source>");
@@ -313,11 +314,13 @@ fn compound(info: &[u8], package: &[u8]) -> Vec<u8> {
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::<prop::sample::Index>(), any::<u8>(), any::<bool>()), 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<u8>, Vec<u8>)> = 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);
+4
View File
@@ -268,6 +268,10 @@ fn flat_opc_limits_count_what_is_not_kept() {
assert!(limited(&r#"<pkg:part pkg:name="/word/media/dot.png"><pkg:binaryData>AA==</pkg:binaryData></pkg:part>"#.repeat(20_000)));
assert!(limited(&"<x/>".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#"<pkg:part pkg:name="/word/unused.xml"><pkg:xmlData><r>{}</r></pkg:xmlData></pkg:part>"#, "<y/>".repeat(8_000_000))));
}
@@ -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);
}
});
}
+42 -1
View File
@@ -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}");
}
}
+1
View File
@@ -18,4 +18,5 @@ log = "0.4"
serde = { workspace = true }
[dev-dependencies]
craft-testkit = { workspace = true }
serde_json = { workspace = true }
+7 -6
View File
@@ -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();
+47 -26
View File
@@ -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));
+3
View File
@@ -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 }
+4 -2
View File
@@ -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;
+6 -5
View File
@@ -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);
+3 -1
View File
@@ -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"
+1 -1
View File
@@ -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 |
+8 -4
View File
@@ -735,11 +735,17 @@ pub struct FontPicker<'a> {
#[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 {
ctx.data(|data| data.get_temp::<StopBuilds>(egui::Id::unique("font_picker_stop_builds")).unwrap_or_default().0)
craft_ui::runtime::memory::with_session::<StopBuilds, _>(ctx, stop_builds_id(), |builds| builds.0)
}
impl<'a> FontPicker<'a> {
@@ -819,9 +825,7 @@ impl<'a> FontPicker<'a> {
/// families in the list's narrowed order. A notice takes no step.
fn stops(&self, cx: &Cx<'_, Self>, settings: Option<&FontPickerSettings>, filters: &FontFilters) -> Vec<Stop> {
#[cfg(feature = "screen-testing")]
cx.response.ctx.data_mut(|data| {
data.get_temp_mut_or_default::<StopBuilds>(egui::Id::unique("font_picker_stop_builds")).0 += 1;
});
craft_ui::runtime::memory::with_session::<StopBuilds, _>(&cx.response.ctx, stop_builds_id(), |builds| builds.0 += 1);
let folder = cx.env.folder();
let host = rank::host_rows(self.host, "", &folder)
.into_iter()
+86 -6
View File
@@ -13,9 +13,10 @@ use std::sync::{Condvar, Mutex};
#[cfg(not(target_arch = "wasm32"))]
use craft_font_catalog::Catalog;
pub use craft_font_store::UserSource;
pub use craft_font_store::PreviewStore;
#[cfg(not(target_arch = "wasm32"))]
use craft_font_store::{Cancel, Client, Face, FontStore, Network, PINNED_INDEX, verify_font};
pub use craft_font_store::{LegalText, PREVIEW_SERVICE_ENV, PreviewServiceSource, UserSource};
use crate::index::{Family, Index};
@@ -100,8 +101,9 @@ fn err(e: impl std::fmt::Display) -> StoreError {
StoreError(e.to_string())
}
/// The font store. Calls block; the app makes the downloading ones on a worker thread.
pub trait Installer: Send + Sync {
/// The font store. Calls block; the app makes the downloading ones on a worker thread. What the preview pool reads
/// (the preview service, the previews setting, the HTTP client and the cache folder) is its [`PreviewStore`] part.
pub trait Installer: PreviewStore {
/// Has the user allowed downloads? The setting is the whole suite's.
fn downloads_allowed(&self) -> bool;
@@ -147,6 +149,30 @@ pub trait Installer: Send + Sync {
fn remove_user_source(&self, _url: &str) -> Result<(), StoreError> {
Err(StoreError(NO_FOLDER.into()))
}
/// Where [`PreviewStore::preview_service`] comes from: the environment variable (the setting
/// can't change it), the saved setting, the host's default
/// ([`PreviewServiceSource::Default`]), or nowhere.
fn preview_service_source(&self) -> PreviewServiceSource {
PreviewServiceSource::None
}
/// Turns previews on or off, as the user's own action.
fn set_previews_enabled(&self, _enabled: bool) -> Result<(), StoreError> {
Err(StoreError(NO_FOLDER.into()))
}
/// Sets or clears the preview service (https, or http for a loopback host), as the user's own
/// action.
fn set_preview_service(&self, _url: Option<&str>) -> Result<(), StoreError> {
Err(StoreError(NO_FOLDER.into()))
}
/// The text of `family`'s licence or NOTICE file: the installed copy, else downloaded when
/// downloads are allowed. `None` when the family has no such file.
fn legal_text(&self, _index: &Index, _family: &Family, _which: LegalText) -> Result<Option<String>, StoreError> {
Err(StoreError(NO_FOLDER.into()))
}
}
const NO_FOLDER: &str = "there is no folder for the font store";
@@ -155,7 +181,6 @@ const NO_FOLDER: &str = "there is no folder for the font store";
/// craft-font-store's store, in the user's font store folder.
pub struct SuiteStore {
store: FontStore,
client: Client,
}
#[cfg(not(target_arch = "wasm32"))]
@@ -163,7 +188,25 @@ impl SuiteStore {
/// The store the catalog's environment names, rescanning `catalog` after each change.
pub fn for_user(catalog: Arc<Catalog>) -> Option<SuiteStore> {
let store = FontStore::for_user(catalog.env())?.with_catalog(catalog);
Some(SuiteStore { store, client: Client::default() })
Some(SuiteStore { store })
}
/// Uses `url` as the preview service while neither [`PREVIEW_SERVICE_ENV`] nor the user's
/// setting names one; see [`FontStore::with_default_preview_service`]. Never saved.
pub fn with_default_preview_service(self, url: &str) -> SuiteStore {
SuiteStore { store: self.store.with_default_preview_service(url) }
}
/// Uses `network` for "Allow font downloads" while the user hasn't chosen; see
/// [`FontStore::with_default_network`]. Never saved.
pub fn with_default_network(self, network: Network) -> SuiteStore {
SuiteStore { store: self.store.with_default_network(network) }
}
/// The store's HTTP client. Clones share the preview service's down state with installs;
/// [`Previews::new`](craft_font_store::preview::Previews::new) takes it through [`PreviewStore::http_client`].
pub fn client(&self) -> Client {
self.store.client()
}
/// The store's source and name for the family holding `files`, which can differ from the
@@ -222,7 +265,7 @@ impl Installer for SuiteStore {
let mut reasons = Vec::new();
for url in index.file_urls(family, file) {
let mut on_bytes = |n: u64| progress(Progress { done: before.saturating_add(n), total });
match self.client.get(&url, file.size, &cancel, &mut on_bytes) {
match self.store.client().get(&url, file.size, &cancel, &mut on_bytes) {
Ok(bytes) => match verify_font(file, &bytes) {
Ok(()) => {
out.push(Downloaded { path: file.path.clone(), bytes });
@@ -261,11 +304,48 @@ impl Installer for SuiteStore {
fn remove_user_source(&self, url: &str) -> Result<(), StoreError> {
self.store.remove_user_source(url).map_err(err)
}
fn preview_service_source(&self) -> PreviewServiceSource {
self.store.preview_service_source()
}
fn set_preview_service(&self, url: Option<&str>) -> Result<(), StoreError> {
self.store.set_preview_service(url).map_err(err)
}
fn set_previews_enabled(&self, enabled: bool) -> Result<(), StoreError> {
self.store.set_previews_enabled(enabled).map_err(err)
}
fn legal_text(&self, index: &Index, family: &Family, which: LegalText) -> Result<Option<String>, StoreError> {
self.store.legal_text(index, family, which, &Cancel::new()).map_err(err)
}
}
#[cfg(not(target_arch = "wasm32"))]
impl PreviewStore for SuiteStore {
fn preview_service(&self) -> Option<String> {
self.store.preview_service()
}
fn http_client(&self) -> Option<Client> {
Some(self.store.client())
}
fn previews_enabled(&self) -> bool {
self.store.previews_enabled()
}
fn preview_cache(&self) -> Option<PathBuf> {
Some(self.store.previews_dir())
}
}
/// The store when the system names no folder for it (no home folder): nothing installs.
pub struct NoStore;
impl PreviewStore for NoStore {}
impl Installer for NoStore {
fn downloads_allowed(&self) -> bool {
false
+52
View File
@@ -4,6 +4,7 @@ use super::{
AtomicBool, Condvar, Downloaded, Family, HashMap, Index, Installer, Mutex, Ordering, Path, PathBuf, Progress, RemoveRequest, StoreError,
UserSource, err,
};
use super::{LegalText, PreviewServiceSource, PreviewStore};
/// What a [`FakeStore`] was asked to do.
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -35,6 +36,8 @@ pub struct FakeStore {
/// Index files user sources "download", by URL.
served_indexes: HashMap<String, Vec<u8>>,
user: Mutex<Vec<UserSource>>,
preview_service: Mutex<Option<String>>,
previews: Mutex<bool>,
/// User sources downloaded so far, and those whose file changed since.
fetched: Mutex<Vec<String>>,
changed: Mutex<Vec<String>>,
@@ -55,6 +58,8 @@ impl FakeStore {
builtin: None,
served_indexes: HashMap::new(),
user: Mutex::new(Vec::new()),
preview_service: Mutex::new(None),
previews: Mutex::new(true),
fetched: Mutex::new(Vec::new()),
changed: Mutex::new(Vec::new()),
held: (Mutex::new(false), Condvar::new()),
@@ -265,4 +270,51 @@ impl Installer for FakeStore {
self.user.lock().map_err(err)?.retain(|s| s.url != url);
Ok(())
}
fn preview_service_source(&self) -> PreviewServiceSource {
if self.preview_service().is_some() { PreviewServiceSource::Saved } else { PreviewServiceSource::None }
}
fn set_previews_enabled(&self, enabled: bool) -> Result<(), StoreError> {
*self.previews.lock().map_err(err)? = enabled;
Ok(())
}
fn set_preview_service(&self, url: Option<&str>) -> Result<(), StoreError> {
// The address check is the native store's; the browser has no preview service to reach.
#[cfg(not(target_arch = "wasm32"))]
let url = url.map(craft_font_store::check_preview_service).transpose().map_err(err)?;
#[cfg(target_arch = "wasm32")]
let url = url.map(str::to_owned);
*self.preview_service.lock().map_err(err)? = url;
Ok(())
}
/// Served from the file table by the index path, like a font.
fn legal_text(&self, _: &Index, family: &Family, which: LegalText) -> Result<Option<String>, StoreError> {
let path = match which {
LegalText::License => family.license_file.as_ref().map(|f| f.path.as_str()).or(family.license_path.as_deref()),
LegalText::Notice => family.notice_file.as_ref().map(|f| f.path.as_str()),
};
let Some(path) = path else { return Ok(None) };
if !self.downloads_allowed() {
return Err(StoreError("downloading fonts is turned off".into()));
}
let bytes = self.files.get(path).ok_or_else(|| StoreError(format!("{path} isn't available")))?;
Ok(Some(String::from_utf8_lossy(bytes).into_owned()))
}
}
impl PreviewStore for FakeStore {
fn preview_service(&self) -> Option<String> {
self.preview_service.lock().ok()?.clone()
}
fn previews_enabled(&self) -> bool {
self.previews.lock().map_or(true, |p| *p)
}
fn preview_cache(&self) -> Option<PathBuf> {
Some(self.dir.join("previews"))
}
}
Binary file not shown.
@@ -0,0 +1,105 @@
{
"about": "Shared test vectors for font-preview-service (server, B2) and craft-font-manager's preview client (C3). Both must produce exactly these strings.",
"rules": {
"codepoints": "The codepoints of the text, minus C0 controls (< U+0020), C1 controls and DEL (U+007F-009F) and surrogates; deduplicated and sorted. Written as lowercase hex without leading zeros; a run of two or more consecutive codepoints is written first-last; items joined by commas. The empty set is the empty string. At most 256 codepoints.",
"closure": "Server only: the codepoints above, plus the NFKD decomposition of each kept character, plus U+0020, U+200C, U+200D and U+25CC. Applied before subsetting; not part of the URL."
},
"vectors": [
{
"text": "Whereas recognition of the inherent dignity",
"codepoints": "20,57,61,63-69,6e-6f,72-74,79",
"closure": "20,57,61,63-69,6e-6f,72-74,79,200c-200d,25cc"
},
{
"text": "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz",
"codepoints": "20,41-5a,61-7a",
"closure": "20,41-5a,61-7a,200c-200d,25cc"
},
{
"text": "0123456789 & ? ! @ # % ( ) [ ] { } $ € £ ¥",
"codepoints": "20-21,23-26,28-29,30-39,3f-40,5b,5d,7b,7d,a3,a5,20ac",
"closure": "20-21,23-26,28-29,30-39,3f-40,5b,5d,7b,7d,a3,a5,200c-200d,20ac,25cc"
},
{
"text": "aab",
"codepoints": "61-62",
"closure": "20,61-62,200c-200d,25cc"
},
{
"text": "ab",
"codepoints": "61-62",
"closure": "20,61-62,200c-200d,25cc"
},
{
"text": "abc",
"codepoints": "61-63",
"closure": "20,61-63,200c-200d,25cc"
},
{
"text": "Line one\nLine two\t!",
"codepoints": "20-21,4c,65,69,6e-6f,74,77",
"closure": "20-21,4c,65,69,6e-6f,74,77,200c-200d,25cc"
},
{
"text": "โดยที่การไม่นำพาและการหมิ่นในคุณค่าของสิทธิมนุษยชน",
"codepoints": "e01-e02,e04,e07,e0a,e13-e14,e17-e19,e1e,e21-e23,e25,e29-e2b,e2d,e30,e32-e35,e38,e41-e44,e48",
"closure": "20,e01-e02,e04,e07,e0a,e13-e14,e17-e19,e1e,e21-e23,e25,e29-e2b,e2d,e30,e32-e35,e38,e41-e44,e48,e4d,200c-200d,25cc"
},
{
"text": "ສະບາຍດີ ນຳ",
"codepoints": "20,e8d,e94,e99-e9a,eaa,eb0,eb2-eb3,eb5",
"closure": "20,e8d,e94,e99-e9a,eaa,eb0,eb2-eb3,eb5,ecd,200c-200d,25cc"
},
{
"text": "चूंकि मानव परिवार के सभी सदस्यों",
"codepoints": "20,902,915,91a,926,928,92a,92d-930,935,938,93e-940,942,947,94b,94d",
"closure": "20,902,915,91a,926,928,92a,92d-930,935,938,93e-940,942,947,94b,94d,200c-200d,25cc"
},
{
"text": "لمّا كان الاعتراف بالكرامة",
"codepoints": "20,627-62a,631,639,641,643-646,651",
"closure": "20,627-62a,631,639,641,643-646,651,200c-200d,25cc"
},
{
"text": "人類社会のすべての構成員",
"codepoints": "3059,3066,306e,3079,4eba,4f1a,54e1,6210,69cb,793e,985e",
"closure": "20,200c-200d,25cc,3059,3066,306e,3078-3079,3099,4eba,4f1a,54e1,6210,69cb,793e,985e"
},
{
"text": "Œuvre fine ²",
"codepoints": "20,65,6e,72,75-76,b2,152,fb01",
"closure": "20,32,65-66,69,6e,72,75-76,b2,152,200c-200d,25cc,fb01"
},
{
"text": "😀 👍🏽",
"codepoints": "20,1f3fd,1f44d,1f600",
"closure": "20,200c-200d,25cc,1f3fd,1f44d,1f600"
},
{
"text": "",
"codepoints": "",
"closure": "20,200c-200d,25cc"
}
],
"sample_hash": {
"rule": "The {h} of /v1/faces/{sha256}/{inst}/sample-{h}.woff2: the first 12 lowercase hex characters of the sha256 of the face's sample text exactly as the index gives it (the file's sample_text, else samples[file.sample_script ?? family.sample_script].text), as UTF-8 bytes, with no normalisation and newlines kept. The subset itself also covers the family name; h covers only the sample text. A request whose h is not the face's current one gets 404; the client then falls back to u/{codepoints}.",
"vectors": [
{
"text": "Whereas recognition of the inherent dignity",
"h": "a79fe905fc38"
},
{
"text": "โดยที่การไม่นำพาและการหมิ่นในคุณค่าของสิทธิมนุษยชน",
"h": "ea9257b96f35"
},
{
"text": "𐊪𐊾𐊠𐊽𐊾𐊲𐊸𐊫𐊷𐋉𐋃𐊷𐊲𐊷𐊲𐊰𐊫𐋇𐊫𐊰𐊪𐊫𐊣\n𐊪𐊾𐊠𐊽𐊾𐊲𐊸𐊫𐊷𐋉𐋃𐊷𐊲𐊷𐊲𐊰𐊫𐋇𐊫𐊰𐊪𐊫𐊣",
"h": "259046b056a5"
},
{
"text": "Hello",
"h": "185f8db32271"
}
]
}
}
+351
View File
@@ -0,0 +1,351 @@
//! The preview service client against the shared test vectors and a local fake service.
//!
//! `data/Tiny-glyf.woff2` is `crates/fonts-build/tests/fixture/subset/Tiny-glyf.ttf` compressed
//! with fontTools 4.67.0: `fonttools ttLib.woff2 compress -o Tiny-glyf.woff2 Tiny-glyf.ttf`.
//! `data/preview-vectors.json` is shared with the preview service, unchanged, so the client's
//! URLs and the service's cache keys can't drift.
use std::collections::HashMap;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::PathBuf;
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};
use craft_font_manager::craft_font_catalog::Os;
use craft_font_manager::store::{FakeStore, Installer, SuiteStore};
use craft_font_manager::{Catalog, FontEnv};
use craft_font_store::preview::{
Codepoints, DiskCache, Instance, MAX_CODEPOINTS, Preview, PreviewError, PreviewKey, PreviewStore, Previews, SampleHash, Subset,
};
use craft_font_store::{Client, is_font};
const WOFF2: &[u8] = include_bytes!("data/Tiny-glyf.woff2");
fn sha(n: u8) -> String {
format!("{n:02x}").repeat(32)
}
fn temp(name: &str) -> PathBuf {
let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("remote").join(name);
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn canonical_codepoints_match_the_shared_vectors() {
let vectors: serde_json::Value = serde_json::from_str(include_str!("data/preview-vectors.json")).unwrap();
let vectors = vectors["vectors"].as_array().unwrap();
assert!(vectors.len() > 10);
for v in vectors {
let text = v["text"].as_str().unwrap();
let expected = v["codepoints"].as_str().unwrap();
let codepoints = Codepoints::from_text(text);
assert_eq!(codepoints.encode(), expected, "{text:?}");
let key = PreviewKey::new(&sha(0xab), Instance::List, Subset::Codepoints(codepoints));
match key {
Some(key) => assert_eq!(key.path(), format!("v1/faces/{}/list/u/{expected}.woff2", sha(0xab))),
None => assert_eq!(expected, "", "only the empty set has no URL"),
}
}
}
#[test]
fn subset_urls() {
let key = |inst, subset| PreviewKey::new(&sha(0x0a), inst, subset).map(|k| k.url("https://fonts.example.com/"));
let base = format!("https://fonts.example.com/v1/faces/{}", sha(0x0a));
assert_eq!(key(Instance::List, Subset::Sample(SampleHash::of("Hello"))), Some(format!("{base}/list/sample-185f8db32271.woff2")));
assert_eq!(key(Instance::List, Subset::Ascii), Some(format!("{base}/list/ascii.woff2")));
assert_eq!(key(Instance::Var, Subset::Sample(SampleHash::of("Hello"))), Some(format!("{base}/var/sample-185f8db32271.woff2")));
assert_eq!(key(Instance::Var, Subset::Codepoints(Codepoints::from_text("ab"))), Some(format!("{base}/var/u/61-62.woff2")));
let upper = PreviewKey::new(&"AB".repeat(32), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap();
assert_eq!(upper.sha256(), "ab".repeat(32));
assert!(PreviewKey::new("../../etc", Instance::List, Subset::Sample(SampleHash::of("Hello"))).is_none());
assert!(PreviewKey::new(&"g".repeat(64), Instance::List, Subset::Sample(SampleHash::of("Hello"))).is_none());
let many: Codepoints = ('\u{4e00}'..).take(MAX_CODEPOINTS + 1).collect();
assert!(PreviewKey::new(&sha(1), Instance::List, Subset::Codepoints(many.clone())).is_none());
let mut fits = many;
fits.retain(|c| c != '\u{4e00}');
assert!(PreviewKey::new(&sha(1), Instance::List, Subset::Codepoints(fits)).is_some());
}
#[test]
fn disk_cache_drops_the_least_recently_used() {
let dir = temp("cache");
let cache = DiskCache::new(&dir, 300);
let bytes = |b: u8| vec![b; 100];
cache.put("a", &bytes(1));
cache.put("b", &bytes(2));
cache.put("c", &bytes(3));
assert_eq!(cache.get("a"), Some(bytes(1)));
cache.put("d", &bytes(4));
assert!(!cache.contains("b"), "b was used least recently");
assert!(cache.contains("a") && cache.contains("c") && cache.contains("d"));
assert_eq!(cache.size(), 300);
assert_eq!(cache.get("b"), None);
// Larger than the whole cache: not kept, and nothing else goes for it.
cache.put("e", &vec![5; 301]);
assert!(!cache.contains("e") && cache.contains("a"));
// Another session reads the same entries, and a smaller limit trims them at once.
std::fs::write(dir.join(".tmp-1-1"), b"half").unwrap();
let files = || std::fs::read_dir(&dir).unwrap().filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().ends_with(".woff2")).count();
assert_eq!(files(), 3);
let again = DiskCache::new(&dir, 300);
assert_eq!(again.size(), 300);
assert_eq!(again.get("d"), Some(bytes(4)));
let smaller = DiskCache::new(&dir, 200);
assert_eq!(smaller.size(), 200);
assert_eq!(files(), 2);
// A file another session cached after this one read the folder.
smaller.put("f", &bytes(6));
assert!(again.contains("f"));
let _ = std::fs::remove_dir_all(dir);
}
/// What the fake service answers for a path.
#[derive(Clone)]
enum Reply {
Ok(Vec<u8>),
/// Waits for [`Service::release`], then answers with the fixture.
Held,
}
/// A local HTTP server standing in for the preview service.
struct Service {
base: String,
routes: Arc<Mutex<HashMap<String, Reply>>>,
log: Arc<Mutex<Vec<String>>>,
gate: Arc<(Mutex<bool>, Condvar)>,
}
impl Service {
fn start() -> Service {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let service = Service { base, routes: Arc::default(), log: Arc::default(), gate: Arc::default() };
let (routes, log, gate) = (service.routes.clone(), service.log.clone(), service.gate.clone());
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(stream) = stream else { continue };
let (routes, log, gate) = (routes.clone(), log.clone(), gate.clone());
std::thread::spawn(move || answer(stream, &routes, &log, &gate));
}
});
service
}
fn serve(&self, key: &PreviewKey, reply: Reply) {
self.routes.lock().unwrap().insert(format!("/{}", key.path()), reply);
}
fn requests(&self) -> Vec<String> {
self.log.lock().unwrap().clone()
}
fn release(&self) {
*self.gate.0.lock().unwrap() = true;
self.gate.1.notify_all();
}
}
fn answer(mut s: TcpStream, routes: &Mutex<HashMap<String, Reply>>, log: &Mutex<Vec<String>>, gate: &(Mutex<bool>, Condvar)) {
let mut head = Vec::new();
let mut b = [0u8; 1];
while !head.ends_with(b"\r\n\r\n") {
match s.read(&mut b) {
Ok(1) => head.push(b[0]),
_ => return,
}
}
let path = String::from_utf8_lossy(&head).split_whitespace().nth(1).unwrap_or("/").to_string();
log.lock().unwrap().push(path.clone());
let reply = routes.lock().unwrap().get(&path).cloned();
let body = match reply {
Some(Reply::Ok(body)) => body,
Some(Reply::Held) => {
let mut open = gate.0.lock().unwrap();
while !*open {
open = gate.1.wait(open).unwrap();
}
WOFF2.to_vec()
}
None => {
let _ = write!(s, "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
return;
}
};
let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Type: font/woff2\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
let _ = s.write_all(&body);
}
/// The results until `n` have come, or two seconds.
fn wait_for(previews: &Previews, n: usize) -> Vec<Preview> {
let deadline = Instant::now() + Duration::from_secs(2);
let mut out = Vec::new();
while out.len() < n && Instant::now() < deadline {
out.extend(previews.poll());
std::thread::sleep(Duration::from_millis(5));
}
out
}
fn wait_until(mut done: impl FnMut() -> bool) {
let deadline = Instant::now() + Duration::from_secs(2);
while !done() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
}
#[test]
fn previews_come_from_the_service_then_the_cache_and_only_with_consent() {
let service = Service::start();
let dir = temp("service");
let store = Arc::new(FakeStore::new(&dir, HashMap::new()));
let sample = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap();
let broken = PreviewKey::new(&sha(2), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap();
service.serve(&sample, Reply::Ok(WOFF2.to_vec()));
service.serve(&broken, Reply::Ok(b"wOF2 but not really".to_vec()));
let previews = Previews::new(store.clone());
// No service: nothing happens.
assert!(!previews.available());
previews.request(sample.clone(), 1);
let got = wait_for(&previews, 1);
assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::NoService));
// A service, but previews off: no request.
store.set_preview_service(Some(&service.base)).unwrap();
store.set_previews_enabled(false).unwrap();
assert!(!previews.available());
previews.request(sample.clone(), 1);
let got = wait_for(&previews, 1);
assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::PreviewsOff));
assert!(service.requests().is_empty());
// Previews on (the default), installs not allowed: decoded, checked and cached anyway.
store.set_previews_enabled(true).unwrap();
assert!(previews.available() && !store.downloads_allowed());
previews.request(sample.clone(), 1);
previews.request(broken.clone(), 1);
let got = wait_for(&previews, 2);
let font = |key: &PreviewKey| got.iter().find(|p| &p.key == key).map(|p| p.font.clone());
assert!(font(&sample).unwrap().is_ok_and(|f| is_font(&f)));
assert_eq!(font(&broken), Some(Err(PreviewError::NotAFont)));
assert_eq!(service.requests().len(), 2);
let cache = previews.cache().unwrap();
assert!(cache.dir().starts_with(&dir) && cache.contains(&sample.path()) && !cache.contains(&broken.path()));
// A new session reads the disk cache, even with previews off.
store.set_previews_enabled(false).unwrap();
let later = Previews::new(store.clone());
later.request(sample.clone(), 1);
assert!(wait_for(&later, 1).first().is_some_and(|p| p.font.as_ref().is_ok_and(|f| is_font(f))));
assert_eq!(service.requests().len(), 2);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn the_suite_store_and_its_previews_share_the_service_down_state() {
let root = temp("suite");
let env = FontEnv { os: Os::Unix, root: root.clone(), font_store: Some(root.join("store")), ..FontEnv::default() };
let store = SuiteStore::for_user(Arc::new(Catalog::new(env).with_font_service(false))).unwrap();
let client = store.http_client().unwrap();
let svc = "https://fonts.example.com";
assert!(!client.service_is_down(svc) && !store.client().service_is_down(svc));
client.mark_service_down(svc);
assert!(store.client().service_is_down(svc));
// The pool's client has its own timeouts and the same down state.
let pool_client = client.with_timeouts(craft_font_store::Timeouts::default());
assert!(pool_client.service_is_down(svc));
let _ = std::fs::remove_dir_all(root);
}
#[test]
fn a_service_marked_down_gets_no_requests() {
let service = Service::start();
let dir = temp("down");
let store = Arc::new(FakeStore::new(&dir, HashMap::new()));
store.set_preview_service(Some(&service.base)).unwrap();
store.allow_downloads(true).unwrap();
let key = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap();
service.serve(&key, Reply::Ok(WOFF2.to_vec()));
// The client is shared with, say, the store's installs, which found the service unreachable.
let client = Client::default();
client.mark_service_down(&service.base);
let previews = Previews::new(store.clone()).with_fetcher(Arc::new(client));
previews.request(key, 1);
let got = wait_for(&previews, 1);
assert!(matches!(got.first().map(|p| p.font.clone()), Some(Err(PreviewError::Failed(_)))));
assert!(service.requests().is_empty());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn highest_priority_first_and_cancelled_requests_deliver_nothing() {
let service = Service::start();
let dir = temp("cancel");
let store = Arc::new(FakeStore::new(&dir, HashMap::new()));
store.allow_downloads(true).unwrap();
store.set_preview_service(Some(&service.base)).unwrap();
let keys: Vec<PreviewKey> = (1..=4).map(|n| PreviewKey::new(&sha(n), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap()).collect();
let [held, low, high, dropped] = [&keys[0], &keys[1], &keys[2], &keys[3]];
service.serve(held, Reply::Held);
for key in [low, high, dropped] {
service.serve(key, Reply::Ok(WOFF2.to_vec()));
}
let previews = Previews::new(store.clone()).with_cache(None).with_workers(1);
previews.request(held.clone(), 9);
wait_until(|| !service.requests().is_empty());
previews.request(low.clone(), 1);
previews.request(dropped.clone(), 1);
previews.request(high.clone(), 5);
assert_eq!(previews.pending(), 4);
previews.cancel(dropped);
assert!(!previews.is_pending(dropped));
// The running request stops while the service still sends nothing.
previews.cancel(held);
let got = wait_for(&previews, 2);
assert_eq!(got.iter().map(|p| &p.key).collect::<Vec<_>>(), [high, low]);
let path = |k: &PreviewKey| format!("/{}", k.path());
assert_eq!(service.requests(), [path(held), path(high), path(low)]);
std::thread::sleep(Duration::from_millis(100));
assert!(previews.poll().is_empty());
assert_eq!(previews.pending(), 0);
service.release();
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn sample_hash_is_the_sha256_prefix_of_the_exact_text() {
let vectors: serde_json::Value = serde_json::from_str(include_str!("data/preview-vectors.json")).unwrap();
let vectors = vectors["sample_hash"]["vectors"].as_array().unwrap();
assert!(vectors.len() >= 4);
for v in vectors {
let text = v["text"].as_str().unwrap();
assert_eq!(SampleHash::of(text).as_str(), v["h"].as_str().unwrap(), "{text:?}");
}
assert_ne!(SampleHash::of("Hello\n"), SampleHash::of("Hello"));
let a = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("a"))).unwrap();
let b = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("b"))).unwrap();
assert_ne!(a.path(), b.path(), "the disk cache key names the text");
}
#[test]
fn a_404_comes_back_as_not_found() {
let service = Service::start();
let dir = temp("notfound");
let store = Arc::new(FakeStore::new(&dir, HashMap::new()));
store.set_preview_service(Some(&service.base)).unwrap();
let key = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap();
let previews = Previews::new(store.clone());
previews.request(key, 1);
let got = wait_for(&previews, 1);
assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::NotFound));
let _ = std::fs::remove_dir_all(dir);
}
+2
View File
@@ -33,6 +33,8 @@ toml = { version = "1", default-features = false, features = ["parse", "serde",
tar = { version = "0.4", default-features = false }
# Blocking HTTPS with rustls and webpki roots: no async runtime, no OpenSSL.
ureq = { version = "3", default-features = false, features = ["rustls", "gzip"] }
# Decodes the preview service's WOFF2 subsets (`preview`); pure Rust. Brotli only: WOFF 1 isn't served.
wuff = { version = "0.2.9", default-features = false, features = ["brotli"] }
[dev-dependencies]
write-fonts = "0.54"
+11 -2
View File
@@ -25,10 +25,14 @@ A source the user adds is an index file at an https URL (`.json` or `.json.gz`).
| Rule | How |
|---|---|
| Off until the user turns it on | `FontStore::network()` is `Network::Off` until `enable_network()`. The setting is `settings.json` in the store folder, so it holds for every app. |
| Off until the user turns it on | `FontStore::network()` is `Network::Off` until `enable_network()`. The setting is `settings.json` in the store folder, so it holds for every app. A host may give its own default for a user who hasn't chosen (`FontStore::with_default_network`); it is never saved, and the user's `enable_network()` or `disable_network()` beats it. A `settings.json` that exists but can't be read, is too large or doesn't parse reads as `Network::Off`, whatever the host's default, and the next saved setting starts from that. |
| Only the user turns it on | `FontStore::for_user` is for the app's own interface; call `enable_network()` from a setting or from the user's Install click. `FontStore::for_agent` (MCP, CLI, scripting) gets `Error::NotAllowed`. An agent can install while the user has the network on. |
| No requests at startup | Nothing in the crate makes a request on its own. Only `fetch_indexes` and the installs do, and they return `Error::NetworkOff` without one while the network is off. |
| One HTTP client | `Client`: ureq with rustls and the webpki roots, HTTPS only, no cookies, `User-Agent: craft-font-store/<version>`. Timeouts: 15 s to connect, 30 s to the response headers, 10 minutes per file. |
| Optional preview service | Off unless set: craft-libs has no default address. `CRAFT_FONT_PREVIEW_URL`, else the `preview_service` field of `settings.json` (`FontStore::set_preview_service`, user only, `Error::NotAllowed` for an agent), else the host's default (`FontStore::with_default_preview_service`), which is never saved, so clearing the setting brings it back and other apps sharing the store don't see it. `FontStore::preview_service()` returns the one in effect and `preview_service_source()` says whether it is `Env`, `Saved`, `Default` or `None`; the variable's name is `PREVIEW_SERVICE_ENV`. A `settings.json` that exists but can't be read or parsed means no saved service and no host default. Installs and `legal_text` try the service's mirror only for curated families (the built-in sources, `Family::is_curated`), so the hashes of files from sources the user added are never sent to it. https only; http is accepted only for the addresses `127.0.0.1` and `::1`, never for a host name, which a resolver can point off the machine. A trailing slash is dropped. Example: `CRAFT_FONT_PREVIEW_URL=https://fonts.example.com`. |
| Previews setting | `previews` in `settings.json`, on by default: `FontStore::previews_enabled()`, `set_previews_enabled(bool)` (user only, `Error::NotAllowed` for an agent). The app fetches previews from a set service only while it is on; installs ignore it. |
| Preview client | `preview`: subset keys and URLs (`PreviewKey`, `Codepoints`, `SampleHash`), the disk cache (`DiskCache`, least recently used out past 50 MB) and the pool that fetches and decodes WOFF2 subsets on threads of its own (`Previews`). The pool reads the service, the previews setting, the client and the cache folder through `PreviewStore`, which the font manager's `Installer` builds on. It requests nothing without a service or with previews off; cached subsets still load. |
| Mirror first | With a service set, an install requests `<service>/v1/files/<sha256>` for each font file and `<service>/v1/licences/<sha256>` for a licence (when the index gives its sha256) before the index's URLs. The size and sha256 checks are the same, and a response that fails them moves on to the next URL. |
| One HTTP client | `Client`: ureq with rustls and the webpki roots, HTTPS only (plain http only to `127.0.0.1` or `::1`, following no redirects, for a preview service run locally), no cookies, `User-Agent: craft-font-store/<version>`. Timeouts: 15 s to connect, 30 s to the response headers, 10 minutes per file. |
A file's URLs come from its source's URL templates, best first. Both built-in sources use `https://cdn.jsdelivr.net/gh/{repo}@{ref}/{path}`, then `https://raw.githubusercontent.com/{repo}/{ref}/{path}`. The store tries the next URL after any failure: a network error, an HTTP error (jsDelivr answers 403 for files over 20 MB, such as the Noto Serif CJK fonts), or bytes that don't verify.
@@ -52,6 +56,10 @@ Reading checks every entry: the version (a major version other than 1 is refused
| `index.sources()`, `index.source_of(family)` | Each source's name, homepage, curated flag, commit, and families left out with why. |
| `family.source`, `family.is_curated()` | The family's source ID, and whether that source is curated. |
| `index.file_urls(family, file)`, `index.license_urls(family)` | The URLs to try, best first. |
| `family.tags`, `family.copyright`, `family.reserved_names`, `family.notice_file`, `family.upstream` | Format 1.2: design traits, the copyright notice, the Reserved Font Names (a client that modifies a font renames it when there are any), an Apache family's `NOTICE` file and where the family is developed. Absent in a 1.1 index: empty or `None`. |
| `file.instances`, `file.list_instance` | Format 1.2: a variable font's named instances, and the position of the one a font list shows (`None`: the default instance). |
| `index.samples()`, `index.sample(script)` | Format 1.2: the default preview text of each script. When sources have one for the same script, the first source's wins. |
| `index.sample_text(family, file)` | The file's preview text: its own `sample_text`, else the sample of its `sample_script`, else of the family's `sample_script`. |
## Exact matches only
@@ -93,6 +101,7 @@ When every file has passed, the store takes `.lock`, moves the files into the fa
settings.json the network setting and the sources the user added
manifest.json what is installed
indexes/ the last indexes fetched: sources.json, <source>.json.gz, user-<hash>
previews/ preview subsets (WOFF2) the preview pool caches, at most 50 MB
<family folder>/ the font files and the licence
language-packs/ installed Language packs, one folder per locale
language-packs.json which Language packs are installed
Binary file not shown.
Binary file not shown.
+3 -3
View File
@@ -1,4 +1,4 @@
{"schema":1,"version":"1.1","indexes":[
{"source":"google/fonts","name":"Google Fonts","curated":true,"path":"indexes/google-fonts.json","size":4724581,"sha256":"72ea418e43785d572e73350ad08e9e6601a5a12f93315805f92bd3e092618a63","gz_path":"indexes/google-fonts.json.gz","gz_size":596893,"gz_sha256":"62d1d5645417a691e4710f6d1b895f925284ea9c804de268a97432bd67e9c1f6","commit":"45e3d5269e4a17d823f6d84470bc084dc5ae46f6","families":2040,"files":3781},
{"source":"notofonts","name":"Noto","curated":true,"path":"indexes/noto.json","size":117706,"sha256":"8243d697c407776ec4fb19fa892c089279a4a528eb4e04cd970ac6ec14ce142a","gz_path":"indexes/noto.json.gz","gz_size":18192,"gz_sha256":"0d467fb79bcd3afe10350ed3caba2ff57af02aedbc413292e06bc78c02994999","commit":"93fac8abebe6c7fed0c5b7d2456d8fa484fa146c","families":30,"files":130}
{"schema":1,"version":"1.2","indexes":[
{"source":"google/fonts","name":"Google Fonts","curated":true,"path":"indexes/google-fonts.json","size":5672345,"sha256":"89ec33d9c7644963f24c9d749787af85c347b94c3586a5f3a5bd22fe6ae6f8eb","gz_path":"indexes/google-fonts.json.gz","gz_size":721528,"gz_sha256":"85e0678cd48f381e858e6728fd93d865e0f502caa12cec4354e954a27bec82f2","commit":"45e3d5269e4a17d823f6d84470bc084dc5ae46f6","families":2040,"files":3781},
{"source":"notofonts","name":"Noto","curated":true,"path":"indexes/noto.json","size":123691,"sha256":"3c9a615d287f9a4e5a745ce94748dd10dbbcf4eb75370e98456e47534629da55","gz_path":"indexes/noto.json.gz","gz_size":19722,"gz_sha256":"0ffe5e43faa4a3d8218faf3bb97145493760ec74c5779f973f0812fd98b05fcb","commit":"93fac8abebe6c7fed0c5b7d2456d8fa484fa146c","families":30,"files":130}
]}
+121 -15
View File
@@ -1,11 +1,13 @@
//! The one HTTP client: blocking HTTPS GET through ureq with rustls, timeouts, a size cap,
//! progress and cancellation.
//! progress and cancellation. Plain http only to a loopback host, and only when the caller opts
//! in for a preview service run locally.
use std::collections::HashMap;
use std::io::Read;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, RecvTimeoutError};
use std::time::Duration;
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
/// Cancels a download from another thread. Clones share the flag.
#[derive(Clone, Debug, Default)]
@@ -47,6 +49,14 @@ impl Default for Timeouts {
}
}
impl FetchError {
/// Whether the server couldn't be reached or didn't answer in time, as opposed to answering
/// with an HTTP status or too much data.
pub fn is_network(&self) -> bool {
matches!(self, FetchError::Failed(m) if !m.starts_with("HTTP "))
}
}
/// Why a request failed.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum FetchError {
@@ -64,13 +74,34 @@ pub enum FetchError {
Failed(String),
}
/// How long a preview service that failed on the network is skipped.
pub const SERVICE_BACKOFF: Duration = Duration::from_secs(60);
/// `scheme://host:port` of `url`, lowercased.
fn service_origin(url: &str) -> String {
let (scheme, rest) = url.split_once("://").unwrap_or(("", url));
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
format!("{}://{}", scheme.to_ascii_lowercase(), authority.to_ascii_lowercase())
}
fn now_millis() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64)
}
/// The User-Agent every request sends: the crate and its version, nothing about the user.
pub const USER_AGENT: &str = concat!("craft-font-store/", env!("CARGO_PKG_VERSION"));
/// The HTTP client. HTTPS only; no cookies, no credentials.
/// The HTTP client. HTTPS only, except [`Client::get_from_service`], which also speaks plain
/// http to `127.0.0.1` or `::1`; no cookies, no credentials.
#[derive(Clone)]
pub struct Client {
agent: ureq::Agent,
/// For `http://` to a loopback host. It follows no redirects, so it never leaves the machine.
loopback: ureq::Agent,
/// The origins of preview services that failed on the network, each with when it may be
/// tried again. Clones share it.
service_down: Arc<Mutex<HashMap<String, u64>>>,
https_only: bool,
/// URL prefixes the tests serve from a local server.
#[cfg(test)]
pub(crate) rewrite: Vec<(String, String)>,
@@ -95,17 +126,26 @@ impl Client {
}
fn build(t: Timeouts, https_only: bool) -> Self {
let config = ureq::Agent::config_builder()
.https_only(https_only)
.user_agent(USER_AGENT)
.timeout_connect(Some(t.connect))
.timeout_recv_response(Some(t.response))
.timeout_global(Some(t.overall))
.max_redirects(3)
.http_status_as_error(true)
.build();
let agent = |https_only: bool, redirects: u32| {
let builder = ureq::Agent::config_builder();
// A loopback request never goes through an environment proxy.
let builder = if https_only || redirects > 0 { builder } else { builder.proxy(None) };
let config = builder
.https_only(https_only)
.user_agent(USER_AGENT)
.timeout_connect(Some(t.connect))
.timeout_recv_response(Some(t.response))
.timeout_global(Some(t.overall))
.max_redirects(redirects)
.http_status_as_error(true)
.build();
ureq::Agent::new_with_config(config)
};
Self {
agent: ureq::Agent::new_with_config(config),
agent: agent(https_only, 3),
loopback: agent(false, 0),
service_down: Arc::new(Mutex::new(HashMap::new())),
https_only,
#[cfg(test)]
rewrite: Vec::new(),
}
@@ -117,6 +157,18 @@ impl Client {
Self::build(t, false)
}
/// A client with other timeouts that shares this one's preview-service down state, so a
/// pool with short timeouts (previews) and the installs agree on which service is down.
pub fn with_timeouts(&self, timeouts: Timeouts) -> Client {
let fresh = Self::build(timeouts, self.https_only);
Client {
service_down: Arc::clone(&self.service_down),
#[cfg(test)]
rewrite: self.rewrite.clone(),
..fresh
}
}
/// Plain `http://` to a local test server, with `https://` prefixes mapped onto it.
#[cfg(test)]
pub(crate) fn for_tests(t: Timeouts, rewrite: Vec<(String, String)>) -> Self {
@@ -136,12 +188,52 @@ impl Client {
/// GETs `url`, at most `max` bytes, calling `on_bytes` with the bytes read so far. The
/// request runs on a helper thread, so `cancel` stops it even while the server sends nothing.
pub fn get(&self, url: &str, max: u64, cancel: &Cancel, on_bytes: &mut dyn FnMut(u64)) -> Result<Vec<u8>, FetchError> {
self.request(url, max, cancel, on_bytes, false)
}
/// [`Client::get`] for a URL built from the validated preview-service setting: plain `http://`
/// to a loopback host is allowed, without following redirects. Never call it with a URL from
/// an index or a user source.
///
/// After a network failure (no connection, a timeout; not an HTTP status) that service (its
/// scheme, host and port) counts as down for [`SERVICE_BACKOFF`]: calls in that time fail at once, so a service that is off
/// doesn't make every request wait out the timeouts. Clones of the client share this.
pub fn get_from_service(&self, url: &str, max: u64, cancel: &Cancel, on_bytes: &mut dyn FnMut(u64)) -> Result<Vec<u8>, FetchError> {
if self.service_is_down(url) {
return Err(FetchError::Failed("the preview service is down".into()));
}
let got = self.request(url, max, cancel, on_bytes, true);
if got.as_ref().is_err_and(FetchError::is_network) {
self.mark_service_down(url);
}
got
}
/// Whether a network failure of the preview service at `service` (its URL or any URL on it)
/// is recent enough to skip it. Another service is not down.
pub fn service_is_down(&self, service: &str) -> bool {
let down = self.service_down.lock().unwrap_or_else(|e| e.into_inner());
down.get(&service_origin(service)).is_some_and(|until| now_millis() < *until)
}
/// Marks the preview service at `service` as down for [`SERVICE_BACKOFF`].
pub fn mark_service_down(&self, service: &str) {
let until = now_millis() + SERVICE_BACKOFF.as_millis() as u64;
let mut down = self.service_down.lock().unwrap_or_else(|e| e.into_inner());
let now = now_millis();
down.retain(|_, until| now < *until);
down.insert(service_origin(service), until);
}
fn request(&self, url: &str, max: u64, cancel: &Cancel, on_bytes: &mut dyn FnMut(u64), allow_loopback_http: bool) -> Result<Vec<u8>, FetchError> {
if cancel.is_cancelled() {
return Err(FetchError::Cancelled);
}
let stop = Arc::new(AtomicBool::new(false));
let (tx, rx) = mpsc::channel();
let (agent, url, flag) = (self.agent.clone(), self.url(url), Arc::clone(&stop));
let url = self.url(url);
let agent = if allow_loopback_http && is_loopback_http(&url) { self.loopback.clone() } else { self.agent.clone() };
let flag = Arc::clone(&stop);
std::thread::Builder::new()
.name("font-store-fetch".into())
.spawn(move || {
@@ -168,6 +260,20 @@ impl Client {
}
}
/// Whether `url` is `http://` to `127.0.0.1` or `[::1]`.
pub(crate) fn is_loopback_http(url: &str) -> bool {
let Some(rest) = url.get(..7).filter(|s| s.eq_ignore_ascii_case("http://")).and_then(|_| url.get(7..)) else { return false };
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
if authority.contains('@') {
return false;
}
let host = match authority.strip_prefix('[') {
Some(v6) => v6.split(']').next().unwrap_or_default(),
None => authority.split(':').next().unwrap_or_default(),
};
matches!(host.to_ascii_lowercase().as_str(), "127.0.0.1" | "::1")
}
enum Msg {
Bytes(u64),
Done(Result<Vec<u8>, FetchError>),
+98 -4
View File
@@ -76,6 +76,29 @@ pub struct Script {
pub name: String,
}
/// A script's default preview text.
#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct Sample {
/// The text: a sentence for `udhr`, the poem for `iroha`, characters for `exemplar`.
pub text: String,
/// Where it comes from: `udhr`, `iroha` or `exemplar`.
#[serde(default)]
pub method: String,
/// The gflanguages ID of the text's language.
#[serde(default)]
pub language: String,
}
/// A named instance of a variable font.
#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct Instance {
/// The instance's subfamily name (`Bold`).
pub name: String,
/// The user coordinate of each axis, by axis tag.
#[serde(default)]
pub coordinates: BTreeMap<String, f32>,
}
/// A variation axis of a font file.
#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct Axis {
@@ -110,6 +133,19 @@ pub struct FontFile {
/// PostScript names: the face's and, for a variable font, each named instance's.
#[serde(default)]
pub postscript: Vec<String>,
/// Format 1.2: a variable font's named instances, in font order; empty for a static font.
#[serde(default)]
pub instances: Vec<Instance>,
/// Format 1.2: the instance a font list shows, as a position in `instances`; none when the
/// list shows the default instance.
#[serde(default)]
pub list_instance: Option<usize>,
/// Format 1.2: the file's own preview script, when not the family's `sample_script`.
#[serde(default)]
pub sample_script: Option<String>,
/// Format 1.2: the file's own preview text, when no script sample fits it.
#[serde(default)]
pub sample_text: Option<String>,
/// The repository holding the file, when not the family's.
#[serde(default)]
pub repo: Option<String>,
@@ -216,6 +252,25 @@ pub struct Family {
/// The licence file, with its size and sha256.
#[serde(default)]
pub license_file: Option<LicenseFile>,
/// Format 1.2: design traits, sorted, from the index's tag vocabulary.
#[serde(default)]
pub tags: Vec<String>,
/// Format 1.2: the script whose sample previews the family.
#[serde(default)]
pub sample_script: Option<String>,
/// Format 1.2: the copyright notice.
#[serde(default)]
pub copyright: Option<String>,
/// Format 1.2: the Reserved Font Names the OFL notice declares. A client that modifies a font
/// must rename it when this isn't empty.
#[serde(default)]
pub reserved_names: Vec<String>,
/// Format 1.2: an Apache family's `NOTICE` file, located like the licence file.
#[serde(default)]
pub notice_file: Option<LicenseFile>,
/// Format 1.2: where the family is developed.
#[serde(default)]
pub upstream: Option<String>,
/// The repository holding the files, when not the source's.
#[serde(default)]
pub repo: Option<String>,
@@ -399,7 +454,7 @@ pub struct SourceProblem {
pub error: String,
}
pub(crate) type Part = (FontSource, Vec<Language>, Vec<Script>, Vec<Family>);
pub(crate) type Part = (FontSource, Vec<Language>, Vec<Script>, BTreeMap<String, Sample>, Vec<Family>);
/// The checked indexes of one or more sources. Families are sorted by name; families of the same
/// name are in source order (built-in sources in `sources.json` order, then the user's), and
@@ -410,6 +465,9 @@ pub struct Index {
problems: Vec<SourceProblem>,
languages: Vec<Language>,
scripts: Vec<Script>,
samples: BTreeMap<String, Sample>,
/// Each source's own samples, by its position in `sources`, for [`Index::merge`].
source_samples: Vec<BTreeMap<String, Sample>>,
families: Vec<Family>,
by_name: HashMap<String, Vec<usize>>,
by_postscript: HashMap<String, Vec<(usize, usize)>>,
@@ -454,10 +512,10 @@ impl Index {
for part in parts {
problems.extend(part.problems);
let mut families = part.families;
for source in part.sources {
for (source, samples) in part.sources.into_iter().zip(part.source_samples) {
let (mine, rest): (Vec<Family>, Vec<Family>) = families.into_iter().partition(|f| f.source == source.id);
families = rest;
list.push((source, part.languages.clone(), part.scripts.clone(), mine));
list.push((source, part.languages.clone(), part.scripts.clone(), samples, mine));
}
}
Self::assemble(list, problems)
@@ -480,8 +538,10 @@ impl Index {
let mut sources: Vec<FontSource> = Vec::new();
let mut languages: BTreeMap<String, Language> = BTreeMap::new();
let mut scripts: BTreeMap<String, Script> = BTreeMap::new();
let mut samples: BTreeMap<String, Sample> = BTreeMap::new();
let mut source_samples = Vec::new();
let mut families: Vec<(Family, Vec<String>)> = Vec::new();
for (source, langs, scrs, fams) in parts {
for (source, langs, scrs, smps, fams) in parts {
if sources.iter().any(|s| s.id == source.id) {
problems.push(SourceProblem {
source: source.user_url.clone().unwrap_or_else(|| source.id.clone()),
@@ -500,6 +560,10 @@ impl Index {
for s in scrs {
scripts.entry(s.id.clone()).or_insert(s);
}
for (script, sample) in &smps {
samples.entry(script.clone()).or_insert_with(|| sample.clone());
}
source_samples.push(smps);
sources.push(source);
}
let position: HashMap<&str, usize> = languages.keys().enumerate().map(|(i, id)| (id.as_str(), i)).collect();
@@ -533,6 +597,8 @@ impl Index {
problems,
languages: languages.into_values().collect(),
scripts: scripts.into_values().collect(),
samples,
source_samples,
families: merged,
by_name,
by_postscript,
@@ -574,6 +640,29 @@ impl Index {
&self.scripts
}
/// The default preview text of every script, by ISO 15924 code. When several sources have one
/// for a script, the first source's wins.
pub fn samples(&self) -> &BTreeMap<String, Sample> {
&self.samples
}
/// The default preview text of a script.
pub fn sample(&self, script: &str) -> Option<&Sample> {
self.samples.get(script)
}
/// The preview text of a file of `family`: the file's own `sample_text`, else the sample of
/// its `sample_script`. A file with its own `sample_script` has none when that script has no
/// sample; only a file without one uses the family's.
pub fn sample_text<'a>(&'a self, family: &'a Family, file: &'a FontFile) -> Option<&'a str> {
if let Some(text) = &file.sample_text {
return Some(text);
}
let sample = |script: &Option<String>| script.as_deref().and_then(|s| self.sample(s));
let script = if file.sample_script.is_some() { &file.sample_script } else { &family.sample_script };
sample(script).map(|s| s.text.as_str())
}
/// The family of this name, ignoring case, from the first source that has it. Only the whole
/// name matches.
pub fn family(&self, name: &str) -> Option<&Family> {
@@ -646,6 +735,11 @@ impl Index {
}
}
/// The URLs of `family`'s NOTICE file, best first; empty when it has none.
pub fn notice_urls(&self, family: &Family) -> Vec<String> {
family.notice_file.as_ref().map(|f| self.urls(family, &f.path, f.repo.as_deref(), f.git_ref.as_deref())).unwrap_or_default()
}
fn urls(&self, family: &Family, path: &str, repo: Option<&str>, git_ref: Option<&str>) -> Vec<String> {
let Some(source) = self.source_of(family) else { return Vec::new() };
let repo = repo.or(family.repo.as_deref()).or(source.repo.as_deref());
@@ -44,7 +44,7 @@ impl FontStore {
let bytes = match source {
IndexSource::Pinned(pin) => {
let check = |b: &[u8]| if sha256_hex(b) == pin.sha256 { Ok(()) } else { Err(VerifyError::Sha256) };
self.fetch(&[pin.url.to_string()], MAX_PACK_INDEX_BYTES, "the Language pack index", cancel, &mut |_| {}, &check)?
self.fetch(&[pin.url.to_string()], 0, MAX_PACK_INDEX_BYTES, "the Language pack index", cancel, &mut |_| {}, &check)?
}
IndexSource::Override(at) => self.get_local(at, MAX_PACK_INDEX_BYTES, "the Language pack index", cancel, &mut |_| {}, &|_| Ok(()))?,
};
@@ -65,7 +65,7 @@ impl FontStore {
check: &dyn Fn(&[u8]) -> Result<(), VerifyError>,
) -> Result<Vec<u8>, Error> {
let bytes = match local_source(at) {
Some(Ok(url)) if url.starts_with("https://") => return self.fetch(&[url.to_string()], max, what, cancel, on_bytes, check),
Some(Ok(url)) if url.starts_with("https://") => return self.fetch(&[url.to_string()], 0, max, what, cancel, on_bytes, check),
Some(Ok(url)) => Client::allowing_http(Timeouts::default())
.get(url, max, cancel, on_bytes)
.map_err(|e| Error::Download { what: what.to_string(), reasons: vec![e.to_string()] })?,
@@ -129,7 +129,7 @@ impl FontStore {
let bytes = if local {
self.get_local(&pack.url, size, &what, cancel, &mut on_bytes, &check)?
} else if pack.url.starts_with("https://") {
self.fetch(std::slice::from_ref(&pack.url), size, &what, cancel, &mut on_bytes, &check)?
self.fetch(std::slice::from_ref(&pack.url), 0, size, &what, cancel, &mut on_bytes, &check)?
} else {
return Err(Error::BadUrl(pack.url.chars().take(200).collect()));
};
+10 -6
View File
@@ -19,11 +19,12 @@
//! ```
//!
//! The index and its lookups, [`verify_font`] and [`IndexPin`] build on every target. The store,
//! the HTTP client and Language packs (the store's second item kind, `language-pack`: see
//! [`FontStore::install_language_pack`]) are native only.
//! the HTTP client, the preview service's client ([`preview`]) and Language packs (the store's
//! second item kind, `language-pack`: see [`FontStore::install_language_pack`]) are native only.
mod index;
mod pin;
mod service;
mod source;
mod sources;
mod verify;
@@ -33,13 +34,16 @@ mod http;
#[cfg(not(target_arch = "wasm32"))]
mod language_packs;
#[cfg(not(target_arch = "wasm32"))]
pub mod preview;
#[cfg(not(target_arch = "wasm32"))]
mod store;
pub use index::{
Axis, Face, Family, FontFile, FontSource, GOOGLE_FONTS, Index, IndexError, LICENSES, Language, LicenseFile, MAJOR_VERSION, MAX_FILE_BYTES,
MAX_INDEX_BYTES, MAX_LICENSE_BYTES, Script, SourceProblem, Unavailable, parse_style,
Axis, Face, Family, FontFile, FontSource, GOOGLE_FONTS, Index, IndexError, Instance, LICENSES, Language, LicenseFile, MAJOR_VERSION,
MAX_FILE_BYTES, MAX_INDEX_BYTES, MAX_LICENSE_BYTES, Sample, Script, SourceProblem, Unavailable, parse_style,
};
pub use pin::{IndexPin, PINNED_INDEX};
pub use service::{LegalText, PREVIEW_SERVICE_ENV, PreviewServiceSource, PreviewStore};
pub use sources::{SourceEntry, SourcesFile};
pub use verify::{VerifyError, is_font, sha256_hex, verify_font};
@@ -58,14 +62,14 @@ pub struct UserSource {
}
#[cfg(not(target_arch = "wasm32"))]
pub use http::{Cancel, Client, FetchError, Timeouts, USER_AGENT};
pub use http::{Cancel, Client, FetchError, SERVICE_BACKOFF, Timeouts, USER_AGENT};
#[cfg(not(target_arch = "wasm32"))]
pub use language_packs::{
InstalledLanguagePack, LANGUAGE_PACK_INDEX_ENV, LANGUAGE_PACKS, MAX_PACK_ARCHIVE_BYTES, MAX_PACK_ENTRIES, MAX_PACK_FILE_BYTES,
MAX_PACK_INDEX_BYTES, MAX_PACK_UNPACKED_BYTES, PackEntry, PackIndex, PackIndexPin, language_pack_index_overridden,
};
#[cfg(not(target_arch = "wasm32"))]
pub use store::{Caller, Error, FontStore, InstalledFamily, InstalledFile, Network, Problem, Progress};
pub use store::{Caller, Error, FontStore, InstalledFamily, InstalledFile, Network, Problem, Progress, check_preview_service};
#[cfg(test)]
mod tests;
+3 -3
View File
@@ -29,10 +29,10 @@ impl IndexPin {
}
}
/// The built-in sources of this build: aiongg/craft-font-index at `5a9a7f8` (Google Fonts at
/// The built-in sources of this build: aiongg/craft-font-index at `995ef20` (Google Fonts at
/// google/fonts `45e3d52`, and Noto), the copy `Index::bundled` compiles in.
pub const PINNED_INDEX: IndexPin = IndexPin {
repo: "aiongg/craft-font-index",
commit: "5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f",
sha256: "4b0c2b9cdec1885027dc3316cdc013ccfbc0d63b6ed9950138d762afaff72e23",
commit: "995ef2000a0159d70da245e22cfa0797a0756ae8",
sha256: "743cfb4c57176befe8190108efcba43f315de33e747b15ec8694c0625a14c24f",
};
+697
View File
@@ -0,0 +1,697 @@
//! The font preview service's client: subset URLs, a pool that fetches and decodes them, and a
//! disk cache.
//!
//! The service serves a small subset of one font file per preview, addressed by the upstream
//! file's sha256: the face's default sample, printable ASCII, or a set of codepoints, at the
//! instance the list shows or with every axis kept. Responses never change, so the cache never
//! revalidates. With the service at `https://fonts.example.com`, the list's sample of a face is
//! `https://fonts.example.com/v1/faces/<sha256>/list/sample-<h>.woff2`.
//!
//! [`Previews`] requests nothing unless a preview service is set and previews are enabled
//! ([`PreviewStore::preview_service`], [`PreviewStore::previews_enabled`]). Previews are on by
//! default; a user setting turns them off. There is no prompt, and the install consent (the font
//! manager's `Installer::downloads_allowed`) is not consulted: previews are fetched whether or not
//! installs are allowed. With previews off nothing goes to the network, but previews already in
//! the disk cache are still used. Without a service the panel keeps its whole-family previews.
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::time::{Duration, SystemTime};
use crate::{Cancel, Client, FetchError, Timeouts, is_font, sha256_hex};
/// The most codepoints one request may name; the service rejects more.
pub const MAX_CODEPOINTS: usize = 256;
/// The largest response accepted. Subsets are a few KB; a `var` subset of CJK text is the largest.
pub const MAX_PREVIEW_BYTES: u64 = 8 << 20;
/// The disk cache's size.
pub const CACHE_LIMIT: u64 = 50 << 20;
/// Requests at a time.
pub const WORKERS: usize = 8;
/// A set of codepoints, as a subset request names them.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Codepoints(BTreeSet<char>);
impl Codepoints {
/// The characters of `text` without C0 and C1 controls and DEL, which no font draws.
pub fn from_text(text: &str) -> Codepoints {
text.chars().collect()
}
/// How many characters the set holds.
pub fn len(&self) -> usize {
self.0.len()
}
/// Whether the set is empty.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Whether `c` is in the set.
pub fn contains(&self, c: char) -> bool {
self.0.contains(&c)
}
/// In ascending order.
pub fn iter(&self) -> impl Iterator<Item = char> + '_ {
self.0.iter().copied()
}
/// Keeps the codepoints `keep` accepts, such as those a face covers.
pub fn retain(&mut self, mut keep: impl FnMut(char) -> bool) {
self.0.retain(|&c| keep(c));
}
/// The canonical form the service accepts, and so the cache key: ascending lowercase hex
/// without leading zeros, a run of two or more as `first-last`, joined by commas
/// (`20,41-5a,e9`). Empty for the empty set.
pub fn encode(&self) -> String {
let mut out = String::new();
let mut rest = self.0.iter().map(|&c| c as u32).peekable();
while let Some(first) = rest.next() {
let mut last = first;
while rest.peek() == Some(&(last + 1)) {
last += 1;
rest.next();
}
if !out.is_empty() {
out.push(',');
}
let _ = if last == first { write!(out, "{first:x}") } else { write!(out, "{first:x}-{last:x}") };
}
out
}
}
impl FromIterator<char> for Codepoints {
/// Without C0 and C1 controls and DEL.
fn from_iter<I: IntoIterator<Item = char>>(chars: I) -> Codepoints {
Codepoints(chars.into_iter().filter(|&c| !matches!(c as u32, 0..0x20 | 0x7f..=0x9f)).collect())
}
}
/// Which instance of a face a subset is drawn at.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Instance {
/// What the list shows: the "Regular" named instance of a variable face, else its default,
/// pinned to a static font.
List,
/// Every axis kept, for the detail view's styles and sliders.
Var,
}
impl Instance {
fn as_str(self) -> &'static str {
match self {
Instance::List => "list",
Instance::Var => "var",
}
}
}
/// The first 12 lowercase hex digits of the sha256 of a sample text (UTF-8, as the index has
/// it), which names the sample subset for that text.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SampleHash(String);
impl SampleHash {
/// The hash of `text`.
pub fn of(text: &str) -> SampleHash {
SampleHash(sha256_hex(text.as_bytes())[..12].to_string())
}
/// The hash as the 12 hex digits it is written as.
pub fn as_str(&self) -> &str {
&self.0
}
}
/// Which characters a subset holds.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Subset {
/// The face's default sample (its script's sentence from the index) and the family name.
/// The hash names the text the client has; the service answers 404 for any other.
Sample(SampleHash),
/// Printable ASCII, U+0020 to U+007E, for faces that cover Latin.
Ascii,
/// These codepoints, for typed text the static subsets don't cover.
Codepoints(Codepoints),
}
/// One subset of one face: a request, a cache entry and the key results come back under.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PreviewKey {
sha256: String,
instance: Instance,
subset: Subset,
}
impl PreviewKey {
/// The subset of the font file with this sha256 (as the index has it). `None` for a sha256
/// that isn't 64 hex digits, and for codepoints that are empty or more than
/// [`MAX_CODEPOINTS`].
pub fn new(sha256: &str, instance: Instance, subset: Subset) -> Option<PreviewKey> {
if sha256.len() != 64 || !sha256.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
if let Subset::Codepoints(c) = &subset
&& (c.is_empty() || c.len() > MAX_CODEPOINTS)
{
return None;
}
Some(PreviewKey { sha256: sha256.to_ascii_lowercase(), instance, subset })
}
/// The sha256 of the font file the preview is of.
pub fn sha256(&self) -> &str {
&self.sha256
}
/// The instance the preview shows.
pub fn instance(&self) -> Instance {
self.instance
}
/// The subset the preview covers.
pub fn subset(&self) -> &Subset {
&self.subset
}
/// The path below the service's base URL: `v1/faces/<sha256>/<instance>/sample-<h>.woff2`,
/// `.../ascii.woff2` or `.../u/<codepoints>.woff2`.
pub fn path(&self) -> String {
let what = match &self.subset {
Subset::Sample(h) => format!("sample-{}", h.as_str()),
Subset::Ascii => "ascii".to_string(),
Subset::Codepoints(c) => format!("u/{}", c.encode()),
};
format!("v1/faces/{}/{}/{what}.woff2", self.sha256, self.instance.as_str())
}
/// The URL at the service whose base URL is `service`.
pub fn url(&self, service: &str) -> String {
format!("{}/{}", service.trim_end_matches('/'), self.path())
}
}
/// Why a preview didn't load.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum PreviewError {
/// The user turned previews off, and the subset isn't cached.
PreviewsOff,
/// No preview service is set.
NoService,
/// The request failed: the network, an HTTP status (503 while the service is busy), the
/// size limit.
Failed(String),
/// The service has no such subset (HTTP 404): for a sample, its text isn't the client's.
NotFound,
/// The response isn't a WOFF2 font with outlines.
NotAFont,
}
impl std::fmt::Display for PreviewError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PreviewError::PreviewsOff => f.write_str("font previews are turned off"),
PreviewError::NoService => f.write_str("no preview service is set"),
PreviewError::Failed(e) => f.write_str(e),
PreviewError::NotFound => f.write_str("the service has no such preview"),
PreviewError::NotAFont => f.write_str("the preview is not a font, or a damaged one"),
}
}
}
impl std::error::Error for PreviewError {}
/// A finished request.
#[derive(Debug)]
#[non_exhaustive]
pub struct Preview {
/// The key the preview was fetched for.
pub key: PreviewKey,
/// The decoded font file (TrueType or OpenType), ready to register.
pub font: Result<Vec<u8>, PreviewError>,
}
pub use crate::service::PreviewStore;
/// How the pool downloads: the store's [`Client`], or a stand-in in tests.
pub trait Fetch: Send + Sync {
/// GETs `url`, built from the preview-service setting, at most `max` bytes, stopping soon after `cancel` is set.
fn get(&self, url: &str, max: u64, cancel: &Cancel) -> Result<Vec<u8>, FetchError>;
}
impl Fetch for Client {
fn get(&self, url: &str, max: u64, cancel: &Cancel) -> Result<Vec<u8>, FetchError> {
Client::get_from_service(self, url, max, cancel, &mut |_| {})
}
}
/// Subsets as the service sent them (WOFF2), one file per key, named by the sha256 of the key's
/// path. The least recently used go once the folder holds more than its limit. Several apps can
/// share the folder: a file another one removed is a miss.
pub struct DiskCache {
dir: PathBuf,
limit: u64,
/// Read from the folder on first use.
entries: Mutex<Option<Entries>>,
}
#[derive(Default)]
struct Entries {
/// File name to its size and last use.
files: HashMap<String, (u64, u64)>,
/// Last use to file name, oldest first.
order: BTreeMap<u64, String>,
total: u64,
tick: u64,
}
impl Entries {
fn touch(&mut self, name: &str, size: u64) {
self.tick += 1;
if let Some((old_size, old_tick)) = self.files.insert(name.to_string(), (size, self.tick)) {
self.order.remove(&old_tick);
self.total = self.total.saturating_sub(old_size);
}
self.order.insert(self.tick, name.to_string());
self.total = self.total.saturating_add(size);
}
fn forget(&mut self, name: &str) {
if let Some((size, tick)) = self.files.remove(name) {
self.order.remove(&tick);
self.total = self.total.saturating_sub(size);
}
}
/// Removes the oldest files, except `keep`, until the rest fit in `limit`.
fn evict(&mut self, dir: &Path, limit: u64, keep: Option<&str>) {
while self.total > limit {
let Some(name) = self.order.values().find(|n| Some(n.as_str()) != keep).cloned() else { break };
let _ = std::fs::remove_file(dir.join(&name));
self.forget(&name);
}
}
}
/// A temporary file older than this belongs to a write that never finished.
const STALE_TEMP: Duration = Duration::from_secs(600);
impl DiskCache {
/// A cache in `dir` (created on the first write) of at most `limit` bytes.
pub fn new(dir: impl Into<PathBuf>, limit: u64) -> DiskCache {
DiskCache { dir: dir.into(), limit, entries: Mutex::new(None) }
}
/// The folder previews are cached in.
pub fn dir(&self) -> &Path {
&self.dir
}
/// The bytes cached for `path` ([`PreviewKey::path`]), marking them as just used.
pub fn get(&self, path: &str) -> Option<Vec<u8>> {
let name = file_name(path);
let file = self.dir.join(&name);
let bytes = std::fs::metadata(&file).ok().filter(|m| m.len() <= MAX_PREVIEW_BYTES).and_then(|_| std::fs::read(&file).ok());
match bytes {
Some(bytes) => {
self.with(|e| e.touch(&name, bytes.len() as u64));
// The modification time keeps the order for the next session.
let _ = std::fs::File::options().write(true).open(&file).and_then(|f| f.set_modified(SystemTime::now()));
Some(bytes)
}
None => {
self.with(|e| e.forget(&name));
None
}
}
}
/// Whether `path` is cached, without marking it used. Asks the folder, which another app
/// sharing it may have added to since it was read.
pub fn contains(&self, path: &str) -> bool {
std::fs::metadata(self.dir.join(file_name(path))).is_ok_and(|m| m.is_file())
}
/// Caches `bytes` for `path`, then removes the least recently used past the limit. Bytes
/// larger than the whole limit aren't cached.
pub fn put(&self, path: &str, bytes: &[u8]) {
let size = bytes.len() as u64;
if size > self.limit {
return;
}
let name = file_name(path);
if std::fs::create_dir_all(&self.dir).is_err() {
return;
}
// A reader never sees half a file: write beside it, then rename.
static N: AtomicU64 = AtomicU64::new(0);
let temp = self.dir.join(format!(".tmp-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
if std::fs::write(&temp, bytes).and_then(|()| std::fs::rename(&temp, self.dir.join(&name))).is_err() {
let _ = std::fs::remove_file(&temp);
return;
}
self.with(|e| {
e.touch(&name, size);
e.evict(&self.dir, self.limit, Some(&name));
});
}
/// Removes the entry for `path`, as when it doesn't decode.
pub fn remove(&self, path: &str) {
let name = file_name(path);
let _ = std::fs::remove_file(self.dir.join(&name));
self.with(|e| e.forget(&name));
}
/// Bytes held.
pub fn size(&self) -> u64 {
self.with(|e| e.total)
}
fn with<R>(&self, f: impl FnOnce(&mut Entries) -> R) -> R {
let mut guard = self.entries.lock().unwrap_or_else(|e| e.into_inner());
f(guard.get_or_insert_with(|| self.scan()))
}
/// The files in the folder, oldest modification first; drops stale temporary files and
/// whatever no longer fits.
fn scan(&self) -> Entries {
let mut found = Vec::new();
for entry in std::fs::read_dir(&self.dir).into_iter().flatten().flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
let Ok(meta) = entry.metadata() else { continue };
let modified = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH);
if name.starts_with(".tmp-") {
if modified.elapsed().is_ok_and(|age| age > STALE_TEMP) {
let _ = std::fs::remove_file(entry.path());
}
} else if meta.is_file() && is_entry_name(&name) {
found.push((modified, name, meta.len()));
}
}
found.sort();
let mut entries = Entries::default();
for (_, name, size) in found {
entries.touch(&name, size);
}
entries.evict(&self.dir, self.limit, None);
entries
}
}
fn file_name(path: &str) -> String {
format!("{}.woff2", sha256_hex(path.as_bytes()))
}
fn is_entry_name(name: &str) -> bool {
name.strip_suffix(".woff2").is_some_and(|h| h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit()))
}
type Wake = Arc<dyn Fn() + Send + Sync>;
/// Fetches subsets on [`WORKERS`] threads of its own, separate from the panel's jobs, highest
/// priority first. Results wait in [`Previews::poll`]; a cancelled request delivers nothing.
///
/// Each request reads the disk cache first. Only on a miss, and only while previews are enabled
/// and a service is set, does it go to the network; the response is decoded, checked and cached.
/// Without a service, requests come back as [`PreviewError::NoService`] at once and nothing is
/// read or fetched.
pub struct Previews {
installer: Arc<dyn PreviewStore>,
fetcher: Arc<dyn Fetch>,
cache: Option<Arc<DiskCache>>,
wake: Option<Wake>,
workers: usize,
shared: Arc<Shared>,
tx: Sender<Preview>,
rx: Receiver<Preview>,
}
struct Shared {
state: Mutex<State>,
ready: Condvar,
}
#[derive(Default)]
struct State {
/// Waiting: priority and order of arrival.
queued: HashMap<PreviewKey, (u32, u64)>,
/// Being fetched: the job's id and its cancel flag.
running: HashMap<PreviewKey, (u64, Cancel)>,
next: u64,
started: bool,
stop: bool,
}
impl State {
/// The highest priority, then the oldest.
fn take_next(&mut self) -> Option<PreviewKey> {
let key = self.queued.iter().max_by_key(|(_, (priority, seq))| (*priority, std::cmp::Reverse(*seq))).map(|(k, _)| k.clone())?;
self.queued.remove(&key);
Some(key)
}
fn is_running(&self, key: &PreviewKey) -> bool {
self.running.get(key).is_some_and(|(_, c)| !c.is_cancelled())
}
}
impl Previews {
/// A pool fetching with the store's client ([`PreviewStore::http_client`]) given short timeouts
/// (10 s to connect, 15 s to respond, 30 s overall; the down state stays shared), else with its
/// own [`Client`]. A network failure of the service pauses its requests for a minute, for every
/// user of the same client (installs too). It caches in the store's
/// [`PreviewStore::preview_cache`] folder, up to [`CACHE_LIMIT`]. It starts its threads on the
/// first request.
pub fn new(installer: Arc<dyn PreviewStore>) -> Previews {
let timeouts = Timeouts { connect: Duration::from_secs(10), response: Duration::from_secs(15), overall: Duration::from_secs(30) };
let client = installer.http_client().map_or_else(|| Client::new(timeouts), |c| c.with_timeouts(timeouts));
let cache = installer.preview_cache().map(|dir| Arc::new(DiskCache::new(dir, CACHE_LIMIT)));
let (tx, rx) = channel();
Previews {
installer,
fetcher: Arc::new(client),
cache,
wake: None,
workers: WORKERS,
shared: Arc::new(Shared { state: Mutex::new(State::default()), ready: Condvar::new() }),
tx,
rx,
}
}
/// Fetches through `fetcher` instead.
pub fn with_fetcher(mut self, fetcher: Arc<dyn Fetch>) -> Previews {
self.fetcher = fetcher;
self
}
/// Caches in `cache`, or with `None` not at all.
pub fn with_cache(mut self, cache: Option<DiskCache>) -> Previews {
self.cache = cache.map(Arc::new);
self
}
/// Runs `workers` requests at a time (at least one) instead of [`WORKERS`].
pub fn with_workers(mut self, workers: usize) -> Previews {
self.workers = workers.max(1);
self
}
/// Calls `wake` from a worker thread after each result, such as egui's `request_repaint`.
pub fn on_ready(mut self, wake: impl Fn() + Send + Sync + 'static) -> Previews {
self.wake = Some(Arc::new(wake));
self
}
/// Whether a preview service is set and previews are enabled. It reads the store's settings, so callers ask when the
/// panel opens or its settings change, not every frame.
pub fn available(&self) -> bool {
self.installer.preview_service().is_some() && self.installer.previews_enabled()
}
/// The disk cache, if there is one.
pub fn cache(&self) -> Option<&DiskCache> {
self.cache.as_deref()
}
/// Queues `key` at `priority` (higher first; the same priority in the order asked). A key
/// already queued takes the new priority; one being fetched is left alone.
pub fn request(&self, key: PreviewKey, priority: u32) {
let mut state = self.lock();
if state.is_running(&key) {
return;
}
if !state.started {
state.started = true;
self.start();
}
let seq = state.next;
state.next += 1;
let entry = state.queued.entry(key).or_insert((priority, seq));
entry.0 = priority;
drop(state);
self.shared.ready.notify_one();
}
/// Drops `key` from the queue, or stops fetching it. Nothing is delivered for it, unless it
/// finished before the call.
pub fn cancel(&self, key: &PreviewKey) {
self.retain(|k| k != key);
}
/// Cancels every queued and running request `keep` rejects, such as rows that scrolled out
/// of the window.
pub fn retain(&self, mut keep: impl FnMut(&PreviewKey) -> bool) {
let mut state = self.lock();
state.queued.retain(|k, _| keep(k));
for (key, (_, cancel)) in &state.running {
if !keep(key) {
cancel.cancel();
}
}
}
/// Whether `key` is queued or being fetched.
pub fn is_pending(&self, key: &PreviewKey) -> bool {
let state = self.lock();
state.queued.contains_key(key) || state.is_running(key)
}
/// Requests queued or being fetched.
pub fn pending(&self) -> usize {
let state = self.lock();
state.queued.len() + state.running.values().filter(|(_, c)| !c.is_cancelled()).count()
}
/// The results since the last call.
pub fn poll(&self) -> Vec<Preview> {
self.rx.try_iter().collect()
}
fn lock(&self) -> MutexGuard<'_, State> {
self.shared.state.lock().unwrap_or_else(|e| e.into_inner())
}
fn start(&self) {
for i in 0..self.workers {
let worker = Worker {
installer: Arc::clone(&self.installer),
fetcher: Arc::clone(&self.fetcher),
cache: self.cache.clone(),
wake: self.wake.clone(),
shared: Arc::clone(&self.shared),
tx: self.tx.clone(),
};
// A pool short of threads still works, more slowly; with none, requests stay queued.
let _ = std::thread::Builder::new().name(format!("font-previews-{i}")).spawn(move || worker.run());
}
}
}
impl Drop for Previews {
fn drop(&mut self) {
let mut state = self.lock();
state.stop = true;
state.queued.clear();
for (_, cancel) in state.running.values() {
cancel.cancel();
}
drop(state);
self.shared.ready.notify_all();
}
}
struct Worker {
installer: Arc<dyn PreviewStore>,
fetcher: Arc<dyn Fetch>,
cache: Option<Arc<DiskCache>>,
wake: Option<Wake>,
shared: Arc<Shared>,
tx: Sender<Preview>,
}
impl Worker {
fn run(self) {
while let Some((key, id, cancel)) = self.next() {
let font = self.load(&key, &cancel);
let mut state = self.shared.state.lock().unwrap_or_else(|e| e.into_inner());
if state.running.get(&key).is_some_and(|(i, _)| *i == id) {
state.running.remove(&key);
}
if cancel.is_cancelled() {
continue;
}
// Sent under the lock, so a cancel that returned has either dropped it or comes after.
let _ = self.tx.send(Preview { key, font });
drop(state);
if let Some(wake) = &self.wake {
wake();
}
}
}
/// Waits for a request; `None` once the pool is dropped.
fn next(&self) -> Option<(PreviewKey, u64, Cancel)> {
let mut state = self.shared.state.lock().unwrap_or_else(|e| e.into_inner());
loop {
if state.stop {
return None;
}
if let Some(key) = state.take_next() {
let id = state.next;
state.next += 1;
let cancel = Cancel::new();
state.running.insert(key.clone(), (id, cancel.clone()));
return Some((key, id, cancel));
}
state = self.shared.ready.wait(state).unwrap_or_else(|e| e.into_inner());
}
}
fn load(&self, key: &PreviewKey, cancel: &Cancel) -> Result<Vec<u8>, PreviewError> {
let Some(service) = self.installer.preview_service() else { return Err(PreviewError::NoService) };
let path = key.path();
if let Some(cache) = &self.cache
&& let Some(bytes) = cache.get(&path)
{
match decode(&bytes) {
Ok(font) => return Ok(font),
Err(_) => cache.remove(&path),
}
}
if !self.installer.previews_enabled() {
return Err(PreviewError::PreviewsOff);
}
let bytes = self.fetcher.get(&key.url(&service), MAX_PREVIEW_BYTES, cancel).map_err(|e| match e {
FetchError::Failed(m) if m == "HTTP 404" => PreviewError::NotFound,
e => PreviewError::Failed(e.to_string()),
})?;
let font = decode(&bytes)?;
if let Some(cache) = &self.cache {
cache.put(&path, &bytes);
}
Ok(font)
}
}
/// The font file inside a WOFF2 response, when it parses and has outlines.
fn decode(woff2: &[u8]) -> Result<Vec<u8>, PreviewError> {
let font = wuff::decompress_woff2(woff2).map_err(|_| PreviewError::NotAFont)?;
if is_font(&font) { Ok(font) } else { Err(PreviewError::NotAFont) }
}
+57
View File
@@ -0,0 +1,57 @@
//! What the font store and the preview service's client share with the font manager on every target: which legal
//! text to read, where the preview service comes from, and what the preview pool reads from a store. The store and
//! the client themselves are native only.
use std::path::PathBuf;
/// Which of a family's legal texts [`FontStore::legal_text`](crate::FontStore::legal_text) reads.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LegalText {
/// The licence file (`OFL.txt`, `LICENSE.txt`).
License,
/// An Apache family's `NOTICE` file.
Notice,
}
/// The environment variable that sets the preview service's base URL; it beats the saved setting.
pub const PREVIEW_SERVICE_ENV: &str = "CRAFT_FONT_PREVIEW_URL";
/// Where the preview service in effect comes from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PreviewServiceSource {
/// [`PREVIEW_SERVICE_ENV`]; the setting can't change it.
Env,
/// The `preview_service` setting in `settings.json`.
Saved,
/// The host's default, [`FontStore::with_default_preview_service`](crate::FontStore::with_default_preview_service).
Default,
/// There is no service.
None,
}
/// What [`Previews`](crate::preview::Previews) reads from the font store: the service and the user's setting on each request, the client and
/// the cache folder when the pool is made. The font manager's `Installer` builds on it.
pub trait PreviewStore: Send + Sync {
/// The preview service's base URL, if one is set: [`PREVIEW_SERVICE_ENV`](crate::PREVIEW_SERVICE_ENV), else the
/// font store's `preview_service` setting, else the host's default. Installs try it as a mirror first.
fn preview_service(&self) -> Option<String> {
None
}
/// The store's HTTP client, if it has one. [`Previews`](crate::preview::Previews) fetches with it, so a preview service that installs
/// found unreachable is skipped by previews too, and the reverse.
#[cfg(not(target_arch = "wasm32"))]
fn http_client(&self) -> Option<crate::Client> {
None
}
/// Whether previews may be fetched from the preview service: the user's setting, on by default.
fn previews_enabled(&self) -> bool {
true
}
/// The folder [`Previews`](crate::preview::Previews) caches preview subsets in; none keeps them only for as long as the caller holds them.
fn preview_cache(&self) -> Option<PathBuf> {
None
}
}
+60 -13
View File
@@ -1,16 +1,18 @@
//! Reading and checking one source's index file, and its URL templates.
use std::collections::HashSet;
use std::collections::{BTreeMap, HashSet};
use serde::Deserialize;
use crate::index::{
Family, FontSource, GOOGLE_FONTS, Index, IndexError, LICENSES, Language, MAJOR_VERSION, MAX_FILE_BYTES, MAX_INDEX_BYTES, MAX_LICENSE_BYTES,
Script,
Sample, Script,
};
pub(crate) const MAX_STR: usize = 1024;
const MAX_LIST: usize = 4096;
/// The most characters a file's own `sample_text` has.
const MAX_SAMPLE_CHARS: usize = 60;
const MAX_FAMILIES: usize = 50_000;
const MAX_FILES: usize = 200_000;
const MAX_SEGMENT: usize = 64;
@@ -60,6 +62,8 @@ struct Raw {
languages: Vec<Language>,
#[serde(default)]
scripts: Vec<Script>,
#[serde(default)]
samples: BTreeMap<String, Sample>,
families: Vec<Family>,
}
@@ -80,8 +84,13 @@ pub(crate) fn check_version(version: &str) -> Result<(), IndexError> {
if major == Some(MAJOR_VERSION) { Ok(()) } else { Err(IndexError::Version(version.chars().take(40).collect())) }
}
/// Direction marks, embeddings and isolates, which can reorder the text around them.
fn is_bidi_control(c: char) -> bool {
matches!(c, '\u{61c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
}
pub(crate) fn check_str(what: &str, s: &str) -> Result<(), IndexError> {
if s.len() > MAX_STR || s.chars().any(char::is_control) {
if s.len() > MAX_STR || s.chars().any(|c| c.is_control() || is_bidi_control(c)) {
return invalid(format!("{what} is too long or has control characters"));
}
Ok(())
@@ -317,8 +326,17 @@ fn check(raw: Raw, origin: Origin<'_>) -> Result<Index, IndexError> {
}
};
let curated = curated && host.is_none();
if raw.families.len() > MAX_FAMILIES || raw.languages.len() > MAX_FAMILIES * 4 || raw.scripts.len() > MAX_LIST {
return invalid("too many families, languages or scripts");
if raw.families.len() > MAX_FAMILIES || raw.languages.len() > MAX_FAMILIES * 4 || raw.scripts.len() > MAX_LIST || raw.samples.len() > MAX_LIST {
return invalid("too many families, languages, scripts or samples");
}
for (script, sample) in &raw.samples {
for s in [script, &sample.method, &sample.language] {
check_str("sample", s)?;
}
// Some samples are several lines (Nüshu, Carian).
if sample.text.len() > MAX_STR || sample.text.chars().any(|c| c.is_control() && c != '\n') {
return invalid(format!("the `{}` sample is too long or has control characters", short(script)));
}
}
for l in &raw.languages {
check_str("language", &l.id)?;
@@ -380,7 +398,7 @@ fn check(raw: Raw, origin: Origin<'_>) -> Result<Index, IndexError> {
repo: raw.repo,
git_ref: raw.git_ref,
};
Ok(Index::assemble(vec![(source, raw.languages, raw.scripts, families)], Vec::new()))
Ok(Index::assemble(vec![(source, raw.languages, raw.scripts, raw.samples, families)], Vec::new()))
}
/// The family folder in google/fonts: every file at `<ofl|apache|ufl>/<dir>/<file>`.
@@ -419,13 +437,20 @@ fn check_family(fam: &mut Family, ctx: &Ctx<'_>) -> Result<(), IndexError> {
if fam.files.is_empty() {
return invalid(format!("`{name}` has no files"));
}
let lists = [fam.categories.len(), fam.subsets.len(), fam.languages.len(), fam.scripts.len(), fam.files.len()];
let lists =
[fam.categories.len(), fam.subsets.len(), fam.languages.len(), fam.scripts.len(), fam.files.len(), fam.tags.len(), fam.reserved_names.len()];
if lists.iter().any(|&n| n > MAX_LIST) {
return invalid(format!("`{name}` has too many entries"));
}
for s in fam.categories.iter().chain(&fam.subsets).chain(&fam.scripts) {
check_str("category, subset or script", s)?;
}
for s in fam.tags.iter().chain(&fam.reserved_names).chain(&fam.sample_script).chain(&fam.copyright) {
check_str("tag, reserved name, sample script or copyright", s)?;
}
if fam.upstream.as_deref().is_some_and(|u| !is_source_url(u)) {
return invalid(format!("the upstream of `{name}` is not an https URL"));
}
if fam.languages.iter().any(|&i| i >= ctx.languages) {
return invalid(format!("`{name}` names a language the index doesn't have"));
}
@@ -463,6 +488,26 @@ fn check_family(fam: &mut Family, ctx: &Ctx<'_>) -> Result<(), IndexError> {
return invalid(format!("`{}` has a bad axis", short(&f.path)));
}
}
if (!f.instances.is_empty() && f.axes.is_empty()) || f.instances.len() > MAX_LIST || f.list_instance.is_some_and(|i| i >= f.instances.len()) {
return invalid(format!("`{}` has a bad list instance", short(&f.path)));
}
// Every instance has a coordinate for each axis and for no other.
for s in f.sample_script.iter().chain(&f.sample_text) {
check_str("sample script or text", s)?;
}
if f.sample_text.as_deref().is_some_and(|t| t.chars().count() > MAX_SAMPLE_CHARS) {
return invalid(format!("`{}` has a sample text over {MAX_SAMPLE_CHARS} characters", short(&f.path)));
}
for i in &f.instances {
check_str("instance name", &i.name)?;
if i.coordinates.len() != f.axes.len() || f.axes.iter().any(|a| !i.coordinates.contains_key(&a.tag)) {
return invalid(format!("`{}` has an instance without its axes", short(&f.path)));
}
let in_range = |a: &crate::index::Axis| i.coordinates.get(&a.tag).is_some_and(|c| c.is_finite() && (a.min..=a.max).contains(c));
if !f.axes.iter().all(in_range) {
return invalid(format!("`{}` has an instance outside its axes' ranges", short(&f.path)));
}
}
for ps in &f.postscript {
check_str("PostScript name", ps)?;
if ps.is_empty() {
@@ -472,22 +517,24 @@ fn check_family(fam: &mut Family, ctx: &Ctx<'_>) -> Result<(), IndexError> {
check_repo_ref(&f.path, f.repo.as_deref(), f.git_ref.as_deref())?;
fill(ctx.templates, &f.path, repo(f.repo.clone()).as_deref(), git_ref(f.git_ref.clone()).as_deref())?;
}
let beside = |path: &str| -> Result<(), IndexError> {
let beside = |what: &str, path: &str| -> Result<(), IndexError> {
if names.contains(&check_path(path)?.to_ascii_lowercase()) {
return invalid(format!("the licence of `{name}` has a font file's name"));
return invalid(format!("the {what} of `{name}` has a font file's name"));
}
Ok(())
};
if let Some(lf) = &fam.license_file {
beside(&lf.path)?;
// The licence and the NOTICE file are checked alike.
for (what, lf) in [("licence", &fam.license_file), ("notice", &fam.notice_file)] {
let Some(lf) = lf else { continue };
beside(what, &lf.path)?;
if !is_sha256(&lf.sha256) || lf.size == 0 || lf.size > MAX_LICENSE_BYTES {
return invalid(format!("the licence of `{name}` has a bad sha256 or size"));
return invalid(format!("the {what} of `{name}` has a bad sha256 or size"));
}
check_repo_ref(&lf.path, lf.repo.as_deref(), lf.git_ref.as_deref())?;
fill(ctx.templates, &lf.path, repo(lf.repo.clone()).as_deref(), git_ref(lf.git_ref.clone()).as_deref())?;
}
if let Some(lp) = &fam.license_path {
beside(lp)?;
beside("licence", lp)?;
if fam.license_file.is_none() {
fill(ctx.templates, lp, repo(None).as_deref(), git_ref(None).as_deref())?;
}
+212 -15
View File
@@ -6,6 +6,7 @@
//! settings.json the consent setting and the sources the user added
//! manifest.json what is installed
//! indexes/ the last indexes fetched: sources.json, one file per source
//! previews/ preview subsets from the preview service (WOFF2), a cache of at most 50 MB
//! <family dir>/ google/fonts' folder name, or <source>/<family>: the fonts and the licence
//! language-packs/ installed Language packs, one folder per locale (`crate::language_packs`)
//! language-packs.json which Language packs are installed, from which index entry
@@ -25,8 +26,11 @@ use serde::{Deserialize, Serialize};
use crate::UserSource;
use crate::http::{Cancel, Client, FetchError};
use crate::index::{Face, Family, FontFile, GOOGLE_FONTS, Index, IndexError, MAX_INDEX_BYTES, MAX_LICENSE_BYTES, SourceProblem, Unavailable};
use crate::index::{
Face, Family, FontFile, GOOGLE_FONTS, Index, IndexError, LicenseFile, MAX_INDEX_BYTES, MAX_LICENSE_BYTES, SourceProblem, Unavailable,
};
use crate::pin::IndexPin;
use crate::service::{LegalText, PREVIEW_SERVICE_ENV, PreviewServiceSource};
use crate::source::{is_source_url, safe_dir, safe_file_name, slug};
use crate::sources::{MAX_SOURCES_BYTES, SourceEntry, SourcesFile};
use crate::verify::{VerifyError, is_font, sha256_hex, verify_font};
@@ -40,6 +44,7 @@ use transaction::{Commit, merge_entry};
const SETTINGS: &str = "settings.json";
const MANIFEST: &str = "manifest.json";
pub(crate) const INDEX_CACHE: &str = "indexes";
const PREVIEWS: &str = "previews";
const SOURCES_CACHE: &str = "sources.json";
const STAGING: &str = ".staging";
const LOCK: &str = ".lock";
@@ -82,6 +87,9 @@ pub enum Error {
/// Not an https URL a source can be added from.
#[error("{0} is not an https URL")]
BadUrl(String),
/// Not a usable preview service address.
#[error("{0} is not an https URL, or an http URL to 127.0.0.1 or [::1]")]
BadServiceUrl(String),
/// No exact match in the index.
#[error(transparent)]
Unavailable(#[from] Unavailable),
@@ -184,12 +192,39 @@ fn google_fonts() -> String {
GOOGLE_FONTS.into()
}
#[derive(Clone, Default, Serialize, Deserialize)]
#[derive(Clone, Serialize, Deserialize)]
struct Settings {
#[serde(default)]
network: Network,
/// `None` until the user chooses. Files written before this field could be absent always
/// hold a value, so an `off` there counts as the user's choice.
#[serde(default, skip_serializing_if = "Option::is_none")]
network: Option<Network>,
#[serde(default)]
user_sources: Vec<UserSource>,
#[serde(default)]
preview_service: Option<String>,
#[serde(default = "on")]
previews: bool,
/// The file exists but couldn't be read or parsed.
#[serde(skip)]
unreadable: bool,
}
fn on() -> bool {
true
}
impl Default for Settings {
fn default() -> Self {
Self { network: None, user_sources: Vec::new(), preview_service: None, previews: true, unreadable: false }
}
}
impl Settings {
/// What a `settings.json` that can't be read or parsed stands for: the network off and no
/// preview service, not even the host's default. A write starts from these.
fn unreadable() -> Self {
Self { network: Some(Network::Off), unreadable: true, ..Self::default() }
}
}
/// Something [`FontStore::verify`] found wrong with an installed file.
@@ -203,6 +238,16 @@ pub struct Problem {
pub error: Option<VerifyError>,
}
/// A licence or NOTICE file's size and sha256, when the index has them. A format 1.0 index has
/// neither for the licence: the size cap is then the only check.
fn check_license(file: Option<&LicenseFile>, bytes: &[u8]) -> Result<(), VerifyError> {
match file {
Some(f) if bytes.len() as u64 != f.size => Err(VerifyError::Size { expected: f.size, actual: bytes.len() as u64 }),
Some(f) if sha256_hex(bytes) != f.sha256 => Err(VerifyError::Sha256),
_ => Ok(()),
}
}
/// The suite's font store.
///
/// Nothing here touches the network on its own: only [`FontStore::fetch_indexes`] and the installs
@@ -214,6 +259,14 @@ pub struct FontStore {
catalog: Option<Arc<Catalog>>,
pub(crate) pack_removal_cursor: AtomicUsize,
pub(crate) pack_removal_round_end: AtomicUsize,
/// The host's preview service, used while neither the environment nor the setting names one.
/// Never saved.
default_preview_service: Option<String>,
/// The host's network setting, used while the user hasn't chosen. Never saved.
default_network: Option<Network>,
/// Tests: stands in for the environment variable.
#[cfg(test)]
preview_env: Option<Option<String>>,
}
impl std::fmt::Debug for FontStore {
@@ -243,9 +296,47 @@ impl FontStore {
catalog: None,
pack_removal_cursor: AtomicUsize::new(0),
pack_removal_round_end: AtomicUsize::new(0),
default_preview_service: None,
default_network: None,
#[cfg(test)]
preview_env: None,
}
}
/// Tests: reads `env` instead of [`PREVIEW_SERVICE_ENV`].
#[cfg(test)]
pub(crate) fn with_preview_env(mut self, env: Option<&str>) -> Self {
self.preview_env = Some(env.map(str::to_string));
self
}
/// The download client. Clones share the preview service's down state, so a pool built on one
/// stops asking a service the store found unreachable, and the reverse.
pub fn client(&self) -> Client {
self.client.clone()
}
/// Uses `url` as the preview service while neither [`PREVIEW_SERVICE_ENV`] nor the user's
/// setting names one. The host's default is never written to `settings.json`, so clearing
/// the setting brings it back, and other apps sharing the store don't see it. An unusable
/// URL counts as none.
pub fn with_default_preview_service(mut self, url: &str) -> Self {
self.default_preview_service = normalize_service_url(url);
debug_assert!(self.default_preview_service.is_some(), "unusable preview service URL {url:?}");
self
}
/// Uses `network` while the user hasn't chosen (no saved choice in `settings.json`). The
/// host's default is never saved: the user's [`FontStore::enable_network`] or
/// [`FontStore::disable_network`] beats it from then on, and other apps sharing the store
/// don't see it. An agent's store ignores it, as an agent can never turn the network on.
pub fn with_default_network(mut self, network: Network) -> Self {
if self.caller == Caller::User {
self.default_network = Some(network);
}
self
}
/// Uses `client` for downloads (other timeouts).
pub fn with_client(mut self, client: Client) -> Self {
self.client = client;
@@ -264,6 +355,12 @@ impl FontStore {
&self.dir
}
/// The folder for the preview service's subsets, which craft-font-manager caches. The store
/// itself never reads or writes it.
pub fn previews_dir(&self) -> PathBuf {
self.dir.join(PREVIEWS)
}
/// Who drives this store.
pub fn caller(&self) -> Caller {
self.caller
@@ -317,7 +414,10 @@ impl FontStore {
for (i, file) in wanted.iter().enumerate() {
let mut on_bytes = |n: u64| progress(Progress { file: i, files: wanted.len(), done: done_before + n, total });
let check = |bytes: &[u8]| verify_font(file, bytes);
let bytes = self.fetch(&index.file_urls(family, file), file.size, file.file_name(), cancel, &mut on_bytes, &check)?;
let mut urls = self.mirror_urls(family, "files", &file.sha256);
let mirrors = urls.len();
urls.extend(index.file_urls(family, file));
let bytes = self.fetch(&urls, mirrors, file.size, file.file_name(), cancel, &mut on_bytes, &check)?;
done_before += file.size;
staged.push((file.file_name().to_string(), stage.write(file.file_name(), &bytes)?));
}
@@ -325,12 +425,12 @@ impl FontStore {
// A format 1.0 index has no size or sha256 for the licence: the size cap is the only
// check.
let max = family.license_file.as_ref().map_or(MAX_LICENSE_BYTES, |f| f.size);
let check = |bytes: &[u8]| match &family.license_file {
Some(f) if bytes.len() as u64 != f.size => Err(VerifyError::Size { expected: f.size, actual: bytes.len() as u64 }),
Some(f) if sha256_hex(bytes) != f.sha256 => Err(VerifyError::Sha256),
_ => Ok(()),
};
let bytes = self.fetch(&index.license_urls(family), max, name, cancel, &mut |_| {}, &check)?;
let check = |bytes: &[u8]| check_license(family.license_file.as_ref(), bytes);
// Without a sha256 there is no mirror address.
let mut urls = family.license_file.as_ref().map(|f| self.mirror_urls(family, "licences", &f.sha256)).unwrap_or_default();
let mirrors = urls.len();
urls.extend(index.license_urls(family));
let bytes = self.fetch(&urls, mirrors, max, name, cancel, &mut |_| {}, &check)?;
staged.push((name.to_string(), stage.write(name, &bytes)?));
}
if cancel.is_cancelled() {
@@ -358,10 +458,50 @@ impl FontStore {
result
}
/// Downloads from each URL in turn until one gives bytes that pass `check`.
/// The text of `family`'s licence or NOTICE file: the copy installed beside its fonts, else
/// downloaded and checked like an install's licence, from the preview service first.
/// `Ok(None)` when the family has no such file.
pub fn legal_text(&self, index: &Index, family: &Family, which: LegalText, cancel: &Cancel) -> Result<Option<String>, Error> {
let (file, name, urls) = match which {
LegalText::License => (family.license_file.as_ref(), family.license_file_name(), index.license_urls(family)),
LegalText::Notice => (family.notice_file.as_ref(), family.notice_file.as_ref().map(LicenseFile::file_name), index.notice_urls(family)),
};
let Some(name) = name else { return Ok(None) };
let max = file.map_or(MAX_LICENSE_BYTES, |f| f.size);
let text = |bytes: &[u8]| String::from_utf8_lossy(bytes).into_owned();
let installed = self.dir.join(family.dir()).join(name);
if std::fs::metadata(&installed).is_ok_and(|m| m.is_file() && m.len() <= max)
&& let Ok(bytes) = std::fs::read(&installed)
&& check_license(file, &bytes).is_ok()
{
return Ok(Some(text(&bytes)));
}
self.require_network()?;
let mut all = file.map(|f| self.mirror_urls(family, "licences", &f.sha256)).unwrap_or_default();
let mirrors = all.len();
all.extend(urls);
let bytes = self.fetch(&all, mirrors, max, name, cancel, &mut |_| {}, &|b| check_license(file, b))?;
Ok(Some(text(&bytes)))
}
/// The preview service's address for a file of `family` by its sha256; empty without a
/// service, and for a family the user's sources added: the service holds only the built-in
/// sources' files, and asking would tell it the file's hash.
fn mirror_urls(&self, family: &Family, kind: &str, sha256: &str) -> Vec<String> {
if !family.is_curated() {
return Vec::new();
}
self.preview_service().map(|base| format!("{base}/v1/{kind}/{sha256}")).into_iter().collect()
}
/// Downloads from each URL in turn until one gives bytes that pass `check`. The first
/// `mirrors` URLs come from the preview-service setting and may use loopback http; the rest
/// are https only.
#[allow(clippy::too_many_arguments)]
pub(crate) fn fetch(
&self,
urls: &[String],
mirrors: usize,
max: u64,
what: &str,
cancel: &Cancel,
@@ -369,14 +509,19 @@ impl FontStore {
check: &dyn Fn(&[u8]) -> Result<(), VerifyError>,
) -> Result<Vec<u8>, Error> {
let mut reasons = Vec::new();
// A rejection by an index URL is a corrupt file; a mirror's alone is one more failed source.
let mut rejected = None;
for url in urls {
match self.client.get(url, max, cancel, on_bytes) {
for (i, url) in urls.iter().enumerate() {
let got =
if i < mirrors { self.client.get_from_service(url, max, cancel, on_bytes) } else { self.client.get(url, max, cancel, on_bytes) };
match got {
Ok(bytes) => match check(&bytes) {
Ok(()) => return Ok(bytes),
Err(e) => {
reasons.push(format!("{}: {e}", host(url)));
rejected.get_or_insert(e);
if i >= mirrors {
rejected.get_or_insert(e);
}
}
},
Err(FetchError::Cancelled) => return Err(Error::Cancelled),
@@ -537,6 +682,58 @@ pub(crate) fn read_limited(path: &Path, max: u64) -> Option<Vec<u8>> {
std::fs::read(path).ok()
}
/// The environment value when set and not empty, else the setting; an unusable value counts as
/// unset.
#[cfg(test)]
pub(crate) fn resolve_preview_service(env: Option<&str>, setting: Option<&str>) -> Option<String> {
resolve_preview_source(env, setting, None).0
}
/// The service in effect and where it came from: the environment value when set and not empty
/// (alone: an unusable one means no service), else the setting when usable, else the host's
/// default.
pub(crate) fn resolve_preview_source(env: Option<&str>, setting: Option<&str>, default: Option<&str>) -> (Option<String>, PreviewServiceSource) {
let (url, source) = match env.map(str::trim).filter(|e| !e.is_empty()) {
Some(e) => (normalize_service_url(e), PreviewServiceSource::Env),
None => match setting.and_then(normalize_service_url) {
Some(url) => (Some(url), PreviewServiceSource::Saved),
None => (default.and_then(normalize_service_url), PreviewServiceSource::Default),
},
};
if url.is_some() { (url, source) } else { (None, PreviewServiceSource::None) }
}
/// The preview-service address `url` stands for: without a trailing slash, when it is an https URL,
/// or an http one for a loopback host, with no credentials, query or fragment. [`Error::BadServiceUrl`]
/// otherwise.
pub fn check_preview_service(url: &str) -> Result<String, Error> {
normalize_service_url(url).ok_or_else(|| Error::BadServiceUrl(url.trim().chars().take(200).collect()))
}
/// `url` without a trailing slash, when it is an https URL, or an http one for a loopback host,
/// with no credentials, query or fragment.
fn normalize_service_url(url: &str) -> Option<String> {
let url = url.trim().trim_end_matches('/');
if url.len() > 2000 || url.chars().any(|c| c.is_control() || c.is_whitespace() || c == '\\') {
return None;
}
let (https, rest) = match (url.strip_prefix("https://"), url.strip_prefix("http://")) {
(Some(r), _) => (true, r),
(None, Some(r)) => (false, r),
_ => return None,
};
let authority = rest.split('/').next().unwrap_or_default();
if authority.is_empty() || authority.contains('@') || url.contains(['?', '#']) {
return None;
}
let host = match authority.strip_prefix('[') {
Some(v6) => v6.split(']').next().unwrap_or_default(),
None => authority.split(':').next().unwrap_or_default(),
};
let loopback = matches!(host.to_ascii_lowercase().as_str(), "127.0.0.1" | "::1");
(https || loopback).then(|| url.to_string())
}
fn host(url: &str) -> &str {
url.split("://").nth(1).and_then(|r| r.split('/').next()).unwrap_or(url)
}
Loaded 100 of 544 files, more files were not shown because too many files have changed in this diff. Show more