diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 66897e207..01b258e23 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -69,7 +69,8 @@ workflows: '.github/workflows/menu.yml': - 'actions/checkout@v7.0.1' - 'dtolnay/rust-toolchain@stable' - '.github/workflows/nightly.yml': [] + '.github/workflows/nightly.yml': + - 'step-security/harden-runner@v2.22.4' '.github/workflows/pcraft-format.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' diff --git a/.github/workflows/crw.yml b/.github/workflows/crw.yml index 1d2b4f389..3e9b430d6 100644 --- a/.github/workflows/crw.yml +++ b/.github/workflows/crw.yml @@ -52,13 +52,22 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - name: Cache the CC0 sample files - uses: actions/cache@v6.1.0 + # Pull requests restore the entry main or next saved and never write their own: the same + # files saved once per pull request took a share of the 10 GB cache budget. + - name: Restore the CC0 sample files + id: samples + uses: actions/cache/restore@v6.1.0 with: path: ${{ runner.temp }}/crw-samples key: crw-samples-${{ hashFiles('crates/crw/tests/samples.json') }} - name: Fetch the pinned CC0 sample files (raw.pixls.us) run: python scripts/fetch-crw-samples.py "$RUNNER_TEMP/crw-samples" + - name: Save the CC0 sample files + if: github.event_name != 'pull_request' && steps.samples.outputs.cache-hit != 'true' + uses: actions/cache/save@v6.1.0 + with: + path: ${{ runner.temp }}/crw-samples + key: ${{ steps.samples.outputs.cache-primary-key }} - run: cargo test -p craft-crw --release --locked --lib -- integration::samples --nocapture env: CRAFT_CRW_SAMPLES: ${{ runner.temp }}/crw-samples diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index ed9d36127..d87302bfe 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -32,3 +32,27 @@ jobs: cache-key: photocraft-corpus cache-key-files: scripts/ci-test-inputs.sh command: cargo nextest run --workspace --all-features --locked --profile ci + + # Pull requests run the Workspace gate's Linux legs only, and pushes to next cancel each other's + # runs, so this starts one Workspace run on next a day that nothing cancels: 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 on next + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + run: gh workflow run workspace.yml --repo "$REPO" --ref next diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index c583402a5..988c94f91 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -16,19 +16,20 @@ permissions: contents: read concurrency: - # A pull request, and main, each have one group, so a newer push cancels the run it supersedes; - # the newest push's run still tests everything before it. Every other run (a release tag, a - # manual run, the scheduled run) gets a group of its own and is neither cancelled nor replaced - # while queued: a release run always finishes, and the scheduled run saves the caches. - group: workspace-${{ (github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main') && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' }} + # A pull request, main and next each have one group, so a newer push cancels the run it + # supersedes; the newest push's run still tests everything before it. Every other run (a release + # tag, a manual run, the scheduled run, nightly.yml's run on next) gets a group of its own and is + # neither cancelled nor replaced while queued: a release run always finishes, the scheduled run + # saves the caches, and next gets one complete macOS and Windows run a day. + group: workspace-${{ (github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'push' && github.ref == 'refs/heads/next') && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'push' && github.ref == 'refs/heads/next' }} jobs: # Whether this run needs the macOS and Windows legs, and which tests every leg runs - # (craft-common-actions' select-platforms). On a pull request the macOS and Windows legs run only - # when it can change platform behaviour: a crate with platform cfg code or one that depends on - # it, the build setup, or a file outside the crates. The tests are those of the crates a change - # reaches: the crates that own a changed file, the crates whose Cargo.toml declares a read of it + # (craft-common-actions' select-platforms). A pull request runs the Linux legs only, unless it + # has the full-ci label (see native-platforms); every other event runs the macOS and Windows legs + # too. The tests are those of the crates a change reaches: the crates that own a changed file, + # the crates whose Cargo.toml declares a read of it # (`[package.metadata.craft] reads`, which this job checks is complete), and every crate that # depends on those. The build setup, a crate's own Cargo.toml or a file outside the crates other # than documentation runs every test; documentation alone runs none. The full-ci label runs @@ -63,10 +64,13 @@ jobs: # 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 +78,8 @@ jobs: with: os: '["ubuntu-latest"]' cache-workspace-crates: true - cold-build: ${{ github.event.schedule == '17 0 * * *' }} + cache-save-on-dispatch: true + 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: | @@ -142,13 +147,14 @@ jobs: 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 - # 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"]' @@ -181,14 +187,15 @@ jobs: 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 +209,11 @@ jobs: env: GH_TOKEN: ${{ github.token }} REPO: ${{ github.repository }} + REF: ${{ github.ref }} run: | set -euo pipefail # `-rust---crates-----...`, newest first. - gh cache list --repo "$REPO" --ref refs/heads/main --limit 100 --sort created_at --order desc --json id,key \ + gh cache list --repo "$REPO" --ref "$REF" --limit 100 --sort created_at --order desc --json id,key \ --jq '.[] | "\(.id) \(.key)"' > "$RUNNER_TEMP/caches" declare -A kept while read -r id key; do diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 3d1ef7749..34e0bcd6f 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -12,9 +12,10 @@ author, source and license. Library code and original assets are under the repos | `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft contributors; generated by `craft_cms::synth::coated_cmyk` | [PhotoCraft `crates/cms`](https://github.com/storytold/photocraft/tree/b3222ee8e7e6bcb4799c37f904c595f20f9baf5e/crates/cms) | CC0-1.0 | | `crates/cms/profiles/craft-coated-fogra39.icc` | craft-libs contributors; generated by `crates/cms/tests/fogra39.rs` from the FOGRA39 data below | this repository | CC0-1.0 | | `crates/ppt-binary/tests/fixtures/old-talk.pps` | DeckCraft contributors; a one-slide PowerPoint 97-2003 show built from records by `crates/ppt-binary/src/tests.rs` (`the_pps_fixture_is_a_built_presentation`, with `CRAFT_WRITE_PPT_FIXTURE=1`); no PowerPoint involved | [storytold/deckcraft#1137](https://github.com/storytold/deckcraft/pull/1137) | CC0-1.0 | -| `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | -| `crates/font-store/index/indexes/google-fonts.json.gz` (unmodified) | craft-font-index contributors; generated from the METADATA.pb files of [google/fonts](https://github.com/google/fonts) at `45e3d5269e4a17d823f6d84470bc084dc5ae46f6` | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | -| `crates/font-store/index/indexes/noto.json.gz` (unmodified) | craft-font-index contributors; generated from [notofonts/notofonts.github.io](https://github.com/notofonts/notofonts.github.io) at `93fac8abebe6c7fed0c5b7d2456d8fa484fa146c` and [noto-cjk](https://github.com/notofonts/noto-cjk) releases | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | +| `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@995ef20](https://github.com/aiongg/craft-font-index/tree/995ef2000a0159d70da245e22cfa0797a0756ae8) | Apache-2.0 | +| `crates/font-store/index/indexes/google-fonts.json.gz` (unmodified) | craft-font-index contributors; generated from the METADATA.pb files of [google/fonts](https://github.com/google/fonts) at `45e3d5269e4a17d823f6d84470bc084dc5ae46f6` | [aiongg/craft-font-index@995ef20](https://github.com/aiongg/craft-font-index/tree/995ef2000a0159d70da245e22cfa0797a0756ae8) | Apache-2.0 | +| `crates/font-store/index/indexes/noto.json.gz` (unmodified) | craft-font-index contributors; generated from [notofonts/notofonts.github.io](https://github.com/notofonts/notofonts.github.io) at `93fac8abebe6c7fed0c5b7d2456d8fa484fa146c` and [noto-cjk](https://github.com/notofonts/noto-cjk) releases | [aiongg/craft-font-index@995ef20](https://github.com/aiongg/craft-font-index/tree/995ef2000a0159d70da245e22cfa0797a0756ae8) | Apache-2.0 | +| `crates/font-manager/tests/data/preview-vectors.json` (sample sentences) | Google Fonts `lang/` contributors; texts from the Universal Declaration of Human Rights via Eric Muller's UDHR in Unicode (translations' own terms not checked); the Iroha poem is public domain | [google/fonts `lang/`](https://github.com/google/fonts/tree/45e3d5269e4a17d823f6d84470bc084dc5ae46f6/lang) at `45e3d52` | Apache-2.0 | | `crates/cms/tests/data/FOGRA39.txt` (unmodified) | Fogra | [Fogra characterisation data](https://fogra.org/en/downloads/work-tools/characterisation-data), `FOGRA39_to_FOGRA60_v2.zip` | Fogra terms: free use and redistribution, unmodified, with Fogra identified as the source; "FOGRA39" identifies the reference data only and implies no certification, approval or endorsement by Fogra (full text in [NOTICE](NOTICE)) | | `vendor/linesweeper/tests/regression/`, `vendor/linesweeper/proptest-regressions/`, the `.snap` files under `vendor/linesweeper/src/` and the path data in `vendor/linesweeper/benches/painted_dreams.rs` (all unmodified; hashes in `vendor/linesweeper/SOURCE.json`) | As published in the package, whose manifest names Joe Neeman as author and records no other source | [linesweeper 0.5.0](https://crates.io/crates/linesweeper/0.5.0) | MIT OR Apache-2.0 (the package's `license` field) | | `crates/i18n/data/collation.postcard` | Unicode, Inc. (ICU 78.1 collation data, CLDR 48.2.1); generated by `crates/i18n/data/generate-collation.sh` | [ICU](https://github.com/unicode-org/icu/releases/tag/release-78.1rc) | Unicode-3.0 | @@ -189,3 +190,13 @@ Retained XFDF source contributors (move-aware blame): Brandon Thomas, Marco Arnu `crates/media-source/src/y4m.rs` adapts the in-house [FilmCraft Y4mSource at 3f137a7e](https://github.com/storytold/filmcraft/blob/3f137a7ed420cac79b32145f5243b7f98b31f71c/crates/codecs/src/y4m.rs), MIT OR Apache-2.0. Original playback by Lloyd Nicholson ([FilmCraft #1303](https://github.com/storytold/filmcraft/pull/1303)); shared-parser integration by Dylan M. Taylor ([FilmCraft #4862](https://github.com/storytold/filmcraft/pull/4862)). The adaptation changes source/frame types and declines payloads above the shared media allocation ceiling before playback. The parser and its previous header-safety work remain in `craft-y4m` ([craft-libs #933](https://github.com/storytold/craft-libs/pull/933)). `crates/media-source/tests/it/y4m.rs` contains original repository-authored synthetic test data under MIT OR Apache-2.0: literal YUV samples and a sparse reader that reports only the length of an oversized frame. It does not use external media or decoder output. + +## Material graph runtime + +`crates/material-graph` moves the graph text format, parser, evaluator, pixel-program compiler, and tests from +[TextureCraft's SPP importer at 22a37c29](https://github.com/vangel76/texturecraft/tree/22a37c29e98d8e6fc8c5e611e22f0ab95b83243d/crates/graph) +(MIT OR Apache-2.0). [xilefenko introduced this runtime in TextureCraft](https://github.com/vangel76/texturecraft/commit/af862722be61bd7050ac782ec57a5e8938a5b017), +adapting code from [PiJellyPin's MaterialCraft](https://github.com/PiJellyPin/MaterialCraft). See the crate's +`NOTICE` for the original attribution. This extraction retains vangel76's subsequent evaluator and GPU work. +The format reference and tests are from the same TextureCraft source. The tests' numerical rule tables document +their provenance in their headers. diff --git a/Cargo.lock b/Cargo.lock index 27b9e695a..96d0cba48 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1846,6 +1846,7 @@ dependencies = [ "craft-lottie", "craft-macho", "craft-markdown", + "craft-material-graph", "craft-materialx", "craft-math", "craft-mcmat", @@ -2754,7 +2755,8 @@ dependencies = [ "epaint_default_fonts", "log", "serde", - "skrifa 0.44.0", + "serde_json", + "skrifa 0.47.0", ] [[package]] @@ -2776,6 +2778,7 @@ dependencies = [ "toml", "ureq", "write-fonts 0.54.1", + "wuff", ] [[package]] @@ -3229,6 +3232,14 @@ dependencies = [ "craft-wordmodel", ] +[[package]] +name = "craft-material-graph" +version = "0.1.0" +dependencies = [ + "libm", + "rayon", +] + [[package]] name = "craft-materialx" version = "0.1.0" @@ -4345,6 +4356,7 @@ name = "craft-ui-canvas" version = "0.1.0" dependencies = [ "craft-behavior", + "craft-host", "craft-i18n", "craft-keymap", "craft-theme", @@ -4352,6 +4364,7 @@ dependencies = [ "craft-ui-macros", "craft-ui-panels", "craft-ui-test-kit", + "craft-window", "egui", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 9e861a40b..2f081aca2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -170,6 +170,7 @@ craft-math = { path = "crates/math" } craft-media = { path = "crates/media", default-features = false } craft-media-source = { path = "crates/media-source" } craft-materialx = { path = "crates/materialx" } +craft-material-graph = { path = "crates/material-graph" } craft-media-testkit = { path = "crates/media-testkit" } craft-midi = { path = "crates/midi" } craft-sf2 = { path = "crates/sf2" } diff --git a/crates/aaf/src/aaf.rs b/crates/aaf/src/aaf.rs index 7ea67f4ec..f7a061ccb 100644 --- a/crates/aaf/src/aaf.rs +++ b/crates/aaf/src/aaf.rs @@ -37,6 +37,7 @@ //! name), `FilmCraft Frame Size` and `FilmCraft Audio Sample Rate` (on the composition). mod ids; +pub mod linked_audio; pub mod properties; mod read; pub(crate) mod store; diff --git a/crates/aaf/src/aaf/linked_audio.rs b/crates/aaf/src/aaf/linked_audio.rs new file mode 100644 index 000000000..7fd48f9a7 --- /dev/null +++ b/crates/aaf/src/aaf/linked_audio.rs @@ -0,0 +1,129 @@ +//! WAV/PCM FileDescriptor metadata, without loading a SourceMob or touching its locators. + +use super::ids::{cls, pid}; + +/// The two audio descriptor classes commonly attached to an external WAV source. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DescriptorKind { + /// A WAVEDescriptor (`.wav` with a RIFF header). + Wave, + /// A PCMDescriptor (raw PCM samples). + Pcm, +} + +impl DescriptorKind { + /// Classify a compound-file storage's CLSID in AAF on-disk AUID byte order + /// (little-endian GUID fields, not RFC 4122/network order). + pub fn from_auid_le(class: [u8; 16]) -> Option { + match class { + cls::WAVE_DESCRIPTOR => Some(Self::Wave), + cls::PCM_DESCRIPTOR => Some(Self::Pcm), + _ => None, + } + } +} + +/// One property from an already framed and caller-validated object. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DescriptorProperty<'a> { + /// The object has no such property. + Missing, + /// The property is stored in a form other than a plain data value. + OtherForm, + /// The property's raw value bytes. + Data(&'a [u8]), +} + +/// Why a descriptor field is unavailable. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DescriptorFieldError { + /// The descriptor has no such property. + Missing, + /// The property is stored in a form other than a plain data value. + OtherForm, + /// The value is shorter than the field's type. + Truncated, +} + +/// A lazy descriptor view over a caller's property store. This neither opens +/// the media file nor determines whether the AAF source is external. +pub struct AudioFileDescriptor { + kind: DescriptorKind, + property: F, +} + +impl<'a, F: Fn(u16) -> DescriptorProperty<'a>> AudioFileDescriptor { + /// Supply the property view for this class; the descriptor chooses AAF property IDs. + pub fn new(kind: DescriptorKind, property: F) -> Self { + Self { kind, property } + } + + /// `FileDescriptor::SampleRate` as the signed numerator and denominator on + /// the wire. The caller's rational policy (including zero) is not applied. + pub fn sample_rate(&self) -> Result<(i32, i32), DescriptorFieldError> { + let [a, b, c, d, e, f, g, h] = self.bytes(pid::SAMPLE_RATE)?; + Ok((i32::from_le_bytes([a, b, c, d]), i32::from_le_bytes([e, f, g, h]))) + } + + /// `FileDescriptor::Length` in sample-rate units, before validating clip ranges. + pub fn length(&self) -> Result { + self.bytes(pid::FILE_LENGTH).map(i64::from_le_bytes) + } + + /// `SoundDescriptor::Channels` for a PCM descriptor. A WAVEDescriptor has + /// no such declared count here; an absent PCM field is also left to the caller. + pub fn pcm_channels(&self) -> Result, DescriptorFieldError> { + if self.kind == DescriptorKind::Wave { + return Ok(None); + } + match self.bytes(pid::CHANNELS) { + Ok(bytes) => Ok(Some(u32::from_le_bytes(bytes))), + Err(DescriptorFieldError::Missing) => Ok(None), + Err(err) => Err(err), + } + } + + fn bytes(&self, pid: u16) -> Result<[u8; N], DescriptorFieldError> { + match (self.property)(pid) { + DescriptorProperty::Data(data) => data.first_chunk().copied().ok_or(DescriptorFieldError::Truncated), + DescriptorProperty::Missing => Err(DescriptorFieldError::Missing), + DescriptorProperty::OtherForm => Err(DescriptorFieldError::OtherForm), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn descriptor_class_and_little_endian_fields_are_typed() { + assert_eq!(DescriptorKind::from_auid_le([1, 1, 1, 13, 1, 1, 0, 0x48, 6, 14, 43, 52, 2, 6, 1, 1]), Some(DescriptorKind::Pcm)); + assert_eq!(DescriptorKind::from_auid_le(cls::WAVE_DESCRIPTOR), Some(DescriptorKind::Wave)); + assert_eq!(DescriptorKind::from_auid_le(cls::CDCI_DESCRIPTOR), None); + let file = AudioFileDescriptor::new(DescriptorKind::Pcm, |tag| match tag { + pid::SAMPLE_RATE => DescriptorProperty::Data(&[0x80, 0xbb, 0, 0, 1, 0, 0, 0]), + pid::FILE_LENGTH => DescriptorProperty::Data(&[2, 1, 0, 0, 0, 0, 0, 0, 99]), + pid::CHANNELS => DescriptorProperty::Data(&[2, 0, 0, 0]), + _ => DescriptorProperty::Missing, + }); + assert_eq!(file.sample_rate(), Ok((48000, 1))); + assert_eq!(file.length(), Ok(258)); + assert_eq!(file.pcm_channels(), Ok(Some(2))); + } + + #[test] + fn descriptor_fields_are_lazy_and_distinguish_missing_form_and_short_data() { + let wave = AudioFileDescriptor::new(DescriptorKind::Wave, |tag| match tag { + pid::SAMPLE_RATE => DescriptorProperty::OtherForm, + pid::FILE_LENGTH => DescriptorProperty::Data(&[0; 7]), + _ => panic!("unexpected field read"), + }); + assert_eq!(wave.pcm_channels(), Ok(None)); + assert_eq!(wave.sample_rate(), Err(DescriptorFieldError::OtherForm)); + assert_eq!(wave.length(), Err(DescriptorFieldError::Truncated)); + let pcm = AudioFileDescriptor::new(DescriptorKind::Pcm, |_| DescriptorProperty::Missing); + assert_eq!(pcm.pcm_channels(), Ok(None)); + assert_eq!(pcm.sample_rate(), Err(DescriptorFieldError::Missing)); + } +} diff --git a/crates/android-res/src/arsc.rs b/crates/android-res/src/arsc.rs index 79a029625..5ef10798e 100644 --- a/crates/android-res/src/arsc.rs +++ b/crates/android-res/src/arsc.rs @@ -3,7 +3,7 @@ //! orientation, SDK level…). Simple and complex (bag) entries, sparse and 16-bit offset tables. use crate::Error; -use crate::axml::{ResValue, StringPool, chunk}; +use crate::axml::{MAX_RETAINED_VALUE_BYTES, ResValue, StringPool, ValueBudget, chunk, report_partial_string_pool}; use crate::bytes::Reader; use serde::Serialize; @@ -21,14 +21,18 @@ const MAX_BAG: usize = 4096; pub struct Limits { /// Most entries decoded across all types and configurations. pub max_entries: usize, + /// Most bytes retained in formatted simple-entry and bag values. + pub max_value_bytes: usize, } impl Default for Limits { fn default() -> Self { - Limits { max_entries: 2_000_000 } + Limits { max_entries: 2_000_000, max_value_bytes: MAX_RETAINED_VALUE_BYTES } } } +const VALUE_BUDGET_WARNING: &str = "resource value budget reached; remaining values were omitted"; + #[derive(Debug, Clone, PartialEq, Serialize)] pub struct TypeInfo { pub id: u8, @@ -300,30 +304,32 @@ pub fn parse(data: &[u8], limits: Limits) -> Result { let r = Reader::new(data); let mut table = Table::default(); let mut global = StringPool::default(); + let mut value_budget = ValueBudget::new(limits.max_value_bytes); let mut pos = h; while pos < size { let Some((ct, _ch, cs)) = chunk(&r, pos) else { + table.truncated = true; table.warnings.push(format!("unreadable chunk at offset {pos}")); break; }; match ct { crate::axml::RES_STRING_POOL => match StringPool::parse(data, pos) { Ok(p) => { - if p.strings.len() < p.declared { - table.truncated = true; - table.warnings.push(format!("global string pool was capped at {} of {} strings", p.strings.len(), p.declared)); - } + report_partial_string_pool(&p, "global string pool", &mut table.truncated, &mut table.warnings); table.global_strings = p.declared; global = p; } - Err(e) => table.warnings.push(format!("global string pool: {e}")), + Err(e) => { + table.truncated = true; + table.warnings.push(format!("global string pool: {e}")); + } }, RES_PACKAGE => { if table.packages.len() >= MAX_PACKAGES { table.truncated = true; table.warnings.push("too many packages; the rest were skipped".into()); } else { - parse_package(data, pos, cs, &global, &mut table, limits); + parse_package(data, pos, cs, &global, &mut table, limits, &mut value_budget); } } _ => {} @@ -336,14 +342,16 @@ pub fn parse(data: &[u8], limits: Limits) -> Result { Ok(table) } -fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: &mut Table, limits: Limits) { +fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: &mut Table, limits: Limits, value_budget: &mut ValueBudget) { let Some(data) = pos.checked_add(cs).and_then(|end| data.get(..end)) else { + table.truncated = true; table.warnings.push("package runs past its resource table".into()); return; }; let r = Reader::new(data); let hsize = usize::from(r.u16_le(pos + 2).unwrap_or(0)); if hsize < 284 { + table.truncated = true; table.warnings.push(format!("package at offset {pos}: incomplete header")); return; } @@ -365,22 +373,17 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: return StringPool::default(); } let Some(start) = pos.checked_add(offset).filter(|&start| offset >= hsize && start < end) else { + table.truncated = true; table.warnings.push(format!("package {name}: {label} string pool is outside its payload")); return StringPool::default(); }; match StringPool::parse(data, start) { Ok(pool) => { - if pool.strings.len() < pool.declared { - table.truncated = true; - table.warnings.push(format!( - "package {name}: {label} string pool was capped at {} of {} strings", - pool.strings.len(), - pool.declared - )); - } + report_partial_string_pool(&pool, &format!("package {name}: {label} string pool"), &mut table.truncated, &mut table.warnings); pool } Err(error) => { + table.truncated = true; table.warnings.push(format!("package {name}: {label} string pool: {error}")); StringPool::default() } @@ -393,12 +396,14 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: let mut c = pos.saturating_add(hsize.max(8)); while c < end { let Some((ct, ch, sz)) = chunk(&r, c) else { + table.truncated = true; table.warnings.push(format!("package {name}: unreadable chunk at offset {c}")); break; }; // Each child was checked against its package; reads within it must also stop before // the next sibling, including fixed-width library records and bag headers. let Some(child) = data.get(..c.saturating_add(sz)) else { + table.truncated = true; table.warnings.push(format!("package {name}: child chunk runs past its package")); break; }; @@ -437,7 +442,7 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: } } } - parse_type(&r, c, (ch, sz), (cfg, locale), &p, tid, global, table, limits); + parse_type(&r, c, (ch, sz), (cfg, locale), &p, tid, global, table, limits, value_budget); } (RES_TYPE_SPEC | RES_TYPE, None) if ch >= 16 => { table.truncated = true; @@ -449,6 +454,9 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: if n > available { table.warnings.push(format!("package {name}: library records run past their chunk")); } + if n > available.min(256) { + table.truncated = true; + } for i in 0..n.min(256).min(available) { let e = c + ch + i * 260; if let Some(lid) = r.u32_le(e) { @@ -457,6 +465,7 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: } } (RES_TYPE_SPEC | RES_TYPE | RES_LIBRARY, _) => { + table.truncated = true; table.warnings.push(format!("package {name}: incomplete chunk header at offset {c}")); } _ => {} @@ -480,6 +489,7 @@ fn parse_type( global: &StringPool, table: &mut Table, limits: Limits, + value_budget: &mut ValueBudget, ) { let tid = r.u8(c + 8).unwrap_or(0); let flags = r.u8(c + 9).unwrap_or(0); @@ -493,10 +503,12 @@ fn parse_type( let mut slots: Vec<(u32, usize)> = Vec::new(); let table_bytes = if sparse || off16 { count.saturating_mul(if sparse { 4 } else { 2 }) } else { count.saturating_mul(4) }; if c.saturating_add(ch).saturating_add(table_bytes) > end { + table.truncated = true; table.warnings.push(format!("{tname} ({cfg}): entry table runs past its chunk")); return; } if count != 0 && (entries_start < ch.saturating_add(table_bytes) || entries_start > sz) { + table.truncated = true; table.warnings.push(format!("{tname} ({cfg}): invalid entry data start")); return; } @@ -517,15 +529,16 @@ fn parse_type( } } } + let mut skipped = 0usize; for (idx, o) in slots { if table.entries.len() >= limits.max_entries { table.truncated = true; - return; + break; } - let Some(e) = c.checked_add(entries_start).and_then(|x| x.checked_add(o)) else { continue }; - if e.saturating_add(8) > end { + let Some(e) = c.checked_add(entries_start).and_then(|x| x.checked_add(o)).filter(|e| e.saturating_add(8) <= end) else { + skipped += 1; continue; - } + }; let esize = usize::from(r.u16_le(e).unwrap_or(0)); let eflags = r.u16_le(e + 2).unwrap_or(0); let id = (p.id << 24) | (u32::from(type_id) << 16) | (idx & 0xffff); @@ -546,7 +559,7 @@ fn parse_type( // Compact entry: key index in the size field, type in the high byte of flags. entry.key = p.keys.get(u32::from(r.u16_le(e).unwrap_or(0))).unwrap_or("").to_string(); let v = ResValue { data_type: (eflags >> 8) as u8, data: r.u32_le(e + 4).unwrap_or(0) }; - entry.value = Some(v.format(global)); + entry.value = value_budget.take(v.format(global), &mut table.truncated, &mut table.warnings, VALUE_BUDGET_WARNING); entry.value_type = Some(v.type_name()); entry.raw = Some(v); } else { @@ -579,21 +592,30 @@ fn parse_type( } let name = r.u32_le(m).unwrap_or(0); let v = ResValue { data_type: r.u8(m + 7).unwrap_or(0), data: r.u32_le(m + 8).unwrap_or(0) }; - entry.bag.push(BagItem { name: format!("@{name:#010x}"), value: v.format(global), value_type: v.type_name() }); + let value = + value_budget.take(v.format(global), &mut table.truncated, &mut table.warnings, VALUE_BUDGET_WARNING).unwrap_or_default(); + entry.bag.push(BagItem { name: format!("@{name:#010x}"), value, value_type: v.type_name() }); m += 12; } } else { let v_at = e.saturating_add(esize.max(8)); if v_at.saturating_add(8) <= end { let v = ResValue { data_type: r.u8(v_at + 3).unwrap_or(0), data: r.u32_le(v_at + 4).unwrap_or(0) }; - entry.value = Some(v.format(global)); + entry.value = value_budget.take(v.format(global), &mut table.truncated, &mut table.warnings, VALUE_BUDGET_WARNING); entry.value_type = Some(v.type_name()); entry.raw = Some(v); + } else { + table.truncated = true; + table.warnings.push(format!("{tname} ({cfg}): incomplete value")); } } } table.entries.push(entry); } + if skipped > 0 { + table.truncated = true; + table.warnings.push(format!("{tname} ({cfg}): {skipped} entries run past their chunk")); + } } impl Table { @@ -642,6 +664,30 @@ mod tests { assert_eq!(style.config, "night-xhdpi-v21"); } + #[test] + fn skipped_type_chunks_and_entries_mark_the_table_partial() { + let bytes = fx::resources_arsc(); + // The French type chunk: RES_TYPE, an 84-byte header, and "fr" in its configuration. + let fr = (0..bytes.len() - 30).find(|&i| bytes[i..i + 4] == [0x01, 0x02, 84, 0] && &bytes[i + 28..i + 30] == b"fr").unwrap(); + let corrupt = |at: usize, value: u32| { + let mut b = bytes.clone(); + b[at..at + 4].copy_from_slice(&value.to_le_bytes()); + parse(&b, Limits::default()).unwrap() + }; + for (what, t) in [ + ("entry table past its chunk", corrupt(fr + 12, 1000)), + ("invalid entry data start", corrupt(fr + 16, 0xffff)), + ("an entry past its chunk", corrupt(fr + 84, 0x1000)), + // The second entry's header fits, but its value runs past the chunk. + ("a value past its chunk", corrupt(fr + 88, 24)), + ] { + let french = t.entries.iter().filter(|e| e.locale == "fr" && e.value.is_some()).count(); + assert!(french < 2, "{what}: the corruption should lose a French value"); + assert!(t.truncated, "{what}: lost content must mark the table partial"); + assert!(!t.warnings.is_empty(), "{what}: lost content must be reported"); + } + } + #[test] fn distinct_locale_scripts_and_variants_keep_separate_keys() { let mut cfg = [0u8; 64]; @@ -674,4 +720,162 @@ mod tests { assert_eq!(q, "es-rMX-land"); assert_eq!(l, "es-rMX"); } + + fn le_u16(v: &mut Vec, x: u16) { + v.extend_from_slice(&x.to_le_bytes()); + } + + fn le_u32(v: &mut Vec, x: u32) { + v.extend_from_slice(&x.to_le_bytes()); + } + + fn type_spec(id: u8, entries: u32) -> Vec { + let mut c = Vec::new(); + le_u16(&mut c, 0x0202); + le_u16(&mut c, 16); + le_u32(&mut c, 16 + 4 * entries); + c.push(id); + c.push(0); + le_u16(&mut c, 0); + le_u32(&mut c, entries); + for _ in 0..entries { + le_u32(&mut c, 0); + } + c + } + + fn type_chunk(id: u8, entries: &[Vec]) -> Vec { + let mut cfg = vec![0u8; 64]; + cfg[0] = 64; + let header = 20 + cfg.len(); + let start = header + 4 * entries.len(); + let mut body = Vec::new(); + let mut offs = Vec::new(); + for e in entries { + offs.push(body.len() as u32); + body.extend_from_slice(e); + } + let mut c = Vec::new(); + le_u16(&mut c, 0x0201); + le_u16(&mut c, header as u16); + le_u32(&mut c, (start + body.len()) as u32); + c.push(id); + c.push(0); + le_u16(&mut c, 0); + le_u32(&mut c, entries.len() as u32); + le_u32(&mut c, start as u32); + c.extend_from_slice(&cfg); + for o in offs { + le_u32(&mut c, o); + } + c.extend(body); + c + } + + fn table_with_entries(pool: &[&str], type_name: &str, keys: &[&str], entries: &[Vec]) -> Vec { + let global = fx::string_pool(pool, true); + let types = fx::string_pool(&[type_name], false); + let key_pool = fx::string_pool(keys, false); + let mut chunks = type_spec(1, entries.len() as u32); + chunks.extend(type_chunk(1, entries)); + let header = 288usize; + let mut pkg = Vec::new(); + le_u16(&mut pkg, 0x0200); + le_u16(&mut pkg, header as u16); + le_u32(&mut pkg, (header + types.len() + key_pool.len() + chunks.len()) as u32); + le_u32(&mut pkg, 0x7f); + pkg.extend(vec![0u8; 256]); + le_u32(&mut pkg, header as u32); + le_u32(&mut pkg, 1); + le_u32(&mut pkg, (header + types.len()) as u32); + le_u32(&mut pkg, keys.len() as u32); + le_u32(&mut pkg, 0); + pkg.extend(types); + pkg.extend(key_pool); + pkg.extend(chunks); + let mut out = Vec::new(); + le_u16(&mut out, 0x0002); + le_u16(&mut out, 12); + le_u32(&mut out, (12 + global.len() + pkg.len()) as u32); + le_u32(&mut out, 1); + out.extend(global); + out.extend(pkg); + out + } + + fn simple_string_entry(key: u32, pool_index: u32) -> Vec { + let mut e = Vec::new(); + le_u16(&mut e, 8); + le_u16(&mut e, 0); + le_u32(&mut e, key); + le_u16(&mut e, 8); + e.push(0); + e.push(0x03); + le_u32(&mut e, pool_index); + e + } + + fn compact_string_entry(key: u16, pool_index: u32) -> Vec { + let mut e = Vec::new(); + le_u16(&mut e, key); + le_u16(&mut e, 0x0308); + le_u32(&mut e, pool_index); + e + } + + fn bag_string_entry(key: u32, pool_indices: &[u32]) -> Vec { + let mut e = Vec::new(); + le_u16(&mut e, 16); + le_u16(&mut e, 1); + le_u32(&mut e, key); + le_u32(&mut e, 0); + le_u32(&mut e, pool_indices.len() as u32); + for (i, idx) in pool_indices.iter().enumerate() { + le_u32(&mut e, 0x0101_0000 + i as u32); + le_u16(&mut e, 8); + e.push(0); + e.push(0x03); + le_u32(&mut e, *idx); + } + e + } + + #[test] + fn value_budget_omits_long_copies_and_keeps_a_later_short_value() { + let long = "x".repeat(16); + let tight = Limits { max_value_bytes: 20, ..Limits::default() }; + let keys = ["a", "b", "c"]; + + let simple = + table_with_entries(&[&long, "ok"], "string", &keys, &[simple_string_entry(0, 0), simple_string_entry(1, 0), simple_string_entry(2, 1)]); + let complete = parse(&simple, Limits::default()).unwrap(); + assert!(!complete.truncated, "{:?}", complete.warnings); + assert_eq!(complete.entries.iter().map(|e| e.value.as_deref()).collect::>(), [Some(long.as_str()), Some(long.as_str()), Some("ok")]); + + let partial = parse(&simple, tight).unwrap(); + assert!(partial.truncated); + assert!(partial.warnings.iter().any(|w| w.contains("value budget")), "{:?}", partial.warnings); + assert_eq!(partial.entries.iter().map(|e| e.value.as_deref()).collect::>(), [Some(long.as_str()), None, Some("ok")]); + + let compact = table_with_entries( + &[&long, "ok"], + "string", + &keys, + &[compact_string_entry(0, 0), compact_string_entry(1, 0), compact_string_entry(2, 1)], + ); + let partial = parse(&compact, tight).unwrap(); + assert!(partial.truncated); + assert!(partial.warnings.iter().any(|w| w.contains("value budget")), "{:?}", partial.warnings); + assert_eq!(partial.entries.iter().map(|e| e.value.as_deref()).collect::>(), [Some(long.as_str()), None, Some("ok")]); + + let bag = table_with_entries(&[&long, "ok"], "style", &["theme"], &[bag_string_entry(0, &[0, 0, 1])]); + let complete = parse(&bag, Limits::default()).unwrap(); + assert!(!complete.truncated, "{:?}", complete.warnings); + assert_eq!(complete.entries[0].bag.iter().map(|i| i.value.as_str()).collect::>(), [long.as_str(), long.as_str(), "ok"]); + + let partial = parse(&bag, tight).unwrap(); + assert!(partial.truncated); + assert!(partial.warnings.iter().any(|w| w.contains("value budget")), "{:?}", partial.warnings); + assert_eq!(partial.entries[0].bag.iter().map(|i| i.value.as_str()).collect::>(), [long.as_str(), "", "ok"]); + } } diff --git a/crates/android-res/src/axml.rs b/crates/android-res/src/axml.rs index 3aea1f7ff..3525e0434 100644 --- a/crates/android-res/src/axml.rs +++ b/crates/android-res/src/axml.rs @@ -20,8 +20,10 @@ const XML_RESOURCE_MAP: u16 = 0x0180; const MAX_STRINGS: usize = 1_000_000; /// Longest string kept (characters). const MAX_STRING: usize = 64 * 1024; +/// Default budget for copied resource and XML values, and the base string-pool byte cap. +pub(crate) const MAX_RETAINED_VALUE_BYTES: usize = 64 << 20; /// Base budget for decoded string bytes; larger chunks allow at most three times their size. -const BASE_POOL_BYTES: usize = 64 << 20; +const BASE_POOL_BYTES: usize = MAX_RETAINED_VALUE_BYTES; /// Most extra UTF-8 length candidates examined across one string pool. const MAX_RECOVERY_PROBES: usize = 65_536; /// Most XML nodes decoded. @@ -54,6 +56,8 @@ pub struct StringPool { pub utf8: bool, /// Strings the pool declared (may exceed `strings.len()` when capped). pub declared: usize, + /// Entries left empty because the UTF-8 recovery probe budget ran out. + pub recovery_omitted: usize, } impl StringPool { @@ -104,12 +108,13 @@ impl StringPool { let strings_reader = Reader::new(string_bytes); let mut strings = Vec::with_capacity(count.min(MAX_STRINGS).min(65_536)); let mut bytes_left = BASE_POOL_BYTES.max(size.saturating_mul(3)); + let mut recovery_omitted = 0; for i in 0..count.min(MAX_STRINGS) { let at = r.u32_le(hdr + i * 4).ok_or_else(|| Error::Truncated("string offsets".into()))? as usize; let s = if at >= string_bytes.len() { None } else if utf8 { - utf8_string(&strings_reader, at, string_bytes.len(), recovery_left) + utf8_string(&strings_reader, at, string_bytes.len(), recovery_left, &mut recovery_omitted) } else { utf16_string(&strings_reader, at, string_bytes.len()) }; @@ -120,7 +125,7 @@ impl StringPool { bytes_left -= s.len(); strings.push(s); } - Ok(StringPool { strings, utf8, declared: count }) + Ok(StringPool { strings, utf8, declared: count, recovery_omitted }) } } @@ -134,7 +139,7 @@ fn utf8_len(r: &Reader<'_>, at: usize) -> Option<(usize, usize)> { } } -fn utf8_string(r: &Reader<'_>, at: usize, end: usize, recovery_left: &mut usize) -> Option { +fn utf8_string(r: &Reader<'_>, at: usize, end: usize, recovery_left: &mut usize, recovery_omitted: &mut usize) -> Option { let (_chars, n1) = utf8_len(r, at)?; let (mut bytes, n2) = utf8_len(r, at.checked_add(n1)?)?; let start = at.checked_add(n1 + n2)?; @@ -146,7 +151,11 @@ fn utf8_string(r: &Reader<'_>, at: usize, end: usize, recovery_left: &mut usize) } // The declared candidate costs one read per entry, already bounded by MAX_STRINGS. if bytes >= 0x8000 { - *recovery_left = recovery_left.checked_sub(1)?; + if *recovery_left == 0 { + *recovery_omitted += 1; + return None; + } + *recovery_left -= 1; } if r.u8(terminator)? == 0 { break; @@ -173,6 +182,56 @@ fn utf16_string(r: &Reader<'_>, at: usize, end: usize) -> Option { Some(String::from_utf16_lossy(&units)) } +/// Record that a string pool was capped or omitted recovery entries. +pub(crate) fn report_partial_string_pool(pool: &StringPool, prefix: &str, truncated: &mut bool, warnings: &mut Vec) { + if pool.strings.len() < pool.declared { + *truncated = true; + warnings.push(format!("{prefix} was capped at {} of {} strings", pool.strings.len(), pool.declared)); + } + if pool.recovery_omitted > 0 { + *truncated = true; + warnings.push(format!("{prefix} omitted {} strings after the UTF-8 recovery budget was exhausted", pool.recovery_omitted)); + } +} + +/// Charge `value` against a retained-byte budget. When it does not fit, report truncation once +/// and return `None`, so a later shorter value can still be kept. +pub(crate) fn retain_value( + left: &mut usize, + value: String, + truncated: &mut bool, + warned: &mut bool, + warnings: &mut Vec, + warning: &str, +) -> Option { + if value.len() > *left { + if !*warned { + warnings.push(warning.to_string()); + *warned = true; + } + *truncated = true; + None + } else { + *left -= value.len(); + Some(value) + } +} + +pub(crate) struct ValueBudget { + left: usize, + warned: bool, +} + +impl ValueBudget { + pub(crate) fn new(max_bytes: usize) -> Self { + Self { left: max_bytes, warned: false } + } + + pub(crate) fn take(&mut self, value: String, truncated: &mut bool, warnings: &mut Vec, warning: &str) -> Option { + retain_value(&mut self.left, value, truncated, &mut self.warned, warnings, warning) + } +} + /// A typed value (`Res_value`): data type and 32-bit data. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub struct ResValue { @@ -313,10 +372,10 @@ pub fn framework_attr(id: u32) -> Option<&'static str> { /// Decode a binary XML file. pub fn parse(data: &[u8]) -> Result { - parse_with_limits(data, MAX_NODES, MAX_DEPTH) + parse_with_limits(data, MAX_NODES, MAX_DEPTH, MAX_RETAINED_VALUE_BYTES) } -fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result { +fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize, max_value_bytes: usize) -> Result { let r = Reader::new(data); let (t, h, size) = chunk(&r, 0).ok_or_else(|| Error::Truncated("binary XML header".into()))?; if t != RES_XML { @@ -329,6 +388,7 @@ fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result< let mut pos = h; let mut depth = 0usize; let mut ns_stack: Vec<(String, String)> = Vec::new(); + let mut value_budget = ValueBudget::new(max_value_bytes); while pos < size { let Some((ct, ch, cs)) = chunk(&r, pos) else { doc.truncated = true; @@ -354,10 +414,7 @@ fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result< match ct { RES_STRING_POOL => match StringPool::parse(data, pos) { Ok(p) => { - if p.strings.len() < p.declared { - doc.truncated = true; - doc.warnings.push(format!("string pool was capped at {} of {} strings", p.strings.len(), p.declared)); - } + report_partial_string_pool(&p, "string pool", &mut doc.truncated, &mut doc.warnings); doc.pool = p; } Err(e) => doc.warnings.push(format!("string pool: {e}")), @@ -431,6 +488,9 @@ fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result< } else { raw.format(&doc.pool) }; + let value = value_budget + .take(value, &mut doc.truncated, &mut doc.warnings, "XML value budget reached; remaining values were omitted") + .unwrap_or_default(); attributes.push(Attribute { namespace: ans, name: aname, @@ -450,6 +510,9 @@ fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result< } XML_CDATA => { let text = r.u32_le(pos + ch).and_then(|i| doc.pool.get(i)).unwrap_or("").to_string(); + let text = value_budget + .take(text, &mut doc.truncated, &mut doc.warnings, "XML value budget reached; remaining values were omitted") + .unwrap_or_default(); doc.nodes.push(Node::Text { depth, text }); } _ => {} @@ -639,6 +702,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 +719,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 +735,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 +747,10 @@ mod tests { assert_eq!(left, 7); assert_eq!(parsed.get(0), Some("")); assert_eq!(parsed.get(1), Some("ok")); + assert_eq!(parsed.recovery_omitted, 0); } - #[test] - fn default_pool_budget_stops_repeated_recovery_before_later_long_strings() { + fn utf8_recovery_exhausted_pool() -> (Vec, usize) { let mut strings = vec![b'x'; 2 * 0x8000 + 16]; strings[..4].copy_from_slice(&[0x80, 0, 0x80, 0]); let long = append_legacy_ascii(&mut strings, 0x8000); @@ -694,13 +760,78 @@ mod tests { let repeated = MAX_RECOVERY_PROBES / 3 + 1; let mut offsets = vec![0; repeated]; offsets.extend([long, short]); - let data = pool_with_offsets(&offsets, &strings); + (pool_with_offsets(&offsets, &strings), repeated) + } + + #[test] + fn default_pool_budget_stops_repeated_recovery_before_later_long_strings() { + let (data, repeated) = utf8_recovery_exhausted_pool(); let parsed = StringPool::parse(&data, 0).unwrap(); assert_eq!(parsed.declared, repeated + 2); assert_eq!(parsed.strings.len(), repeated + 2); assert!(parsed.strings[..repeated].iter().all(String::is_empty)); assert_eq!(parsed.get(repeated as u32), Some("")); assert_eq!(parsed.get((repeated + 1) as u32), Some("ok")); + assert!(parsed.recovery_omitted > 0); + } + + #[test] + fn xml_and_resource_tables_disclose_recovery_omissions() { + let (pool, repeated) = utf8_recovery_exhausted_pool(); + let short_index = (repeated + 1) as u32; + { + let doc = parse(&pool_container(RES_XML, 8, &pool)).unwrap(); + assert!(doc.truncated); + assert!(doc.warnings.iter().any(|w| w.contains("string pool") && w.contains("UTF-8 recovery budget"))); + assert_eq!(doc.pool.get(short_index), Some("ok")); + assert!(doc.pool.recovery_omitted > 0); + } + let table = crate::arsc::parse(&pool_container(2, 12, &pool), crate::arsc::Limits::default()).unwrap(); + assert!(table.truncated); + assert!(table.warnings.iter().any(|w| w.contains("global string pool") && w.contains("UTF-8 recovery budget"))); + for (field, label) in [(268, "type"), (276, "key")] { + let mut package = pool_container(0x0200, 288, &pool); + package[8..12].copy_from_slice(&0x7fu32.to_le_bytes()); + package[field..field + 4].copy_from_slice(&288u32.to_le_bytes()); + let table = crate::arsc::parse(&pool_container(2, 12, &package), crate::arsc::Limits::default()).unwrap(); + assert!(table.truncated, "{label}"); + assert!( + table.warnings.iter().any(|w| w.contains(&format!("{label} string pool")) && w.contains("UTF-8 recovery budget")), + "{label}: {:?}", + table.warnings + ); + } + } + + #[test] + fn xml_value_budget_omits_long_copies_and_keeps_a_later_short_value() { + let long = "x".repeat(16); + let attrs = vec![ + fx::AxAttr { name: "a", res_id: None, val: fx::AxVal::Str(&long) }, + fx::AxAttr { name: "b", res_id: None, val: fx::AxVal::Str(&long) }, + fx::AxAttr { name: "c", res_id: None, val: fx::AxVal::Str("ok") }, + ]; + let bytes = fx::axml(&[fx::AxNode::Start("root", attrs), fx::AxNode::End("root")]); + let complete = parse(&bytes).unwrap(); + assert!(!complete.truncated); + let Node::Start { attributes, .. } = complete.nodes.iter().find(|n| matches!(n, Node::Start { name, .. } if name == "root")).unwrap() else { + panic!("expected the root start"); + }; + assert_eq!( + attributes.iter().map(|a| (a.name.as_str(), a.value.as_str())).collect::>(), + [("a", long.as_str()), ("b", long.as_str()), ("c", "ok")] + ); + + let partial = parse_with_limits(&bytes, MAX_NODES, MAX_DEPTH, 20).unwrap(); + assert!(partial.truncated); + assert!(partial.warnings.iter().any(|w| w.contains("value budget"))); + let Node::Start { attributes, .. } = partial.nodes.iter().find(|n| matches!(n, Node::Start { name, .. } if name == "root")).unwrap() else { + panic!("expected the root start"); + }; + assert_eq!( + attributes.iter().map(|a| (a.name.as_str(), a.value.as_str())).collect::>(), + [("a", long.as_str()), ("b", ""), ("c", "ok")] + ); } fn chunk_at(data: &[u8], kind: u16) -> usize { @@ -757,11 +888,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 +901,19 @@ mod tests { fn nesting_limit_keeps_an_exact_prefix_instead_of_saturating_depth() { let bytes = fx::axml(&[fx::AxNode::Start("root", vec![]), fx::AxNode::Start("child", vec![]), fx::AxNode::End("child"), fx::AxNode::End("root")]); - let complete = parse_with_limits(&bytes, 5, 2).unwrap(); + let complete = parse_with_limits(&bytes, 5, 2, MAX_RETAINED_VALUE_BYTES).unwrap(); assert!(!complete.truncated); assert!(matches!(complete.nodes[3], Node::End { depth: 1, .. })); assert!(matches!(complete.nodes[4], Node::End { depth: 0, .. })); - let partial = parse_with_limits(&bytes, 5, 1).unwrap(); + let partial = parse_with_limits(&bytes, 5, 1, MAX_RETAINED_VALUE_BYTES).unwrap(); assert!(partial.truncated); assert_eq!(partial.nodes, complete.nodes[..2]); } #[test] fn values_format() { - let p = StringPool { strings: vec!["x".into()], utf8: false, declared: 1 }; + let p = StringPool { strings: vec!["x".into()], utf8: false, declared: 1, recovery_omitted: 0 }; assert_eq!(ResValue { data_type: 0x05, data: (16 << 8) | 1 }.format(&p), "16dp"); assert_eq!(ResValue { data_type: 0x12, data: 0xffff_ffff }.format(&p), "true"); assert_eq!(ResValue { data_type: 0x1c, data: 0xff00_ff00 }.format(&p), "#ff00ff00"); diff --git a/crates/automation/src/client_tests.rs b/crates/automation/src/client_tests.rs index 0514a62d3..46687dae3 100644 --- a/crates/automation/src/client_tests.rs +++ b/crates/automation/src/client_tests.rs @@ -10,12 +10,18 @@ use super::*; const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; +/// Writes `reply` and its newline in one write. `writeln!` on a bare stream writes in pieces, so the client can see +/// part of a line and close the connection before the rest is sent. +fn say(out: &mut impl std::io::Write, reply: serde_json::Value) -> std::io::Result<()> { + out.write_all(format!("{reply}\n").as_bytes()) +} + // call returns Ok(result) for ok replies and Err(error) otherwise. // A stale reply left by a timed-out call is skipped, and a transport failure closes the client. #[trial] fn replies_are_matched_by_id() { - use std::io::{BufRead, Write}; + use std::io::BufRead; let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); let server = std::thread::spawn(move || { @@ -24,11 +30,11 @@ fn replies_are_matched_by_id() { let mut out = stream; let mut line = String::new(); reader.read_line(&mut line).unwrap(); - writeln!(out, "{}", json!({"id": 1, "ok": true})).unwrap(); + say(&mut out, json!({"id": 1, "ok": true})).unwrap(); line.clear(); reader.read_line(&mut line).unwrap(); - writeln!(out, "{}", json!({"id": 99, "ok": true, "result": "stale"})).unwrap(); - writeln!(out, "{}", json!({"id": 2, "ok": true, "result": "fresh"})).unwrap(); + say(&mut out, json!({"id": 99, "ok": true, "result": "stale"})).unwrap(); + say(&mut out, json!({"id": 2, "ok": true, "result": "fresh"})).unwrap(); // Closing the connection ends the third call. }); let mut client = ControlClient::connect(addr, TOKEN).unwrap(); @@ -42,7 +48,7 @@ fn replies_are_matched_by_id() { // later call. #[trial] fn a_cancelled_call_stops_waiting_and_closes_the_connection() { - use std::io::{BufRead, Write}; + use std::io::BufRead; let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); let (done, wait) = std::sync::mpsc::channel::<()>(); @@ -52,12 +58,12 @@ fn a_cancelled_call_stops_waiting_and_closes_the_connection() { let mut out = stream; let mut line = String::new(); reader.read_line(&mut line).unwrap(); - writeln!(out, "{}", json!({"id": 1, "ok": true})).unwrap(); + say(&mut out, json!({"id": 1, "ok": true})).unwrap(); // The call is read and never answered while the client waits. line.clear(); reader.read_line(&mut line).unwrap(); wait.recv().unwrap(); - writeln!(out, "{}", json!({"id": 2, "ok": true, "result": "late"})).ok(); + say(&mut out, json!({"id": 2, "ok": true, "result": "late"})).ok(); }); let mut client = ControlClient::connect(addr, TOKEN).unwrap(); let asked = std::cell::Cell::new(0); @@ -86,12 +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(); - // One write: `writeln!` on a bare stream sends the line and its newline apart, and the client closes on - // the first bytes, so the newline met a reset (BrokenPipe) now and then. - let unasked = format!("{}\n", json!({"id": null, "ok": false, "error": "idle connection closed"})); - out.write_all(unasked.as_bytes()).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(); @@ -121,7 +124,7 @@ fn a_refusal_waiting_at_sign_in_is_the_reason_connect_gives() { let (stream, _) = listener.accept().unwrap(); let mut reader = std::io::BufReader::new(stream.try_clone().unwrap()); let mut out = stream; - writeln!(out, "{}", json!({"id": null, "ok": false, "error": "connection limit reached"})).unwrap(); + say(&mut out, json!({"id": null, "ok": false, "error": "connection limit reached"})).unwrap(); out.flush().unwrap(); let mut line = String::new(); reader.read_line(&mut line).ok().filter(|&read| read > 0).map(|_| line) diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index 5d93b4ee6..3cae59522 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -109,6 +109,7 @@ craft-kra = { workspace = true, optional = true } craft-latex = { workspace = true, optional = true } craft-lottie = { workspace = true, optional = true } craft-markdown = { workspace = true, optional = true } +craft-material-graph = { workspace = true, optional = true } craft-materialx = { workspace = true, optional = true } craft-math = { workspace = true, optional = true } craft-mesh = { workspace = true, optional = true } @@ -609,6 +610,8 @@ macho-serde = ["macho", "craft-macho/serde"] markdown = ["dep:craft-markdown"] +material-graph = ["dep:craft-material-graph"] + materialx = ["dep:craft-materialx"] math = ["dep:craft-math"] diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index 5eba7a44d..caeb7d526 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -221,6 +221,8 @@ pub use craft_lottie as lottie; pub use craft_macho as macho; #[cfg(feature = "markdown")] pub use craft_markdown as markdown; +#[cfg(feature = "material-graph")] +pub use craft_material_graph as material_graph; #[cfg(feature = "materialx")] pub use craft_materialx as materialx; #[cfg(feature = "math")] diff --git a/crates/develop/src/camera_raw/mod.rs b/crates/develop/src/camera_raw/mod.rs index 0119fa1a0..feaff7b4f 100644 --- a/crates/develop/src/camera_raw/mod.rs +++ b/crates/develop/src/camera_raw/mod.rs @@ -67,10 +67,10 @@ mod whites_blacks; pub use local_tone::{LocalTone, ToneKind, TonePass}; pub use per_pixel::{ - CURVE_LUT, Grade, Grain, PerPixel, Vignette, VignetteStyle, WB_STEPS, WhitesBlacks, WhitesBlacksModel, per_pixel, spatial, white_black_points, - whites_blacks_model, + CURVE_LUT, Grade, Grain, PerPixel, Vignette, VignetteStyle, WB_STEPS, WhitesBlacks, WhitesBlacksModel, per_pixel, spatial, spatial_tone, + white_black_points, whites_blacks_model, }; -pub use spatial::{Clarity, Dehaze, Texture}; +pub use spatial::{Clarity, Dehaze, Detail, Texture}; /// How the pixels encode light: the sRGB curve (gamma 0) or a pure power law (ProPhoto's 1.8, /// Adobe RGB's 2.2). The tone controls work on light, so the document's own curve decodes it. @@ -243,6 +243,7 @@ fn box_mean(v: &[f32], w: usize, h: usize, r: usize) -> Vec { } /// Approximate Gaussian (three box passes). +#[cfg(test)] fn gauss(v: &[f32], w: usize, h: usize, sigma: f32) -> Vec { box_means(v, w, h, &spatial::gauss_radii(sigma)) } @@ -484,7 +485,6 @@ pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: & if px.is_empty() || p.is_identity() { return; } - let ps = inputs.pixel_scale.clamp(0.01, 1.0); // 1. White balance + exposure in linear light. if let Some(g) = per_pixel::gains(p) { par_rows(px, w, 1, |_, row| { @@ -629,8 +629,8 @@ pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: & }); } // 8. Detail. - if p.noise_luminance > 0.0 || p.noise_color > 0.0 || p.sharpen_amount > 0.0 { - detail(px, w, h, p, ps); + if let Some(d) = Detail::new(p, inputs) { + detail(px, w, h, &d); } // 9. Effects. if p.vignette_amount != 0.0 { @@ -843,54 +843,41 @@ fn sharpening_detail(detail: f32) -> f32 { detail / 100.0 } -fn detail(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, ps: f32) { - // The controls' documented 0..=100 range: raw values drive the filter radii below. - let [nl, nld, nc, ncd] = [p.noise_luminance, p.noise_luminance_detail, p.noise_color, p.noise_color_detail].map(|v| v.clamp(0.0, 100.0)); +fn detail(px: &mut [[f32; 4]], w: usize, h: usize, d: &Detail) { // Work in Y + chroma (BT.709 luma, B−Y, R−Y). let mut y: Vec = px.iter().map(|q| luma([q[0], q[1], q[2]])).collect(); let mut cb: Vec = px.iter().zip(&y).map(|(q, l)| q[2] - l).collect(); let mut cr: Vec = px.iter().zip(&y).map(|(q, l)| q[0] - l).collect(); - if nl > 0.0 { - let n = nl / 100.0; - let r = ((1.0 + 3.0 * n) * ps).round().max(1.0) as usize; - let smooth = guided(&y, &y, w, h, r, (n * 0.06).powi(2) + 1e-6); - let keep = nld / 100.0 * 0.5; + if let Some(n) = &d.luminance { + let smooth = guided(&y, &y, w, h, n.radius, n.eps); for i in 0..w * h { - y[i] = smooth[i] + (y[i] - smooth[i]) * keep; + y[i] = smooth[i] + (y[i] - smooth[i]) * n.keep; } } - if nc > 0.0 { - let sigma = (nc / 100.0 * 6.0 * ps).max(0.3); - let (bcb, bcr) = (gauss(&cb, w, h, sigma), gauss(&cr, w, h, sigma)); - let keep = ncd / 100.0 * 0.3; + if let Some(c) = &d.color { + let (bcb, bcr) = (box_means(&cb, w, h, &c.radii), box_means(&cr, w, h, &c.radii)); for i in 0..w * h { - cb[i] = bcb[i] + (cb[i] - bcb[i]) * keep; - cr[i] = bcr[i] + (cr[i] - bcr[i]) * keep; + cb[i] = bcb[i] + (cb[i] - bcb[i]) * c.keep; + cr[i] = bcr[i] + (cr[i] - bcr[i]) * c.keep; } } - if p.sharpen_amount > 0.0 { - let sigma = (p.sharpen_radius.clamp(0.5, 3.0) * ps).max(0.3); - let blur = gauss(&y, w, h, sigma); + if let Some(s) = &d.sharpen { + let blur = box_means(&y, w, h, &s.radii); // Masking: an edge mask from the gradient of a smoothed luminance. - let mask: Option> = (p.sharpen_masking > 0.0).then(|| { - let s = gauss(&y, w, h, 1.0 * ps.max(0.5)); - let t = p.sharpen_masking / 100.0 * 0.08; + let mask: Option> = s.mask.as_ref().map(|(radii, [e0, e1])| { + let s = box_means(&y, w, h, radii); util::par_map(w * h, |i| { let (x, yy) = (i % w, i / w); let gx = s[yy * w + (x + 1).min(w - 1)] - s[yy * w + x.saturating_sub(1)]; let gy = s[(yy + 1).min(h - 1) * w + x] - s[yy.saturating_sub(1) * w + x]; - smoothstep(t * 0.5, t + 1e-4, gx.hypot(gy)) + smoothstep(*e0, *e1, gx.hypot(gy)) }) }); - let amt = p.sharpen_amount / 100.0 * 1.2; - let det = sharpening_detail(p.sharpen_detail); for i in 0..w * h { - let hp = y[i] - blur[i]; // Low Detail damps large (halo-producing) differences. - let limit = 0.03 + det * 0.3; - let hp = hp.clamp(-limit, limit) * (0.5 + 0.5 * det); + let hp = (y[i] - blur[i]).clamp(-s.limit, s.limit) * s.scale; let m = mask.as_ref().map_or(1.0, |m| m[i]); - y[i] += amt * hp * m; + y[i] += s.amount * hp * m; } } for i in 0..w * h { @@ -1204,6 +1191,23 @@ mod tests { assert!(per_pixel(&cr! { exposure: 0.5}, 2, 2, false, None).is_some()); } + #[test] + fn detail_reaches_the_per_pixel_stages_after_measured_whites_and_blacks() { + // Detail runs after Whites and Blacks, so another implementation can take its parameters + // and still measure the points on the per-pixel image. + let sharpened = cr! { sharpen_amount: 60.0, noise_luminance: 30.0, whites: 20.0}; + let stages = per_pixel(&sharpened, 8, 8, false, Some((0.05, 0.9))).expect("Detail alone stays on the per-pixel stages"); + assert_eq!(stages.detail, Detail::new(&sharpened, &DevelopInputs::default())); + assert!(stages.detail.is_some() && stages.whites_blacks.is_some() && stages.measure_whites_blacks.is_none()); + let px = vec![[0.4f32, 0.5, 0.6, 1.0]; 64]; + assert!(white_black_points(&px, 8, 8, &sharpened, &DevelopInputs::default()).is_some()); + // A stage before Whites and Blacks still leaves the measuring to whatever runs it. + let clarified = cr!(sharpened.clone() => clarity: 30.0); + assert!(white_black_points(&px, 8, 8, &clarified, &DevelopInputs::default()).is_none()); + assert!(per_pixel(&clarified, 8, 8, false, None).is_some_and(|s| s.measure_whites_blacks.is_some())); + assert!(spatial(&sharpened) && !spatial_tone(&sharpened) && spatial_tone(&clarified)); + } + #[test] fn calibration_turns_primaries_keeps_neutrals_and_tints_shadows() { let w = calibration_weights(0.0); diff --git a/crates/develop/src/camera_raw/per_pixel.rs b/crates/develop/src/camera_raw/per_pixel.rs index 9273036bc..d4b1eacd1 100644 --- a/crates/develop/src/camera_raw/per_pixel.rs +++ b/crates/develop/src/camera_raw/per_pixel.rs @@ -1,11 +1,11 @@ //! Develop's stages resolved for one image: every constant and table the per-pixel ones use, so //! another implementation of them (the GPU preview, `photocraft_gpu::CameraRawDevelop`) runs the //! same maths. [`develop`](super::develop) builds its own constants with the same functions. -//! The spatial stages other than Detail come as their parameters: Dehaze, Clarity and Texture -//! (see [`spatial`](super::spatial)), Shadows and Highlights as a [`LocalTone`]. +//! The spatial stages come as their parameters: Dehaze, Clarity, Texture and Detail (see +//! [`spatial`](super::spatial)), Shadows and Highlights as a [`LocalTone`]. use super::local_tone::{LocalTone, WORK_SIDE}; -use super::spatial::{Clarity, Dehaze, Texture}; +use super::spatial::{Clarity, Dehaze, Detail, Texture}; use super::types::VignetteStyle as StoredStyle; use super::{ CameraRaw, DevelopInputs, Encoding, Wheel, calibration_neutral, curve_lut, grade_neutral, hsl_neutral, hsv_to_rgb, is_linear, luma, @@ -177,7 +177,7 @@ pub struct PerPixel { /// 3b. Whites and Blacks, in the document's encoding. pub whites_blacks: Option, /// 3b. Whites and Blacks to measure the image's points for (the sliders, −100 … 100), when a - /// spatial stage is set: the points then depend on its output, so whatever runs it + /// spatial stage before them is set (any but Detail): the points then depend on its output, so whatever runs it /// measures them and picks the curves from [`whites_blacks_model`]. `whites_blacks` is /// then `None`. pub measure_whites_blacks: Option<[f32; 2]>, @@ -193,6 +193,8 @@ pub struct PerPixel { pub hsl: Option<[[f32; 8]; 3]>, /// 7. Color Grading. pub grade: Option, + /// 8. Detail: noise reduction and sharpening. + pub detail: Option, /// 9. Vignette. pub vignette: Option, /// 9. Grain. @@ -204,20 +206,22 @@ pub struct PerPixel { /// Whether developing needs a stage that reads neighbouring pixels: Dehaze, Shadows and /// Highlights, Texture, Clarity, sharpening or noise reduction. pub fn spatial(p: &CameraRaw) -> bool { - p.dehaze != 0.0 || [p.highlights, p.shadows, p.texture, p.clarity].iter().any(|v| *v != 0.0) || detail_on(p) + spatial_tone(p) || p.sharpen_amount > 0.0 || p.noise_luminance > 0.0 || p.noise_color > 0.0 } -/// Whether developing needs Detail: sharpening or noise reduction. -fn detail_on(p: &CameraRaw) -> bool { - p.sharpen_amount > 0.0 || p.noise_luminance > 0.0 || p.noise_color > 0.0 +/// Whether a stage before Whites and Blacks reads neighbouring pixels: Dehaze, Shadows and +/// Highlights, Texture or Clarity (all of [`spatial`] but Detail). The image's points then +/// depend on its output. +pub fn spatial_tone(p: &CameraRaw) -> bool { + p.dehaze != 0.0 || [p.highlights, p.shadows, p.texture, p.clarity].iter().any(|v| *v != 0.0) } /// The image's black and white points that Whites and Blacks adapt to, for `px` (`w × h`, /// display-encoded) developed per pixel with `p`: what [`develop`](super::develop) measures /// after white balance and Contrast. `None` when Whites and Blacks are 0 or `p` needs a -/// spatial stage. +/// spatial stage before them ([`spatial_tone`]; Detail comes after). pub fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: &DevelopInputs) -> Option<(f32, f32)> { - if (p.whites == 0.0 && p.blacks == 0.0) || spatial(p) || px.len() != w.saturating_mul(h) { + if (p.whites == 0.0 && p.blacks == 0.0) || spatial_tone(p) || px.len() != w.saturating_mul(h) { return None; } let enc = Encoding::of(inputs.encoding_gamma); @@ -228,14 +232,14 @@ pub fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, p: &CameraRaw, in })) } -/// Develop's stages for settings without Detail or Calibration, on a `w × h` image; `points` are -/// the image's [`white_black_points`]. `None` when `p` needs Detail or Calibration (these stages -/// run neither), Shadows or Highlights on a frame wider than the filter's working copy (the +/// Develop's stages for settings without Calibration, on a `w × h` image; `points` are the image's +/// [`white_black_points`]. `None` when `p` needs Calibration (these stages don't run it), Shadows +/// or Highlights on a frame wider than the filter's working copy (the /// develop then filters a reduced copy) or only 2 pixels on its short side, or Whites or Blacks /// without a spatial stage and without `points`. The points themselves leave Calibration out, so a /// caller may cache them across Calibration changes. pub fn per_pixel(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize, float: bool, points: Option<(f32, f32)>) -> Option { - if detail_on(p) || !calibration_neutral(p) { + if !calibration_neutral(p) { return None; } // The develop leaves frames under 2 pixels on a side alone. @@ -277,6 +281,7 @@ pub fn per_pixel(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize, floa point: [pts(&p.point_curve), pts(&p.point_curve_red), pts(&p.point_curve_green), pts(&p.point_curve_blue)], hsl: (!hsl_neutral(p)).then_some([p.hsl_hue, p.hsl_sat, p.hsl_lum]), grade: (!grade_neutral(p)).then(|| Grade::new(p)), + detail: Detail::new(p, inputs), vignette: (p.vignette_amount != 0.0).then(|| Vignette::new(w, h, p)), grain: (p.grain_amount > 0.0).then(|| Grain::new(p, inputs)), clamp: !float && !identity, diff --git a/crates/develop/src/camera_raw/spatial.rs b/crates/develop/src/camera_raw/spatial.rs index a7b17347f..a74ea7a05 100644 --- a/crates/develop/src/camera_raw/spatial.rs +++ b/crates/develop/src/camera_raw/spatial.rs @@ -1,6 +1,6 @@ #![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))] -//! Dehaze, Clarity and Texture resolved for one frame: the sizes, radii and constants their +//! Dehaze, Clarity, Texture and Detail resolved for one frame: the sizes, radii and constants their //! filters use, so another implementation of them (the GPU preview, //! `photocraft_gpu::CameraRawDevelop`) runs the same filters. [`develop`](super::develop) builds //! its own from the same constructors. @@ -13,6 +13,9 @@ //! J. Sun, *Fast Guided Filter*, arXiv 2015), weighted toward the midtones. //! - **Texture** raises its difference from a Gaussian blur (three box passes), limited to //! ±[`TEXTURE_LIMIT`]. +//! - **Detail** works on BT.709 luminance and two chroma planes: a guided filter of the luminance +//! by itself for luminance noise, a Gaussian of the chroma for colour noise, then an unsharp +//! mask of the luminance, optionally weighted by its smoothed gradient. use super::{CameraRaw, DevelopInputs}; @@ -144,6 +147,80 @@ impl Texture { } } +/// Detail (noise reduction, then sharpening) on BT.709 luminance Y and the chroma B − Y, R − Y, +/// resolved for one frame. Each part is `None` when it is off. +#[derive(Clone, Debug, PartialEq)] +pub struct Detail { + pub luminance: Option, + pub color: Option, + pub sharpen: Option, +} + +/// Luminance noise reduction: a guided filter of Y by itself, with some of the detail kept. +#[derive(Clone, Debug, PartialEq)] +pub struct LuminanceNoise { + /// The guided filter's radius. + pub radius: usize, + /// Its regularisation. + pub eps: f32, + /// The share of Y's difference from the filter that stays. + pub keep: f32, +} + +/// Colour noise reduction: a Gaussian of both chroma planes, with some of the detail kept. +#[derive(Clone, Debug, PartialEq)] +pub struct ColorNoise { + /// The Gaussian's box radii, in order. + pub radii: Vec, + /// The share of the chroma's difference from the blur that stays. + pub keep: f32, +} + +/// Sharpening: Y plus `amount` times its difference from a Gaussian (after noise reduction), +/// clamped to ±`limit` and scaled by `scale`, optionally weighted by an edge mask. +#[derive(Clone, Debug, PartialEq)] +pub struct Sharpen { + /// The Gaussian's box radii, in order. + pub radii: Vec, + pub amount: f32, + pub limit: f32, + pub scale: f32, + /// Masking: the box radii of another Gaussian of Y, and the smoothstep edges its gradient's + /// length is weighed between. + pub mask: Option<(Vec, [f32; 2])>, +} + +impl Detail { + /// Detail for `p` at the job's pixel scale; `None` when sharpening and both noise reductions + /// are off. + pub fn new(p: &CameraRaw, inputs: &DevelopInputs) -> Option { + let ps = inputs.pixel_scale.clamp(0.01, 1.0); + // The controls' documented 0..=100 range: raw values drive the filter radii below. + let [nl, nld, nc, ncd] = [p.noise_luminance, p.noise_luminance_detail, p.noise_color, p.noise_color_detail].map(|v| v.clamp(0.0, 100.0)); + let luminance = (nl > 0.0).then(|| { + let n = nl / 100.0; + LuminanceNoise { radius: ((1.0 + 3.0 * n) * ps).round().max(1.0) as usize, eps: (n * 0.06).powi(2) + 1e-6, keep: nld / 100.0 * 0.5 } + }); + let color = (nc > 0.0).then(|| ColorNoise { radii: gauss_radii((nc / 100.0 * 6.0 * ps).max(0.3)), keep: ncd / 100.0 * 0.3 }); + let sharpen = (p.sharpen_amount > 0.0).then(|| { + let det = super::sharpening_detail(p.sharpen_detail); + // Masking: an edge mask from the gradient of a smoothed luminance. + let mask = (p.sharpen_masking > 0.0).then(|| { + let t = p.sharpen_masking / 100.0 * 0.08; + (gauss_radii(1.0 * ps.max(0.5)), [t * 0.5, t + 1e-4]) + }); + Sharpen { + radii: gauss_radii((p.sharpen_radius.clamp(0.5, 3.0) * ps).max(0.3)), + amount: p.sharpen_amount / 100.0 * 1.2, + limit: 0.03 + det * 0.3, + scale: 0.5 + 0.5 * det, + mask, + } + }); + (luminance.is_some() || color.is_some() || sharpen.is_some()).then_some(Detail { luminance, color, sharpen }) + } +} + /// The box radii of develop's Gaussian of `sigma`: none below 0.3. pub(crate) fn gauss_radii(sigma: f32) -> Vec { if sigma < 0.3 { @@ -189,6 +266,31 @@ mod tests { ); } + #[test] + fn detail_parts_follow_their_sliders_and_shrink_on_a_proxy() { + let full = DevelopInputs::default(); + let scale = |pixel_scale| DevelopInputs { pixel_scale, ..full }; + assert!(Detail::new(&CameraRaw::default(), &full).is_none()); + // Each part is on only when its own slider is. + let parts = |p: &CameraRaw| Detail::new(p, &full).map(|d| (d.luminance.is_some(), d.color.is_some(), d.sharpen.is_some())); + assert_eq!(parts(&cr! { noise_luminance: 40.0}), Some((true, false, false))); + assert_eq!(parts(&cr! { noise_color: 40.0}), Some((false, true, false))); + assert_eq!(parts(&cr! { sharpen_amount: 40.0}), Some((false, false, true))); + let masked = |m| Detail::new(&cr! { sharpen_amount: 40.0, sharpen_masking: m}, &full).and_then(|d| d.sharpen).map(|s| s.mask.is_some()); + assert_eq!((masked(0.0), masked(50.0)), (Some(false), Some(true))); + // Out-of-range noise sliders act as their ends. + assert_eq!(Detail::new(&cr! { noise_luminance: 1e30}, &full), Detail::new(&cr! { noise_luminance: 100.0}, &full)); + // On the dialog's proxy the filters are no wider than at full size. + let p = cr! { noise_luminance: 80.0, noise_color: 80.0, sharpen_amount: 80.0, sharpen_radius: 3.0, sharpen_masking: 50.0}; + let (big, small) = (Detail::new(&p, &full).unwrap(), Detail::new(&p, &scale(0.143)).unwrap()); + let reach = |r: &[usize]| r.iter().sum::(); + let (bl, sl) = (big.luminance.unwrap(), small.luminance.unwrap()); + assert!(sl.radius < bl.radius); + assert!(reach(&small.color.unwrap().radii) < reach(&big.color.unwrap().radii)); + let (bs, ss) = (big.sharpen.unwrap(), small.sharpen.unwrap()); + assert!(reach(&ss.radii) < reach(&bs.radii) && reach(&ss.mask.unwrap().0) <= reach(&bs.mask.unwrap().0)); + } + #[test] fn dehaze_cells_average_blocks_after_white_balance_and_refuse_a_wrong_size() { let d = Dehaze::new(&cr! { dehaze: 10.0}, 3, 1).unwrap(); diff --git a/crates/develop/src/sensor/mod.rs b/crates/develop/src/sensor/mod.rs index f7f20ab0a..4174ecbdd 100644 --- a/crates/develop/src/sensor/mod.rs +++ b/crates/develop/src/sensor/mod.rs @@ -168,7 +168,7 @@ impl RawDevelopExt for RawImage { fn develop_balanced_masked(&self, method: Method, wb: [f32; 3], clip: f32) -> Result<(Rgb32f, Option>)> { let n = self.normalized()?; - let mask = clip_mask(self, &n, method, clip); + let mask = raw_clip_mask(self, &n, method, clip); Ok((develop_full(self, n, method, Some(wb)), mask)) } @@ -253,17 +253,34 @@ fn scale_mosaic(n: &mut Normalized, method: Method, gains: [f32; 3]) -> bool { true } -fn clip_mask(raw: &RawImage, n: &Normalized, method: Method, clip: f32) -> Option> { +fn raw_clip_mask(raw: &RawImage, n: &Normalized, method: Method, clip: f32) -> Option> { + let crop = raw.develop_crop(n.width, n.height); + if !raw.opcodes.list3.is_empty() || stretched_height(crop.height, raw.pixel_aspect) != crop.height { + return None; + } + clip_mask(n, crop, method, clip) +} + +/// The [`highlight::reconstruct_masked`] mask for the output of [`demosaic()`] with `method` on the single-plane CFA +/// mosaic `n`, cropped to `crop` (one entry per pixel of `crop`, row-major). `n` holds sensor values normalised so +/// that 1.0 is white and before white balance; samples at or above `clip` count as clipped. Use it when the mosaic +/// is demosaicked by the caller (for example white-balanced first) rather than through [`RawDevelopExt`]. +/// `None` when nothing is clipped, `n` is not a single-plane RGB CFA mosaic, `crop` does not fit inside it, or `clip` +/// is not a positive finite level. +pub fn clip_mask(n: &Normalized, crop: Rect, method: Method, clip: f32) -> Option> { use highlight::{CLIPPED_BITS, FROM_CLIPPED_BITS}; // This radius covers samples read directly by the directional interpolators. Estimates // that build on interpolated green can depend on samples farther away. const REACH: usize = 2; - let cfa = n.cfa.as_ref().filter(|_| n.cpp == 1)?; + let cfa = n.cfa.as_ref().filter(|c| n.cpp == 1 && cfa_valid(c) && c.pattern.iter().all(|&p| p <= 2))?; let (w, h) = (n.width, n.height); - let crop = raw.develop_crop(w, h); - if !clip.is_finite() || clip <= 0.0 || !raw.opcodes.list3.is_empty() || stretched_height(crop.height, raw.pixel_aspect) != crop.height { + let fits = crop.width > 0 + && crop.height > 0 + && crop.x.checked_add(crop.width).is_some_and(|r| r <= w) + && crop.y.checked_add(crop.height).is_some_and(|b| b <= h); + if !clip.is_finite() || clip <= 0.0 || !fits || w.checked_mul(h) != Some(n.data.len()) { return None; } let is_clipped = |v: &f32| *v >= clip; diff --git a/crates/develop/tests/it/balanced.rs b/crates/develop/tests/it/balanced.rs index 4c8584304..bf7b6bbca 100644 --- a/crates/develop/tests/it/balanced.rs +++ b/crates/develop/tests/it/balanced.rs @@ -1,7 +1,7 @@ //! Original synthetic RAW scenes from storytold/lightcraft#1463, generated in these tests. use craft_develop::raster::Rgb32f; -use craft_develop::sensor::{Method, RawDevelopExt, highlight}; +use craft_develop::sensor::{self, Method, RawDevelopExt, highlight}; use craft_raw::opcodes::{Opcode, OpcodeLists}; use craft_raw::{BlackLevel, Cfa, ColorData, Orientation, RawData, RawFormat, RawImage, Rect}; @@ -355,6 +355,30 @@ fn the_clip_mask_marks_the_colours_interpolated_from_clipped_samples() { assert!(raw.develop_balanced_masked(Method::Ahd, DAYLIGHT, CLIP).unwrap().1.is_none()); } +#[test] +fn a_caller_demosaicking_its_own_mosaic_gets_the_same_clip_mask() { + let (w, h) = (40usize, 30usize); + let light = photograph(w, h, |x, y| if (x - 18.0).powi(2) + (y - 14.0).powi(2) < 49.0 { 6.0 } else { 0.4 }); + let mut cases = layouts(); + cases.push(("RGGB bilinear".into(), Cfa::bayer("RGGB").unwrap(), Method::Bilinear)); + for (name, cfa, method) in cases { + let mut raw = raw_of(w, h, &cfa, DAYLIGHT, |x, y| [light[y * w + x]; 3]); + raw.crop = Rect::new(2, 1, 33, 27); + let (_, expected) = raw.develop_balanced_masked(method, DAYLIGHT, CLIP).unwrap(); + let n = raw.normalized().unwrap(); + let crop = raw.develop_crop(n.width, n.height); + assert_eq!(sensor::clip_mask(&n, crop, method, CLIP), expected, "{name}"); + assert!(expected.is_some(), "{name}: clipped samples"); + let outside = Rect::new(crop.x + 1, crop.y, n.width - crop.x, crop.height); + assert!(sensor::clip_mask(&n, outside, method, CLIP).is_none(), "{name}: a crop past the mosaic"); + let mut four_colour = n.clone(); + four_colour.cfa.as_mut().unwrap().pattern[0] = 3; + assert!(sensor::clip_mask(&four_colour, crop, method, CLIP).is_none(), "{name}: a colour index past blue"); + let huge = sensor::Normalized { width: usize::MAX, height: 2, data: Vec::new(), ..n.clone() }; + assert!(sensor::clip_mask(&huge, Rect::new(0, 0, 1, 1), method, CLIP).is_none(), "{name}: dimensions past usize"); + } +} + #[test] fn ppg_clip_mask_marks_same_colour_dependencies() { let cfa = Cfa::bayer("RGGB").unwrap(); diff --git a/crates/font-manager/Cargo.toml b/crates/font-manager/Cargo.toml index e3fd1e677..fbaa41999 100644 --- a/crates/font-manager/Cargo.toml +++ b/crates/font-manager/Cargo.toml @@ -46,7 +46,7 @@ craft-theme = { workspace = true, optional = true } serde = { workspace = true, optional = true } log = { version = "0.4", optional = true } # Variation axes and named instances of a face (`axes`), on every feature set. -skrifa = { version = "0.44", default-features = false, features = ["std"] } +skrifa = { version = "0.47", default-features = false, features = ["std"] } [build-dependencies] # The Arabic sample story's face, from the craft fonts set when `CRAFT_FONTS_DIR` names one. @@ -54,6 +54,8 @@ craft-fonts-build = { workspace = true } [dev-dependencies] craft-font-manager = { path = ".", features = ["suite"] } +# The shared preview test vectors. +serde_json = { workspace = true } [[test]] name = "it" diff --git a/crates/font-manager/README.md b/crates/font-manager/README.md index ba54bbce7..5c4fd076f 100644 --- a/crates/font-manager/README.md +++ b/crates/font-manager/README.md @@ -10,7 +10,7 @@ Fonts tab; the standalone app | `filter` | always | Search over the index: family names ignoring case and accents, category, language (English name, autonym or id) and script | | `index` | always | The pinned built-in indexes (Google Fonts and Noto) compiled into [`craft-font-store`](../font-store/README.md) (`bundled`), each family's source (`source_label`: its name and whether it is curated), and the categories | | `installed` | always | The installed fonts [`craft-font-catalog`](../font-catalog/README.md) sees, grouped by family and source | -| `store` | always | `Installer`, what the interface needs from the font store: the download consent, install, remove, downloads for a preview, the indexes (`indexes`, `fetch_indexes`) and the sources the user added (`user_sources`, `add_user_source`, `remove_user_source`). `SuiteStore` is craft-font-store's store (native only), `FakeStore` a stand-in for tests, `NoStore` one for when the store folder is unknown | +| `store` | always | `Installer`, what the interface needs from the font store: the download consent, install, remove, downloads for a preview, the indexes (`indexes`, `fetch_indexes`) and the sources the user added (`user_sources`, `add_user_source`, `remove_user_source`). `SuiteStore` is craft-font-store's store (native only), `FakeStore` a stand-in for tests, `NoStore` one for when the store folder is unknown. What the preview pool (craft-font-store's `preview`) reads is the `PreviewStore` part | | `FontsPanel` | `ui` | The whole interface as one egui panel | | `glyphs` | `ui` | `GlyphsPanel`: the character grid of a face with categories, zoom and Recently Used; the app supplies the glyphs through `GlyphSource`, which also reports when it is ready and when its faces change. Sizes are the `glyphs.*` tokens | | `missing` | `ui` | `document_fonts`, `missing_font_warnings` and `MissingFontsDialog`: which fonts a document names are not installed, and a replacement for each | diff --git a/crates/font-manager/src/picker.rs b/crates/font-manager/src/picker.rs index 145c7b2fc..4831d8f12 100644 --- a/crates/font-manager/src/picker.rs +++ b/crates/font-manager/src/picker.rs @@ -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::(egui::Id::unique("font_picker_stop_builds")).unwrap_or_default().0) + craft_ui::runtime::memory::with_session::(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 { #[cfg(feature = "screen-testing")] - cx.response.ctx.data_mut(|data| { - data.get_temp_mut_or_default::(egui::Id::unique("font_picker_stop_builds")).0 += 1; - }); + craft_ui::runtime::memory::with_session::(&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() diff --git a/crates/font-manager/src/store.rs b/crates/font-manager/src/store.rs index ca76c2da0..4e8bc303d 100644 --- a/crates/font-manager/src/store.rs +++ b/crates/font-manager/src/store.rs @@ -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::preview::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, 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) -> Option { 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, 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 { + self.store.preview_service() + } + + fn http_client(&self) -> Option { + Some(self.store.client()) + } + + fn previews_enabled(&self) -> bool { + self.store.previews_enabled() + } + + fn preview_cache(&self) -> Option { + 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 diff --git a/crates/font-manager/src/store/fake.rs b/crates/font-manager/src/store/fake.rs index eb7019499..e91e8c356 100644 --- a/crates/font-manager/src/store/fake.rs +++ b/crates/font-manager/src/store/fake.rs @@ -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>, user: Mutex>, + preview_service: Mutex>, + previews: Mutex, /// User sources downloaded so far, and those whose file changed since. fetched: Mutex>, changed: Mutex>, @@ -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,47 @@ 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> { + let url = url.map(craft_font_store::check_preview_service).transpose().map_err(err)?; + *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, 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 { + self.preview_service.lock().ok()?.clone() + } + + fn previews_enabled(&self) -> bool { + self.previews.lock().map_or(true, |p| *p) + } + + fn preview_cache(&self) -> Option { + Some(self.dir.join("previews")) + } } diff --git a/crates/font-manager/tests/data/Tiny-glyf.woff2 b/crates/font-manager/tests/data/Tiny-glyf.woff2 new file mode 100644 index 000000000..f44e1433d Binary files /dev/null and b/crates/font-manager/tests/data/Tiny-glyf.woff2 differ diff --git a/crates/font-manager/tests/data/preview-vectors.json b/crates/font-manager/tests/data/preview-vectors.json new file mode 100644 index 000000000..e9c78938d --- /dev/null +++ b/crates/font-manager/tests/data/preview-vectors.json @@ -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" + } + ] + } +} \ No newline at end of file diff --git a/crates/font-manager/tests/remote.rs b/crates/font-manager/tests/remote.rs new file mode 100644 index 000000000..e8c1062ea --- /dev/null +++ b/crates/font-manager/tests/remote.rs @@ -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), + /// 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>>, + log: Arc>>, + gate: Arc<(Mutex, 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 { + 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>, log: &Mutex>, gate: &(Mutex, 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 { + 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 = (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::>(), [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); +} diff --git a/crates/font-store/Cargo.toml b/crates/font-store/Cargo.toml index d840ff48e..ce801088d 100644 --- a/crates/font-store/Cargo.toml +++ b/crates/font-store/Cargo.toml @@ -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" diff --git a/crates/font-store/README.md b/crates/font-store/README.md index d54b0a923..322cac747 100644 --- a/crates/font-store/README.md +++ b/crates/font-store/README.md @@ -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/`. 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 `/v1/files/` for each font file and `/v1/licences/` 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/`. 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, .json.gz, user- +previews/ preview subsets (WOFF2) the preview pool caches, at most 50 MB / the font files and the licence language-packs/ installed Language packs, one folder per locale language-packs.json which Language packs are installed diff --git a/crates/font-store/index/indexes/google-fonts.json.gz b/crates/font-store/index/indexes/google-fonts.json.gz index 9d4b92406..f4989d4e3 100644 Binary files a/crates/font-store/index/indexes/google-fonts.json.gz and b/crates/font-store/index/indexes/google-fonts.json.gz differ diff --git a/crates/font-store/index/indexes/noto.json.gz b/crates/font-store/index/indexes/noto.json.gz index bb40f4754..3a3d3c23b 100644 Binary files a/crates/font-store/index/indexes/noto.json.gz and b/crates/font-store/index/indexes/noto.json.gz differ diff --git a/crates/font-store/index/sources.json b/crates/font-store/index/sources.json index e124d132d..fa9ed6aa3 100644 --- a/crates/font-store/index/sources.json +++ b/crates/font-store/index/sources.json @@ -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} ]} diff --git a/crates/font-store/src/http.rs b/crates/font-store/src/http.rs index 3c6d007bd..f264dac2c 100644 --- a/crates/font-store/src/http.rs +++ b/crates/font-store/src/http.rs @@ -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>>, + 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, 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, 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, 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, FetchError>), diff --git a/crates/font-store/src/index.rs b/crates/font-store/src/index.rs index 5a082d26f..07bea9fd7 100644 --- a/crates/font-store/src/index.rs +++ b/crates/font-store/src/index.rs @@ -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, +} + /// 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, + /// Format 1.2: a variable font's named instances, in font order; empty for a static font. + #[serde(default)] + pub instances: Vec, + /// 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, + /// Format 1.2: the file's own preview script, when not the family's `sample_script`. + #[serde(default)] + pub sample_script: Option, + /// Format 1.2: the file's own preview text, when no script sample fits it. + #[serde(default)] + pub sample_text: Option, /// The repository holding the file, when not the family's. #[serde(default)] pub repo: Option, @@ -216,6 +252,25 @@ pub struct Family { /// The licence file, with its size and sha256. #[serde(default)] pub license_file: Option, + /// Format 1.2: design traits, sorted, from the index's tag vocabulary. + #[serde(default)] + pub tags: Vec, + /// Format 1.2: the script whose sample previews the family. + #[serde(default)] + pub sample_script: Option, + /// Format 1.2: the copyright notice. + #[serde(default)] + pub copyright: Option, + /// 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, + /// Format 1.2: an Apache family's `NOTICE` file, located like the licence file. + #[serde(default)] + pub notice_file: Option, + /// Format 1.2: where the family is developed. + #[serde(default)] + pub upstream: Option, /// The repository holding the files, when not the source's. #[serde(default)] pub repo: Option, @@ -399,7 +454,7 @@ pub struct SourceProblem { pub error: String, } -pub(crate) type Part = (FontSource, Vec, Vec