Merge craft-libs main dc2cb42b15 into the branch

This commit is contained in:
skylartaylor committed 2026-11-26 08:34:47 +01:00
commit b4466f52b2
362 files changed
+35639 -1839

No files matched your search

+7 -1
View File
@@ -15,8 +15,10 @@ on:
- "crates/silhouette-studio/**"
- "crates/tiff/**"
- "crates/heif/**"
- "crates/pst/**"
- "crates/cms/**"
- "crates/cdr/**"
- "crates/texture/**"
- "Cargo.toml"
- "Cargo.lock"
- ".github/workflows/formats.yml"
@@ -33,8 +35,10 @@ on:
- "crates/silhouette-studio/**"
- "crates/tiff/**"
- "crates/heif/**"
- "crates/pst/**"
- "crates/cms/**"
- "crates/cdr/**"
- "crates/texture/**"
- "Cargo.toml"
- "Cargo.lock"
- ".github/workflows/formats.yml"
@@ -67,9 +71,11 @@ jobs:
- { crate: craft-svg-paths, features: "" }
- { crate: craft-silhouette-studio, features: "" }
- { crate: craft-tiff, features: "" }
- { crate: craft-heif, features: "testdata" }
- { crate: craft-heif, features: "testdata test-support" }
- { crate: craft-pst, features: "test-writer test-support" }
- { crate: craft-cms, features: "" }
- { crate: craft-cdr, features: "synth" }
- { crate: craft-texture, features: "dds parallel" }
# fmt, clippy with default and with all features, and the tests run in the Workspace gate on
# every OS; this lints each feature alone and checks the web build.
name: ${{ matrix.crate }} feature sets, WASM
+3 -1
View File
@@ -122,10 +122,12 @@ jobs:
cache-version: &cache-version v2-${{ needs.platforms.outputs.profile }}
cold-build: ${{ github.event.schedule == '17 0 * * *' || github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/next' }}
lint-cache: false
# The vendored crates are on the workspace `exclude` list, so unreached-rs has no module tree for them.
# The vendored crates are on the workspace `exclude` list and craft-pdf's read-only contract is a
# workspace of its own (pdf.yml tests it), so unreached-rs has no module tree for them.
unreached-rs-allow: |
**/fixtures/**
vendor/**
crates/pdf/read-only-contract/**
timeout-minutes: &timeout 120
# Every leg runs its tests with nextest, and its doctests with cargo test (.config/nextest.toml).
tools: &tools cargo-nextest@0.9.150
+2 -2
View File
@@ -65,7 +65,7 @@ The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are used as in RFC 2119
Shared Rust libraries for the Craft Apps: a Cargo workspace (edition 2024, resolver 3) of crates under `crates/<name>`. See `README.md` for layout and released versions.
- **New crates** go in `crates/<name>`, named `craft-<name>`, inherit the workspace package fields and lints, and are listed in `[workspace.dependencies]`. A new crate's `Cargo.toml` includes `[lints] workspace = true`.
- **New crates** go in `crates/<name>`, named `craft-<name>`, inherit the workspace package fields and lints, and are listed in `[workspace.dependencies]`. A new crate's `Cargo.toml` includes `[lints] workspace = true` (`crates/font-os-windows` is the one exception; see `unsafe` below).
- **No app code.** A crate here is useful to more than one app and does not depend on any app.
- **`unsafe`:** the workspace sets `unsafe_code = "forbid"`, and no crate in `crates/` allows it, so no module here may use `unsafe`. The one exception is vendored upstream code in `vendor/hayro-syntax`.
- **`unsafe`:** the workspace sets `unsafe_code = "forbid"`, so no module here may use `unsafe`, with two exceptions: vendored upstream code in `vendor/hayro-syntax`, and `crates/font-os-windows`, because loading a font into the running Windows session needs `AddFontResourceW`, which the Windows crates offer only as an unsafe call. That crate copies the workspace lints with `unsafe_code = "deny"` instead of `[lints] workspace = true`, and allows `unsafe` only on the functions that make Win32 calls.
- **Checks for the crates you changed:** `cargo fmt --check`, `cargo clippy -p <crate> --all-targets -- -D warnings`, `cargo test -p <crate>`.
+3
View File
@@ -94,6 +94,7 @@ and the exact transfer revision are recorded in each vendored crate's SOURCE.jso
| `crates/raster-codecs/src/xpm/x11_colors.rs` | X.Org Foundation and X11 contributors (X11 `rgb.txt` colour names and values, normalised into a lookup table) | <https://cgit.freedesktop.org/xorg/app/rgb/tree/rgb.txt>, via [PhotoCraft `crates/codecs`](https://github.com/storytold/photocraft/tree/63b641b55e54bf8f5c83efd977fdb16a2c255431/crates/codecs/src/codecs/xpm) | MIT (X.Org app/rgb) |
| `crates/psd/tests/fixtures/atn/*.atn` (seven synthetic action sets, encoded field by field; `crates/psd/tests/fixtures/atn/README.md`) | PhotoCraft contributors | [PhotoCraft `crates/psd/tests/fixtures/atn`](https://github.com/storytold/photocraft/tree/63b641b55e54bf8f5c83efd977fdb16a2c255431/crates/psd/tests/fixtures/atn) | MIT OR Apache-2.0 |
| `crates/lottie/tests/fixtures/` | EffectCraft contributors (original work: four hand-written Lottie JSON documents, written from the public Lottie format description; not exported from any Adobe product or third-party file) | [EffectCraft `crates/lottie/tests/fixtures`](https://github.com/storytold/effectcraft/tree/e18f48fb/crates/lottie/tests/fixtures) | MIT OR Apache-2.0 |
| `crates/i18n-build/tests/fixture/` | craft-libs contributors (original work: nine hand-written catalogs of a few common interface words, in craft-i18n's catalog format; not copied from craft-i18n or any app) | this repository | MIT OR Apache-2.0 |
| `crates/pkcs7/tests/data/` | PdfCraft contributors (original work: throw-away test keys and certificates made with OpenSSL 3 for these tests, as seven PKCS #12 files with the password `test` and two PEM certificates; they protect nothing; commands in `crates/pkcs7/tests/data/README.md`) | [PdfCraft `crates/sign/tests/data`](https://github.com/storytold/pdfcraft/tree/1d7a9f9f/crates/sign/tests/data) | MIT OR Apache-2.0 |
| `crates/affinity/tests/support/corpus.tsv`, `crates/affinity/tests/support/affinity3-signatures.txt` (manifest and measured signatures only; the 113 files, 90 of them documents, are not bundled, `scripts/fetch-affinity-corpus.sh` downloads them outside the checkout) | The authors of each document: samuel-etver (vector-art), satoshoe-dev (affinity-samples), Seth A. Robinson (Patchy fixtures), Nick Beeuwsaert (AFDesignLoad), Jeremy Cantu (Branding), eviltwo (AssetStoreTemplate), Square (leakcanary) | each file's pinned upstream URL and SHA-256 in the manifest; every name from [VectorCraft `xtask/src/affinity_corpus.rs`](https://github.com/storytold/vectorcraft/blob/bada8e17103db9917de44e40a1cead5a7fc71c3c/xtask/src/affinity_corpus.rs) and [PhotoCraft `xtask/affinity-corpus.sha256`](https://github.com/storytold/photocraft/blob/629751503165118d5fec5f70e64fe2d6592f7b53/xtask/affinity-corpus.sha256) | CC0-1.0, MIT or Apache-2.0 (per file, in the manifest) |
| `crates/raw/docs/coverage/adobe-cameras.tsv` | Facts (maker, model, extension, profile, minimum Camera Raw version) parsed by LightCraft contributors from Adobe's published list | [Adobe Camera Raw supported cameras](https://helpx.adobe.com/camera-raw/desktop/dng-and-file-formats/camera-raw-plug-supported-cameras.html), Wayback capture 20261003133011; moved from [LightCraft `docs/raw`](https://github.com/storytold/lightcraft/tree/5ff567a4a2e067bef1b6bce152c11e7f727ccbaf/docs/raw) | Facts, not copyrightable expression; the file is MIT OR Apache-2.0 |
@@ -124,6 +125,8 @@ The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper
`crates/audio-dsp` combines FilmCraft `crates/audio-dsp` at `3f137a7ed420cac79b32145f5243b7f98b31f71c` and SoundCraft `crates/dsp` at `648ed9db9a0e98cc55643babffac381521a556c8` (both MIT OR Apache-2.0). `crates/audio-dsp/NOTICE` keeps the copyright notices of both projects.
`crates/audio-dsp/src/effects/voice.rs` adapts the two crossfaded read taps of SoundCraft `crates/dsp/src/plugins/pitch.rs` and the YIN pitch tracker of `crates/dsp/src/pitch_detect.rs` at `915481be1b49d7e0502e07b059d0c0198c61911a` (MIT OR Apache-2.0). The taps are centered on a fixed 10 ms latency and spaced by whole periods of the tracked pitch, and the tracker runs on a decimated copy of the input in buffers sized at creation.
## GIMP palette reader
`crates/palette` extracts the GPL text parser from AniCraft `crates/doc/src/swatch.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0), introduced by Tanish Manku in `a64130a9da9bdde545463b852d95d6a6774b1dfd` (AniCraft #270). The import preserves Tanish as primary author. Neutral RGB/name adaptation separates application display-name sanitization and the `Untitled` policy; validation tests and integration are subsequent Dylan M. Taylor changes.
Generated
+122 -65
View File
@@ -1125,32 +1125,36 @@ dependencies = [
[[package]]
name = "candle-core"
version = "0.9.2"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c15b675b80d994b2eadb20a4bbe434eabeb454eac3ee5e2b4cf6f147ee9be091"
checksum = "d11c8be87cfbaef9ebb62fb3f850d1fc8e00cc1d11d393fdbe55a4d5c2cdb325"
dependencies = [
"byteorder",
"float8",
"gemm",
"half",
"libc",
"libm",
"memmap2",
"num-traits",
"num_cpus",
"parking_lot",
"rand 0.9.5",
"rand_distr",
"rayon",
"safetensors",
"thiserror 2.0.21",
"tokenizers",
"yoke",
"zip 7.4.0",
"zerocopy",
"zip",
]
[[package]]
name = "candle-nn"
version = "0.9.2"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3045fa9e7aef8567d209a27d56b692f60b96f4d0569f4c3011f8ca6715c65e03"
checksum = "437fabe77547c2447c7bdf3cc946e19db29a2832440176b419f77c80b0a9a05e"
dependencies = [
"candle-core",
"half",
@@ -1164,14 +1168,14 @@ dependencies = [
[[package]]
name = "candle-transformers"
version = "0.9.2"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b538ec4aa807c416a2ddd3621044888f188827862e2a6fcacba4738e89795d01"
checksum = "2b1e1abeac23d7df4f94e8a3852b3dbb661d332e37c3bef479507bac867187b2"
dependencies = [
"byteorder",
"candle-core",
"candle-nn",
"fancy-regex 0.17.0",
"fancy-regex 0.19.2",
"num-traits",
"rand 0.9.5",
"rayon",
@@ -1786,6 +1790,7 @@ dependencies = [
"craft-drawingml",
"craft-dwg",
"craft-dxf",
"craft-ease",
"craft-ecproj-format",
"craft-elf",
"craft-eps",
@@ -1804,6 +1809,7 @@ dependencies = [
"craft-flow",
"craft-font-catalog",
"craft-font-manager",
"craft-font-os-windows",
"craft-font-store",
"craft-font-subset",
"craft-format",
@@ -1825,6 +1831,7 @@ dependencies = [
"craft-html",
"craft-http-url",
"craft-i18n",
"craft-i18n-build",
"craft-ical",
"craft-idml",
"craft-image-codecs",
@@ -1868,6 +1875,7 @@ dependencies = [
"craft-ora",
"craft-pages",
"craft-palette",
"craft-pbr",
"craft-pcap",
"craft-pcraft-bundle",
"craft-pcraft-format",
@@ -2270,6 +2278,7 @@ version = "0.1.0"
dependencies = [
"craft-ai-agents",
"craft-atomic",
"craft-control-protocol",
"craft-flags",
"dirs",
"getrandom 0.3.4",
@@ -2338,7 +2347,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"zip 9.1.3",
"zip",
]
[[package]]
@@ -2477,7 +2486,7 @@ dependencies = [
"craft-zip",
"serde_json",
"thiserror 2.0.21",
"zip 9.1.3",
"zip",
]
[[package]]
@@ -2502,7 +2511,7 @@ dependencies = [
"thiserror 2.0.21",
"unicode-bidi",
"zeroize",
"zip 9.1.3",
"zip",
]
[[package]]
@@ -2562,6 +2571,14 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-ease"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "craft-ecproj-format"
version = "0.1.0"
@@ -2597,7 +2614,7 @@ dependencies = [
"craft-xml",
"craft-zip",
"thiserror 2.0.21",
"zip 9.1.3",
"zip",
]
[[package]]
@@ -2661,7 +2678,7 @@ dependencies = [
"ruzstd",
"serde_json",
"thiserror 2.0.21",
"zip 9.1.3",
"zip",
]
[[package]]
@@ -2672,7 +2689,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"zip 9.1.3",
"zip",
]
[[package]]
@@ -2772,6 +2789,14 @@ dependencies = [
"skrifa 0.47.0",
]
[[package]]
name = "craft-font-os-windows"
version = "0.1.0"
dependencies = [
"windows-registry",
"windows-sys 0.61.2",
]
[[package]]
name = "craft-font-store"
version = "0.1.0"
@@ -2779,6 +2804,7 @@ dependencies = [
"cap-primitives",
"craft-atomic",
"craft-font-catalog",
"craft-font-os-windows",
"flate2",
"log",
"ruzstd",
@@ -3010,6 +3036,21 @@ dependencies = [
"writeable",
]
[[package]]
name = "craft-i18n-build"
version = "0.1.0"
dependencies = [
"craft-i18n",
"craft-i18n-build-consumer",
]
[[package]]
name = "craft-i18n-build-consumer"
version = "0.1.0"
dependencies = [
"craft-i18n-build",
]
[[package]]
name = "craft-ical"
version = "0.1.0"
@@ -3025,7 +3066,7 @@ dependencies = [
"craft-xml",
"craft-zip",
"thiserror 2.0.21",
"zip 9.1.3",
"zip",
]
[[package]]
@@ -3033,6 +3074,7 @@ name = "craft-image-codecs"
version = "0.1.0"
dependencies = [
"avif-serialize",
"craft-cms",
"craft-dds",
"craft-heif",
"craft-jpeg",
@@ -3048,7 +3090,7 @@ dependencies = [
"hayro-jpeg2000",
"image",
"image-webp",
"jpeg-encoder 0.6.1",
"jpeg-encoder 0.7.1",
"jxl-oxide",
"png 0.18.1",
"proptest",
@@ -3192,7 +3234,7 @@ dependencies = [
"craft-xml",
"craft-zip",
"thiserror 2.0.21",
"zip 9.1.3",
"zip",
]
[[package]]
@@ -3324,6 +3366,7 @@ dependencies = [
"craft-frame",
"craft-media",
"craft-time",
"craft-video",
"craft-y4m",
"serde",
"serde_json",
@@ -3438,7 +3481,7 @@ dependencies = [
"sha2 0.11.1",
"thiserror 2.0.21",
"zeroize",
"zip 9.1.3",
"zip",
]
[[package]]
@@ -3446,6 +3489,7 @@ name = "craft-ods"
version = "0.1.0"
dependencies = [
"craft-odf",
"craft-ods",
"craft-sheet",
"craft-xml",
"thiserror 2.0.21",
@@ -3475,7 +3519,7 @@ dependencies = [
"craft-zip",
"log",
"thiserror 2.0.21",
"zip 9.1.3",
"zip",
]
[[package]]
@@ -3501,7 +3545,7 @@ dependencies = [
"craft-xml",
"craft-zip",
"thiserror 2.0.21",
"zip 9.1.3",
"zip",
]
[[package]]
@@ -3524,6 +3568,18 @@ dependencies = [
name = "craft-palette"
version = "0.1.0"
[[package]]
name = "craft-pbr"
version = "0.1.0"
dependencies = [
"craft-pbr",
"craft-texture",
"glam 0.30.10",
"naga",
"rayon",
"thiserror 2.0.21",
]
[[package]]
name = "craft-pcap"
version = "0.1.0"
@@ -3627,7 +3683,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"zip 9.1.3",
"zip",
]
[[package]]
@@ -4051,7 +4107,7 @@ dependencies = [
"kurbo",
"serde_json",
"thiserror 2.0.21",
"zip 9.1.3",
"zip",
]
[[package]]
@@ -4218,6 +4274,9 @@ dependencies = [
[[package]]
name = "craft-testkit"
version = "0.1.0"
dependencies = [
"rustix 1.1.6",
]
[[package]]
name = "craft-text"
@@ -4617,7 +4676,7 @@ dependencies = [
"verifysign",
"winreg",
"winsafe",
"zip 9.1.3",
"zip",
]
[[package]]
@@ -4850,6 +4909,7 @@ name = "craft-xtask"
version = "0.1.0"
dependencies = [
"craft-atomic",
"libc",
"serde_json",
"tempfile",
]
@@ -4874,7 +4934,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"zip 9.1.3",
"zip",
]
[[package]]
@@ -5105,6 +5165,12 @@ dependencies = [
"zeroize",
]
[[package]]
name = "daachorse"
version = "3.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5614204febbc33cc07a2806aa6440b904ac012b68eecc37f4493ea4a76455a3d"
[[package]]
name = "darling"
version = "0.20.11"
@@ -5178,7 +5244,7 @@ checksum = "e917a58e17b27d2f15626c490754ccced7f46592dc5b5f39a3013b89cba5f068"
dependencies = [
"astc-decode",
"bitflags 2.13.2",
"glam",
"glam 0.25.0",
"resize",
"zerocopy",
]
@@ -5571,7 +5637,7 @@ dependencies = [
[[package]]
name = "ecolor"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
dependencies = [
"bytemuck",
"emath",
@@ -5627,7 +5693,7 @@ dependencies = [
[[package]]
name = "eframe"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
dependencies = [
"ahash",
"bytemuck",
@@ -5662,7 +5728,7 @@ dependencies = [
[[package]]
name = "egui"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
dependencies = [
"accesskit",
"ahash",
@@ -5681,7 +5747,7 @@ dependencies = [
[[package]]
name = "egui-wgpu"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
dependencies = [
"ahash",
"bytemuck",
@@ -5700,7 +5766,7 @@ dependencies = [
[[package]]
name = "egui-winit"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
dependencies = [
"block2 0.6.2",
"bytemuck",
@@ -5720,7 +5786,7 @@ dependencies = [
[[package]]
name = "egui_glow"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
dependencies = [
"bytemuck",
"egui",
@@ -5733,7 +5799,7 @@ dependencies = [
[[package]]
name = "egui_kittest"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
dependencies = [
"eframe",
"egui",
@@ -5810,7 +5876,7 @@ dependencies = [
[[package]]
name = "emath"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
dependencies = [
"bytemuck",
]
@@ -5883,7 +5949,7 @@ dependencies = [
[[package]]
name = "epaint"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
dependencies = [
"ahash",
"bytemuck",
@@ -5909,7 +5975,7 @@ dependencies = [
[[package]]
name = "epaint_default_fonts"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
[[package]]
name = "equator"
@@ -6184,9 +6250,9 @@ dependencies = [
[[package]]
name = "float8"
version = "0.6.1"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "719a903cc23e4a89e87962c2a80fdb45cdaad0983a89bd150bb57b4c8571a7d5"
checksum = "c2d1f04709a8ac06e8e8042875a3c466cc4832d3c1a18dbcb9dba3c6e83046bc"
dependencies = [
"half",
"num-traits",
@@ -6725,6 +6791,12 @@ version = "0.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "151665d9be52f9bb40fc7966565d39666f2d1e69233571b71b87791c7e0528b3"
[[package]]
name = "glam"
version = "0.30.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9"
[[package]]
name = "glifo"
version = "0.1.1"
@@ -11409,13 +11481,15 @@ checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714"
[[package]]
name = "safetensors"
version = "0.7.0"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "675656c1eabb620b921efea4f9199f97fc86e36dd6ffd1fbbe48d0f59a4987f5"
checksum = "79b079b829cb27a1c3c374341345ed2e8b2c0c839034522cee576c140bd7f846"
dependencies = [
"hashbrown 0.16.1",
"libc",
"serde",
"serde_json",
"tempfile",
]
[[package]]
@@ -12809,16 +12883,17 @@ dependencies = [
[[package]]
name = "tokenizers"
version = "0.22.2"
version = "0.23.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b238e22d44a15349529690fb07bd645cf58149a1b1e44d6cb5bd1641ff1a6223"
checksum = "7afbf6e88718afcc138bad01d6ccc3051dbbc3b2ce9793d8b8a3aeb610969cfc"
dependencies = [
"ahash",
"aho-corasick",
"compact_str",
"daachorse",
"dary_heap",
"derive_builder",
"esaxx-rs",
"fancy-regex 0.17.0",
"getrandom 0.3.4",
"itertools 0.14.0",
"log",
@@ -13064,12 +13139,6 @@ dependencies = [
"rustc-hash 2.1.3",
]
[[package]]
name = "typed-path"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54ec2755506471f54baf5e4bb5499d8e510cc1caf271270e778a736bd2d7336c"
[[package]]
name = "typed-path"
version = "0.13.0"
@@ -15124,18 +15193,6 @@ dependencies = [
"syn 3.0.6",
]
[[package]]
name = "zip"
version = "7.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc12baa6db2b15a140161ce53d72209dacea594230798c24774139b54ecaa980"
dependencies = [
"crc32fast",
"indexmap",
"memchr",
"typed-path 0.12.4",
]
[[package]]
name = "zip"
version = "9.1.3"
@@ -15148,7 +15205,7 @@ dependencies = [
"indexmap",
"memchr",
"nix",
"typed-path 0.13.0",
"typed-path",
"windows-sys 0.61.2",
]
@@ -15241,19 +15298,19 @@ dependencies = [
[[patch.unused]]
name = "egui_demo_lib"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
[[patch.unused]]
name = "egui_extras"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
[[patch.unused]]
name = "egui_inspection"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
[[patch.unused]]
name = "egui_system_font_provider"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
+18 -14
View File
@@ -102,6 +102,7 @@ craft-deckcraft-format = { path = "crates/deckcraft-format" }
craft-designcraft-format = { path = "crates/designcraft-format" }
craft-dxf = { path = "crates/dxf" }
craft-drawingml = { path = "crates/drawingml" }
craft-ease = { path = "crates/ease" }
craft-eps = { path = "crates/eps" }
craft-elf = { path = "crates/elf" }
craft-file-formats = { path = "crates/file-formats" }
@@ -123,6 +124,7 @@ craft-exr = { path = "crates/exr" }
craft-flags = { path = "crates/flags" }
craft-font-catalog = { path = "crates/font-catalog" }
craft-font-manager = { path = "crates/font-manager" }
craft-font-os-windows = { path = "crates/font-os-windows" }
craft-font-store = { path = "crates/font-store" }
craft-gainmap = { path = "crates/gainmap" }
craft-flow = { path = "crates/flow" }
@@ -144,6 +146,7 @@ craft-gpu-null = { path = "crates/gpu-null" }
craft-gpu-providers = { path = "crates/gpu-providers" }
craft-gpu-wgpu = { path = "crates/gpu-wgpu" }
craft-i18n = { path = "crates/i18n" }
craft-i18n-build = { path = "crates/i18n-build" }
craft-ipc = { path = "crates/ipc" }
craft-idml = { path = "crates/idml" }
craft-indd = { path = "crates/indd" }
@@ -226,6 +229,7 @@ craft-testkit = { path = "crates/testkit" }
craft-text = { path = "crates/text" }
craft-tcraft = { path = "crates/tcraft" }
craft-texture = { path = "crates/texture" }
craft-pbr = { path = "crates/pbr" }
craft-tga = { path = "crates/tga" }
craft-timeline = { path = "crates/timeline" }
craft-tiff = { path = "crates/tiff" }
@@ -316,20 +320,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" }
linesweeper = { path = "vendor/linesweeper" }
vello_common = { path = "vendor/vello_common" }
vello_cpu = { path = "vendor/vello_cpu" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
# symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid
+24 -3
View File
@@ -229,6 +229,26 @@ The colour management module in crates/cms is extracted from:
Licensed MIT OR Apache-2.0. Its generated ICC profile is dedicated to the public domain
(CC0-1.0); see ATTRIBUTION.md.
The image-based lighting in crates/pbr (craft-pbr) is adapted from:
- TextureCraft, crates/render/src/ibl.rs, revision fe8ee1bdb0243335560d3e726633cc0433ee99fc,
copied without its tests to crates/pbr/tests/it/reference/texturecraft.rs.
https://github.com/storytold/texturecraft
Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors.
- MaterialCraft, crates/render/src/ibl.rs, revision 4ff5af9af7371613ee37b186e03caf49ee6dbd88,
whose differing parts are copied to crates/pbr/tests/it/reference/materialcraft.rs.
https://github.com/storytold/materialcraft
Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors.
The BRDF, environment BRDF and default environment in crates/pbr are adapted from:
- EffectCraft, crates/render/src/three_d/adv/shade.rs and adv/scene.rs, revision
41da144555a1c8ddbbe94876a00259832322d00c, whose shading functions and default environment
are copied to crates/pbr/tests/it/reference/effectcraft.rs.
https://github.com/storytold/effectcraft
Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors.
The WGSL text in crates/pbr/src/shade.wgsl is adapted from:
- EffectCraft, crates/gpu/src/shaders/advanced3d.wgsl, revision
f4d45dfef3a280d96aff1d4eb5f1950160adefc2 (above).
All four sources are licensed MIT OR Apache-2.0. crates/pbr/README.md lists the changes from them.
Optional PDF writer
Krilla 0.8.2 (https://github.com/LaurenzV/krilla), MIT OR Apache-2.0.
@@ -269,9 +289,10 @@ linesweeper
linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in
vendor/linesweeper with its upstream license files and local patches, to src/sweep/sweep_line.rs,
src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its manifest names Joe Neeman as author, and
its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/linesweeper/README.craft.md and
vendor/linesweeper/SOURCE.json for provenance, the local patches and the files left out.
src/curve/transverse.rs, src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its manifest names
Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See
vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local
patches and the files left out.
Platform lifecycle source provenance
+17 -3
View File
@@ -77,6 +77,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
model (cues with exact tick times): SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and
TTML / IMSC1 / DFXP readers and writers, and CEA-608 / CEA-708 byte-pair coding. Carved from
FilmCraft.
- [`craft-cdr`](crates/cdr/README.md): bounded reader and writer of `.cdr` drawings: versions 1 to
27 and `.cmx` files read into one drawing model (pages, layers, groups, shapes, fills and
outlines), and version 15 `.cdr` files written.
- [`craft-cfb`](crates/cfb/README.md): clean-room Compound File Binary ([MS-CFB], OLE structured
storage) reader and writer: the container of legacy Office files, Outlook messages, encrypted
OOXML packages and AAF. Bounded on hostile input; what the streams hold stays with each format.
@@ -126,6 +129,10 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
EMU units and `a:xfrm`, colours with theme slots and colour transforms, preset shape outlines
(`a:prstGeom`), custom geometry with guide formulas (`a:custGeom`) and preset text warps
(`a:prstTxWarp`). From DeckCraft. Takes `craft-xml` trees; packages stay with each format.
- [`craft-ease`](crates/ease/README.md): easing curves, keyed tracks, constant-speed motion paths
and damped springs for animation: named eases, CSS `cubic-bezier()`, speed and influence,
editable custom and sampled curves, hold keys and a spring stepped by its exact solution.
From AniCraft and EffectCraft. No dependencies without the optional `serde` feature.
- [`craft-elf`](crates/elf/src/lib.rs): ELF program headers and dynamic section entries from untrusted bytes, from Craft Anything: 32- or 64-bit in either byte order, bounded counts and overflow-checked offsets, virtual-address-to-file mapping through `PT_LOAD`, and segment, permission and dynamic tag names.
- [`craft-eps`](crates/eps/README.md): Encapsulated PostScript files as a container: the binary
preview header (read and write), the DSC header comments and bounding boxes (also `(atend)`),
@@ -182,6 +189,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
and filters over the Google Fonts index, installed fonts by family, the font store interface,
and (`ui` feature) `FontsPanel`, the whole interface as one panel for the launcher's Fonts tab
and the standalone app.
- [`craft-font-os-windows`](crates/font-os-windows/src/lib.rs): the Win32 calls `craft-font-store`
needs on Windows to make a font available to every app of the user (the per-user font
registry, `AddFontResourceW`, `WM_FONTCHANGE`), behind a safe API.
- [`craft-font-store`](crates/font-store/README.md): the suite's font store: the pinned Google
Fonts and Noto indexes plus indexes the user adds (never curated), exact lookup by family and
style or PostScript name, and installs from each source's URLs (jsDelivr, then raw GitHub)
@@ -216,6 +226,10 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
lookup with fallback (`pt-br` → `pt` → English), plurals, language names, the system locale and
a pseudo locale. The catalogs stay a fully optional build input; apps keep `tl!` and their
language setting.
- [`craft-i18n-build`](crates/i18n-build/README.md): embeds the optional craft-i18n catalogs
from an app's `build.rs` (`CRAFT_I18N_DIR`, `CRAFT_I18N_REQUIRED`) as the table `craft-i18n`
reads, with each regional locale's parent and the app's own catalogs merged in. No
dependencies.
- [`craft-raw`](crates/raw/README.md): camera raw files, the file-format layer, from LightCraft with
what PhotoCraft's and FilmCraft's readers added: container parsing and decompression to a neutral
raw image (samples, CFA, black and white levels, active area, crop, orientation, colour tags,
@@ -399,8 +413,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
out of range, and `std::time::Instant` in code the web build runs. Its `deadline` module fails a test
whose body runs past a limit, or whose condition does not hold in time; a variable the caller names
replaces each limit. Its `hostile` module runs a parser on every truncation and on seeded damaged
copies of a valid input, and fails the test with the case that panicked or did not finish. Not
published.
copies of a valid input, and fails the test with the case that panicked or did not finish. Its `rng`
module holds two seeded generators for repeatable test input. Not published.
- [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds
hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns
for 47 more languages (one cargo feature each). With `ui`, the canvas text editor, Character and
@@ -476,7 +490,7 @@ architecture: [docs/craft-framework.md](docs/craft-framework.md).
- [`craft-theme`](crates/theme/README.md) and [`craft-theme-store`](crates/theme-store/README.md): the token model,
the built-in themes and the suite's theme selection ([docs/suite-themes.md](docs/suite-themes.md)).
- [`craft-host`](crates/host/README.md): the services an app installs once and every feature reads.
- `craft-win32`: the Win32 calls that need `unsafe`, behind a safe API; the one crate that allows `unsafe`.
- `craft-win32`: the window-procedure and window-handle Win32 calls that need `unsafe`, behind a safe API.
- Tools, not shipped in apps: `craft-ui-gallery` (the story viewer), `story-render` (one component's stories to
PNG files), [`craft-design-lint`](crates/design-lint/README.md), `craft-ui-bench`, `craft-ui-test-kit`.
+4 -4
View File
@@ -19,10 +19,10 @@ dirs = "7"
sysinfo = "0.39"
ureq = { version = "3", features = ["json"] }
sha2 = "0.11"
candle-core = { version = "0.9", optional = true }
candle-nn = { version = "0.9", optional = true }
candle-transformers = { version = "0.9", optional = true }
tokenizers = { version = "0.22", optional = true, default-features = false, features = ["onig"] }
candle-core = { version = "0.11.1", optional = true }
candle-nn = { version = "0.11.1", optional = true }
candle-transformers = { version = "0.11.1", optional = true }
tokenizers = { version = "0.23", optional = true, default-features = false, features = ["onig"] }
[features]
# Local GGUF inference on candle. Heavy dependency tree; apps opt in.
+5 -1
View File
@@ -12,7 +12,8 @@ and contains no `unsafe` code.
(compressor, expander and gate, limiter, maximizer, multiband and tube-modeled compressors),
delays and reverbs (including convolution and surround), modulation, restoration (denoise,
dehum, click remover, de-esser, de-reverb, speech enhancement), channel tools, distortion,
dither, a signal generator and a loudness meter.
dither, a signal generator, a loudness meter, and a pitch shifter for a live voice with 10 ms
of latency.
- `loudness`: an ITU-R BS.1770-4 / EBU R128 meter with momentary, short-term and integrated
loudness, loudness range (EBU Tech 3342), sample peak and true peak.
- `pan`: stereo pan laws, a surround panner over any layout of up to 16 speakers, and first-order
@@ -76,6 +77,9 @@ The crate combines two crates from the ArtCraft apps, with changes:
`648ed9db9a0e98cc55643babffac381521a556c8`: the tail length, offline mode, events, saved state
and editor parts of the trait, the maximizer, dither, panning, the signal generator and the
offline resampler.
- [storytold/soundcraft](https://github.com/storytold/soundcraft) `crates/dsp` at
`915481be1b49d7e0502e07b059d0c0198c61911a`: the two crossfaded read taps of the voice pitch
shifter (`src/plugins/pitch.rs`) and its YIN pitch tracker (`src/pitch_detect.rs`).
`NOTICE` keeps the copyright notices of both projects.
+3
View File
@@ -17,6 +17,7 @@ pub(crate) mod special;
mod stft;
pub(crate) mod time;
pub(crate) mod util;
pub(crate) mod voice;
pub(crate) use channel::{Amplify, Balance, ChannelVolume, Invert, Route, Routing};
pub(crate) use declick::ClickRemover;
@@ -35,6 +36,7 @@ pub(crate) use reverbs::{ConvolutionReverb, SurroundReverb};
pub use special::LoudnessMeterFx;
pub(crate) use special::{AmbisonicsPanner, Binauralizer, ChannelMixer, Distortion, GuitarSuite, Mastering, Mute, StereoExpander, VocalEnhancer};
pub(crate) use time::{Delay, Reverb};
pub use voice::VoicePitch;
use crate::{AudioEffect, ParamSpec, sane_channels, sane_sample_rate};
@@ -124,6 +126,7 @@ static REGISTRY: &[EffectInfo] = &[
entry!("dehum", "DeHum", Restoration, DeHum),
entry!("denoise", "DeNoise", Restoration, DeNoise),
entry!("pitch_shifter", "Pitch Shifter", Pitch, PitchShifter),
entry!("voice_pitch", "Voice Pitch", Pitch, VoicePitch),
entry!("deesser", "DeEsser", Restoration, DeEsser),
entry!("dereverb", "DeReverb", Restoration, DeReverb),
entry!("speech_enhance", "Enhance Speech", Filter, SpeechEnhance),
@@ -147,7 +147,7 @@ fn latency_is_where_the_impulse_lands() {
// settings (FFT filter / convolution / existing STFT effects). The click remover repairs a
// lone impulse in silence as a click, so its latency is checked on noise by
// `neutral_settings_are_delayed_identity`.
for (id, p) in [("fft_filter", vec![]), ("convolution_reverb", vec![("mix", 0.0)])] {
for (id, p) in [("fft_filter", vec![]), ("convolution_reverb", vec![("mix", 0.0)]), ("voice_pitch", vec![])] {
let mut e = fx(id, &p);
let lat = e.latency();
assert!(lat > 0, "{id}");
@@ -976,6 +976,7 @@ fn direct_constructors_cap_the_channel_count() {
channel::Amplify,
filters::FullParametricEq,
pitch::PitchShifter,
voice::VoicePitch,
);
}
+575
View File
@@ -0,0 +1,575 @@
//! Voice pitch shifter for live use: two read taps sweep through a short delay line and crossfade
//! (sin² and cos² gains), so the output moves by the pitch ratio with a latency of 10 ms.
//!
//! The taps sit half a sweep apart and are centered on the latency, so the delay of each one
//! stays within `latency ± spacing`. A pitch tracker (YIN, on a copy of the input low-passed and
//! decimated to about 12 kHz, over the last 42.7 ms of history) sets the spacing to a whole number
//! of periods whenever one tap passes the center, so the two taps read the same point of a
//! period and a voiced sound crossfades without beating. A period longer than the room inside the
//! latency (below about 100 Hz), and unvoiced input, use the widest spacing that fits; below
//! 100 Hz each crossfade then steps the phase of the voice, which can move its pitch by a few
//! hertz (5 Hz for 85 Hz shifted up 5 semitones). At a shift
//! of 0 the effect crossfades over 20 ms to the input delayed by the latency, so a neutral setting
//! is a plain delay.
use crate::biquad::{Biquad, Coeffs, FilterType};
use crate::{AudioEffect, ParamSpec, ParamValues, Unit, block_len, flush32, param_plumbing};
use std::f64::consts::PI;
/// Latency, and the most a tap may read either side of it.
const LATENCY_MS: f32 = 10.0;
/// Lowest and highest fundamental the tracker reports.
const MIN_HZ: f32 = 70.0;
const MAX_HZ: f32 = 1000.0;
/// Rate the tracker analyzes at, before rounding to a whole decimation factor.
const TRACK_RATE: f32 = 12_000.0;
/// YIN's threshold on the cumulative mean normalized difference.
const THRESHOLD: f32 = 0.15;
/// Length of the crossfade to and from the plain delay at a shift of 0.
const BYPASS_MS: f32 = 20.0;
/// Samples kept between a tap and the newest sample, for the cubic interpolation.
const MARGIN: f64 = 2.0;
/// Largest step of the sweep phase per sample; one step never crosses two tap boundaries.
const MAX_STEP: f64 = 0.45;
/// Analysis input is clipped to this level, so a huge sample cannot overflow the tracker.
const TRACK_CLIP: f64 = 1.0e4;
/// Fundamental period of the recent input, from YIN (de Cheveigné and Kawahara, 2002) run on a
/// low-passed, decimated copy. Every buffer is sized at creation.
///
/// It keeps two copies: the mean of the channels, and the first channel alone. A frame whose
/// mean holds less than a quarter of the first channel's energy (channels of opposite polarity
/// cancel in the mean) is analyzed on the first channel.
#[derive(Clone, Debug)]
struct Tracker {
/// Input samples per analysis sample.
factor: usize,
count: usize,
coeffs: [Coeffs; 2],
feeds: [Feed; 2],
at: usize,
hop: usize,
since: usize,
frame: Vec<f32>,
diff: Vec<f32>,
min_tau: usize,
max_tau: usize,
/// Period in input samples, or `None` when the last frame was unvoiced.
period: Option<f64>,
}
impl Tracker {
fn new(sample_rate: f32) -> Self {
let factor = (sample_rate / TRACK_RATE).round().max(1.0) as usize;
let rate = sample_rate / factor as f32;
let max_hz = MAX_HZ.min(rate / 4.0);
let min_tau = ((rate / max_hz).floor() as usize).max(2);
let max_tau = (rate / MIN_HZ).ceil() as usize + 1;
let len = (2 * max_tau + 2).next_power_of_two();
// Fourth-order Butterworth low-pass at a quarter of the analysis rate.
let (sr, fc) = (sample_rate as f64, rate as f64 / 4.0);
let coeffs = [0.541_196_1, 1.306_563].map(|q| Coeffs::design(FilterType::LowPass, sr, fc, q, 0.0));
Tracker {
factor,
count: 0,
coeffs,
feeds: [Feed::new(len), Feed::new(len)],
at: 0,
hop: len / 4,
since: 0,
frame: vec![0.0; len],
diff: vec![0.0; max_tau + 2],
min_tau,
max_tau,
period: None,
}
}
fn reset(&mut self) {
self.count = 0;
self.feeds.iter_mut().for_each(Feed::reset);
self.at = 0;
self.since = 0;
self.period = None;
}
/// Takes one input sample, as the mean of the channels and the first channel; runs an
/// analysis every `hop` analysis samples.
fn push(&mut self, mean: f32, first: f32) {
let clipped = [mean, first].map(|x| (x as f64).clamp(-TRACK_CLIP, TRACK_CLIP));
for (feed, x) in self.feeds.iter_mut().zip(clipped) {
feed.filter(&self.coeffs, x);
}
self.count += 1;
if self.count < self.factor {
return;
}
self.count = 0;
let mask = self.frame.len() - 1;
for feed in &mut self.feeds {
feed.ring[self.at] = feed.last as f32;
}
self.at = (self.at + 1) & mask;
self.since += 1;
if self.since >= self.hop {
self.since = 0;
self.analyze();
}
}
fn analyze(&mut self) {
let [mean, first] = [0, 1].map(|f| self.feeds[f].ring.iter().map(|v| v * v).sum::<f32>());
let feed = if mean < 0.25 * first { &self.feeds[1] } else { &self.feeds[0] };
let mask = self.frame.len() - 1;
for (i, v) in self.frame.iter_mut().enumerate() {
*v = feed.ring[(self.at + i) & mask];
}
self.period = yin(&self.frame, &mut self.diff, self.min_tau, self.max_tau).map(|t| t * self.factor as f64);
}
/// Tap spacing for the current period: the most whole periods that fit in `max`, or `max`
/// itself for unvoiced input and for a period longer than `max`.
fn spacing(&self, max: f64) -> f64 {
match self.period {
Some(t) if t <= max => (max / t).floor() * t,
_ => max,
}
}
}
/// One low-passed, decimated copy of the input that the tracker can analyze.
#[derive(Clone, Debug)]
struct Feed {
lowpass: [Biquad; 2],
/// The newest low-passed sample, kept at every input sample.
last: f64,
ring: Vec<f32>,
}
impl Feed {
fn new(len: usize) -> Self {
Feed { lowpass: [Biquad::new(), Biquad::new()], last: 0.0, ring: vec![0.0; len] }
}
fn reset(&mut self) {
self.lowpass.iter_mut().for_each(Biquad::reset);
self.last = 0.0;
self.ring.iter_mut().for_each(|v| *v = 0.0);
}
fn filter(&mut self, coeffs: &[Coeffs; 2], x: f64) {
let y = self.lowpass[0].tick(&coeffs[0], x);
self.last = self.lowpass[1].tick(&coeffs[1], y);
}
}
/// YIN on `frame`: the lag in samples, with parabolic interpolation, or `None` when no lag in
/// `min_tau..max_tau` falls below the threshold. `diff` holds at least `max_tau + 1` values.
fn yin(frame: &[f32], diff: &mut [f32], min_tau: usize, max_tau: usize) -> Option<f64> {
let w = frame.len().checked_sub(max_tau)?;
if max_tau <= min_tau + 2 || diff.len() <= max_tau || w == 0 {
return None;
}
difference(frame, &mut diff[..=max_tau], w);
normalize(&mut diff[..=max_tau]);
pick(&diff[..=max_tau], min_tau)
}
/// Squared difference of the frame with itself at every lag.
fn difference(frame: &[f32], diff: &mut [f32], w: usize) {
diff[0] = 0.0;
for (tau, d) in diff.iter_mut().enumerate().skip(1) {
*d = frame[..w].iter().zip(&frame[tau..tau + w]).map(|(a, b)| (a - b) * (a - b)).sum();
}
}
/// Cumulative mean normalized difference, in place.
fn normalize(diff: &mut [f32]) {
diff[0] = 1.0;
let mut running = 0.0f32;
for (tau, d) in diff.iter_mut().enumerate().skip(1) {
running += *d;
*d = if running > 0.0 { *d * tau as f32 / running } else { 1.0 };
}
}
/// The first dip below the threshold, walked to its local minimum and interpolated.
fn pick(cmnd: &[f32], min_tau: usize) -> Option<f64> {
let last = cmnd.len() - 1;
let mut tau = (min_tau..last).find(|&t| cmnd[t] < THRESHOLD)?;
while tau + 1 < last && cmnd[tau + 1] < cmnd[tau] {
tau += 1;
}
let (a, b, c) = (cmnd[tau - 1] as f64, cmnd[tau] as f64, cmnd[tau + 1] as f64);
let denom = a - 2.0 * b + c;
let shift = if denom.abs() > 1e-12 { (0.5 * (a - c) / denom).clamp(-1.0, 1.0) } else { 0.0 };
Some(tau as f64 + shift)
}
/// Four-point cubic Hermite read of `line` at a fractional `delay` behind `pos`. `delay` is at
/// least 2 and leaves two samples in the line behind it.
#[inline]
fn read(line: &[f32], mask: usize, pos: usize, delay: f64) -> f64 {
let i = delay as usize;
let f = delay - i as f64;
let at = |k: usize| line[(pos + line.len() - k) & mask] as f64;
let (ym1, y0, y1, y2) = (at(i - 1), at(i), at(i + 1), at(i + 2));
let c1 = 0.5 * (y1 - ym1);
let c2 = ym1 - 2.5 * y0 + 2.0 * y1 - 0.5 * y2;
let c3 = 0.5 * (y2 - ym1) + 1.5 * (y0 - y1);
((c3 * f + c2) * f + c1) * f + y0
}
/// Read positions and gains of both taps for one sample.
#[derive(Clone, Copy, Debug)]
struct Taps {
wet: f64,
delay_a: f64,
gain_a: f64,
delay_b: f64,
}
/// Pitch shifter for a live voice, 10 ms of latency (±24 semitones and ±100 cents).
pub struct VoicePitch {
pv: ParamValues,
latency: usize,
/// Widest tap spacing that keeps both taps inside the line, in samples.
max_spacing: f64,
lines: Vec<Vec<f32>>,
mask: usize,
pos: usize,
tracker: Tracker,
ratio: f64,
/// Sweep phase in `[0, 1)`: tap A is at the latency when it is 0.5, tap B when it is 0.
phase: f64,
spacing: f64,
/// Share of the shifted signal against the plain delay.
wet: f64,
wet_step: f64,
}
impl VoicePitch {
pub const PARAMS: &'static [ParamSpec] = &[
ParamSpec::new("semitones", "Pitch", -24.0, 24.0, 0.0, Unit::Semitones),
ParamSpec::new("cents", "Fine Tune (cents)", -100.0, 100.0, 0.0, Unit::None),
];
pub fn new(sample_rate: f32, channels: usize) -> Self {
let sample_rate = crate::sane_sample_rate(sample_rate);
let ch = crate::sane_channels(channels);
let latency = ((sample_rate * LATENCY_MS / 1000.0).round() as usize).max(4);
let len = (2 * latency + 8).next_power_of_two();
let mut s = VoicePitch {
pv: ParamValues::new(Self::PARAMS),
latency,
max_spacing: latency as f64 - MARGIN,
lines: vec![vec![0.0; len]; ch],
mask: len - 1,
pos: 0,
tracker: Tracker::new(sample_rate),
ratio: 1.0,
phase: 0.5,
spacing: latency as f64 - MARGIN,
wet: 0.0,
wet_step: 1.0 / (sample_rate * BYPASS_MS / 1000.0).max(1.0) as f64,
};
s.apply_params(true);
s
}
fn apply_params(&mut self, snap: bool) {
let shift = self.pv.v("semitones") as f64 + self.pv.v("cents") as f64 / 100.0;
self.ratio = 2f64.powf(shift / 12.0);
if snap {
self.wet = self.target_wet();
}
}
fn target_wet(&self) -> f64 {
if self.ratio == 1.0 { 0.0 } else { 1.0 }
}
/// Moves the crossfade and the sweep by one sample and returns where the taps read.
fn advance(&mut self) -> Taps {
let target = self.target_wet();
self.wet = if self.wet < target { (self.wet + self.wet_step).min(target) } else { (self.wet - self.wet_step).max(target) };
if self.wet == 0.0 {
// Fully on the plain delay: the next shift starts with tap A at the latency.
self.phase = 0.5;
self.spacing = self.max_spacing;
} else {
self.sweep();
}
let pb = if self.phase >= 0.5 { self.phase - 0.5 } else { self.phase + 0.5 };
let (l, s) = (self.latency as f64, self.spacing);
Taps { wet: self.wet, delay_a: l + (self.phase - 0.5) * 2.0 * s, gain_a: (PI * self.phase).sin().powi(2), delay_b: l + (pb - 0.5) * 2.0 * s }
}
/// Advances the sweep phase. A tap whose delay changes by `1 - ratio` per sample reads the
/// input `ratio` times as fast.
fn sweep(&mut self) {
let step = ((1.0 - self.ratio) / (2.0 * self.spacing)).clamp(-MAX_STEP, MAX_STEP);
let raw = self.phase + step;
let wrapped = !(0.0..1.0).contains(&raw);
let p = raw - raw.floor();
if wrapped || (p >= 0.5) != (self.phase >= 0.5) {
self.regrain(p, wrapped);
} else {
self.phase = p;
}
}
/// One tap has just passed the latency and the other is silent at the end of its sweep:
/// take the tracker's spacing, and scale the centered tap's small offset so its delay does
/// not jump.
fn regrain(&mut self, p: f64, wrapped: bool) {
let new = self.tracker.spacing(self.max_spacing);
let k = self.spacing / new;
self.spacing = new;
let phase = if wrapped {
// Tap B is centered; its offset from the center is `p` (just past 0) or `p - 1`.
let u = (if p < 0.5 { p } else { p - 1.0 }) * k;
let u = u.clamp(-MAX_STEP, MAX_STEP);
if u < 0.0 { u + 1.0 } else { u }
} else {
0.5 + ((p - 0.5) * k).clamp(-MAX_STEP, MAX_STEP)
};
self.phase = if phase < 1.0 { phase } else { 0.0 };
}
}
impl AudioEffect for VoicePitch {
param_plumbing!("voice_pitch");
fn latency(&self) -> usize {
self.latency
}
fn tail_samples(&self) -> usize {
// A tap reads up to `latency + max_spacing` samples back and the cubic read two samples
// more, which is twice the latency in all.
self.latency
}
fn reset(&mut self) {
self.lines.iter_mut().for_each(|l| l.iter_mut().for_each(|v| *v = 0.0));
self.pos = 0;
self.tracker.reset();
self.phase = 0.5;
self.spacing = self.max_spacing;
self.wet = self.target_wet();
}
fn process(&mut self, channels: &mut [&mut [f32]]) {
let len = block_len(channels);
let ch = channels.len().min(self.lines.len());
let dry_at = self.mask + 1 - self.latency;
for i in 0..len {
let mut sum = 0.0f32;
for (line, io) in self.lines.iter_mut().zip(channels.iter()) {
// A non-finite sample is stored as silence, so it never reaches the output.
let x = flush32(io[i]);
line[self.pos] = x;
sum += x;
}
let first = self.lines[0][self.pos];
self.tracker.push(sum / ch as f32, first);
let t = self.advance();
for (line, io) in self.lines.iter().zip(channels.iter_mut()) {
let dry = line[(self.pos + dry_at) & self.mask] as f64;
let y = if t.wet == 0.0 {
dry
} else {
let shifted =
t.gain_a * read(line, self.mask, self.pos, t.delay_a) + (1.0 - t.gain_a) * read(line, self.mask, self.pos, t.delay_b);
t.wet * shifted + (1.0 - t.wet) * dry
};
io[i] = y.clamp(-f32::MAX as f64, f32::MAX as f64) as f32;
}
self.pos = (self.pos + 1) & self.mask;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::*;
const SR: f32 = 48000.0;
fn shifter(semitones: f32, cents: f32) -> VoicePitch {
let mut p = VoicePitch::new(SR, 2);
assert!(p.set_param("semitones", semitones) && p.set_param("cents", cents));
p.reset();
p
}
fn run(p: &mut VoicePitch, x: &[f32]) -> Vec<f32> {
let (mut l, mut r) = (x.to_vec(), x.to_vec());
p.process(&mut [&mut l, &mut r]);
assert_eq!(l, r, "both channels get the same shift");
l
}
/// One second of output after the first half second.
fn settled(y: &[f32]) -> &[f32] {
&y[SR as usize / 2..SR as usize * 3 / 2]
}
/// Frequency of the strongest component between `lo` and `hi` Hz, to 0.01 Hz.
fn peak_hz(x: &[f32], lo: f64, hi: f64) -> f64 {
let best = |from: f64, to: f64, step: f64| {
let n = ((to - from) / step) as usize;
(0..=n)
.map(|i| from + i as f64 * step)
.max_by(|a, b| tone_amplitude(x, *a, SR as f64).total_cmp(&tone_amplitude(x, *b, SR as f64)))
.unwrap_or(from)
};
let coarse = best(lo, hi, 0.25);
best(coarse - 0.25, coarse + 0.25, 0.01)
}
fn cents(f: f64, want: f64) -> f64 {
1200.0 * (f / want).log2()
}
/// A voiced tone shifted by an octave either way, or by a fifth with a fine offset, lands on
/// the shifted frequency within 2 cents.
#[test]
fn a_shifted_tone_reads_the_shifted_frequency() {
for (f_in, semis, fine) in [(220.0, 12.0, 0.0), (220.0, -12.0, 0.0), (180.0, 7.0, 30.0), (110.0, -24.0, 0.0)] {
let mut p = shifter(semis, fine);
let y = run(&mut p, &sine(f_in, 0.5, SR as f64, SR as usize * 2, 0.0));
let want = f_in * 2f64.powf((semis as f64 + fine as f64 / 100.0) / 12.0);
let got = peak_hz(settled(&y), want * 0.9, want * 1.1);
assert!(cents(got, want).abs() < 2.0, "{f_in} Hz {semis:+} st {fine:+} ct: {got} Hz, want {want}");
}
}
/// On a voiced tone the taps are spaced by whole periods, so the crossfades do not beat:
/// almost all the output is the shifted tone.
#[test]
fn a_voiced_tone_crossfades_without_beating() {
for (f_in, semis) in [(220.0, 7.0), (150.0, -5.0), (300.0, 12.0)] {
let mut p = shifter(semis, 0.0);
let y = run(&mut p, &sine(f_in, 0.5, SR as f64, SR as usize * 2, 0.0));
let rest = beside_tone_db(&y, f_in * 2f64.powf(semis as f64 / 12.0));
assert!(rest < -40.0, "{f_in} Hz {semis:+} st: {rest:.1} dB beside the tone");
}
}
/// A voice whose two channels have opposite polarity, which cancel in their mean, is still
/// tracked and crossfades without beating.
#[test]
fn opposite_polarity_channels_are_still_tracked() {
let mut p = shifter(7.0, 0.0);
let mut l = sine(220.0, 0.5, SR as f64, SR as usize * 2, 0.0);
let mut r: Vec<f32> = l.iter().map(|v| -v).collect();
p.process(&mut [&mut l, &mut r]);
assert!(l.iter().zip(&r).all(|(a, b)| *a == -*b));
let rest = beside_tone_db(&l, 220.0 * 2f64.powf(7.0 / 12.0));
assert!(rest < -40.0, "{rest:.1} dB beside the tone");
}
/// Level of everything but the strongest component near `want`, against that component, in
/// the settled output.
fn beside_tone_db(y: &[f32], want: f64) -> f64 {
let tail = settled(y);
let tone = tone_amplitude(tail, peak_hz(tail, want * 0.98, want * 1.02), SR as f64) / std::f64::consts::SQRT_2;
db((rms(tail).powi(2) - tone * tone).max(0.0).sqrt() / tone)
}
/// The output of a burst, shifted or not, comes from taps within the spacing of the latency:
/// nothing sounds earlier than `latency - tail` or later than `latency + tail` around it.
#[test]
fn a_shifted_burst_stays_within_the_spacing_of_the_latency() {
for semis in [0.0, -24.0, -3.0, 5.0, 24.0] {
let mut p = shifter(semis, 0.0);
let (n, at, len) = (8000, 1777, 1000);
let mut rng = Rng::new(7);
let mut x = vec![0.0f32; n];
x[at..at + len].iter_mut().for_each(|v| *v = 0.5 * rng.uniform());
let y = run(&mut p, &x);
let reach = p.tail_samples();
let (lo, hi) = (at + p.latency() - reach, at + len + p.latency() + reach);
assert!(y.iter().enumerate().all(|(i, v)| *v == 0.0 || (lo..hi).contains(&i)), "{semis}");
assert!(y.iter().any(|v| v.abs() > 0.05), "{semis}: the burst is lost");
}
}
/// Over whole sweeps, the oldest sample either tap reads, interpolation included, lies within
/// the latency plus the tail, so a render that compensates the latency and runs the tail past
/// the end of the input keeps every sample the taps still hold.
#[test]
fn the_tail_covers_the_oldest_sample_a_tap_reads() {
for semis in [-24.0, -3.0, 5.0, 24.0] {
let mut p = shifter(semis, 0.0);
let oldest = (0..SR as usize).map(|_| p.advance()).map(|t| t.delay_a.max(t.delay_b) as usize + 2).max().unwrap_or(0);
assert!(oldest > p.latency(), "{semis}: the taps never sweep past the latency");
assert!(oldest <= p.latency() + p.tail_samples(), "{semis}: a tap reads {oldest} samples back");
}
}
/// A gliding voiced tone with a shift change part way gives the same output however the
/// stream is cut into blocks, spacing changes included.
#[test]
fn output_does_not_depend_on_how_the_stream_is_cut() {
let n = 40_000;
let x: Vec<f32> = (0..n)
.map(|i| (0.4 * (2.0 * std::f64::consts::PI * (120.0 * i as f64 / 48_000.0 + 0.6 * (i as f64 / 48_000.0).powi(2) * 200.0)).sin()) as f32)
.collect();
let change = 17_321;
let run_cut = |sizes: &mut dyn FnMut() -> usize| {
let mut p = shifter(4.0, -20.0);
let mut y = x.clone();
let mut pos = 0;
while pos < n {
if pos == change {
p.set_param("semitones", -9.0);
}
let mut len = sizes().min(n - pos);
if pos < change {
len = len.min(change - pos);
}
p.process(&mut [&mut y[pos..pos + len]]);
pos += len;
}
y
};
let whole = run_cut(&mut || usize::MAX);
let mut rng = Rng::new(11);
let cut = run_cut(&mut || (rng.next_u64() % 700) as usize);
assert!(whole.iter().zip(&cut).all(|(a, b)| a.to_bits() == b.to_bits()));
}
/// NaN, infinite and the largest finite samples in a shifted voice give finite output, and
/// the voice is still shifted afterwards.
#[test]
fn non_finite_and_huge_samples_give_finite_output() {
let mut p = shifter(-7.0, 0.0);
let mut x = sine(200.0, 0.5, SR as f64, SR as usize * 2, 0.0);
for (i, bad) in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX, -f32::MAX].into_iter().enumerate() {
x[3000 + i * 1500] = bad;
x[3001 + i * 1500] = bad;
}
let y = run(&mut p, &x);
assert!(y.iter().all(|v| v.is_finite()));
let want = 200.0 * 2f64.powf(-7.0 / 12.0);
let tail = settled(&y);
assert!(cents(peak_hz(tail, want * 0.9, want * 1.1), want).abs() < 2.0);
assert!(db(rms(tail) / (0.5 / std::f64::consts::SQRT_2)).abs() < 1.0, "level {}", rms(tail));
}
/// The tracker finds a voice's period down to 70 Hz and reports nothing for silence.
#[test]
fn the_tracker_reaches_70_hz() {
for f in [72.0, 110.0, 440.0, 950.0] {
let mut t = Tracker::new(SR);
for v in sine(f, 0.3, SR as f64, SR as usize / 4, 0.0) {
t.push(v, v);
}
let period = t.period.unwrap_or(0.0);
assert!((SR as f64 / period / f - 1.0).abs() < 0.005, "{f} Hz read as {} Hz", SR as f64 / period);
}
let mut t = Tracker::new(SR);
(0..SR as usize / 4).for_each(|_| t.push(0.0, 0.0));
assert!(t.period.is_none());
}
}
+5 -3
View File
@@ -214,9 +214,11 @@ packet. Opus with empty `extradata` and 1 or 2 channels (RTP, MPEG-TS) needs no
To seek: position your demuxer at the packet that starts `preroll()` frames or more before the
target, call `reset()`, decode from there, and drop the output before the target.
The codec modules are also usable on their own. `aac::Decoder` and `opus::Decoder` return the
codec's channel order; `aac::wav_order(channel_config)` and `opus::wav_order(channels)` map it to
WAV order. `ac3::Decoder` and `mpa::Decoder` output WAV order.
The codec modules are also usable on their own. `aac::Decoder`, `opus::Decoder` and
`vorbis::decoder::Decoder` return the codec's channel order; `aac::wav_order(channel_config)`,
`opus::wav_order(channels)` and `vorbis::wav_order(channels)` map it to WAV order, and
`vorbis::layout(channels)` gives the speakers of the result. `ac3::Decoder` and `mpa::Decoder`
output WAV order.
### Encode a file
+76
View File
@@ -1,7 +1,83 @@
//! Vorbis I: the pure-Rust [`decoder`] (feature `vorbis-decode`) and [`encoder`] (feature
//! `vorbis-encode`). `craft_audio::decode` still reads Vorbis files through symphonia.
//!
//! Both work in Vorbis channel order (Vorbis I §4.3.9). [`wav_order`] maps decoded channels to the
//! WAV order the rest of craft-audio uses, and [`layout`] gives the speakers they then feed.
use crate::ChannelLayout;
#[cfg(feature = "vorbis-decode")]
pub mod decoder;
#[cfg(feature = "vorbis-encode")]
pub mod encoder;
/// Channel order for Vorbis surround (Vorbis I §4.3.9: L C R for three, L C R Ls Rs for five,
/// L C R Ls Rs LFE for 5.1, L C R Ls Rs Cb LFE for 6.1, L C R Ls Rs Lb Rb LFE for 7.1): output
/// channel → decoded channel, giving the WAV order (L R C LFE back… side…) of [`layout`]. `None` for
/// 1, 2 and 4 channels, which are already in WAV order, and for more than 8, whose order the
/// specification leaves to the application.
///
/// ```
/// let vorbis: Vec<Vec<f32>> = (0..6).map(|c| vec![c as f32]).collect(); // L C R Ls Rs LFE
/// let order = craft_audio::vorbis::wav_order(6).unwrap();
/// let wav: Vec<Vec<f32>> = order.iter().map(|&c| vorbis[c].clone()).collect(); // L R C LFE Ls Rs
/// assert_eq!(wav[3], vec![5.0]);
/// ```
pub fn wav_order(channels: usize) -> Option<&'static [usize]> {
Some(match channels {
3 => &[0, 2, 1],
5 => &[0, 2, 1, 3, 4],
6 => &[0, 2, 1, 5, 3, 4],
7 => &[0, 2, 1, 6, 5, 3, 4],
8 => &[0, 2, 1, 7, 5, 6, 3, 4],
_ => return None,
})
}
/// The speakers of a Vorbis stream with `channels` channels, in WAV order (after [`wav_order`]):
/// mono, stereo, L R C, quad, 5.0, 5.1, 6.1 with a back center and side surrounds, and 7.1 with
/// backs and sides. Other counts are unordered. For 7 channels this differs from
/// [`ChannelLayout::default_for`], which puts the surrounds at the back.
pub fn layout(channels: u16) -> ChannelLayout {
match channels {
1 => ChannelLayout::MONO,
2 => ChannelLayout::STEREO,
3 => ChannelLayout::SURROUND_3_0,
4 => ChannelLayout::QUAD,
5 => ChannelLayout::SURROUND_5_0,
6 => ChannelLayout::SURROUND_5_1,
7 => ChannelLayout::SURROUND_6_1,
8 => ChannelLayout::SURROUND_7_1,
_ => ChannelLayout::unordered(channels),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Speaker::{self, *};
/// Vorbis I §4.3.9, one row per channel count, in the order a stream carries the channels.
const VORBIS_ORDER: [&[Speaker]; 8] = [
&[FrontCenter],
&[FrontLeft, FrontRight],
&[FrontLeft, FrontCenter, FrontRight],
&[FrontLeft, FrontRight, BackLeft, BackRight],
&[FrontLeft, FrontCenter, FrontRight, BackLeft, BackRight],
&[FrontLeft, FrontCenter, FrontRight, BackLeft, BackRight, Lfe],
&[FrontLeft, FrontCenter, FrontRight, SideLeft, SideRight, BackCenter, Lfe],
&[FrontLeft, FrontCenter, FrontRight, SideLeft, SideRight, BackLeft, BackRight, Lfe],
];
#[test]
fn reordered_channels_feed_the_layout_speakers() {
for (i, stream) in VORBIS_ORDER.iter().enumerate() {
let channels = i + 1;
let wav: Vec<Speaker> = match wav_order(channels) {
Some(order) => order.iter().map(|&c| stream[c]).collect(),
None => stream.to_vec(),
};
assert_eq!(wav, layout(channels as u16).speakers(), "{channels} channels");
}
}
}
+15
View File
@@ -340,6 +340,16 @@ pub enum Action<P> {
/// The destination.
to: Target<P>,
},
/// Move one shown panel, without the rest of its group, to a recorded place, as reopening a closed panel
/// restores it: the split size, sibling subtree, group, column and accordion state of `location` come back
/// with it. Dock Panel returns a floating panel to the docked place it left this way.
#[non_exhaustive]
Restore {
/// The panel the action applies to.
panel: P,
/// Where the panel goes back.
location: Location<P>,
},
}
impl<P> Location<P> {
@@ -489,6 +499,11 @@ impl<P> Action<P> {
pub fn move_panel(panel: P, to: Target<P>) -> Self {
Self::MovePanel { panel, to }
}
/// Builds [`Action::Restore`].
pub fn restore(panel: P, location: Location<P>) -> Self {
Self::Restore { panel, location }
}
}
impl<P> DockPlacement<P> {
+12
View File
@@ -78,6 +78,18 @@ impl<P: Clone + Eq + Hash> Layout<P> {
return Err(DockError::NotAllowed);
}
}
Action::Restore { panel, location } => {
let policy = permissions(panel);
let allowed = policy.movable
&& location
.anchor
.as_ref()
.is_none_or(|anchor| location.placement.allowed_by(permissions(anchor)) && (!floats(anchor) || policy.floatable))
&& (location.floating.is_none() || policy.floatable);
if !allowed {
return Err(DockError::NotAllowed);
}
}
Action::MoveGroup { panel, to } | Action::MoveColumn { panel, to } | Action::MoveWindow { panel, to } => {
let members = self.members(panel, unit_of(&action))?;
if members.iter().any(|p| !permissions(p).movable) {
+4
View File
@@ -145,6 +145,10 @@ impl<P: Clone + Eq + Hash> Layout<P> {
self.insert_moving(Moving::taken(Group::new(vec![entry.panel], 0), source), to, canvas)
}
},
Action::Restore { panel, location } => {
self.take(&panel).ok_or(DockError::MissingPanel)?;
self.restore(panel, &location)
}
Action::CloseGroup { ref panel } | Action::CloseWindow { ref panel } => self.take_unit(panel, unit_of(&action)).map(|_| ()),
Action::CloseOthers { panel } => {
for other in self.members(&panel, Unit::Group)? {
+15 -7
View File
@@ -41,8 +41,8 @@ pub struct Workspace<P> {
/// goes back.
#[serde(default)]
hidden: Vec<(P, Location<P>)>,
/// Floating panels with the docked location each one left, so Dock Panel can return it. Saved with the
/// workspace.
/// Floating panels, and closed panels that were floating, with the docked location each one left, so Dock Panel
/// can return it. A closed panel's record lives as long as its `hidden` record. Saved with the workspace.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
floated: Vec<(P, Location<P>)>,
/// Counts the replacements of this live workspace. Not saved, and not part of equality.
@@ -105,7 +105,7 @@ impl<P> Workspace<P> {
&self.hidden
}
/// The floating panels with the docked location each one left.
/// The floating panels, and the closed panels that were floating, with the docked location each one left.
pub fn floated(&self) -> &[(P, Location<P>)] {
&self.floated
}
@@ -409,11 +409,12 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
}
}
/// Update the floated records after an action that turned `before` into the current layout: drop the records of
/// panels that no longer float, and record the docked place of each panel that floats now and did not before.
/// Update the floated records after an action that turned `before` into the current layout: drop the stale
/// records ([`Self::drop_stale_floated`]), and record the docked place of each panel that floats now and did not
/// before.
fn track_floated(&mut self, before: &Layout<P>) {
self.drop_stale_floated();
let layout = &self.layout;
self.floated.retain(|(p, _)| floats(layout, p));
let fresh: Vec<(P, Location<P>)> = layout
.panels()
.into_iter()
@@ -423,6 +424,13 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
self.floated.extend(fresh);
}
/// Drop the floated records of panels that neither float nor are hidden: a panel that closed while floating keeps
/// its record as long as its hidden record, so it docks back to its place after it reopens floating.
fn drop_stale_floated(&mut self) {
let (layout, hidden) = (&self.layout, &self.hidden);
self.floated.retain(|(p, _)| floats(layout, p) || hidden.iter().any(|(q, _)| q == p));
}
/// Restore `panel` where the chain of hidden anchors from its location ends, else at the
/// nearest location before that end that restores. The hidden panels it passed then anchor
/// on the panel before them in the chain, on the recorded side, so reopening them joins it
@@ -492,7 +500,6 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
self.layout.take(panel);
}
self.hidden.extend(locations);
self.floated.retain(|(p, _)| registered(p));
let known: HashSet<P> = self.layout.panels().into_iter().chain(self.hidden.iter().map(|(p, _)| p)).cloned().collect();
let mut missing: Vec<(P, Location<P>)> = Vec::new();
for panel in default.layout.panels() {
@@ -536,6 +543,7 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
!drop
});
self.hidden.truncate(MAX_PANELS);
self.drop_stale_floated();
}
}
+10 -4
View File
@@ -224,9 +224,10 @@ fn tabs_closed_together_reopen_together_and_a_tab_closed_alone_stays_closed() {
assert_eq!(group_members(workspace.layout(), 2), [2, 3], "it reopens beside 2");
}
/// A panel that floats keeps its docked place until it docks or closes; floating again from the float keeps the first.
/// A panel that floats keeps its docked place until it docks; floating again from the float keeps the first, and a
/// float that closes keeps it while it is closed and after it reopens floating.
#[test]
fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() {
fn a_floated_panel_keeps_where_it_was_docked_until_it_docks() {
let mut workspace = Workspace::new(docked());
let docked_at = workspace.layout().location(&2).unwrap();
workspace.apply(Action::float(2, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap();
@@ -235,10 +236,15 @@ fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() {
assert_eq!(workspace.floated(), [(2, docked_at)], "floating again from the float keeps the first record");
workspace.apply(Action::move_beside(2, 11, DockPlacement::tab(None)), false, allow).unwrap();
assert!(workspace.floated().is_empty(), "docking drops the record");
let docked_at = workspace.layout().location(&3).unwrap();
workspace.apply(Action::float(3, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap();
assert_eq!(workspace.floated().len(), 1);
workspace.apply(Action::close(3), false, allow).unwrap();
assert!(workspace.floated().is_empty(), "closing drops the record");
assert_eq!(workspace.floated(), [(3, docked_at.clone())], "closing keeps the record");
workspace.apply(Action::open(3, None), false, allow).unwrap();
assert!(floats(workspace.layout(), 3), "it reopens floating");
assert_eq!(workspace.floated(), [(3, docked_at.clone())], "reopening keeps the record");
workspace.apply(Action::restore(3, docked_at), false, allow).unwrap();
assert!(!floats(workspace.layout(), 3) && workspace.floated().is_empty(), "docking back drops the record");
}
/// Canvas 1; an end dock with an expanded column [2] and a collapsed column [3], [4]; a floating window [6].
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "craft-cdr"
description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing"
description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing; writer for version 15 .cdr drawings"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -11,7 +11,7 @@ repository.workspace = true
workspace = true
[features]
# Synthetic-file builders for tests and fuzz seeds; not a .cdr writer.
# Synthetic-file builders for tests and fuzz seeds, of every version; `write` is the crate's writer.
synth = []
[dependencies]
+17 -5
View File
@@ -1,7 +1,8 @@
# Where each layout comes from
The reader relies on the record layouts below. Code cites a row by its id (`R1` ...), and
`tests/it/provenance.rs` fails when a cited id has no row here.
The reader relies on the record layouts below, and the writer (`src/write.rs`) lays out version 15
files by the same rows, with R64 to R73 for what only the writer needs. Code cites a row by its id
(`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row here.
Sources:
@@ -18,8 +19,9 @@ Sources:
https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT, and RFC 1951 (DEFLATE),
https://www.rfc-editor.org/rfc/rfc1951
- **F**: the magic database of the `file` utility (BSD-2-Clause),
https://github.com/file/file/blob/b778217dbd35/magic/Magdir/images and
https://github.com/file/file/blob/b778217dbd35/magic/Magdir/riff
https://github.com/file/file/blob/b778217dbd35/magic/Magdir/images,
https://github.com/file/file/blob/b778217dbd35/magic/Magdir/riff and
https://github.com/file/file/blob/b778217dbd35/magic/Magdir/archive
- **PR**: the PRONOM registry's signatures for versions 1.0, 2.0 and 4.0,
https://pronom.nationalarchives.gov.uk/fmt/467.xml,
https://pronom.nationalarchives.gov.uk/fmt/466.xml and
@@ -119,7 +121,7 @@ file is committed.
| R50 | Bit 5 (0x20) of the outline's line type scales the outline's width and dashes with the shape's matrix. The engine multiplies them by the square root of the matrix's area factor (VectorCraft's own value for a matrix that scales x and y differently) | S: UC `outl_scale_with_cdr7.cdr` to `outl_scale_with_cdr12.cdr`, of whose outlines only one, 3.969 mm wide, has line type 0x22 and the others 0x02 or 0x01; TDF 76771 (version 15), whose outline of line type 0x22 is 10 mm wide on a shape that the matrix stretches and skews, and whose picture draws that outline several times wider and skewed | sample (the bit; the single width for a matrix that scales x and y differently: VectorCraft's own) |
| R51 | A `trfd` offsets table holds one offset more than the entries; each entry runs from its offset to the next, and the last offset is the record's end | KF L1079, L1113-L1121; S: every `trfd` of versions 4 to 25 in the sample files (25,425 records) has the extra offset, equal to the record's length | public-spec |
| R52 | Byte 0 of argument 14001 is the fill's winding flag. VectorCraft reads a byte other than 0 as the nonzero fill rule, and 0 or an object without the argument as even-odd | KF L575-L583, L1047; S: the argument is 4 bytes in the sample files that carry it, with byte 0 = 1 on LT `complexshape_blackfill_nooutline` of `testset/12` and `testset/15` to `testset/25` and on objects of TDF 127576 (13) and 60026 (14), and 0 on 27 objects of TP `example.cdr` (17) | public-spec (the flag: KF; which rule each value means, and the rule without the argument: VectorCraft's own reading, and a wrong reading fills or leaves holes where a curve's subpaths overlap) |
| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list (VectorCraft's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample |
| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list. When that chunk is one the reader passes over or a `page`, the reader may resume instead at a `page` chunk that starts 8 to 64 bytes after it, inside its body, is not empty, ends inside the list and, when the chunk found ends inside the list, reaches its end. It does so only when that page reads with objects and without damage in its instructions, and when walking on from the chunk found and from the page, each without this recovery and entering lists as the reader does, reaches the same position inside the same lists, or leaves the list (at its end, or at stray bytes with no chunk id after them), within 16 steps, with every chunk the reader uses that the first walk reads before then also read by the second, with its body cut at the same place (pages that read without objects aside). Of the chunks that only the second walk reads, or that it reads with its body cut at another place than the first walk does, the header or a table is used only when no other chunk of its id is read, and a page is kept only when it reads with objects and without damage in its instructions. Letters spelling `page` whose length runs past the list are checked the same way. In one read, the search for pages to resume at spends at most four times the length of the RIFF form (cut at the file's length), or 1,048,576 when that is more, counting 64 for each step of a walk and the length of each page body judged; past that, the reader resumes at the first chunk id found. It does the same when a limit stops the read of a page it judges. Pages kept this way are read after the other pages, so they spend only what the limits leave, and keep their place in the file; each is judged once more before it is read. One that a limit stops, or leaves without objects, is left out with the warning for limits; one the limits cut short is read as far as they allow, as other pages are. When the chunks that only these recoveries read make the read stop at a limit, the file is read again without the recoveries, with the warning for limits. Resuming at an inner page, at a chunk the reader passes over that is not followed by another chunk id or by the list's end, or after letters whose length runs past the list is reported as damage (this reader's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample |
| R54 | `cont`: byte 52 is the coordinate size as an ASCII digit, `4` for 32-bit coordinates and `2` for 16-bit ones (refused); bytes 64 to 72 hold an f64, the size of a coordinate unit in meters. A value that isn't above 0 and at most 1 reads as 0.1 µm (VectorCraft's own fallback) | CN "Container"; S: the nine CX files with `4` all hold 1e-7; `abydos.cmx`, `CM33.CMX`, `LIZARDS.CMX`, `output.000.cmx` and `test.cmx` hold `2` | sample |
| R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample |
| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) |
@@ -130,3 +132,13 @@ file is committed.
| R61 | Field 4 of instruction 9: the page's width and height, u32 each in coordinate units. Without it, field 1 gives the drawing's bounds: a u16 page number, a u32, then the left, top, right and bottom edges as i32 in coordinate units; the page takes the bounds' size and is centered on them (VectorCraft's own choice). Without either, the page has no size, and the importer gives it 612 × 792 pt as it does a `.cdr` page without one (VectorCraft's own size) | CN "page: instructions"; S: none of the CX files has field 4; in all nine with 32-bit coordinates, the four edges in field 1 match the extent of the file's curves | public-notes (field 4), sample (field 1) |
| R62 | A layer's name: field 4 as a u32 count and UTF-16 units, or field 1 from byte 12 as a u16 count and 8-bit characters (read as Windows-1252, VectorCraft's own choice); a layer without a name is left unnamed, as a `.cdr` layer is. A curve: field 1 its rendering attributes, field 2 a u16 point count, the points as i32 x and y, then a type byte for each as R16; coordinates are from the page's center, y up. A field 2 too short for its count is read as whole points with their type bytes when its length is a multiple of 9, and the curve is left out as damaged otherwise (VectorCraft's own rule) | CN "page: instructions" and "Coordinates"; S: the 8-bit names `Layer 1`, `Desktop`, `Grid` and `Guides` of the CX files (the last three hold nothing in every file); every curve of the CX files has field 2 of exactly 2 + 9 bytes per point | sample (8-bit names, curves), public-notes (field 4) |
| R63 | Rendering attributes: a mask (1 fill, 2 outline, 4 lens, 8 canvas, 16 container; lenses, canvases and containers are not read, with a warning), then a field list for the fill when the mask names it and one for the outline. The fill's field 1 is a u16 type and a field list; type 0 is no fill, type 1 a uniform fill whose field 1 is the color entry (u16) and a screen (u16); other types (2 fountain and more) are not read. The outline's field 1 is its `rotl` entry (u16) | CN "Rendering attributes"; S: masks 1, 2 and 3, fill types 1, 2 and 6, and uniform fills with a 4-byte field 1 in the CX files | sample |
| R64 | A package of versions 14 to 16 starts with a stored member `mimetype` holding `application/x-vnd.corel.draw.document+zip`; in versions 14 and 15 the RIFF file follows in `content/riffData.cdr` (R25) | F `archive` L1902-L1906 (a first member named `mimetype` at offset 30, stored, with no extra field), L2071-L2077 (the text at offsets 50 and 62); S: every file of LT `testset/15` | public-spec |
| R65 | A `trfd` record has a fourth header field, 0xFFFF, after where its offsets lie; in version 15 its offsets table starts at byte 16; each entry starts with the tag 1300 and a u32 before its type, and a matrix entry ends with 8 bytes after the six f64. The specification names the u32 `len_body`; every sample entry holds 0 there, and the writer writes 0 | KF L1079-L1106 (the 0xFFFF field), L1134-L1141 (the tag and `len_body`); S: every `trfd` record of the 15 files of LT `testset/15` without text (96 bytes, the offsets 24 and 96) | public-spec (the u32 after the tag and the 8 bytes at the end: sample) |
| R66 | A fill's property list from version 13 ends with an empty property (type 0, length 0), then two u16, the overprint flag (u32), an angle and a u32, inside the list's length; a uniform fill's record ends with 8 bytes after the list. The specification names 0, 45 degrees and 60 as the usual values of the first u16, the angle and the last u32, and lists 0, 1 and 13 for the flag | K L1100-L1121 (the 8 bytes), L1122-L1186 (the list and its end); S: the uniform fills of LT `square_blackfill_nooutline_transparency50percent_cdr15.cdr`, whose lists hold 0 in the flag, 45 degrees and 60 there | public-spec |
| R67 | Byte 2 of an object's `flgs` holds 0x08 when the object carries argument 8000 and 0x10 when it is a clipping container (argument 8005); the group of `LIST clpt` that a container clips has 0x80 there | S: LT `square_blackfill_nooutline_transparency50percent_cdr15.cdr` (0x08), `powerclipsquare_blackfill_whiterectangleinside_cdr15.cdr` (0x10 on the container, 0x80 on the clipped group) and `square_blackfill_nooutline_cdr15.cdr` (0 on a plain object) | sample (the reader does not use these bits) |
| R68 | Bit 2 of a point's type byte marks a node that can be edited. In most of the specification's samples it is set on move points and on line and curve ends and clear on control points and on the end that closes a subpath, with exceptions in a few samples of versions 13 and 14; the writer uses that common pattern. A closed subpath ends with an explicit line or curve end at its move point's coordinates, carrying bit 3 | K L2747-L2789 (`can_modify`, `is_closing_path`, from the specification's notes on its sample files) | public-spec (the reader does not use bit 2) |
| R69 | In a version 1300 uniform transparency record (R47), the u32 at byte 105 is a fill id, followed by 8 bytes. The sample's record also holds 261 as a u32 at byte 0, 0xFFFFFFFF at byte 57, 100.0 as an f64 at byte 69 and 2 at byte 81, and 0 in every other byte outside the fields R47 names | KF L707-L745 (`fill_id`); S: the record of LT `square_blackfill_nooutline_transparency50percent_cdr15.cdr` names fill 1, a uniform fill of RGB 255, 255, 255 | public-spec (the field), sample (the white fill and the other values, which the writer writes as the sample holds them; the reader does not use them) |
| R70 | Argument 40050 of a layer is a 16-byte id, different for each layer. The other pages hold an entry for each of the master page's guides, desktop and grid layers: a layer with byte 2 of its flags set and the master layer's object type, name and id, holding nothing; the guides and desktop entries come before the page's own layers and the grid entry after them. The master page holds a guides, a desktop and a grid layer, the grid hidden and locked | K L873-L883 (the id, and the master page's layers named from the other pages by the same id); S: LT `square_blackfill_nooutline_cdr15.cdr` (the master page's three layers, and the entries on its page, in that order, with the master layers' ids) | public-spec (the id), sample (the entries and their order; the reader does not use the id, and leaves the entries out as empty layers that are not drawing layers) |
| R71 | An `outl` chunk from version 13 holds records up to the one of id 1, whose length the specification's samples give as the bytes left in the chunk less 8. In the version 15 samples the id 1 record holds 130 bytes, 8 bytes follow it, and its body holds an f64 1 at bytes 16 and 48, 45 degrees at byte 84 and 60 at byte 88; the writer writes that layout and those values. A record of id 2 holds a color property list that ends at its empty property, without the fields R66 names after a fill's list | KF L1158-L1244 (the records, type 2 a color property list, and the id 1 length in its samples); S: the 18 `outl` chunks of the LT `testset/15` files without text (each 237 bytes, the id 1 record 130 bytes long with those values and 8 bytes of 0 after it, the id 2 record 43 bytes long) | public-spec (the record types and the length), sample (the values; the reader does not use them) |
| R72 | In the version 15 samples an `mcfg` chunk starts with the tag 1300 and the length of the rest of the chunk, then 4 bytes of 0 (the 12 bytes R10 names), and each `fild` chunk sits in a `LIST filc` of its own inside `LIST filt` | S: the 15 LT `testset/15` files without text (every `mcfg` starts with 1300 and its size less 8; each of their 31 `fild` chunks is the only chunk of a `LIST filc`) | sample (the reader skips the 12 bytes and finds `fild` chunks at any depth) |
| R73 | The specification reads the id in a container's argument 8005 (R46) as the stored u32 plus 1, halved, and the `spnd` id as stored. Sample files hold the same stored u32 in both places, even ids included, which the halved reading would not match. The writer numbers containers 1, 2, 3 and so on, and writes the same number in the clipped group's `spnd` | KF L799-L807 (`powerclip_id`), L2305-L2312 (`spnd`); S: the container and `spnd` of LT `powerclipsquare_blackfill_whiterectangleinside.cdr` of `testset/12` (156091928) and `powerclipsquare_blackfill_whiterectangleinside_cdr15.cdr` (1), the eight UC files `corel_powerclip_*` of versions 7 to 13 (47834832) and TDF 114901 (515235504) | sample (the halved reading: not followed) |
+64 -3
View File
@@ -1,10 +1,12 @@
# craft-cdr
A bounded Rust reader for `.cdr` drawings of versions 1 to 27 (and `.cdt` templates).
A bounded Rust reader for `.cdr` drawings of versions 1 to 27 (and `.cdt` templates), and a
writer of version 15 drawings.
It reads the `WL` files of versions 1 and 2, the RIFF chunk tree of versions 3 and later with its
compressed lists, the ZIP packages that versions 14 and later save (with the data streams of
versions 16 and later) and the records listed below, and hands the engine a drawing in points,
with each object's transform. It does not write `.cdr` files.
with each object's transform. `write` writes a drawing back out as a `.cdr` file of version 15
(see [Writing](#writing)).
## What is read
@@ -95,9 +97,68 @@ arrowheads and lenses are not read; the drawing's `warnings` name each kind it h
path is left out and the objects it clips are read without it. Files in big-endian byte order and
files with 16-bit coordinates are refused.
## Writing
`write` writes a drawing as a `.cdr` file of version 15: a ZIP package whose first member,
`mimetype`, names the format and whose member `content/riffData.cdr` holds the RIFF file. Each
record is laid out as the reader reads it, by the `PROVENANCE.md` rows it cites. The reader reads
the written file back as the drawing it was written from, to the precision the file stores
(1/254000 inch for coordinates, 1/255 for color components), with the changes listed below the
table.
| In the drawing | Written as |
|---|---|
| Pages and their sizes; the drawing's page size | pages with a page size argument; `mcfg` |
| The master page's layers and the drawing's guidelines | the master page, with a guides, a desktop and a grid layer |
| Layers: name, kind, hidden and locked | layers with their flags and their kind as the object type |
| Guidelines of a layer | guideline objects in that layer |
| Groups, and clipping containers with the objects they clip | `LIST grp ` lists; containers naming groups of the document's `LIST clpt` |
| Paths, rectangles with each corner's radius, ellipses | curves, rectangles of the version 15 layout, ellipses |
| Uniform fills and outlines (width, color, caps, joins, dashes, behind the fill, scaled with the shape) | fill and outline records, one for each different fill or outline |
| RGB, CMYK, gray, registration and spot colors | color models 5, 3, 9 and 20; a spot color as its look with its tint and its name |
| The nonzero fill rule, opacity and blend modes | the winding argument and the uniform transparency argument |
Opacity is written as the reader reads argument 8000 (R47), and the fill rule as the reader reads
argument 14001 (R52). The uniform transparency of every public sample R47 cites is 50%, and the
specifications R52 cites do not say which fill rule each winding value means, so the direction of
the opacity value and the value written for nonzero rest on the reader's own reading. Each layer
gets an id (argument 40050), and every other page names the master page's guides, desktop and grid
layers by those ids (R70); the master page's drawing layers are not named from the other pages.
The drawing's version and warnings are not written. A group that holds no shape or container is
left out, a clipping container whose objects hold none is written as a plain shape, a subpath
without segments is left out, as the reader leaves it out, and a drawing without pages gets one
empty page. A closed subpath whose last segment ends away from its start gets a closing line to
its start, as the file closes subpaths with an explicit point. A drawing without a page size of
its own is written without `mcfg`. Guidelines on the master page's layers read back as the
drawing's guidelines. An empty layer of a page other than a drawing layer, and an empty layer of
the master page, are written and read back left out, as the reader leaves out such layers in any
file. A guideline on a hidden layer reads back hidden, and a guideline angle past the field's
range is written as the same angle within one turn. Hidden groups and objects carry the same hide
bit as hidden layers (R19); the specification's notes date that bit on groups and objects to a
later program release than version 15 files, so a program of that version may show them. A spot
color without a look is written with a black look. Dash lengths are written to whole outline
widths and spot color tints to whole percent, as the file stores them.
Writing refuses a drawing that the reader would not read whole within the same `Limits`
(objects, coordinates, dashes, arguments, chunks, clipped chunks, nesting depth, clip nesting,
members and sizes), and groups nested deeper than the nesting depth, groups that hold nothing
included. It also refuses what the file cannot hold or the reader would read back otherwise
changed: a coordinate past 32 bits of 1/254000 inch, a number that is not finite, a page width or
height that rounds to less than one coordinate unit, a negative outline width or a positive one
that rounds to 0, a corner radius below 0 or more than a billionth past half the rectangle's
shorter side (a radius within that is written as half), a color value, tint or opacity outside 0
to 1, more than 10 dash lengths, a negative one or one that rounds past 65,535, a pattern whose
lengths all round to 0, a name longer than 256 UTF-16 units or holding a NUL, a spot color without
a name, at a tint that rounds to 0 percent or at a tint too low for its look to read back within
one step of 1/255, objects on the master page's grid layer, and a guideline at the edge of the
coordinate range with no room for a second point on it whose rounded coordinates lie within 1
degree of its angle.
## Provenance
`PROVENANCE.md` lists every record layout the reader relies on, with its public source and status.
`PROVENANCE.md` lists every record layout the reader relies on, and the rows only the writer
needs, with their public sources and status.
Code cites the rows by id (`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row.
The test inputs are synthetic drawings built by `src/synth.rs` and `src/synth_cmx.rs` (the
`synth` feature); no third-party file is committed.
+304 -34
View File
@@ -4,6 +4,8 @@
//! and outlines (R63). Text, images, rectangles, ellipses, clipping paths, other fills and lenses
//! are left out with a warning.
use std::collections::BTreeSet;
use crate::bytes::{Rd, u32_at};
use crate::geometry::path_of;
use crate::layout::{self, Profile};
@@ -19,6 +21,16 @@ const FORM: [u8; 4] = *b"CMX1";
const DEFAULT_UNIT: f64 = 1e-7;
/// How far past a chunk that runs short the next chunk id is looked for (R53).
const RESYNC: usize = 64;
/// How many steps (a chunk, or a jump over stray bytes) the reader walks on from a position it
/// could resume at, to compare it with the first chunk id found (R53).
const LOOKAHEAD: usize = 16;
/// The work counted for one step of a walk ([`walk`]) against [`PROBE_FLOOR`] (R53).
const STEP_COST: usize = 64;
/// The least work one read may spend on recoveries after stray bytes (R53), counted as
/// [`STEP_COST`] for each step of a walk and as the length of each page body judged. A read may
/// spend four times the length of the RIFF form, cut at the file's length, when that is more. Past it, the reader resumes at the
/// first chunk id found.
const PROBE_FLOOR: usize = 1 << 20;
/// The chunks the reader uses (R53 to R60).
const READ_IDS: [[u8; 4]; 9] = [*b"LIST", *b"cont", *b"page", *b"rclr", *b"rpen", *b"rott", *b"rdot", *b"rotl", *b"rota"];
/// The most UTF-16 units read of a layer's name; [`name`] keeps 256 of them.
@@ -52,6 +64,15 @@ struct Chunk<'a> {
id: [u8; 4],
body: &'a [u8],
start: usize,
/// Only a recovery after stray bytes reads the chunk ([`inner_page`]): the header or a table
/// is taken from it only when no other chunk of its id is read, and a page is kept only when it
/// reads with objects and without damage in its instructions.
recovered: bool,
}
/// The first chunk of id `id` that is not recovered, or else the first recovered one.
fn first_of<'c, 'a>(chunks: &'c [Chunk<'a>], id: &[u8; 4]) -> Option<&'c Chunk<'a>> {
chunks.iter().find(|c| c.id == *id && !c.recovered).or_else(|| chunks.iter().find(|c| c.id == *id))
}
/// The tables that page instructions refer to by 1-based index (R55 to R59).
@@ -66,9 +87,35 @@ struct Tables {
/// Line type, screen, color, arrowheads, pen and dashes.
outlines: Vec<Option<[u16; 6]>>,
arrowheads: Vec<(u16, u16)>,
/// Missing entries are not reported as damage: a page is read only to judge its instructions
/// ([`page_reads`]).
quiet: bool,
}
/// The drawing in `bytes` (R53 to R63). When the chunks that only a recovery after stray bytes
/// reads make the read stop at a limit, the file is read again without the recovery, with the
/// warning for limits.
pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result<Drawing, Error> {
let fresh = budget.clone();
match read_drawing(bytes, budget, true) {
Err(Error::Limit(_)) => {
*budget = fresh;
let mut d = read_drawing(bytes, budget, false)?;
push(&mut d.warnings, Warning::TooDeep);
Ok(d)
}
read => read,
}
}
/// The drawing as the reader reads it when it resumes after stray bytes only at the first chunk
/// id found, never at a page inside that chunk (R53).
#[cfg(any(test, feature = "synth"))]
pub(crate) fn drawing_without_recovery(bytes: &[u8], budget: &mut Budget) -> Result<Drawing, Error> {
read_drawing(bytes, budget, false)
}
fn read_drawing(bytes: &[u8], budget: &mut Budget, recover: bool) -> Result<Drawing, Error> {
if !is_cmx(bytes) {
return Err(Error::NotCmx);
}
@@ -76,8 +123,8 @@ pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result<Drawing, Erro
return Err(Error::Unsupported("big-endian CMX files"));
}
let mut warn = Vec::new();
let chunks = chunks(bytes, budget, &mut warn)?;
let cont = chunks.iter().find(|c| c.id == *b"cont").map(|c| c.body).ok_or(Error::Damaged("CMX header"))?;
let chunks = chunks(bytes, budget, &mut warn, recover)?;
let cont = first_of(&chunks, b"cont").map(|c| c.body).ok_or(Error::Damaged("CMX header"))?;
match cont.get(52) {
Some(b'4') => {}
Some(b'2') => return Err(Error::Unsupported("CMX files with 16-bit coordinates")),
@@ -86,15 +133,38 @@ pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result<Drawing, Erro
let meters = Rd::at(cont, 64).f64().filter(|m| *m > 0.0 && *m <= 1.0).unwrap_or(DEFAULT_UNIT);
let unit = meters / 0.0254 * 72.0;
let tables = Tables::read(&chunks, unit, budget, &mut warn)?;
// The pages read without the recovery go first, so that recovered pages spend only what the
// limits leave after them; the pages keep the order of the file.
let mut pages = Vec::new();
for c in chunks.iter().filter(|c| c.id == *b"page") {
pages.push(PageRead::new(&tables, unit, budget, &mut warn).read(c)?);
for c in chunks.iter().filter(|c| c.id == *b"page" && !c.recovered) {
pages.push((c.start, PageRead::new(&tables, unit, budget, &mut warn).read(c)?));
}
for c in chunks.iter().filter(|c| c.id == *b"page" && c.recovered) {
// A recovered page is judged however much the recoveries spent. One that a limit stops,
// or leaves without objects, is left out with the warning that says so; one the limits
// cut short is read as far as they allow, as the other pages are.
let read = match judgement(c, budget) {
Ok((true, false, _)) => PageRead::new(&tables, unit, budget, &mut warn).read(c),
Ok((_, _, true)) | Err(Error::Limit(_)) => {
push(&mut warn, Warning::TooDeep);
continue;
}
_ => continue,
};
match read {
Ok(page) => pages.push((c.start, page)),
Err(Error::Limit(_)) => push(&mut warn, Warning::TooDeep),
Err(e) => return Err(e),
}
}
pages.sort_by_key(|(start, _)| *start);
let pages = pages.into_iter().map(|(_, page)| page).collect();
Ok(Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: warn })
}
/// The chunks of the file in order, those inside `LIST` chunks in place (R53).
fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<Vec<Chunk<'a>>, Error> {
/// The chunks of the file in order, those inside `LIST` chunks in place (R53). With `recover`, the
/// reader may resume after stray bytes at a page inside the first chunk id found ([`inner_page`]).
fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec<Warning>, recover: bool) -> Result<Vec<Chunk<'a>>, Error> {
let declared = u32_at(b, 4).and_then(|n| (n as usize).checked_add(8)).unwrap_or(b.len());
if declared > b.len() {
// The file was cut short of the size its header gives.
@@ -102,15 +172,23 @@ fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec<Warning>) -> Resu
}
let end = declared.min(b.len());
let mut out = Vec::new();
// (position, end, depth) of the lists still to walk; a list's children go before the rest of
// the list that holds it.
let mut stack = vec![(12usize, end, 0usize)];
while let Some((mut pos, end, depth)) = stack.pop() {
// Where the chunks start that only a recovery reads ([`rejoins`]).
let mut extra = BTreeSet::new();
// The work the recoveries may still spend ([`PROBE_FLOOR`]).
let mut left = end.saturating_mul(4).max(PROBE_FLOOR);
// (position, end, depth, recovered) of the lists still to walk; a list's children go before
// the rest of the list that holds it.
let mut stack = vec![(12usize, end, 0usize, false)];
while let Some((mut pos, end, depth, in_recovered)) = stack.pop() {
while pos.saturating_add(8) <= end {
let Some(id) = Rd::at(b, pos).fourcc() else { break };
if !is_id(&id) {
match resync(b, pos, end) {
Some(next) => {
match resync(b, pos, end, depth, recover.then_some(&*budget), &mut left) {
Some((next, damaged, found)) => {
if damaged {
push(warn, Warning::Damaged);
}
extra.extend(found);
pos = next;
continue;
}
@@ -126,30 +204,38 @@ fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec<Warning>) -> Resu
let stop = start.saturating_add(size);
if stop > end {
// Stray bytes that happen to start with four letters give a length past the list:
// look for the next chunk id after them. A chunk the reader uses is kept, cut at
// the end of the list.
if !READ_IDS.contains(&id)
&& let Some(next) = resync(b, pos, end)
{
// look for the next chunk id after them, and report the damage. A chunk the reader
// uses is kept, cut at the end of the list, unless it is a page that holds a page
// the reader resumes at.
push(warn, Warning::Damaged);
let resume = if !READ_IDS.contains(&id) {
resync(b, pos, end, depth, recover.then_some(&*budget), &mut left).map(|(next, _, found)| (next, found))
} else if recover && id == *b"page" {
inner_page(b, pos, end, depth, budget, &mut left)
} else {
None
};
if let Some((next, found)) = resume {
extra.extend(found);
pos = next;
continue;
}
push(warn, Warning::Damaged);
}
let stop = stop.min(end);
let next = stop.saturating_add(size & 1);
let recovered = in_recovered || extra.contains(&pos);
if id == LIST {
if depth >= budget.limits.depth {
push(warn, Warning::TooDeep);
pos = next;
continue;
}
stack.push((next, end, depth));
stack.push((start + 4, stop, depth + 1));
stack.push((next, end, depth, in_recovered));
stack.push((start + 4, stop, depth + 1, recovered));
break;
}
if let Some(body) = b.get(start..stop) {
out.push(Chunk { id, body, start });
out.push(Chunk { id, body, start, recovered });
}
pos = next;
}
@@ -162,15 +248,199 @@ fn is_id(t: &[u8]) -> bool {
matches!(t, [first, rest @ ..] if t.len() == 4 && first.is_ascii_alphabetic() && rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b' '))
}
/// Where the next chunk after `pos` lies: the first chunk id at an even distance of 2 to [`RESYNC`]
/// bytes that names a chunk the reader uses, or another chunk whose length keeps it inside the list
/// that ends at `end` (R53).
fn resync(b: &[u8], pos: usize, end: usize) -> Option<usize> {
let fits = |p: usize| u32_at(b, p + 4).and_then(|s| (p + 8).checked_add(s as usize)).is_some_and(|stop| stop <= end);
let chunk_at = |p: usize| Rd::at(b, p).fourcc().is_some_and(|id| is_id(&id) && (READ_IDS.contains(&id) || fits(p)));
/// The chunk id at `p`, when the four bytes there read as one.
fn id_at(b: &[u8], p: usize) -> Option<[u8; 4]> {
Rd::at(b, p).fourcc().filter(|id| is_id(id))
}
/// Where the body of the chunk at `p` ends by its length, before its pad byte.
fn chunk_stop(b: &[u8], p: usize) -> Option<usize> {
u32_at(b, p + 4).and_then(|s| (p + 8).checked_add(s as usize))
}
/// The first chunk id after `pos`, at an even distance of 2 to [`RESYNC`] bytes, that names a
/// chunk the reader uses or another chunk whose length keeps it inside the list that ends at `end`
/// (R53).
fn first_chunk(b: &[u8], pos: usize, end: usize) -> Option<usize> {
let fits = |p: usize| chunk_stop(b, p).is_some_and(|stop| stop <= end);
let chunk_at = |p: usize| id_at(b, p).is_some_and(|id| READ_IDS.contains(&id) || fits(p));
(pos + 2..=pos.saturating_add(RESYNC).min(end.saturating_sub(8))).step_by(2).find(|&p| chunk_at(p))
}
/// Where the next chunk after stray bytes at `pos` lies, whether the bytes passed over are
/// reported as damage, and where the chunks start that only the recovery reads (R53). It is
/// [`first_chunk`], or, with `judge` (the read's budget), a page inside that chunk ([`inner_page`]),
/// found with at most `left` work ([`PROBE_FLOOR`]). The flag is set when the reader resumes at an
/// inner page, or at a chunk it passes over that is not followed by another chunk id or by the end
/// of the list. `depth` is how many lists hold the one that ends at `end`.
fn resync(b: &[u8], pos: usize, end: usize, depth: usize, judge: Option<&Budget>, left: &mut usize) -> Option<(usize, bool, Vec<usize>)> {
let p = first_chunk(b, pos, end)?;
if let Some((k, found)) = judge.and_then(|budget| inner_page(b, p, end, depth, budget, left)) {
return Some((k, true, found));
}
let known = id_at(b, p).is_some_and(|id| READ_IDS.contains(&id));
let followed = chunk_stop(b, p).filter(|stop| *stop <= end).is_some_and(|stop| {
let n = stop.saturating_add((stop - p - 8) & 1);
n >= end || (n.saturating_add(8) <= end && id_at(b, n).is_some())
});
Some((p, !known && !followed, Vec::new()))
}
/// A page the reader resumes at instead of the chunk at `p`, the first chunk id after stray bytes
/// or letters spelling `page` whose length runs past the list (R53). It is a page id at an even
/// distance of 8 to [`RESYNC`] bytes after `p`, inside the body of that chunk, whose length is not
/// 0, keeps it inside the list and, when the chunk at `p` ends inside the list, reaches the end of
/// that chunk. A `LIST`, the header and the tables at `p` are always kept. Walking on from `p` and
/// from the page by the reader's rule without this recovery must meet ([`rejoins`]). The first page
/// that meets is taken, with the chunks only the walk from it reads. The walks and the pages judged
/// spend `left` ([`PROBE_FLOOR`]); when it runs out, no page is taken. `depth` is how many lists
/// hold the one that ends at `end`.
fn inner_page(b: &[u8], p: usize, end: usize, depth: usize, budget: &Budget, left: &mut usize) -> Option<(usize, Vec<usize>)> {
let id = id_at(b, p)?;
if READ_IDS.contains(&id) && id != *b"page" {
return None;
}
let stop = chunk_stop(b, p).filter(|stop| *stop <= end);
let body_end = stop.unwrap_or(end);
// The chunk at `k` ends, with its pad byte, at or past the end of the chunk at `p`.
let reaches =
|k: usize| chunk_stop(b, k).is_some_and(|s| s > k + 8 && s <= end && stop.is_none_or(|stop| s.saturating_add((s - k - 8) & 1) >= stop));
let mut found = (p + 8..=p.saturating_add(RESYNC).min(end.saturating_sub(8)))
.step_by(2)
.filter(|&k| k < body_end && id_at(b, k) == Some(*b"page") && reaches(k))
.peekable();
found.peek()?;
let lists = budget.limits.depth.saturating_sub(depth);
let first = walk(b, p, end, lists, left)?;
found.find_map(|k| {
let alt = walk(b, k, end, lists, left)?;
rejoins(b, &first, &alt, budget, left).map(|extra| (k, extra))
})
}
/// Positions a walk through a list passes and the chunks it reads, for at most [`LOOKAHEAD`]
/// steps.
struct Walk {
/// Where the walk starts, and its place after each step: the position, and for each `LIST`
/// chunk it is inside, where that list's body ends and where the reader goes on after it.
at: Vec<(usize, Vec<(usize, usize)>)>,
/// Where each chunk the walk read starts, and where its body ends, cut at the end of the list
/// that holds it; a `LIST` chunk it enters counts by the chunks inside.
read: Vec<(usize, usize)>,
/// The walk left the list it started in: at its end, or at stray bytes with no chunk id after
/// them, where [`chunks`] stops reading that list too.
ended: bool,
}
/// Walk the list that ends at `end` from `from` as [`chunks`] does without recovery, entering at
/// most `lists` nested `LIST` chunks as it does, and spending [`STEP_COST`] of `left` for each step;
/// `None` when `left` runs out first.
fn walk(b: &[u8], from: usize, end: usize, lists: usize, left: &mut usize) -> Option<Walk> {
let mut w = Walk { at: vec![(from, Vec::new())], read: Vec::new(), ended: false };
let mut pos = from;
let mut inside: Vec<(usize, usize)> = Vec::new();
for _ in 0..LOOKAHEAD {
*left = left.checked_sub(STEP_COST)?;
let list_end = inside.last().map_or(end, |&(stop, _)| stop);
match step(b, pos, list_end) {
Some((next, Some(chunk))) if id_at(b, chunk) == Some(LIST) && inside.len() < lists => {
// [`chunks`] reads the list's children before the rest of the list that holds it.
let stop = chunk_stop(b, chunk).map_or(list_end, |stop| stop.min(list_end));
inside.push((stop, next));
pos = chunk + 12;
}
Some((next, chunk)) => {
w.read.extend(chunk.map(|c| (c, chunk_stop(b, c).map_or(list_end, |stop| stop.min(list_end)))));
pos = next;
}
None => match inside.pop() {
Some((_, after)) => pos = after,
None => {
w.ended = true;
break;
}
},
}
w.at.push((pos, inside.clone()));
}
Some(w)
}
/// One step of [`chunks`] without recovery at `pos`: the position after it, and where the chunk
/// it read starts when it read one; `None` when the walk ends there.
fn step(b: &[u8], pos: usize, end: usize) -> Option<(usize, Option<usize>)> {
if pos.saturating_add(8) > end {
return None;
}
let id = Rd::at(b, pos).fourcc()?;
if !is_id(&id) {
return first_chunk(b, pos, end).map(|next| (next, None));
}
let size = u32_at(b, pos + 4).map_or(0, |s| s as usize);
let stop = (pos + 8).saturating_add(size);
if stop > end
&& !READ_IDS.contains(&id)
&& let Some(next) = first_chunk(b, pos, end)
{
return Some((next, None));
}
Some((stop.min(end).saturating_add(size & 1), Some(pos)))
}
/// Where the chunks start that the walk from an inner page `alt` reads and the walk from the first
/// chunk id `first` does not read with the same body, when the two walks meet at a place both pass (a position inside the
/// same lists) or both end, and `alt` reads at least what `first` reads until then (R53). The page
/// `alt` starts at reads with objects and without damage in its instructions. Each chunk the reader
/// uses that `first` reads before that point, `alt` reads too, with the same body, unless it is a
/// page that reads without objects. The pages judged spend `left`; when it runs out, or when the
/// read of a page judged stops, the walks do not meet.
fn rejoins(b: &[u8], first: &Walk, alt: &Walk, budget: &Budget, left: &mut usize) -> Option<Vec<usize>> {
let meet = first.at.iter().find(|q| alt.at.contains(q)).map(|(q, _)| *q).or((first.ended && alt.ended).then_some(usize::MAX))?;
let uses = |q: usize| q < meet && id_at(b, q).is_some_and(|id| READ_IDS.contains(&id));
let used = |w: &Walk| -> Vec<(usize, usize)> { w.read.iter().copied().filter(|&(q, _)| uses(q)).collect() };
let (kept, taken) = (used(first), used(alt));
let (start, stop) = *alt.read.first()?;
if page_reads(b, start, stop, budget, left)? != (true, false) {
return None;
}
for &(q, stop) in kept.iter().filter(|q| !taken.contains(q)) {
// A page that reads without objects is the only chunk the walk from `alt` may leave out,
// or read with a body cut shorter by a list.
if id_at(b, q) != Some(*b"page") || page_reads(b, q, stop, budget, left)?.0 {
return None;
}
}
Some(taken.into_iter().filter(|q| !kept.contains(q)).map(|(q, _)| q).collect())
}
/// Whether the page chunk at `at` reads with objects, and whether its instructions read with
/// damage ([`judge_page`]); `None` when `left` does not cover its body or the read stops.
fn page_reads(b: &[u8], at: usize, end: usize, budget: &Budget, left: &mut usize) -> Option<(bool, bool)> {
let stop = chunk_stop(b, at).map_or(end, |stop| stop.min(end));
let Some(body) = b.get(at + 8..stop) else { return Some((false, true)) };
judge_page(&Chunk { id: *b"page", body, start: at + 8, recovered: true }, budget, left)
}
/// Whether page `c` reads with objects, and whether its instructions read with damage. It is read
/// with empty tables whose missing entries are not reported, and with a copy of `budget` so that the
/// read's own budget is not spent. The length of its body is taken from `left` first; `None` when
/// `left` holds less, or when the read stops.
fn judge_page(c: &Chunk, budget: &Budget, left: &mut usize) -> Option<(bool, bool)> {
*left = left.checked_sub(c.body.len())?;
judgement(c, budget).ok().map(|(objects, damaged, _)| (objects, damaged))
}
/// Whether page `c` reads with objects, whether its instructions read with damage, and whether
/// the read left something out at one of the limits, read as [`judge_page`] reads it; the error
/// when the read stops.
fn judgement(c: &Chunk, budget: &Budget) -> Result<(bool, bool, bool), Error> {
let tables = Tables { quiet: true, ..Tables::default() };
let mut scratch = budget.clone();
let mut warn = Vec::new();
let page = PageRead::new(&tables, 1.0, &mut scratch, &mut warn).read(c)?;
Ok((!page.layers.is_empty(), warn.contains(&Warning::Damaged), warn.contains(&Warning::TooDeep)))
}
/// The end of the field list at `pos` of `b`: after its 0xff, or the end of `b` when a field runs
/// past it (R55).
fn list_end(b: &[u8], mut pos: usize) -> usize {
@@ -224,7 +494,7 @@ fn entries<'a>(d: &'a [u8], budget: &mut Budget) -> Result<Vec<&'a [u8]>, Error>
impl Tables {
/// The first chunk of each table; a table that is missing is empty.
fn read(chunks: &[Chunk], unit: f64, budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<Tables, Error> {
let first = |id: &[u8; 4]| chunks.iter().find(|c| c.id == *id).map_or(&[][..], |c| c.body);
let first = |id: &[u8; 4]| first_of(chunks, id).map_or(&[][..], |c| c.body);
// A color record of field 10 holds a property list as a `.cdr` fill does (R56).
let record = layout::for_version(1300);
let mut t = Tables::default();
@@ -265,26 +535,26 @@ impl Tables {
}
/// Entry `index` (1-based) of `list`, or `None` with a warning when there is none.
fn get<T: Clone>(list: &[Option<T>], index: u16, warn: &mut Vec<Warning>) -> Option<T> {
fn get<T: Clone>(&self, list: &[Option<T>], index: u16, warn: &mut Vec<Warning>) -> Option<T> {
let found = usize::from(index).checked_sub(1).and_then(|i| list.get(i)).cloned().flatten();
if found.is_none() {
if found.is_none() && !self.quiet {
push(warn, Warning::Damaged);
}
found
}
fn color(&self, index: u16, warn: &mut Vec<Warning>) -> Color {
Tables::get(&self.colors, index, warn).unwrap_or(Color::Rgb([0.0; 3]))
self.get(&self.colors, index, warn).unwrap_or(Color::Rgb([0.0; 3]))
}
/// The outline of `rotl` entry `index`, or `None` when its line type draws none (R57, R58).
fn outline(&self, index: u16, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Outline> {
let [line, _screen, color, arrows, pen, dash] = Tables::get(&self.outlines, index, warn)?;
let (flags, caps_join) = Tables::get(&self.line_types, line, warn).unwrap_or((2, 0));
let [line, _screen, color, arrows, pen, dash] = self.get(&self.outlines, index, warn)?;
let (flags, caps_join) = self.get(&self.line_types, line, warn).unwrap_or((2, 0));
if flags & 1 != 0 {
return None;
}
let width = Tables::get(&self.pens, pen, warn).unwrap_or(0.0);
let width = self.get(&self.pens, pen, warn).unwrap_or(0.0);
let mut dashes = Vec::new();
if flags & 4 != 0 {
let stored = usize::from(dash).checked_sub(1).and_then(|i| self.dashes.get(i));
+6 -1
View File
@@ -8,7 +8,10 @@
//!
//! Every record layout the reader relies on is listed in `PROVENANCE.md` with its public source
//! and status; code cites the row ids (R1 ...). Reading is bounded by [`Limits`], never recurses and does not
//! panic. Nothing here writes `.cdr` or `.cmx` files.
//! panic.
//!
//! [`write()`] writes a [`Drawing`] as a `.cdr` file of version 15, laying out each record as the
//! reader reads it. Nothing here writes `.cmx` files.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -32,11 +35,13 @@ pub mod synth;
#[cfg(any(test, feature = "synth"))]
pub mod synth_cmx;
mod wl;
mod write;
mod zip;
pub use limits::Limits;
pub use model::{Drawing, Warning};
pub use preview::{Preview, PreviewFormat, preview};
pub use write::{WRITTEN_VERSION, WriteError, write};
/// Does `bytes` look like a `.cdr` drawing: a RIFF file, a ZIP package holding one, or a `WL` file
/// of version 1 or 2 whose header offsets fit the file?
+1 -1
View File
@@ -74,7 +74,7 @@ impl Default for Limits {
}
/// The running counters of one read against its [`Limits`].
#[derive(Debug)]
#[derive(Clone, Debug)]
pub(crate) struct Budget {
pub(crate) limits: Limits,
inflated: usize,
+9
View File
@@ -285,3 +285,12 @@ pub fn sample() -> Vec<u8> {
children.extend(tables());
riff(&children)
}
/// Read `bytes` as [`crate::read_cmx`] does, except that after stray bytes the reader resumes only
/// at the first chunk id found, never at a page inside that chunk (R53). Tests compare the two.
pub fn read_cmx_without_recovery(bytes: &[u8], limits: crate::Limits) -> Result<crate::Drawing, crate::Error> {
if bytes.len() > limits.input {
return Err(crate::Error::Limit("input size"));
}
crate::cmx::drawing_without_recovery(bytes, &mut crate::limits::Budget::new(limits))
}
File diff suppressed because it is too large. Load diff
+749 -41
View File
@@ -1,11 +1,39 @@
//! Reading synthetic `.cmx` files built from the layouts in `PROVENANCE.md` (R53 to R63), and
//! hostile ones.
use craft_cdr::model::{Cap, Color, Geometry, Join, Object, Shape};
use craft_cdr::model::{Cap, Color, Geometry, Join, Object, Page, Shape};
use craft_cdr::synth_cmx::*;
use craft_cdr::{Error, Limits, Warning, is_cdr, is_cmx, read_cmx};
use craft_cdr::{Drawing, Error, Limits, Warning, is_cdr, is_cmx, read_cmx};
use proptest::prelude::*;
/// Read `bytes`, and check that the reader never reads less than it does when it resumes after
/// stray bytes only at the first chunk id found (R53): when that read succeeds, this one does too,
/// and every page that read holds with objects is read here unchanged and in the same order.
fn read_checked(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
read_compared(bytes, limits, |p, q| p == q)
}
/// As [`read_checked`], except that a page only has to keep its layers and the number of objects
/// on each: a header or a table that only the recovery reads may change their colors and sizes
/// (R53).
fn read_kept(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
read_compared(bytes, limits, |p, q| {
p.layers.len() == q.layers.len() && p.layers.iter().zip(&q.layers).all(|(a, b)| a.name == b.name && a.objects.len() == b.objects.len())
})
}
fn read_compared(bytes: &[u8], limits: Limits, same: fn(&Page, &Page) -> bool) -> Result<Drawing, Error> {
let d = read_cmx(bytes, limits);
if let Ok(first) = read_cmx_without_recovery(bytes, limits) {
let Ok(read) = &d else { panic!("{d:?} where the first chunk id gives {first:?}") };
let mut rest = read.pages.iter();
for p in first.pages.iter().filter(|p| !p.layers.is_empty()) {
assert!(rest.any(|q| same(q, p)), "{p:?} is not read");
}
}
d
}
fn shape(o: &Object) -> &Shape {
match o {
Object::Shape(s) => s,
@@ -52,7 +80,7 @@ fn a_cmx_file_is_told_from_a_cdr_drawing() {
#[test]
fn pages_layers_groups_and_curves() {
let d = read_cmx(&sample(), Limits::default()).unwrap();
let d = read_checked(&sample(), Limits::default()).unwrap();
assert_eq!(d.version, 0);
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
assert_eq!(d.pages.len(), 1);
@@ -107,7 +135,7 @@ fn layer_names_and_layers_without_objects() {
end_layer(),
end_page(),
]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
let page = &d.pages[0];
assert_eq!(page.size, None);
// The empty layer is left out, and the UTF-16 name wins over the 8-bit one.
@@ -118,7 +146,7 @@ fn layer_names_and_layers_without_objects() {
#[test]
fn objects_before_any_layer_get_one() {
let p = page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
assert_eq!(d.pages[0].layers.len(), 1);
// The layer is left unnamed, as a `.cdr` drawing's is; the importer names it by its place.
assert_eq!(d.pages[0].layers[0].name, "");
@@ -134,7 +162,7 @@ fn a_page_without_a_size_takes_the_drawings_bounds() {
end_layer(),
end_page(),
]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
let page = &d.pages[0];
let side = 100.0 / 25.4 * 72.0;
let (w, h) = page.size.unwrap();
@@ -150,7 +178,7 @@ fn curves_and_open_groups() {
curve(&attrs(None, Some(1), false), &[(0, 0), (100, 0), (100, 100), (0, 100), (200, 200), (300, 200)], &[0x00, 0xc0, 0xc0, 0x84, 0x00, 0x44]);
// A group the layer leaves open closes with it.
let p = page(&[begin_page(None), begin_layer("L", None), begin_group(), c, end_layer()]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
let objects = &d.pages[0].layers[0].objects;
let Object::Group { objects: kids, .. } = &objects[0] else { panic!("{objects:?}") };
let s = shape(&kids[0]);
@@ -164,7 +192,7 @@ fn curves_and_open_groups() {
#[test]
fn a_curve_without_its_points_is_reported() {
let p = page(&[begin_page(None), begin_layer("L", None), instr(67, &fields(&[field(1, &attrs(Some(1), None, false))])), end_layer()]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
}
@@ -174,7 +202,7 @@ fn a_layer_name_too_short_to_read_in_utf_16_reads_in_8_bit() {
d.extend(b"Art");
let layer = instr(11, &fields(&[field(1, &d), field(4, &[3, 0])]));
let p = page(&[begin_page(None), layer, square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
assert_eq!(d.pages[0].layers[0].name, "Art");
}
@@ -192,7 +220,7 @@ fn what_is_not_read_is_reported() {
square(&attrs(Some(1), None, true), 0, 0, 1000),
end_layer(),
]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
for w in [Warning::UnsupportedObjects, Warning::UnsupportedFills, Warning::Lenses] {
assert!(d.warnings.contains(&w), "{w:?}: {:?}", d.warnings);
}
@@ -213,7 +241,7 @@ fn colors_of_other_models_and_missing_entries() {
square(&attrs(Some(2), None, false), 0, 0, 1000),
]));
children.push(table(b"rclr", &[color(7, &[1, 2, 3, 4]), color(3, &[255, 0, 0, 255])]));
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::UnknownColors) && d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
let objects = &d.pages[0].layers[0].objects;
assert_eq!(shape(&objects[0]).fill, Some(Color::Cmyk([1.0, 0.0, 0.0, 1.0])));
@@ -231,7 +259,7 @@ fn gray_cmy_and_rgb_colors_of_the_older_fields() {
square(&attrs(Some(3), None, false), 0, 0, 1000),
]));
children.push(table(b"rclr", &[color(9, &[51]), color(4, &[255, 0, 51]), color(5, &[255, 0, 0])]));
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
let objects = &d.pages[0].layers[0].objects;
// The model holds objects front to back: the RGB square, the CMY one, then the gray one.
@@ -251,7 +279,7 @@ fn outline_arrowheads_are_reported() {
children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)]));
children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rota")));
children.push(arrowheads(&[(0, 2)]));
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.warnings, vec![Warning::Arrowheads]);
}
@@ -275,7 +303,7 @@ fn a_long_instruction_and_a_jump_over_image_bytes() {
.concat();
let mut children = vec![cont(b'4', 1e-7), chunk(b"page", &body)];
children.extend(tables());
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
let d = read_checked(&riff(&children), Limits::default()).unwrap();
// The images jumped over are not read, and the warning says so.
assert_eq!(d.warnings, [Warning::UnsupportedObjects]);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
@@ -286,7 +314,7 @@ fn bytes_after_a_chunk_that_runs_short_are_passed_over() {
let stray = vec![0x10, 0x00, 0x16, 0x00, 0x01, 0x0b, 0x00, 0x01, 0, 0, 0, 0, 0, 0, 0, 0xff];
let mut children = vec![cont(b'4', 1e-7), stray, list(b"pgls", &[page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)])])];
children.extend(tables());
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
@@ -295,12 +323,12 @@ fn bytes_after_a_chunk_that_runs_short_are_passed_over() {
fn other_byte_orders_and_coordinate_sizes_are_refused() {
let mut f = sample();
f[..4].copy_from_slice(b"RIFX");
assert_eq!(read_cmx(&f, Limits::default()), Err(Error::Unsupported("big-endian CMX files")));
assert_eq!(read_checked(&f, Limits::default()), Err(Error::Unsupported("big-endian CMX files")));
let mut children = vec![cont(b'2', 1e-3)];
children.extend(tables());
assert_eq!(read_cmx(&riff(&children), Limits::default()), Err(Error::Unsupported("CMX files with 16-bit coordinates")));
assert_eq!(read_cmx(&riff(&tables()), Limits::default()), Err(Error::Damaged("CMX header")));
assert_eq!(read_cmx(&riff(&[cont(b'9', 1e-7)]), Limits::default()), Err(Error::Damaged("CMX header")));
assert_eq!(read_checked(&riff(&children), Limits::default()), Err(Error::Unsupported("CMX files with 16-bit coordinates")));
assert_eq!(read_checked(&riff(&tables()), Limits::default()), Err(Error::Damaged("CMX header")));
assert_eq!(read_checked(&riff(&[cont(b'9', 1e-7)]), Limits::default()), Err(Error::Damaged("CMX header")));
}
#[test]
@@ -308,7 +336,7 @@ fn a_header_without_a_usable_unit_reads_0_1_micrometers() {
for meters in [0.0, -1.0, f64::NAN, 2.0] {
let mut children = vec![cont(b'4', meters), page(&[begin_page(Some((2_100_000, 2_970_000)))])];
children.extend(tables());
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
let d = read_checked(&riff(&children), Limits::default()).unwrap();
let (w, _) = d.pages[0].size.unwrap();
assert!(near(w, 210.0 / 25.4 * 72.0), "{meters}: {w}");
}
@@ -325,7 +353,7 @@ fn groups_past_the_depth_limit_are_left_out() {
ins.push(end_group());
}
ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000));
let d = read_cmx(&file(&[page(&ins)]), Limits { depth: 3, ..Limits::default() }).unwrap();
let d = read_checked(&file(&[page(&ins)]), Limits { depth: 3, ..Limits::default() }).unwrap();
assert!(d.warnings.contains(&Warning::TooDeep));
// The square after the groups is still read, beside the three groups kept.
let objects = &d.pages[0].layers[0].objects;
@@ -346,18 +374,18 @@ fn groups_past_the_depth_limit_are_left_out() {
fn counts_past_the_limits_are_bounded() {
let ins: Vec<Vec<u8>> = std::iter::once(begin_page(None)).chain((0..50).map(|_| square(&attrs(Some(1), None, false), 0, 0, 1000))).collect();
let f = file(&[page(&ins)]);
let d = read_cmx(&f, Limits { objects: 10, ..Limits::default() }).unwrap();
let d = read_checked(&f, Limits { objects: 10, ..Limits::default() }).unwrap();
assert_eq!(d.pages[0].layers[0].objects.len(), 10);
assert!(d.warnings.contains(&Warning::TooDeep));
let d = read_cmx(&f, Limits { coordinates: 12, ..Limits::default() }).unwrap();
let d = read_checked(&f, Limits { coordinates: 12, ..Limits::default() }).unwrap();
assert_eq!(d.pages[0].layers[0].objects.len(), 2);
assert_eq!(read_cmx(&f, Limits { chunks: 20, ..Limits::default() }), Err(Error::Limit("chunk count")));
assert_eq!(read_cmx(&f, Limits { input: 10, ..Limits::default() }), Err(Error::Limit("input size")));
assert_eq!(read_checked(&f, Limits { chunks: 20, ..Limits::default() }), Err(Error::Limit("chunk count")));
assert_eq!(read_checked(&f, Limits { input: 10, ..Limits::default() }), Err(Error::Limit("input size")));
let dashed = |n: u16| {
let mut children = vec![cont(b'4', 1e-7)];
children.push(page(&[begin_page(None), square(&attrs(None, Some(3), false), 0, 0, 1000), square(&attrs(None, Some(3), false), 0, 0, 1000)]));
children.extend(tables());
read_cmx(&riff(&children), Limits { dashes: usize::from(n), ..Limits::default() }).unwrap()
read_checked(&riff(&children), Limits { dashes: usize::from(n), ..Limits::default() }).unwrap()
};
let d = dashed(3);
let o: Vec<usize> = d.pages[0].layers[0].objects.iter().map(|o| shape(o).outline.as_ref().unwrap().dashes.len()).collect();
@@ -372,7 +400,7 @@ fn a_curve_cut_short_keeps_the_points_it_holds() {
let at = c.windows(2).position(|w| w == [3, 0]).unwrap();
c[at] = 9;
let p = page(&[begin_page(None), c]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged));
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
@@ -387,7 +415,7 @@ fn a_curve_that_lost_type_bytes_keeps_its_first_points() {
}
g.extend([0x0c, 0x44]);
let c = instr(67, &fields(&[field(1, &attrs(None, Some(1), false)), field(2, &g)]));
let d = read_cmx(&file(&[page(&[begin_page(None), c])]), Limits::default()).unwrap();
let d = read_checked(&file(&[page(&[begin_page(None), c])]), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
let Geometry::Path(p) = &shape(&d.pages[0].layers[0].objects[0]).geometry else { panic!() };
let side = 100.0 / 25.4 * 72.0;
@@ -403,14 +431,14 @@ fn a_file_cut_short_of_its_declared_size_is_reported() {
let mut f = file(&[]);
let declared = (f.len() as u32 - 8 + 100).to_le_bytes();
f[4..8].copy_from_slice(&declared);
let d = read_cmx(&f, Limits::default()).unwrap();
let d = read_checked(&f, Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
}
#[test]
fn a_page_that_ends_inside_an_instruction_is_reported() {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), vec![1, 0]]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
@@ -420,7 +448,7 @@ fn a_chunk_64_bytes_past_stray_bytes_is_found() {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut children = vec![cont(b'4', 1e-7), [vec![1u8; 64], p].concat()];
children.extend(tables());
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
@@ -432,7 +460,687 @@ fn stray_letters_with_a_length_past_the_file_are_passed_over() {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut children = vec![cont(b'4', 1e-7), [stray, p].concat()];
children.extend(tables());
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
/// Stray bytes, then letters whose length covers exactly the page chunk after them, then the page.
fn page_inside_stray_letters(stray: &[u8]) -> Vec<u8> {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut b = stray.to_vec();
b.extend(b"abcd");
b.extend((p.len() as u32).to_le_bytes());
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
riff(&children)
}
#[test]
fn after_stray_letters_the_page_is_preferred_to_letters_that_hold_it() {
let mut stray = b"wxyz".to_vec();
stray.extend(0xFFFF_FF00u32.to_le_bytes());
let d = read_checked(&page_inside_stray_letters(&stray), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn after_stray_bytes_the_page_is_preferred_to_letters_that_hold_it() {
let d = read_checked(&page_inside_stray_letters(&[1, 1]), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn letters_64_bytes_past_stray_bytes_do_not_hide_the_page_they_hold() {
let d = read_checked(&page_inside_stray_letters(&[1; 64]), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn after_stray_bytes_a_page_after_three_page_headers_that_do_not_read_inside_letters_is_read() {
// Stray bytes, then letters whose length covers three page headers that reach its end and
// whose instructions do not fit, then the page.
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let len = 24 + p.len();
let mut body = Vec::new();
for k in 0..3 {
body.extend(b"page");
body.extend(((len - 8 * k - 8) as u32).to_le_bytes());
}
body.extend(p);
let mut b = vec![1u8; 2];
b.extend(b"abcd");
b.extend((body.len() as u32).to_le_bytes());
b.extend(body);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn after_stray_bytes_recoveries_stop_once_a_read_has_spent_its_allowance() {
// Many copies of stray bytes followed by a chunk the reader passes over that holds a page:
// the first pages are read, and once the checks have spent the read's allowance the reader
// resumes at the chunk that holds each page, as it does without the recovery.
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut unit = vec![1u8; 2];
unit.extend(chunk(b"inf1", &p));
let copies = 2000;
let mut children = vec![cont(b'4', 1e-7), unit.repeat(copies)];
children.extend(tables());
let f = riff(&children);
let d = read_checked(&f, Limits::default()).unwrap();
assert!(!d.pages.is_empty() && d.pages.len() < copies, "{} of {copies} pages", d.pages.len());
assert!(read_cmx_without_recovery(&f, Limits::default()).unwrap().pages.is_empty());
}
#[test]
fn after_stray_bytes_a_page_past_a_limit_is_left_out_with_a_warning() {
let f = page_inside_stray_letters(&[1, 1]);
let all = read_cmx(&f, Limits::default()).unwrap().pages.len();
assert_eq!(all, 1);
let mut cut = 0;
for chunks in 1..200 {
let Ok(d) = read_checked(&f, Limits { chunks, ..Limits::default() }) else { continue };
if d.pages.len() < all {
cut += 1;
assert!(d.warnings.contains(&Warning::TooDeep), "{chunks}: {:?}", d.warnings);
}
}
assert!(cut > 0);
}
#[test]
fn a_recovered_page_spends_only_what_the_limits_leave_after_the_other_pages() {
// Stray bytes, letters whose length covers a page, the page, then another page: with room for
// one object, the last page keeps it and the warning tells of the page left out; with room for
// both, the recovered page reads first.
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let q = page(&[begin_page(None), begin_layer("M", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]);
let mut b = vec![1u8; 2];
b.extend(b"abcd");
b.extend((p.len() as u32).to_le_bytes());
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b, q];
children.extend(tables());
let f = riff(&children);
let d = read_checked(&f, Limits { objects: 1, ..Limits::default() }).unwrap();
assert_eq!(d.pages.len(), 1, "{:?}", d.pages);
let last = d.pages.last().unwrap();
assert_eq!((last.layers[0].name.as_str(), last.layers[0].objects.len()), ("M", 1));
assert!(d.warnings.contains(&Warning::TooDeep), "{:?}", d.warnings);
let d = read_checked(&f, Limits::default()).unwrap();
assert_eq!(d.pages.iter().map(|p| p.layers[0].name.as_str()).collect::<Vec<_>>(), ["L", "M"]);
}
#[test]
fn chunks_only_a_recovery_reads_do_not_stop_a_read_that_fits_without_them() {
// A page, then letters spelling `page` whose length runs past the file and that hold another
// page and an empty chunk: at every chunk limit at which the file opens without the recovery,
// it opens with it, and where the recovered page does not fit, the warning tells of it.
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let q = page(&[begin_page(None), begin_layer("M", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]);
let mut b = b"page".to_vec();
b.extend(0xFFFF_FF00u32.to_le_bytes());
b.extend(q);
b.extend(chunk(b"junk", &[]));
let mut children = vec![cont(b'4', 1e-7)];
children.extend(tables());
children.push(p);
children.push(b);
let f = riff(&children);
let names = |d: &Drawing| d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.clone()).collect::<Vec<_>>();
assert_eq!(names(&read_checked(&f, Limits::default()).unwrap()), ["L", "M"]);
let mut cut = 0;
for chunks in 1..200 {
let limits = Limits { chunks, ..Limits::default() };
if read_cmx_without_recovery(&f, limits).is_err() {
continue;
}
let d = read_checked(&f, limits).unwrap();
if names(&d) != ["L", "M"] {
cut += 1;
assert!(d.warnings.contains(&Warning::TooDeep), "{chunks}: {:?}", d.warnings);
}
}
assert!(cut > 0);
}
#[test]
fn after_stray_bytes_a_page_is_read_when_the_chunk_found_lands_inside_a_list() {
// Stray bytes, then letters whose length ends on the header of an empty page at the end of the
// page after them. That empty page's length ends on the first page inside the list that
// follows. Walking on from the page reads the same page inside the list, so the page is read.
let (name, q) = ["Q", "Qa"]
.iter()
.map(|n| {
let carried = long_instr(-1, &[b"page".as_slice(), &12u32.to_le_bytes()].concat());
(*n, [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), carried].concat())
})
.find(|(_, body)| body.len() % 2 == 0)
.unwrap();
let r = page(&[begin_page(None), begin_layer("R", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]);
let mut b = vec![1u8; 2];
b.extend(b"abcd");
b.extend((q.len() as u32).to_le_bytes());
b.extend(chunk(b"page", &q));
b.extend(list(b"pgls", &[r]));
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
let names: Vec<&str> = d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.as_str()).collect();
assert_eq!(names, [name, "R"]);
}
#[test]
fn after_stray_bytes_a_page_is_not_read_when_a_list_cuts_short_the_page_both_walks_reach() {
// As above, except that the list ends after the header of the page inside it, so walking on
// from the inner page reads that page without its body. Walking on from the letters reads the
// whole page, so the reader resumes at the letters and the page keeps its square.
let (name, q) = ["Q", "Qa"]
.iter()
.map(|n| {
let carried = long_instr(-1, &[b"page".as_slice(), &12u32.to_le_bytes()].concat());
(*n, [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), carried].concat())
})
.find(|(_, body)| body.len() % 2 == 0)
.unwrap();
let r = page(&[begin_page(None), begin_layer("R", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]);
let mut b = vec![1u8; 2];
b.extend(b"abcd");
b.extend((q.len() as u32).to_le_bytes());
b.extend(chunk(b"page", &q));
b.extend(b"LIST");
b.extend(12u32.to_le_bytes());
b.extend(b"pgls");
b.extend(r);
let mut children = vec![cont(b'4', 1e-7)];
children.extend(tables());
children.push(b);
let d = read_checked(&riff(&children), Limits::default()).unwrap();
let names: Vec<&str> = d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.as_str()).collect();
assert!(!names.contains(&name), "{names:?}");
assert_eq!(names, ["R"]);
assert_eq!(d.pages.last().unwrap().layers[0].objects.len(), 1);
}
#[test]
fn after_stray_bytes_a_page_a_list_cuts_short_only_without_the_recovery_is_judged_as_recovered() {
// Stray bytes, then letters whose length ends on the header of a list at the end of the page
// after them. The list ends after the header of the next page, so the walk from the letters
// reads that page without its body, and the walk from the page inside the letters reads the
// whole page. Only the recovery reads that whole page, and it ends inside an instruction, so the
// reader leaves it out.
let (name, q) = ["Q", "Qa"]
.iter()
.map(|n| {
let carried = long_instr(-1, &[b"LIST".as_slice(), &12u32.to_le_bytes(), b"pgls"].concat());
(*n, [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), carried].concat())
})
.find(|(_, body)| body.len() % 2 == 0)
.unwrap();
let r = page(&[begin_page(None), begin_layer("R", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer(), vec![1, 0]]);
let mut b = vec![1u8; 2];
b.extend(b"abcd");
b.extend((q.len() as u32 - 4).to_le_bytes());
b.extend(chunk(b"page", &q));
b.extend(r);
let mut children = vec![cont(b'4', 1e-7)];
children.extend(tables());
children.push(b);
let d = read_checked(&riff(&children), Limits::default()).unwrap();
let names: Vec<&str> = d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.as_str()).collect();
assert_eq!(names, [name]);
}
#[test]
fn after_stray_bytes_a_page_whose_check_stops_at_a_limit_is_not_replaced_by_a_page_inside_it() {
// Stray bytes, then letters whose body holds the start of a page of one square. That page's last
// instruction carries the page of thirty squares that follows the letters, and ends where it
// ends. At a chunk limit that stops the check of the page of thirty squares while the check of
// the page inside the letters fits, the page inside the letters never takes its place.
let squares = (1..=30).map(|i| square(&attrs(Some(1), None, false), 0, 0, 100 * i));
let p = page(&[begin_page(None), begin_layer("P", None)].into_iter().chain(squares).chain([end_layer()]).collect::<Vec<_>>());
let carried = long_instr(-1, &p);
let head = &carried[..carried.len() - p.len()];
let q = ["Q", "Qa"]
.iter()
.map(|n| [begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer(), head.to_vec()].concat())
.find(|body| body.len() % 2 == 0)
.unwrap();
let mut b = vec![1u8; 2];
b.extend(b"abcd");
b.extend((q.len() as u32 + 8).to_le_bytes());
b.extend(b"page");
b.extend(((q.len() + p.len()) as u32).to_le_bytes());
b.extend(q);
b.extend(p);
let mut children = vec![cont(b'4', 1e-7)];
children.extend(tables());
children.push(b);
let f = riff(&children);
let names = |d: &Drawing| d.pages.iter().filter_map(|p| p.layers.first()).map(|l| l.name.clone()).collect::<Vec<_>>();
assert_eq!(names(&read_checked(&f, Limits::default()).unwrap()), ["P"]);
for chunks in 1..200 {
if let Ok(d) = read_checked(&f, Limits { chunks, ..Limits::default() }) {
assert_eq!(names(&d), ["P"], "{chunks}: {:?}", d.warnings);
}
}
}
/// A page that fills with color 1, then, inside a list, letters spelling `page` whose length runs
/// past the list and that hold another page and a color table of one red entry, then `after`.
fn page_and_recovered_red(after: &[Vec<u8>]) -> Vec<u8> {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let q = page(&[begin_page(None), begin_layer("M", None), square(&attrs(Some(1), None, false), 0, 0, 2000), end_layer()]);
let mut b = b"page".to_vec();
b.extend(0xFFFF_FF00u32.to_le_bytes());
b.extend(q);
b.extend(table(b"rclr", &[color(5, &[255, 0, 0])]));
let mut children = vec![cont(b'4', 1e-7)];
children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rclr")));
children.push(p);
children.push(list(b"pgls", &[b]));
children.extend(after.iter().cloned());
riff(&children)
}
/// The fill of the first object of each page.
fn fills(d: &Drawing) -> Vec<Option<Color>> {
d.pages.iter().map(|p| shape(&p.layers[0].objects[0]).fill.clone()).collect()
}
#[test]
fn a_color_table_only_the_recovery_reads_colors_every_page() {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)]);
let red = fills(&read_checked(&file(&[p]), Limits::default()).unwrap())[0].clone();
assert!(red.is_some());
let d = read_kept(&page_and_recovered_red(&[]), Limits::default()).unwrap();
assert_eq!(fills(&d), [red.clone(), red]);
}
#[test]
fn a_color_table_read_without_the_recovery_wins_over_one_only_the_recovery_reads() {
let green = table(b"rclr", &[color(5, &[0, 255, 0])]);
let mut children = vec![cont(b'4', 1e-7)];
children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)]));
children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rclr")));
children.push(green.clone());
let green_fill = fills(&read_checked(&riff(&children), Limits::default()).unwrap())[0].clone();
let d = read_checked(&page_and_recovered_red(&[green]), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 2);
assert_eq!(fills(&d), [green_fill.clone(), green_fill]);
}
#[test]
fn after_stray_bytes_a_page_inside_a_chunk_with_more_after_it_is_not_read() {
// Stray bytes, a chunk the reader passes over that holds a page followed by another chunk,
// then the page: only the last page is read.
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut b = vec![1u8; 2];
b.extend(chunk(b"inf1", &[p.clone(), chunk(b"junk", &[0; 4])].concat()));
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
assert_eq!(d.pages.len(), 1);
}
#[test]
fn a_list_between_stray_bytes_is_read_as_a_list() {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let b = [vec![1u8; 2], list(b"pgls", &[p.clone(), p]), vec![1u8; 2]].concat();
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
assert_eq!(d.pages.len(), 2);
}
#[test]
fn after_stray_bytes_an_empty_page_header_inside_another_chunk_is_not_a_page() {
// Stray bytes, a chunk the reader passes over that holds only an empty page header, then the
// page: only the page is read.
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut b = vec![1u8; 2];
b.extend(chunk(b"inf1", &chunk(b"page", &[])));
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn after_stray_bytes_an_empty_page_is_kept_before_the_next_page() {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut b = vec![1u8; 2];
b.extend(chunk(b"page", &[]));
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 2);
assert!(d.pages[0].layers.is_empty(), "{:?}", d.pages[0].layers);
assert_eq!(d.pages[1].layers[0].objects.len(), 1);
}
#[test]
fn a_page_between_stray_bytes_is_preferred_to_letters_that_end_inside_it() {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut b = vec![1u8; 2];
b.extend(b"abcd");
b.extend(8u32.to_le_bytes());
b.extend(p);
b.extend([1u8; 2]);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn after_stray_bytes_a_page_is_preferred_to_page_letters_that_end_inside_it() {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut b = vec![1u8; 2];
b.extend(b"page");
b.extend(8u32.to_le_bytes());
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn a_page_between_stray_bytes_is_kept() {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let b = [vec![1u8; 2], p, vec![1u8; 2]].concat();
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn after_stray_bytes_a_page_header_that_ends_inside_another_chunk_is_not_a_page() {
// Stray bytes, a chunk the reader passes over whose body starts with a short page chunk, more
// stray bytes, then the page: only the last page is read.
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut inner = b"page".to_vec();
inner.extend(4u32.to_le_bytes());
inner.extend([0; 10]);
let mut b = vec![1u8; 2];
b.extend(chunk(b"inf1", &inner));
b.extend([1u8; 2]);
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
// The chunk passed over is followed by more stray bytes, and the warning says so.
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn after_stray_bytes_a_header_too_short_to_read_inside_another_chunk_is_passed_over() {
// Stray bytes, then a chunk the reader passes over that holds a one-byte header, then the
// header: the drawing opens with the header after it.
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let first = [vec![1u8; 2], chunk(b"inf1", &chunk(b"cont", &[0]))].concat();
let mut children = vec![first, cont(b'4', 1e-7), p];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn after_stray_bytes_letters_ending_on_a_layer_name_do_not_hide_the_page() {
// Stray bytes, then letters whose length ends on the letters of a layer name inside the page
// after them, then the page.
let names = ["Background", "aBackground"];
let (p, at) = names
.iter()
.map(|n| page(&[begin_page(None), begin_layer(n, None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]))
.find_map(|p| p.windows(4).position(|w| w == b"Back").filter(|at| at % 2 == 0).map(|at| (p, at)))
.unwrap();
let mut b = vec![1u8; 2];
b.extend(b"abcd");
b.extend((at as u32).to_le_bytes());
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn after_stray_bytes_a_page_followed_by_a_chunk_inside_another_chunk_is_not_read_before_more_stray_bytes() {
// Stray bytes, a chunk the reader passes over that holds a page and another chunk, more stray
// bytes, then the page: only the last page is read.
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut b = vec![1u8; 2];
b.extend(chunk(b"inf1", &[p.clone(), chunk(b"junk", &[0; 4])].concat()));
b.extend([1u8; 2]);
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
}
#[test]
fn after_stray_bytes_a_header_without_a_coordinate_size_inside_another_chunk_is_passed_over() {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let first = [vec![1u8; 2], chunk(b"inf1", &chunk(b"cont", &[0; 60]))].concat();
let mut children = vec![first, cont(b'4', 1e-7), p];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn after_stray_bytes_a_table_inside_another_chunk_that_ends_inside_the_next_page_is_passed_over() {
// Stray bytes, a chunk the reader passes over that holds the start of a color table whose
// length ends inside the page after more stray bytes: the page is read.
let sq = square(&attrs(Some(1), None, false), 0, 0, 1000);
let p = page(&[begin_page(None), begin_layer("L", None), sq.clone(), sq.clone(), sq, end_layer()]);
let mut inner = b"rclr".to_vec();
inner.extend(14u32.to_le_bytes());
inner.extend([0; 2]);
let mut b = vec![1u8; 2];
b.extend(chunk(b"inf1", &inner));
b.extend([1u8; 2]);
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 3);
}
#[test]
fn a_page_between_stray_bytes_is_kept_when_its_body_holds_chunk_letters() {
// A layer name near the start of the page holds a color table chunk and another chunk id.
let mut tail = b"rclr".to_vec();
tail.extend([4, 0, 0, 0, 0, 0, 0, 0]);
tail.extend(b"junk");
tail.extend([0; 4]);
let tail = String::from_utf8(tail).unwrap();
let (p, at) = ["", "x"]
.iter()
.map(|pre| {
page(&[begin_page(None), begin_layer(&format!("{pre}{tail}"), None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()])
})
.find_map(|p| p.windows(4).position(|w| w == b"rclr").filter(|at| at % 2 == 0).map(|at| (p, at)))
.unwrap();
assert!((8..=64).contains(&at), "{at}");
let b = [vec![1u8; 2], p, vec![1u8; 2]].concat();
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn after_stray_bytes_a_page_too_short_for_an_instruction_inside_another_chunk_is_not_a_page() {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut b = vec![1u8; 2];
b.extend(chunk(b"inf1", &chunk(b"page", &[0; 2])));
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn after_stray_bytes_a_short_page_is_not_hidden_by_a_table_inside_the_chunk_before_it() {
// Stray bytes, a chunk the reader passes over that holds the start of a color table whose
// length ends inside the short page after more stray bytes: the page is read.
let p = page(&[begin_page(None)]);
let mut inner = b"rclr".to_vec();
inner.extend(10u32.to_le_bytes());
inner.extend([0; 2]);
let mut b = vec![1u8; 2];
b.extend(chunk(b"inf1", &inner));
b.extend([1u8; 2]);
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
}
#[test]
fn a_last_page_before_stray_bytes_at_the_end_of_the_file_is_preferred_to_letters_that_end_inside_it() {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut b = vec![1u8; 2];
b.extend(b"abcd");
b.extend(8u32.to_le_bytes());
b.extend(p);
b.extend([1u8; 2]);
let mut children = vec![cont(b'4', 1e-7)];
children.extend(tables());
children.push(b);
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn a_page_between_stray_bytes_is_kept_when_its_body_holds_a_table_that_reaches_its_end() {
// Bytes the page's long instruction carries hold a color table whose length reaches the end
// of the page.
let sq = square(&attrs(Some(1), None, false), 0, 0, 1000);
let mut table = b"rclr".to_vec();
let rest = [begin_layer("L", None), sq, end_layer()].concat();
// The table's body: the rest of the long instruction (2 bytes), then the instructions after it.
table.extend(((2 + rest.len()) as u32).to_le_bytes());
table.extend([0; 2]);
let carried = long_instr(-1, &table);
let p = page(&[begin_page(None), carried, rest]);
let at = p.windows(4).position(|w| w == b"rclr").unwrap();
assert!(at % 2 == 0 && (8..=64).contains(&at), "{at}");
let b = [vec![1u8; 2], p, vec![1u8; 2]].concat();
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn after_stray_bytes_a_page_whose_first_instruction_is_empty_inside_another_chunk_is_not_a_page() {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut b = vec![1u8; 2];
b.extend(chunk(b"inf1", &chunk(b"page", &[0; 4])));
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn a_header_between_stray_bytes_is_kept_when_its_body_holds_a_table_that_reaches_its_end() {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut c = cont(b'4', 1e-7);
let inner = (c.len() - 24) as u32;
c[16..20].copy_from_slice(b"rclr");
c[20..24].copy_from_slice(&inner.to_le_bytes());
let mut children = vec![[vec![1u8; 2], c, vec![1u8; 2]].concat(), p];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn after_stray_bytes_a_table_whose_entries_do_not_fit_inside_another_chunk_is_passed_over() {
// Stray bytes, then a chunk the reader passes over that holds a color table of one entry with
// no bytes for it, then the real tables: the colors come from the real tables.
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let read = |junk: &[u8]| {
let mut children = vec![cont(b'4', 1e-7), junk.to_vec()];
children.extend(tables());
children.push(p.clone());
read_checked(&riff(&children), Limits::default()).unwrap()
};
let junk = [vec![1u8; 2], chunk(b"inf1", &chunk(b"rclr", &[1, 0]))].concat();
let d = read(&junk);
let clean = read(&[]);
assert_eq!(format!("{:?}", d.pages), format!("{:?}", clean.pages));
}
#[test]
fn after_stray_bytes_a_page_whose_second_instruction_is_empty_inside_another_chunk_is_not_a_page() {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut b = vec![1u8; 2];
b.extend(chunk(b"inf1", &chunk(b"page", &[instr(-1, &[]), vec![0; 4]].concat())));
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn after_stray_bytes_page_letters_with_a_length_past_the_list_do_not_hide_the_page() {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut b = vec![1u8; 2];
b.extend(b"page");
b.extend(0xFFFF_FF00u32.to_le_bytes());
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
@@ -444,7 +1152,7 @@ fn a_dash_pattern_of_zero_lengths_draws_a_solid_line() {
children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rdot") && !t.starts_with(b"rotl")));
children.push(table(b"rdot", &[dashes(&[0, 0])]));
children.push(table(b"rotl", &[outline([3, 1, 2, 1, 1, 1])]));
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
let o = shape(&d.pages[0].layers[0].objects[0]).outline.clone().unwrap();
assert!(o.dashes.is_empty(), "{:?}", o.dashes);
@@ -462,7 +1170,7 @@ fn a_curve_field_that_lost_points_is_left_out() {
g.extend(1_000_000i32.to_le_bytes());
g.extend([0x40, 0x42]);
let c = instr(67, &fields(&[field(1, &attrs(Some(1), None, false)), field(2, &g)]));
let d = read_cmx(&file(&[page(&[begin_page(None), begin_layer("L", None), c])]), Limits::default()).unwrap();
let d = read_checked(&file(&[page(&[begin_page(None), begin_layer("L", None), c])]), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
assert!(d.pages[0].layers.is_empty(), "{:?}", d.pages[0].layers);
}
@@ -476,7 +1184,7 @@ fn a_chunk_whose_id_has_a_digit_is_found_after_stray_bytes() {
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
@@ -493,7 +1201,7 @@ fn padding_and_ids_with_impossible_lengths_are_not_taken_for_chunks() {
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
@@ -513,7 +1221,7 @@ fn after_stray_bytes_a_chunk_the_reader_passes_over_keeps_what_it_holds() {
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
let d = read_checked(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
@@ -525,7 +1233,7 @@ fn a_canvas_or_a_container_is_reported() {
let mut a = attrs(Some(1), None, false);
a[0] |= bit;
let p = page(&[begin_page(None), begin_layer("L", None), square(&a, 0, 0, 1000), end_layer()]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
let d = read_checked(&file(&[p]), Limits::default()).unwrap();
assert_eq!(d.warnings, vec![Warning::UnsupportedObjects], "{bit}");
assert!(shape(&d.pages[0].layers[0].objects[0]).fill.is_some());
}
@@ -536,7 +1244,7 @@ fn a_library_color_with_its_name_reads_as_a_spot_color() {
let mut children = vec![cont(b'4', 1e-7)];
children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)]));
children.push(table(b"rclr", &[color_record_named(5, [0, 0, 255, 0], Some("Brick 12"))]));
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
let d = read_checked(&riff(&children), Limits::default()).unwrap();
match shape(&d.pages[0].layers[0].objects[0]).fill.clone() {
Some(Color::Spot { name, tint, look }) => {
assert_eq!((name.as_str(), tint), ("Brick 12", 1.0));
@@ -553,7 +1261,7 @@ proptest! {
fn never_panics_on_garbage(bytes in prop::collection::vec(any::<u8>(), 0..2048)) {
let mut b = b"RIFF\0\0\0\0CMX1".to_vec();
b.extend(bytes);
let _ = read_cmx(&b, Limits::default());
let _ = read_kept(&b, Limits::default());
}
#[test]
@@ -563,6 +1271,6 @@ proptest! {
for (at, v) in edits {
b[at % n] = v;
}
let _ = read_cmx(&b, Limits::default());
let _ = read_kept(&b, Limits::default());
}
}
+1
View File
@@ -6,3 +6,4 @@ mod bench;
mod cmx;
mod provenance;
mod read;
mod write;
+976
View File
@@ -0,0 +1,976 @@
//! Writing drawings and reading them back.
use std::io::Read as _;
use craft_cdr::WriteError as Error;
use craft_cdr::model::{
Blend, Cap, Color, Drawing, Flags, Geometry, Guideline, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Path, Pt, Segment, Shape, SubPath,
};
use craft_cdr::{Limits, WRITTEN_VERSION, is_cdr, read, write};
use proptest::prelude::*;
/// `n` coordinate units (1/254000 inch) in points, which the file stores exactly.
fn u(n: i32) -> f64 {
f64::from(n) * (72.0 / 254_000.0)
}
fn pt(x: i32, y: i32) -> Pt {
Pt { x: u(x), y: u(y) }
}
/// A byte value as a color component, which the file stores exactly.
fn c(v: u8) -> f32 {
f32::from(v) / 255.0
}
fn moved(x: f64, y: f64) -> Matrix {
Matrix([1.0, 0.0, 0.0, 1.0, x, y])
}
fn layer(name: &str, objects: Vec<Object>) -> Layer {
Layer { name: name.into(), kind: LayerKind::Drawing, flags: Flags::default(), objects, guides: Vec::new() }
}
fn rect(w: i32, h: i32, fill: Option<Color>) -> Object {
Object::Shape(Box::new(Shape::new(Geometry::Rect { w: u(w), h: u(h), radii: [0.0; 4] }, moved(10.0, -20.0), fill, None)))
}
/// A drawing of one page and one layer holding `objects`.
fn one_layer(objects: Vec<Object>) -> Drawing {
Drawing {
version: WRITTEN_VERSION,
page_size: None,
pages: vec![Page { size: None, layers: vec![layer("A", objects)] }],
master: Vec::new(),
guides: Vec::new(),
warnings: Vec::new(),
}
}
/// A drawing with every kind of thing the writer writes.
fn everything() -> Drawing {
let black = Outline {
width: u(5080),
color: Color::Gray(1.0),
cap: Cap::Butt,
join: Join::Miter,
dashes: Vec::new(),
behind_fill: false,
scale_with: false,
};
let dashed = Outline {
width: u(2540),
color: Color::Cmyk([c(0), c(128), c(255), c(13)]),
cap: Cap::Round,
join: Join::Bevel,
dashes: vec![3.0, 1.0],
behind_fill: true,
scale_with: true,
};
let curve = Path {
subpaths: vec![
SubPath {
start: pt(0, 0),
segments: vec![Segment::Line(pt(254_000, 0)), Segment::Cubic(pt(254_000, 50_000), pt(100_000, 254_000), pt(0, 254_000))],
closed: true,
},
SubPath { start: pt(-1000, -1000), segments: vec![Segment::Line(pt(-5000, -9000))], closed: false },
],
};
let mut path =
Shape::new(Geometry::Path(curve), Matrix([0.5, 0.25, -0.25, 2.0, 100.0, -40.0]), Some(Color::Rgb([c(255), c(64), c(0)])), Some(dashed));
path.nonzero = true;
path.opacity = 0.75;
path.blend = Blend::Multiply;
let mut rounded = Shape::new(
Geometry::Rect { w: u(200_000), h: u(-100_000), radii: [u(10_000), u(0), u(25_000), u(50_000)] },
moved(0.0, 0.0),
Some(Color::Registration),
Some(black.clone()),
);
rounded.flags = Flags { hidden: true, locked: true };
let spot = Color::Spot { name: "Sky Blue".into(), tint: 1.0, look: Some([0.0, c(255), 0.0]) };
let ellipse = Shape::new(
Geometry::Ellipse { w: u(80_000), h: u(40_000) },
moved(-30.0, 30.0),
Some(spot.clone()),
Some(Outline { color: spot, ..black.clone() }),
);
let container = Shape::new(Geometry::Rect { w: u(100_000), h: u(100_000), radii: [0.0; 4] }, moved(0.0, 0.0), None, Some(black.clone()));
let inner = Object::Clip { container: Box::new(container.clone()), objects: vec![rect(10_000, 10_000, Some(Color::Gray(c(128))))] };
let clip = Object::Clip { container: Box::new(container), objects: vec![rect(20_000, 30_000, None), inner] };
let group = Object::Group {
objects: vec![Object::Shape(Box::new(ellipse)), rect(1000, 2000, Some(Color::Gray(0.0)))],
flags: Flags { hidden: true, locked: false },
};
let mut art = layer("Art", vec![Object::Shape(Box::new(path)), Object::Shape(Box::new(rounded)), group, clip]);
art.guides.push(Guideline { at: pt(0, 254_000), angle: -45.0, hidden: false });
let mut back = layer("Back ünïcode", vec![rect(5000, 5000, Some(Color::Rgb([c(1), c(2), c(3)])))]);
back.flags = Flags { hidden: true, locked: true };
let mut desktop = layer("Desktop", vec![rect(3000, 3000, None)]);
desktop.kind = LayerKind::Desktop;
Drawing {
version: WRITTEN_VERSION,
page_size: Some((u(2_159_000), u(2_794_000))),
pages: vec![
Page { size: Some((u(2_159_000), u(2_794_000))), layers: vec![art, back] },
Page { size: Some((u(1_000_000), u(500_000))), layers: vec![layer("Second", vec![rect(7000, 8000, None)])] },
],
master: vec![desktop],
guides: vec![Guideline { at: pt(254_000, 0), angle: 90.0, hidden: false }],
warnings: Vec::new(),
}
}
/// Rounds every number of `d` past the precision a round trip keeps.
fn rounded(mut d: Drawing) -> Drawing {
fn r(v: &mut f64) {
*v = (*v * 1e4).round() / 1e4 + 0.0;
}
fn rc(c: &mut Color) {
let f = |v: &mut f32| *v = (*v * 1e3).round() / 1e3 + 0.0;
match c {
Color::Rgb(v) => v.iter_mut().for_each(f),
Color::Cmyk(v) => v.iter_mut().for_each(f),
Color::Gray(v) => f(v),
Color::Registration => {}
Color::Spot { tint, look, .. } => {
f(tint);
if let Some(l) = look {
l.iter_mut().for_each(f);
}
}
}
}
fn rp(p: &mut Pt) {
r(&mut p.x);
r(&mut p.y);
}
fn rs(s: &mut Shape) {
s.matrix.0.iter_mut().for_each(r);
match &mut s.geometry {
Geometry::Rect { w, h, radii } => {
r(w);
r(h);
radii.iter_mut().for_each(r);
}
Geometry::Ellipse { w, h } => {
r(w);
r(h);
}
Geometry::Path(p) => {
for sp in &mut p.subpaths {
rp(&mut sp.start);
for seg in &mut sp.segments {
match seg {
Segment::Line(a) => rp(a),
Segment::Cubic(a, b, e) => [a, b, e].into_iter().for_each(rp),
}
}
}
}
}
s.fill.iter_mut().for_each(rc);
if let Some(o) = &mut s.outline {
r(&mut o.width);
rc(&mut o.color);
}
s.opacity = (s.opacity * 1e3).round() / 1e3;
}
let mut stack: Vec<&mut Object> = Vec::new();
for l in d.pages.iter_mut().flat_map(|p| p.layers.iter_mut()).chain(d.master.iter_mut()) {
for g in &mut l.guides {
rp(&mut g.at);
}
stack.extend(l.objects.iter_mut());
}
while let Some(o) = stack.pop() {
match o {
Object::Shape(s) => rs(s),
Object::Group { objects, .. } => stack.extend(objects.iter_mut()),
Object::Clip { container, objects } => {
rs(container);
stack.extend(objects.iter_mut());
}
}
}
for g in &mut d.guides {
rp(&mut g.at);
}
for (w, h) in d.pages.iter_mut().filter_map(|p| p.size.as_mut()).chain(d.page_size.as_mut()) {
r(w);
r(h);
}
d
}
/// `d` as it reads back once written: rounded, and each closed subpath whose last segment ends away
/// from its start given a closing line to its start.
fn as_read(d: Drawing) -> Drawing {
let mut d = rounded(d);
let mut stack: Vec<&mut Object> = d.pages.iter_mut().flat_map(|p| p.layers.iter_mut()).flat_map(|l| l.objects.iter_mut()).collect();
stack.extend(d.master.iter_mut().flat_map(|l| l.objects.iter_mut()));
while let Some(o) = stack.pop() {
let shape = match o {
Object::Shape(s) => s,
Object::Group { objects, .. } => {
stack.extend(objects.iter_mut());
continue;
}
Object::Clip { container, objects } => {
stack.extend(objects.iter_mut());
container
}
};
let Geometry::Path(p) = &mut shape.geometry else { continue };
for sp in &mut p.subpaths {
let end = sp.segments.last().map(|s| match s {
Segment::Line(e) | Segment::Cubic(_, _, e) => *e,
});
if sp.closed && end.is_some_and(|e| e != sp.start) {
sp.segments.push(Segment::Line(sp.start));
}
}
}
d
}
/// The RIFF file inside a written package.
fn riff_of(file: &[u8]) -> Vec<u8> {
// The second member, after the stored `mimetype`.
let (name, data) = member(file, 0);
assert_eq!((name, data), (&b"mimetype"[..], &b"application/x-vnd.corel.draw.document+zip"[..]));
let next = 30 + name.len() + data.len();
let (name, data) = member(file, next);
assert_eq!(name, b"content/riffData.cdr");
let mut out = Vec::new();
flate2::read::DeflateDecoder::new(data).read_to_end(&mut out).unwrap();
out
}
/// The name and packed bytes of the member whose local header is at `at`.
fn member(file: &[u8], at: usize) -> (&[u8], &[u8]) {
let le16 = |i: usize| usize::from(u16::from_le_bytes([file[at + i], file[at + i + 1]]));
let packed = u32::from_le_bytes(file[at + 18..at + 22].try_into().unwrap()) as usize;
let name = &file[at + 30..at + 30 + le16(26)];
let start = at + 30 + le16(26) + le16(28);
(name, &file[start..start + packed])
}
fn count(hay: &[u8], needle: &[u8]) -> usize {
hay.windows(needle.len()).filter(|w| *w == needle).count()
}
#[test]
fn a_written_drawing_reads_back_as_written() {
let d = everything();
let file = write(&d, Limits::default()).unwrap();
let back = read(&file, Limits::default()).unwrap();
assert!(back.warnings.is_empty(), "{:?}", back.warnings);
assert_eq!(rounded(back), as_read(d));
}
#[test]
fn a_written_file_is_a_version_15_package_and_the_same_each_time() {
let file = write(&everything(), Limits::default()).unwrap();
assert!(is_cdr(&file) && file.starts_with(b"PK\x03\x04"));
let riff = riff_of(&file);
assert_eq!(&riff[8..12], b"CDRF");
assert_eq!(&riff[12..18], b"vrsn\x02\0");
assert_eq!(read(&file, Limits::default()).unwrap().version, 1500);
assert_eq!(file, write(&everything(), Limits::default()).unwrap());
// `mcfg` starts with the tag 1300 and the length of the rest (R72).
let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize;
let mcfg = riff.windows(4).position(|w| w == b"mcfg").unwrap();
assert_eq!((le32(mcfg + 8), le32(mcfg + 12)), (1300, le32(mcfg + 4) - 8));
// Every child of `LIST filt` is a `LIST filc` that holds one `fild` and nothing else (R72).
let padded = |size: usize| 8 + size + (size & 1);
let filt = riff.windows(12).position(|w| &w[..4] == b"LIST" && &w[8..] == b"filt").unwrap();
let (mut at, end) = (filt + 12, filt + 8 + le32(filt + 4));
let mut lists = 0;
while at < end {
assert_eq!((&riff[at..at + 4], &riff[at + 8..at + 12], &riff[at + 12..at + 16]), (&b"LIST"[..], &b"filc"[..], &b"fild"[..]));
assert_eq!(at + 12 + padded(le32(at + 16)), at + padded(le32(at + 4)));
at += padded(le32(at + 4));
lists += 1;
}
assert_eq!((at, lists), (end, count(&riff, b"fild")));
assert!(lists > 0);
}
#[test]
fn each_container_names_its_own_clipped_group_by_the_stored_id() {
let riff = riff_of(&write(&everything(), Limits::default()).unwrap());
let ids: Vec<u32> =
(0..riff.len() - 12).filter(|&p| &riff[p..p + 4] == b"spnd").map(|p| u32::from_le_bytes(riff[p + 8..p + 12].try_into().unwrap())).collect();
let mut distinct = ids.clone();
distinct.sort_unstable();
distinct.dedup();
assert!(ids.len() > 1 && distinct.len() == ids.len(), "{ids:?}");
// The first u32 of each container argument (8005), from every `loda` record: a `loda` chunk's
// body starts with its own length.
let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize;
let mut named: Vec<u32> = (0..riff.len() - 28)
.filter(|&p| &riff[p..p + 4] == b"loda" && le32(p + 4) == le32(p + 8))
.flat_map(|p| {
let loda = p + 8;
let (n, offsets, types) = (le32(loda + 4), loda + le32(loda + 8), loda + le32(loda + 12));
(0..n).filter(move |i| le32(types + 4 * (n - 1 - i)) == 8005).map(move |i| le32(loda + le32(offsets + 4 * i)) as u32)
})
.collect();
named.sort_unstable();
// Each container names its group by the group's `spnd` id unchanged, and no two name one group.
assert_eq!(named, distinct);
}
#[test]
fn shapes_with_the_same_fill_and_outline_share_one_record_of_each() {
let fill = || Some(Color::Rgb([c(10), c(20), c(30)]));
let records = |d: &Drawing| {
let riff = riff_of(&write(d, Limits::default()).unwrap());
(count(&riff, b"fild"), count(&riff, b"outl"))
};
assert_eq!(records(&one_layer((0..50).map(|i| rect(1000 + i, 1000, fill())).collect())), records(&one_layer(vec![rect(1000, 1000, fill())])));
}
#[test]
fn a_closed_subpath_ends_at_its_start_and_its_other_nodes_can_be_edited() {
let start = pt(1234, 5678);
let open_end = SubPath { start, segments: vec![Segment::Line(pt(90_000, 5678)), Segment::Line(pt(1234, 90_000))], closed: true };
let triangle =
|sp: SubPath| one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Path(Path { subpaths: vec![sp] }), Matrix::IDENTITY, None, None)))]);
let riff = riff_of(&write(&triangle(open_end.clone()), Limits::default()).unwrap());
// The closing point at the start, then the type bytes: an editable closed move, two editable
// line ends and the closing line end, which is not editable.
let tail: Vec<u8> = [1234i32, 5678].iter().flat_map(|v| v.to_le_bytes()).chain([0x0C, 0x44, 0x44, 0x48]).collect();
assert_eq!(count(&riff, &tail), 1);
// A subpath that already ends at its start is written as it is.
let mut ends_at_start = open_end;
ends_at_start.segments.push(Segment::Line(start));
assert_eq!(riff_of(&write(&triangle(ends_at_start), Limits::default()).unwrap()), riff);
}
#[test]
fn every_page_names_the_master_pages_guides_desktop_and_grid_by_their_ids() {
let mut d = everything();
// A drawing layer of the master page, which the other pages do not name. The drawing has no
// grid layer of its own, as a read drawing has none.
d.master.push(layer("Master art", vec![rect(100, 100, None)]));
let riff = riff_of(&write(&d, Limits::default()).unwrap());
let layers = layer_entries(&riff);
// Each page names the master page's guides, desktop and grid layers (object types 12, 17 and
// 11) once each, by kind, name and id: the guides and desktop before the page's own layers,
// the grid after them.
let named = |page: usize, kinds: &[usize]| {
let kept = |l: &&Entry| l.0 == page && l.1 == 1 && kinds.contains(&l.2);
let mut v: Vec<_> = layers.iter().filter(kept).map(|l| (l.2, &l.3, &l.4)).collect();
v.sort();
v
};
assert_eq!(named(0, &[11, 12, 17]).len(), 3);
for page in 1..=d.pages.len() {
assert_eq!(named(page, &[11, 12, 17, 0]), named(0, &[11, 12, 17]));
let kinds: Vec<usize> = layers.iter().filter(|l| l.0 == page).map(|l| if l.1 == 0 { 0 } else { l.2 }).collect();
let own = kinds.iter().position(|k| *k == 0).unwrap();
assert!(kinds[..own].iter().all(|k| [12, 17].contains(k)) && kinds[own..].iter().filter(|k| **k != 0).all(|k| *k == 11), "{kinds:?}");
assert!(kinds.ends_with(&[11]), "{kinds:?}");
}
// The master page's layers and the pages' own layers each have their own 16-byte id.
let mut own: Vec<&[u8]> = layers.iter().filter(|l| l.0 == 0 || l.1 == 0).map(|l| &l.4[..]).collect();
assert!(own.iter().all(|id| id.len() == 16));
let count = own.len();
own.sort();
own.dedup();
assert_eq!(own.len(), count);
// The guides layer, the first layer written, gets another id in a drawing that differs only in
// a fill color.
// A guides layer of the drawing's own master page takes the drawing's guidelines too, and is
// the only guides layer there; a hidden or locked one keeps them off it.
let guide = |x: i32| Guideline { at: pt(x, 0), angle: 90.0, hidden: false };
let with_guides = |flags: Flags, drawing_guides: Vec<Guideline>| {
let mut guides = layer("Guides", Vec::new());
guides.kind = LayerKind::Guides;
guides.flags = flags;
guides.guides = vec![guide(100)];
Drawing { master: vec![guides], guides: drawing_guides, ..one_layer(Vec::new()) }
};
for (flags, drawing_guides, layers) in [
(Flags::default(), vec![guide(200)], 1),
(Flags { hidden: true, locked: false }, Vec::new(), 1),
(Flags { hidden: true, locked: false }, vec![guide(200)], 2),
(Flags { hidden: false, locked: true }, vec![guide(200)], 2),
] {
let d = with_guides(flags, drawing_guides.clone());
let file = write(&d, Limits::default()).unwrap();
let entries = layer_entries(&riff_of(&file));
assert_eq!(entries.iter().filter(|l| l.0 == 0 && l.2 == 12).count(), layers, "{flags:?}");
// Each guideline once, the drawing's in a layer that is shown and unlocked: each guideline
// object's x (in units), and bytes 0 and 1 of the flags of the layer it is in.
let riff = riff_of(&file);
let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize;
let mut placed: Vec<(i32, u8, u8)> = (0..riff.len() - 28)
.filter(|&p| &riff[p..p + 4] == b"loda" && le32(p + 8 + 16) == 0x16)
.map(|p| {
let arg = p + 8 + le32(p + 8 + le32(p + 8 + 8));
let layr = riff[..p].windows(8).rposition(|w| w == b"layrflgs").unwrap();
(i32::from_le_bytes(riff[arg + 16..arg + 20].try_into().unwrap()), riff[layr + 12], riff[layr + 13])
})
.collect();
placed.sort();
let xs: Vec<i32> = placed.iter().map(|g| g.0).collect();
assert_eq!(xs, if drawing_guides.is_empty() { vec![100] } else { vec![100, 200] }, "{flags:?}");
assert!(placed.iter().filter(|g| g.0 == 200).all(|g| g.1 & 0x10 == 0 && g.2 == 0), "{flags:?}");
}
let first = |c: Color| layer_entries(&riff_of(&write(&one_layer(vec![rect(100, 100, Some(c))]), Limits::default()).unwrap()))[0].4.clone();
assert_ne!(first(Color::Gray(0.0)), first(Color::Gray(1.0)));
}
/// A layer list of a written file: its page (0 the master page), byte 2 of its flags, its object
/// type, and its name and id arguments.
type Entry = (usize, u8, usize, Vec<u8>, Vec<u8>);
/// The layer lists of `riff`, each `layr` with its `flgs` chunk, then `LIST lgob` with its `loda`.
fn layer_entries(riff: &[u8]) -> Vec<Entry> {
let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize;
let pages: Vec<usize> = riff.windows(12).enumerate().filter(|(_, w)| &w[..4] == b"LIST" && &w[8..] == b"page").map(|(p, _)| p).collect();
riff.windows(8)
.enumerate()
.filter(|(_, w)| w == b"layrflgs")
.map(|(p, _)| {
let page = pages.iter().filter(|&&at| at < p).count() - 1;
let loda = p + 36;
let (n, offsets, types) = (le32(loda + 4), loda + le32(loda + 8), loda + le32(loda + 12));
let arg = |t: usize| {
let i = (0..n).find(|i| le32(types + 4 * (n - 1 - i)) == t).unwrap();
riff[loda + le32(offsets + 4 * i)..loda + le32(offsets + 4 * i + 4)].to_vec()
};
(page, riff[p + 14], le32(loda + 16), arg(1000), arg(40050))
})
.collect()
}
#[test]
fn a_guideline_runs_along_the_angle_it_stores() {
// Starts `by` units inside a corner of the coordinate range.
let near = |by: f64| Pt { x: u(i32::MAX) - by * u(1), y: u(i32::MAX) - by * u(1) };
let guide = |at: Pt, angle: f64| Drawing { guides: vec![Guideline { at, angle, hidden: false }], ..one_layer(Vec::new()) };
// A quarter of a unit past the corner, on the corner itself, and less than half a unit inside
// it, the start rounds onto the corner, and no other point of the line rounds within the range
// along it. The last line runs almost level, so every point of it in the range rounds onto the
// corner too, as does the line that starts on the corner and half a unit past it.
let on_corner = Pt { x: 608_735.521_984_251_9, y: 608_735.521_984_251_9 };
let level = [(near(-0.49), -0.9), (Pt { x: 608_735.521_984_252, y: 608_735.522_125_984_2 }, -0.00004)];
for (at, angle) in [near(-0.25), on_corner, near(0.1), near(0.01), near(0.00025)].map(|at| (at, -45.0)).into_iter().chain(level) {
assert!(matches!(write(&guide(at, angle), Limits::default()), Err(Error::Unwritable(_))), "{at:?}");
}
let inside = [(pt(1000, 2000), 30.0), (pt(1000, 2000), -45.0), (pt(1000, 2000), 1e20)];
// A unit or more inside the corner, a point a whole unit or more away on each axis fits;
// at 1.25 units the farthest points in the range round off the angle and a nearer one does not.
// At -44 degrees the only point along the line turns from it by exactly a degree. At -18
// degrees the one point along the line lies between whole units on both axes.
let between = Pt { x: u(i32::MAX) - 2.0 * u(1), y: u(i32::MAX) - 1.48 * u(1) };
// A start a unit and a half and half a unit inside the corner lies on the edges of rounding.
let edges = Pt { x: 608_735.521_559_055_1, y: 608_735.521_842_519_8 };
let near_corner = [(near(1000.0), -45.0), (near(1.25), -45.0), (near(1.0), -45.0), (near(1.0), -44.0), (between, -18.0), (edges, -45.0)];
for (at, angle) in inside.into_iter().chain(near_corner) {
let corner = at.x > u(1_000_000);
let d = Drawing { guides: vec![Guideline { at, angle, hidden: false }], ..one_layer(Vec::new()) };
let riff = riff_of(&write(&d, Limits::default()).unwrap_or_else(|e| panic!("{at:?} {angle}: {e}")));
let le32 = |at: usize| u32::from_le_bytes(riff[at..at + 4].try_into().unwrap()) as usize;
let i32_at = |at: usize| f64::from(i32::from_le_bytes(riff[at..at + 4].try_into().unwrap()));
// The guideline object's `loda` (object type 0x16) and its first argument: 12 bytes, the
// angle in millionths of a degree, then the point and a second point on the line.
let loda = riff.windows(4).enumerate().map(|(p, _)| p).find(|&p| &riff[p..p + 4] == b"loda" && le32(p + 8 + 16) == 0x16).unwrap() + 8;
let arg = loda + le32(loda + le32(loda + 8));
let a = (i32_at(arg + 12) / 1e6).to_radians();
let (dx, dy) = (i32_at(arg + 24) - i32_at(arg + 16), i32_at(arg + 28) - i32_at(arg + 20));
assert!(dx.hypot(dy) > if corner { 0.0 } else { 1000.0 });
// Off the stored direction by no more than the coordinates' rounding, and, on either
// side, by no more than a degree.
assert!((dx * a.sin() - dy * a.cos()).abs() <= 1.5, "{angle}: {dx} {dy}");
let turn = (dx * a.sin() - dy * a.cos()).abs().atan2((dx * a.cos() + dy * a.sin()).abs());
assert!(turn <= 1f64.to_radians() + 1e-12, "{angle}: {dx} {dy}");
}
}
#[test]
fn an_outline_record_ends_8_bytes_before_its_chunk_and_its_color_list_at_its_empty_property() {
let spot = Color::Spot { name: "Ink".into(), tint: 1.0, look: Some([0.0; 3]) };
let o = Outline { width: u(2540), color: spot, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new(), behind_fill: false, scale_with: false };
let outlined = one_layer(vec![Object::Shape(Box::new(Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(o))))]);
let riff = riff_of(&write(&outlined, Limits::default()).unwrap());
let le32 = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize;
let at = riff.windows(4).position(|w| w == b"outl").unwrap();
let chunk = &riff[at + 8..at + 8 + le32(&riff, at + 4)];
// The outline's id, then records (type, length, body) up to the one of type 1.
let mut p = 4;
let mut types = Vec::new();
loop {
let (kind, len) = (le32(chunk, p), le32(chunk, p + 4));
types.push(kind);
if kind == 1 {
assert_eq!(len, chunk.len() - p - 8 - 8);
// The body as sample files lay it out (R71): 130 bytes, an f64 1 at bytes 16 and 48,
// 45 degrees at byte 84 and 60 at byte 88.
let body = &chunk[p + 8..p + 8 + len];
let f64_at = |at: usize| f64::from_le_bytes(body[at..at + 8].try_into().unwrap());
assert_eq!((len, f64_at(16), f64_at(48), le32(body, 84), le32(body, 88)), (130, 1.0, 1.0, 45_000_000, 60));
break;
}
// The color property list (type byte, length, body) ends at its first empty property.
if kind == 2 {
let mut q = p + 8;
while chunk[q] != 0 {
q += 5 + le32(chunk, q + 1);
}
assert_eq!((q + 5, le32(chunk, q + 1)), (p + 8 + len, 0));
}
p += 8 + len;
}
assert_eq!(types, [2, 1]);
}
#[test]
fn a_transparency_names_a_white_fill_record_of_the_file() {
let mut s = Shape::new(rect_geometry(), Matrix::IDENTITY, Some(Color::Gray(1.0)), None);
s.opacity = 0.5;
let riff = riff_of(&write(&one_layer(vec![Object::Shape(Box::new(s))]), Limits::default()).unwrap());
let head: Vec<u8> = [1300u32, 117].iter().flat_map(|v| v.to_le_bytes()).collect();
let at = riff.windows(head.len()).position(|w| w == head).unwrap() + head.len();
let id = &riff[at + 105..at + 109];
// The `fild` chunk of that id (chunk id, size, record id) holds the RGB color record of white.
let fild = riff.windows(12).position(|w| &w[..4] == b"fild" && &w[8..] == id).unwrap();
let size = u32::from_le_bytes(riff[fild + 4..fild + 8].try_into().unwrap()) as usize;
let white = [5, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 0];
assert_eq!(count(&riff[fild + 8..fild + 8 + size], &white), 1);
}
#[test]
fn empty_groups_are_left_out_and_a_container_without_objects_is_a_shape() {
let container = Shape::new(Geometry::Ellipse { w: u(10_000), h: u(10_000) }, Matrix::IDENTITY, None, None);
let objects = vec![
Object::Group { objects: Vec::new(), flags: Flags::default() },
Object::Clip { container: Box::new(container.clone()), objects: Vec::new() },
];
let back = read(&write(&one_layer(objects), Limits::default()).unwrap(), Limits::default()).unwrap();
assert_eq!(back.pages[0].layers[0].objects, vec![Object::Shape(Box::new(container.clone()))]);
assert!(back.warnings.is_empty());
// A container whose objects are groups that draw nothing is written as the plain shape is.
let hollow = Object::Group { objects: vec![Object::Group { objects: Vec::new(), flags: Flags::default() }], flags: Flags::default() };
let clips_hollow = one_layer(vec![Object::Clip { container: Box::new(container.clone()), objects: vec![hollow] }]);
let file = write(&clips_hollow, Limits::default()).unwrap();
assert_eq!(file, write(&one_layer(vec![Object::Shape(Box::new(container))]), Limits::default()).unwrap());
// A group that holds only groups that draw nothing is written as no group at all.
assert_eq!(write(&one_layer(vec![hollow_group()]), Limits::default()).unwrap(), write(&one_layer(Vec::new()), Limits::default()).unwrap());
}
fn hollow_group() -> Object {
Object::Group { objects: vec![Object::Group { objects: Vec::new(), flags: Flags::default() }], flags: Flags::default() }
}
#[test]
fn a_drawing_without_pages_is_written_with_one_empty_page() {
let d = Drawing { pages: Vec::new(), ..one_layer(Vec::new()) };
let back = read(&write(&d, Limits::default()).unwrap(), Limits::default()).unwrap();
assert_eq!(back.pages.len(), 1);
assert!(back.pages[0].layers.iter().all(|l| l.objects.is_empty()));
// Without a page size of its own, the drawing reads back without one.
assert_eq!(back.page_size, None);
}
/// At the smallest value of a limit at which the reader reads `d`'s file whole, the writer writes
/// it; one below, the writer refuses it.
fn writes_at_the_readers_limit(d: &Drawing, set: fn(&mut Limits, usize)) -> usize {
let limits = |n| {
let mut l = Limits::default();
set(&mut l, n);
l
};
let file = write(d, Limits::default()).unwrap();
let whole = |n| read(&file, limits(n)).is_ok_and(|b| b.warnings.is_empty());
// The smallest value that reads whole: a read that fits a limit fits every larger one.
let (mut n, mut above) = (0, 100_000);
while n < above {
let mid = (n + above) / 2;
if whole(mid) { above = mid } else { n = mid + 1 }
}
assert!(whole(n), "{n}");
assert_eq!(write(d, limits(n)).as_ref(), Ok(&file), "{n}");
assert!(n > 0 && matches!(write(d, limits(n - 1)), Err(Error::Limit(_))), "{n}");
n
}
#[test]
fn every_limit_a_read_applies_is_applied_when_writing() {
let d = everything();
let set: [fn(&mut Limits, usize); 10] = [
|l, n| l.input = n,
|l, n| l.inflated = n,
|l, n| l.arguments = n,
|l, n| l.clipped_chunks = n,
|l, n| l.chunks = n,
|l, n| l.member = n,
|l, n| l.dashes = n,
|l, n| l.objects = n,
|l, n| l.coordinates = n,
|l, n| l.members = n,
];
for set in set {
writes_at_the_readers_limit(&d, set);
}
// Without clipped groups the outline table ends the file: an empty drawing, and one whose
// last record is an outline.
let o = Outline {
width: u(2540),
color: Color::Gray(0.0),
cap: Cap::Butt,
join: Join::Miter,
dashes: Vec::new(),
behind_fill: false,
scale_with: false,
};
let outlined = one_layer(vec![Object::Shape(Box::new(Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(o))))]);
let bytes: [fn(&mut Limits, usize); 3] = [|l, n| l.input = n, |l, n| l.inflated = n, |l, n| l.member = n];
for d in [one_layer(Vec::new()), outlined] {
for set in bytes {
writes_at_the_readers_limit(&d, set);
}
}
// A group that holds only an empty group is left out, and takes nothing of the object count.
let hollow =
one_layer(vec![Object::Group { objects: vec![Object::Group { objects: Vec::new(), flags: Flags::default() }], flags: Flags::default() }]);
assert!(write(&hollow, Limits { objects: 0, ..Limits::default() }).is_ok());
}
#[test]
fn a_path_past_the_coordinate_count_stops_before_its_points_are_written() {
// The closing point's coordinates are past the file's range; the count is refused first.
let mut segments: Vec<Segment> = (1..10).map(|i| Segment::Line(pt(i * 100, 0))).collect();
segments.push(Segment::Line(Pt { x: 1e30, y: 0.0 }));
let path = Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed: true }] };
let d = one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Path(path), Matrix::IDENTITY, None, None)))]);
assert!(matches!(write(&d, Limits::default()), Err(Error::Unwritable(_))));
assert!(matches!(write(&d, Limits { coordinates: 5, ..Limits::default() }), Err(Error::Limit(_))));
// A shape takes at least three arguments, counted before its points.
assert_eq!(write(&d, Limits { arguments: 2, ..Limits::default() }), Err(Error::Limit("argument count")));
// So is the file's size, from the segment count: a long path refused at half its bytes.
let long = |end: Pt| {
let mut segments: Vec<Segment> = (1..1000).map(|i| Segment::Line(pt(i * 100, i % 2 * 100))).collect();
segments.push(Segment::Line(end));
let path = Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed: true }] };
one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Path(path), Matrix::IDENTITY, None, None)))])
};
let member = riff_of(&write(&long(pt(0, 100)), Limits::default()).unwrap()).len() - 1000 * 9 / 2;
assert!(matches!(write(&long(Pt { x: 1e30, y: 0.0 }), Limits::default()), Err(Error::Unwritable(_))));
assert!(matches!(write(&long(Pt { x: 1e30, y: 0.0 }), Limits { member, ..Limits::default() }), Err(Error::Limit(_))));
// So are the shape's nested lists: one level short of what a rectangle in its place takes.
let fits = |n| write(&one_layer(vec![rect(100, 100, None)]), Limits { depth: n, ..Limits::default() }).is_ok();
let depth = (1..64).find(|&n| fits(n)).unwrap();
assert_eq!(write(&d, Limits { depth: depth - 1, ..Limits::default() }), Err(Error::Limit("nesting depth")));
// In a clipped group, every other chunk of the file counts too: one chunk short of what the
// drawing takes with a path in range, the clipped path is refused before its points.
let clipped = |path: Path| {
let container = Shape::new(rect_geometry(), Matrix::IDENTITY, None, None);
// A fill of its own, whose record counts as well.
let shape = Shape::new(Geometry::Path(path), Matrix::IDENTITY, Some(Color::Gray(0.5)), None);
one_layer(vec![Object::Clip { container: Box::new(container), objects: vec![Object::Shape(Box::new(shape))] }])
};
let Some(Object::Shape(s)) = d.pages[0].layers[0].objects.first() else { panic!("no path") };
let Geometry::Path(past) = s.geometry.clone() else { panic!("no path") };
let mut within = past.clone();
within.subpaths[0].segments.pop();
let chunks = (1..1000).find(|&n| write(&clipped(within.clone()), Limits { chunks: n, ..Limits::default() }).is_ok()).unwrap();
assert!(matches!(write(&clipped(past.clone()), Limits::default()), Err(Error::Unwritable(_))));
assert_eq!(write(&clipped(past), Limits { chunks: chunks - 1, ..Limits::default() }), Err(Error::Limit("chunk count")));
}
#[test]
fn a_rectangle_repeats_the_scale_of_its_transform() {
// Scaled by 2 and 3, then turned a quarter turn: the scale fields hold 2 and 3 (R29).
for m in [Matrix([2.0, 0.0, 0.0, 3.0, 5.0, 7.0]), Matrix([0.0, 2.0, -3.0, 0.0, 5.0, 7.0])] {
let shape = Shape::new(Geometry::Rect { w: u(1000), h: u(2000), radii: [0.0; 4] }, m, None, None);
let riff = riff_of(&write(&one_layer(vec![Object::Shape(Box::new(shape))]), Limits::default()).unwrap());
// The record's width and height in coordinate units, then the two scale fields.
let units = |v: f64| (v * (254_000.0 / 72.0)).to_le_bytes();
let fields = [units(u(1000)), units(u(2000)), 2.0f64.to_le_bytes(), 3.0f64.to_le_bytes()].concat();
assert_eq!(count(&riff, &fields), 1, "{m:?}");
}
}
#[test]
fn the_pages_clipped_groups_and_records_share_the_byte_limit() {
// A long path on the page and another in a clipped group each fit the limit; together they do
// not, and writing stops at the second before it reaches the unwritable shape after it.
let long = || {
let segments = (1..4000).map(|i| Segment::Line(pt(i * 100, (i % 7) * 100))).collect();
let path = Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed: false }] };
Object::Shape(Box::new(Shape::new(Geometry::Path(path), Matrix::IDENTITY, None, None)))
};
let container = || Box::new(Shape::new(rect_geometry(), Matrix::IDENTITY, None, None));
let fits = one_layer(vec![long(), Object::Clip { container: container(), objects: vec![long()] }]);
let past = Shape::new(Geometry::Rect { w: 1e30, h: 1.0, radii: [0.0; 4] }, Matrix::IDENTITY, None, None);
let stops = one_layer(vec![long(), Object::Clip { container: container(), objects: vec![long(), Object::Shape(Box::new(past))] }]);
assert!(matches!(write(&stops, Limits::default()), Err(Error::Unwritable(_))));
let member = riff_of(&write(&fits, Limits::default()).unwrap()).len() - 4000 * 9 / 2;
assert!(matches!(write(&stops, Limits { member, ..Limits::default() }), Err(Error::Limit(_))));
// Shapes whose fills all differ: the page fits the limit, and the fill table takes it past
// before the writer reaches the unwritable shape at the end of the page.
let shapes = || (0..=255u8).map(|v| rect(1000, 1000, Some(Color::Gray(c(v))))).collect::<Vec<_>>();
let riff = riff_of(&write(&one_layer(shapes()), Limits::default()).unwrap());
let filt = riff.windows(12).position(|w| &w[..4] == b"LIST" && &w[8..] == b"filt").unwrap();
let table = u32::from_le_bytes(riff[filt + 4..filt + 8].try_into().unwrap()) as usize;
let member = riff.len() - table / 2;
let past = Shape::new(Geometry::Rect { w: 1e30, h: 1.0, radii: [0.0; 4] }, Matrix::IDENTITY, None, None);
let stops = one_layer(shapes().into_iter().chain([Object::Shape(Box::new(past))]).collect());
assert!(matches!(write(&stops, Limits::default()), Err(Error::Unwritable(_))));
assert!(matches!(write(&stops, Limits { member, ..Limits::default() }), Err(Error::Limit(_))));
}
#[test]
fn clips_nest_as_deep_as_a_read_takes() {
let nested = |depth: usize| {
let mut o = rect(100, 100, None);
for _ in 0..depth {
let container = Shape::new(Geometry::Ellipse { w: u(1000), h: u(1000) }, Matrix::IDENTITY, None, None);
o = Object::Clip { container: Box::new(container), objects: vec![o] };
}
one_layer(vec![o])
};
let back = read(&write(&nested(64), Limits::default()).unwrap(), Limits::default()).unwrap();
assert!(back.warnings.is_empty(), "{:?}", back.warnings);
assert_eq!(rounded(back), as_read(nested(64)));
assert_eq!(write(&nested(65), Limits::default()), Err(Error::Limit("clip nesting")));
}
#[test]
fn ten_dashes_fit_before_the_arrowheads_and_eleven_do_not() {
let dashed = |n: usize| {
let o = Outline {
width: u(2540),
color: Color::Gray(1.0),
cap: Cap::Butt,
join: Join::Miter,
dashes: (1..=n).map(|d| d as f64).collect(),
behind_fill: false,
scale_with: false,
};
one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Ellipse { w: u(1000), h: u(1000) }, Matrix::IDENTITY, None, Some(o))))])
};
let back = read(&write(&dashed(10), Limits::default()).unwrap(), Limits::default()).unwrap();
assert!(back.warnings.is_empty(), "{:?}", back.warnings);
assert_eq!(rounded(back), as_read(dashed(10)));
assert!(matches!(write(&dashed(11), Limits::default()), Err(Error::Unwritable(_))));
}
#[test]
fn names_and_values_the_reader_would_change_are_refused() {
let named = |name: String| Drawing { pages: vec![Page { size: None, layers: vec![layer(&name, Vec::new())] }], ..one_layer(Vec::new()) };
let back = read(&write(&named("é".repeat(256)), Limits::default()).unwrap(), Limits::default()).unwrap();
assert_eq!(back.pages[0].layers[0].name, "é".repeat(256));
assert!(back.warnings.is_empty());
for name in ["é".repeat(257), "A\0B".to_string()] {
assert!(matches!(write(&named(name), Limits::default()), Err(Error::Unwritable(_))));
}
let filled = |c: Color| one_layer(vec![rect(100, 100, Some(c))]);
// At a 10% tint, the stored byte nearest a black look reads back a step off, and the next one
// reads back black.
let black_tint = Color::Spot { name: "Ink".into(), tint: 0.1, look: Some([0.0; 3]) };
let back = read(&write(&filled(black_tint.clone()), Limits::default()).unwrap(), Limits::default()).unwrap();
assert_eq!(rounded(back), rounded(filled(black_tint)));
for c in [
Color::Rgb([f32::NAN, 0.0, 0.0]),
Color::Gray(1.5),
Color::Spot { name: String::new(), tint: 1.0, look: None },
Color::Spot { name: "Red".into(), tint: 0.0, look: Some([1.0, 0.0, 0.0]) },
Color::Spot { name: "Gray".into(), tint: 0.01, look: Some([0.5, 0.5, 0.5]) },
] {
assert!(matches!(write(&filled(c), Limits::default()), Err(Error::Unwritable(_))));
}
// A corner past half the shorter side, a page of no width, a dash past what a u16 holds.
let corner = Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [9.0, 0.0, 0.0, 0.0] }, Matrix::IDENTITY, None, None);
assert!(matches!(write(&one_layer(vec![Object::Shape(Box::new(corner))]), Limits::default()), Err(Error::Unwritable(_))));
let flat = Drawing { page_size: Some((0.0, 10.0)), ..one_layer(Vec::new()) };
assert!(matches!(write(&flat, Limits::default()), Err(Error::Unwritable(_))));
let long = Outline {
width: 1.0,
color: Color::Gray(1.0),
cap: Cap::Butt,
join: Join::Miter,
dashes: vec![100_000.0],
behind_fill: false,
scale_with: false,
};
let fine = Outline { dashes: vec![0.4, 0.4], ..long.clone() };
for o in [long, fine] {
let dashed = Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(o));
assert!(matches!(write(&one_layer(vec![Object::Shape(Box::new(dashed))]), Limits::default()), Err(Error::Unwritable(_))));
}
let mut see_through = Shape::new(rect_geometry(), Matrix::IDENTITY, None, None);
see_through.opacity = f32::NAN;
assert!(matches!(write(&one_layer(vec![Object::Shape(Box::new(see_through))]), Limits::default()), Err(Error::Unwritable(_))));
let mut grid = layer("Grid", vec![rect(100, 100, None)]);
grid.kind = LayerKind::Grid;
assert!(matches!(write(&Drawing { master: vec![grid], ..one_layer(Vec::new()) }, Limits::default()), Err(Error::Unwritable(_))));
}
fn rect_geometry() -> Geometry {
Geometry::Rect { w: u(1000), h: u(1000), radii: [0.0; 4] }
}
#[test]
fn a_grid_layer_keeps_its_lock_state() {
for locked in [false, true] {
let mut grid = layer("Grid", vec![rect(100, 100, None)]);
grid.kind = LayerKind::Grid;
grid.flags.locked = locked;
let d = Drawing { pages: vec![Page { size: None, layers: vec![grid] }], ..one_layer(Vec::new()) };
let back = read(&write(&d, Limits::default()).unwrap(), Limits::default()).unwrap();
assert_eq!((back.pages[0].layers[0].kind, back.pages[0].layers[0].flags.locked), (LayerKind::Grid, locked));
}
}
/// A drawing at a limit is written and read whole; one past it is refused.
#[test]
fn drawings_past_what_a_read_takes_are_refused() {
let flat = |n: i32| one_layer((0..n).map(|i| rect(100 + i, 100, None)).collect());
let limits = Limits { objects: 10, ..Limits::default() };
let back = read(&write(&flat(10), limits).unwrap(), limits).unwrap();
assert!(back.warnings.is_empty());
assert_eq!(write(&flat(11), limits), Err(Error::Limit("object count")));
// Groups nested in groups: each one takes a list.
let nested = |depth: usize| {
let mut o = rect(100, 100, None);
for _ in 0..depth {
o = Object::Group { objects: vec![o], flags: Flags::default() };
}
one_layer(vec![o])
};
// The smallest depth a read of eight nested groups takes whole is the smallest the writer
// takes, and a ninth group is refused at it.
let depth = writes_at_the_readers_limit(&nested(8), |l, n| l.depth = n);
assert_eq!(write(&nested(9), Limits { depth, ..Limits::default() }), Err(Error::Limit("nesting depth")));
let limits = Limits { depth: 12, ..Limits::default() };
// Groups that hold nothing are refused past the depth too, in a layer and in a clip.
let hollow = |depth: usize| {
let mut o = Object::Group { objects: Vec::new(), flags: Flags::default() };
for _ in 0..depth {
o = Object::Group { objects: vec![o], flags: Flags::default() };
}
o
};
// `hollow(n)` is n + 1 groups deep.
let clip = |o| Object::Clip { container: Box::new(Shape::new(rect_geometry(), Matrix::IDENTITY, None, None)), objects: vec![o] };
for wrap in [|o| o, clip] {
assert!(write(&one_layer(vec![wrap(hollow(11))]), limits).is_ok());
assert_eq!(write(&one_layer(vec![wrap(hollow(12))]), limits), Err(Error::Limit("nesting depth")));
}
let limits = Limits { coordinates: 3, ..Limits::default() };
let line = |n: i32| {
let segments = (1..n).map(|i| Segment::Line(pt(i, i))).collect();
let path = Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed: false }] };
one_layer(vec![Object::Shape(Box::new(Shape::new(Geometry::Path(path), Matrix::IDENTITY, None, None)))])
};
assert!(read(&write(&line(3), limits).unwrap(), limits).unwrap().warnings.is_empty());
assert_eq!(write(&line(4), limits), Err(Error::Limit("coordinate count")));
}
#[test]
fn numbers_the_file_cant_hold_are_refused() {
let with = |s: Shape| one_layer(vec![Object::Shape(Box::new(s))]);
let far = Shape::new(Geometry::Ellipse { w: 1e9, h: 1.0 }, Matrix::IDENTITY, None, None);
assert!(matches!(write(&with(far), Limits::default()), Err(Error::Unwritable(_))));
let nan = Shape::new(Geometry::Rect { w: f64::NAN, h: 1.0, radii: [0.0; 4] }, Matrix::IDENTITY, None, None);
assert!(matches!(write(&with(nan), Limits::default()), Err(Error::Unwritable(_))));
let inf = Shape::new(Geometry::Ellipse { w: 1.0, h: 1.0 }, Matrix([f64::INFINITY, 0.0, 0.0, 1.0, 0.0, 0.0]), None, None);
assert!(matches!(write(&with(inf), Limits::default()), Err(Error::Unwritable(_))));
}
#[test]
fn values_outside_their_range_are_refused() {
let with = |s: Shape| one_layer(vec![Object::Shape(Box::new(s))]);
let outlined = |width: f64| Outline {
width,
color: Color::Gray(1.0),
cap: Cap::Butt,
join: Join::Miter,
dashes: Vec::new(),
behind_fill: false,
scale_with: false,
};
let mut opaque = Shape::new(rect_geometry(), Matrix::IDENTITY, None, None);
opaque.opacity = 1.5;
let far = Path { subpaths: vec![SubPath { start: Pt { x: 1e9, y: 0.0 }, segments: vec![Segment::Line(pt(0, 0))], closed: false }] };
let cases = [
("negative outline width", with(Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(outlined(-1.0))))),
// A width of 0 reads back as no width.
("positive outline width that rounds to 0", with(Shape::new(rect_geometry(), Matrix::IDENTITY, None, Some(outlined(u(1) / 4.0))))),
("negative corner radius", with(Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [-1.0, 0.0, 0.0, 0.0] }, Matrix::IDENTITY, None, None))),
("opacity past 1", with(opaque)),
("tint past 1", one_layer(vec![rect(100, 100, Some(Color::Spot { name: "Red".into(), tint: 1.5, look: Some([1.0, 1.0, 1.0]) }))])),
("path point past 32 bits", with(Shape::new(Geometry::Path(far), Matrix::IDENTITY, None, None))),
("page size past 32 bits", Drawing { page_size: Some((1e9, 10.0)), ..one_layer(Vec::new()) }),
];
let written: Vec<_> =
cases.iter().filter(|(_, d)| !matches!(write(d, Limits::default()), Err(Error::Unwritable(_)))).map(|(what, _)| *what).collect();
assert!(written.is_empty(), "{written:?}");
}
fn arb_color() -> impl Strategy<Value = Color> {
prop_oneof![
any::<[u8; 3]>().prop_map(|v| Color::Rgb(v.map(c))),
any::<[u8; 4]>().prop_map(|v| Color::Cmyk(v.map(c))),
any::<u8>().prop_map(|v| Color::Gray(c(v))),
Just(Color::Registration),
]
}
fn arb_shape() -> impl Strategy<Value = Shape> {
let size = || (-1_000_000i32..1_000_000, -1_000_000i32..1_000_000);
let geometry = prop_oneof![
size().prop_map(|(w, h)| Geometry::Rect { w: u(w), h: u(h), radii: [0.0; 4] }),
size().prop_map(|(w, h)| Geometry::Ellipse { w: u(w), h: u(h) }),
(prop::collection::vec(size(), 1..20), any::<bool>()).prop_map(|(pts, closed)| {
let segments = pts.iter().map(|&(x, y)| Segment::Line(pt(x, y))).collect();
Geometry::Path(Path { subpaths: vec![SubPath { start: pt(0, 0), segments, closed }] })
}),
];
(geometry, prop::option::of(arb_color()), any::<bool>(), -500i32..500)
.prop_map(|(g, fill, nonzero, x)| Shape { nonzero, ..Shape::new(g, moved(f64::from(x), -f64::from(x)), fill, None) })
}
proptest! {
#![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })]
#[test]
fn random_drawings_read_back_as_written(shapes in prop::collection::vec(arb_shape(), 0..30), grouped in 0usize..30) {
let mut objects: Vec<Object> = shapes.into_iter().map(|s| Object::Shape(Box::new(s))).collect();
let tail = objects.split_off(grouped.min(objects.len()));
if !tail.is_empty() {
objects.push(Object::Group { objects: tail, flags: Flags::default() });
}
let d = Drawing { page_size: Some((u(1_000_000), u(1_000_000))), ..one_layer(objects) };
let back = read(&write(&d, Limits::default()).unwrap(), Limits::default()).unwrap();
prop_assert!(back.warnings.is_empty());
prop_assert_eq!(rounded(back), as_read(d));
}
#[test]
fn writing_never_panics(
w in prop_oneof![-1e4..1e4f64, any::<f64>()],
h in prop_oneof![-1e4..1e4f64, any::<f64>()],
m in prop_oneof![prop::array::uniform6(-1e3..1e3f64), any::<[f64; 6]>()],
dashes in prop::collection::vec(prop_oneof![-1.0..20.0f64, any::<f64>()], 0..12),
opacity in prop_oneof![-0.5..1.5f32, any::<f32>()],
) {
let outline =
Outline { width: w, color: Color::Gray(opacity), cap: Cap::Square, join: Join::Round, dashes, behind_fill: false, scale_with: false };
// Corners within half the shorter side, so a rectangle of a size the file holds is written.
let r = w.abs().min(h.abs()) / 4.0;
let mut s = Shape::new(Geometry::Rect { w, h, radii: [r, 0.0, r, 0.0] }, Matrix(m), Some(Color::Rgb([opacity; 3])), Some(outline));
s.opacity = opacity;
let d = Drawing { pages: vec![Page { size: Some((w, h)), layers: vec![layer("A", vec![Object::Shape(Box::new(s))])] }], ..everything() };
if let Ok(file) = write(&d, Limits::default()) {
prop_assert!(read(&file, Limits::default()).is_ok());
}
}
}
+13
View File
@@ -37,3 +37,16 @@ write never truncates its target in place. It writes a new sibling file and rena
over the target, so the target's directory entry is replaced rather than its bytes being
overwritten. A rename only ever changes one name; it does not reach through to any other name,
inside the root or out, that happens to point at the same inode.
## Concurrent saves
A `Job::Write` checks the file's etag again just before the rename, and holds one lock for this
process from that check until the rename is done. Within one process, when two saves are made
from the same etag, the second gets `Fault::Conflict`, unless the first save left the file with an
unchanged etag (see the next paragraph). A second process writing the same folder does not take
that lock, so its save can still land between the check and the rename. A deployment that needs
the guarantee across processes needs a backend whose provider offers a conditional write.
The etag is the file's length and modification time. On a filesystem whose timestamps are coarser
than the time between two saves, two saves of the same length can leave the same etag, and the
second save is then not refused.
+484 -52
View File
@@ -62,6 +62,7 @@ use std::ffi::OsStr;
use std::fs;
use std::io::{Read as _, Write as _};
use std::path::{Component, Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use cap_std::fs::{Dir, OpenOptions};
@@ -208,8 +209,9 @@ fn is_windows_reserved_name(name: &str) -> bool {
/// outright first, because a Unix build's [`Component`] parser does not
/// treat either as a separator and would wave a Windows drive letter or UNC
/// prefix (`C:`, `\\server\share`) straight through as one ordinary name. A
/// Windows reserved device name is refused the same way. None of this costs
/// anything here, unlike applying it to a name `list` merely discovered.
/// Windows reserved device name is refused the same way, and so is a name
/// [`is_temp_name`] matches, which [`list`] would leave out. None of this
/// costs anything here, unlike applying it to a name `list` merely discovered.
fn confine_name(name: &str) -> Result<&str, Fault> {
if name.contains('\\') || name.contains(':') {
return Err(Fault::Refused(format!("{name} is not a plain file name")));
@@ -217,6 +219,9 @@ fn confine_name(name: &str) -> Result<&str, Fault> {
if is_windows_reserved_name(name) {
return Err(Fault::Refused(format!("{name} is a reserved device name on Windows")));
}
if is_temp_name(name) {
return Err(Fault::Refused(format!("{name} is a name this backend uses for its temporary files")));
}
confine_segment(name)
}
@@ -252,6 +257,13 @@ fn io_fault(error: &std::io::Error) -> Fault {
}
}
/// Lists the files and folders in `path`.
///
/// A regular file whose name [`is_temp_name`] matches is left out before its
/// metadata is read. Such a file is a save in progress, or one that was
/// stopped between its create and its rename, and it is not a document.
/// [`confine_name`] refuses these names for a new file. A folder or a link
/// with such a name is listed.
fn list(root: &Path, path: &str) -> Result<Vec<Entry>, Fault> {
let rel = relative(path)?;
let dir = open_root(root)?;
@@ -260,8 +272,11 @@ fn list(root: &Path, path: &str) -> Result<Vec<Entry>, Fault> {
let mut entries = Vec::new();
for item in read {
let item = item.map_err(|error| io_fault(&error))?;
let meta = item.metadata().map_err(|error| io_fault(&error))?;
let name = item.file_name().to_string_lossy().into_owned();
if is_temp_name(&name) && item.file_type().is_ok_and(|kind| kind.is_file()) {
continue;
}
let meta = item.metadata().map_err(|error| io_fault(&error))?;
let id = child_path(path, &name);
entries.push(Entry {
room: format!("local:{id}"),
@@ -322,64 +337,154 @@ fn read(root: &Path, entry: &Entry) -> Result<(Entry, Vec<u8>), Fault> {
/// so a hard link sharing the target's inode keeps its own, unmodified copy:
/// the rename replaces `entry.id`'s directory entry, and never reaches
/// through to any other name pointing at the same inode.
///
/// The etag is checked once before any bytes are written, and again under
/// [`WRITE_LOCK`] just before the rename. Two saves made from the same etag
/// at once otherwise both pass the check before either renames, both report
/// success, and the later rename replaces the first save without a
/// [`Fault::Conflict`].
fn write(root: &Path, entry: &Entry, bytes: &[u8]) -> Result<Entry, Fault> {
let rel = relative(&entry.id)?;
let dir = open_root(root)?;
match dir.symlink_metadata(&rel) {
Ok(meta) if meta.is_symlink() => return Err(Fault::Refused("that path is a link, not a plain file".to_owned())),
Ok(meta) => {
if Some(etag_of(&meta)) != entry.etag {
return Err(Fault::Conflict);
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(io_fault(&error)),
}
check_unchanged(&dir, &rel, entry)?;
if let Some(parent) = rel.parent() {
dir.create_dir_all(parent).map_err(|error| io_fault(&error))?;
}
write_replacing(&dir, &rel, bytes)?;
let meta = dir.metadata(&rel).map_err(|error| io_fault(&error))?;
let meta = write_replacing(&dir, &rel, bytes, || check_unchanged(&dir, &rel, entry))?;
Ok(Entry { size: Some(meta.len()), etag: Some(etag_of(&meta)), ..entry.clone() })
}
/// Refuses a link at `rel`, and a file whose etag is no longer `entry.etag`.
/// A file that does not exist passes.
fn check_unchanged(dir: &Dir, rel: &Path, entry: &Entry) -> Result<(), Fault> {
match dir.symlink_metadata(rel) {
Ok(meta) if meta.is_symlink() => Err(Fault::Refused("that path is a link, not a plain file".to_owned())),
Ok(meta) if Some(etag_of(&meta)) != entry.etag => Err(Fault::Conflict),
Ok(_) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(io_fault(&error)),
}
}
/// Held by [`write_replacing`] from its last check until the rename is done
/// and the new file's metadata is read, and by [`create_in_place`] from the
/// moment it creates its file until the file is complete or removed. No other
/// save in this process can change the file between a save's check and its
/// rename, a save cannot replace a file that `create_in_place` is still
/// writing, and `create_in_place` cannot remove a replacement when its own
/// write fails. The temporary file is written and synced before the lock is
/// taken, so a slow save does not hold up the others. Another process writing
/// the same folder is not covered.
static WRITE_LOCK: Mutex<()> = Mutex::new(());
/// The next in a run of sibling temporary names, unique within this process.
/// Not meant to resist a second process picking the same name; the create
/// this writes with is exclusive (`create_new`), so a collision there is
/// just retried under a new counter value rather than silently overwritten.
/// [`open_temp`] does is exclusive (`create_new`), so a collision there is
/// retried under a new counter value rather than silently overwritten.
static TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
/// How many temporary names [`open_temp`] tries before it gives up.
const TEMP_ATTEMPTS: usize = 16;
/// The start of every name [`temp_name`] makes.
const TEMP_PREFIX: &str = ".craft-save-";
/// The end of every name [`temp_name`] makes.
const TEMP_SUFFIX: &str = ".tmp";
/// The temporary name for process `pid`, clock part `started` and sequence
/// value `n`. [`is_temp_name`] matches every name this returns.
fn temp_name(pid: u32, started: u128, n: u64) -> String {
format!("{TEMP_PREFIX}{pid}-{started:x}-{n}{TEMP_SUFFIX}")
}
/// Whether [`temp_name`] returns exactly `name` for some process id, clock
/// part and sequence value. The three parts are read back from `name` and
/// passed to `temp_name`, so a name the two would format differently (a
/// leading zero, an uppercase hexadecimal digit, a sign) does not match.
/// [`list`] leaves these names out. A name with only the same prefix and
/// suffix, such as `.craft-save-notes.tmp`, does not match and is listed.
fn is_temp_name(name: &str) -> bool {
let Some(middle) = name.strip_prefix(TEMP_PREFIX).and_then(|rest| rest.strip_suffix(TEMP_SUFFIX)) else {
return false;
};
let mut parts = middle.split('-');
let (Some(pid), Some(started), Some(n), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else {
return false;
};
match (pid.parse::<u32>(), u128::from_str_radix(started, 16), n.parse::<u64>()) {
(Ok(pid), Ok(started), Ok(n)) => temp_name(pid, started, n) == name,
_ => false,
}
}
/// Creates a new hidden temporary file beside `rel`, named from
/// [`TEMP_SEQUENCE`], and returns its path and handle. A name that already
/// exists (a file another process or an earlier run left) is skipped for the
/// next one, and never opened or removed. The name does not include `rel`'s
/// file name, so a file name near the filesystem's length limit still gets a
/// temporary name that fits.
fn open_temp(dir: &Dir, rel: &Path) -> Result<(PathBuf, cap_std::fs::File), Fault> {
if rel.file_name().is_none() {
return Err(Fault::Refused("that path names no file".to_owned()));
}
let mut options = OpenOptions::new();
options.write(true).create_new(true);
// The clock part keeps a stale file from an earlier run with the same
// process id from matching a run of names, so needing all the attempts
// takes 16 files made for this exact moment.
let started = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |since| since.as_nanos());
#[cfg(test)]
let started = if tests::FIXED_TEMP_CLOCK.with(std::cell::Cell::get) { 0 } else { started };
let mut last = None;
for _ in 0..TEMP_ATTEMPTS {
let temp_name = temp_name(std::process::id(), started, TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed));
let temp_rel = match rel.parent() {
Some(parent) if !parent.as_os_str().is_empty() => parent.join(&temp_name),
_ => PathBuf::from(&temp_name),
};
match dir.open_with(&temp_rel, &options) {
Ok(handle) => return Ok((temp_rel, handle)),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => last = Some(error),
Err(error) => return Err(io_fault(&error)),
}
}
Err(last.map_or_else(|| Fault::Unreachable("no temporary name was free".to_owned()), |error| io_fault(&error)))
}
/// Writes `bytes` to a new sibling of `rel` inside `dir`, then renames that
/// sibling over `rel`. See the module docs for why: a direct write would
/// truncate whatever `rel` currently names in place, and if that happens to
/// be a hard link to a file outside `root`, the outside copy would be
/// corrupted along with it. A rename only ever replaces `rel`'s own
/// directory entry.
fn write_replacing(dir: &Dir, rel: &Path, bytes: &[u8]) -> Result<(), Fault> {
let name = rel.file_name().ok_or_else(|| Fault::Refused("that path names no file".to_owned()))?;
let mut temp_name = OsStr::new(".").to_os_string();
temp_name.push(name);
temp_name.push(format!(".tmp-{}-{}", std::process::id(), TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed)));
let temp_rel = match rel.parent() {
Some(parent) if !parent.as_os_str().is_empty() => parent.join(&temp_name),
_ => PathBuf::from(&temp_name),
};
let mut options = OpenOptions::new();
options.write(true).create_new(true);
let written = (|| -> Result<(), Fault> {
let mut handle = dir.open_with(&temp_rel, &options).map_err(|error| io_fault(&error))?;
handle.write_all(bytes).map_err(|error| io_fault(&error))?;
handle.sync_all().map_err(|error| io_fault(&error))
})();
///
/// `check` runs under [`WRITE_LOCK`] right before the rename; when it fails,
/// the temporary file is removed and `rel` is left as it was. Returns the
/// metadata of the file just published.
fn write_replacing(dir: &Dir, rel: &Path, bytes: &[u8], check: impl FnOnce() -> Result<(), Fault>) -> Result<cap_std::fs::Metadata, Fault> {
let (temp_rel, mut handle) = open_temp(dir, rel)?;
let written = handle.write_all(bytes).map_err(|error| io_fault(&error)).and_then(|()| handle.sync_all().map_err(|error| io_fault(&error)));
drop(handle);
if let Err(fault) = written {
let _ = dir.remove_file(&temp_rel);
return Err(fault);
}
if let Err(error) = dir.rename(&temp_rel, dir, rel) {
#[cfg(test)]
tests::before_lock();
let published = {
let _serialized = WRITE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
check().and_then(|()| {
#[cfg(test)]
tests::after_check();
dir.rename(&temp_rel, dir, rel).map_err(|error| io_fault(&error))?;
dir.metadata(rel).map_err(|error| io_fault(&error))
})
};
if published.is_err() {
let _ = dir.remove_file(&temp_rel);
return Err(io_fault(&error));
}
Ok(())
published
}
fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result<Entry, Fault> {
@@ -397,24 +502,46 @@ fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result<Entry,
let rel_folder = relative(folder)?;
dir.create_dir_all(&rel_folder).map_err(|error| io_fault(&error))?;
let rel = rel_folder.join(name);
// Exclusive creation, not an `exists` check ahead of a separate write: two
// creates of the same name racing both see "not there yet" otherwise, and
// the second write silently replaces the first with neither ever refused.
// `create_new` asks the filesystem to open and create in one step, so the
// loser gets an error instead of a chance to overwrite the winner. It also
// refuses outright when `name` already exists as a symlink, dangling or
// not: `O_EXCL` never follows one to decide whether it is "in the way".
let mut create_options = OpenOptions::new();
create_options.write(true).create_new(true);
let mut handle = match dir.open_with(&rel, &create_options) {
Ok(handle) => handle,
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
return Err(Fault::Refused(format!("{name} already exists")));
}
// A taken name is refused before any bytes are written. The hard link
// below is still the check that settles a race.
match dir.symlink_metadata(&rel) {
Ok(_) => return Err(Fault::Refused(format!("{name} already exists"))),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(io_fault(&error)),
};
handle.write_all(bytes).map_err(|error| io_fault(&error))?;
}
// The bytes go to a sibling temporary file first. A write that fails part
// way (a full disk, a lost share) leaves only that file, which is removed,
// so the name stays free for the next Save As instead of holding a partial
// file that makes it fail with "already exists".
let (temp_rel, mut handle) = open_temp(&dir, &rel)?;
let written = write_new(&mut handle, bytes).and_then(|()| sync_new(&handle));
drop(handle);
if let Err(fault) = written {
let _ = dir.remove_file(&temp_rel);
return Err(fault);
}
// The finished file takes `name` with a hard link, not an `exists` check
// ahead of a rename: two creates of the same name racing both see "not
// there yet" otherwise, and the second silently replaces the first. A link
// fails when the name is taken, so the loser gets an error instead of a
// chance to overwrite the winner. It also fails when `name` already exists
// as a symlink, dangling or not.
#[cfg(not(test))]
let linked = dir.hard_link(&temp_rel, &dir, &rel);
#[cfg(test)]
let linked = if tests::NO_HARD_LINKS.with(std::cell::Cell::get) {
Err(std::io::Error::other("no hard links"))
} else {
dir.hard_link(&temp_rel, &dir, &rel)
};
let _ = dir.remove_file(&temp_rel);
match linked {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => return Err(Fault::Refused(format!("{name} already exists"))),
// A filesystem without hard links (FAT, some network shares): the
// temporary copy is gone by now, and the file is created in place.
Err(_) => create_in_place(&dir, &rel, name, bytes)?,
}
let meta = dir.metadata(&rel).map_err(|error| io_fault(&error))?;
let id = child_path(folder, name);
Ok(Entry {
@@ -432,9 +559,314 @@ fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result<Entry,
})
}
/// Creates `rel` with `create_new` and writes `bytes` into it, for a
/// filesystem where [`create`] cannot publish with a hard link. `create_new`
/// opens and creates in one step, so a name that is taken, or that exists as
/// a symlink, is refused instead of overwritten. The bytes are synced, so a
/// share that reports a full disk only at sync is a failed create. When the
/// write or the sync fails, the file this call created is removed.
/// [`WRITE_LOCK`] is held throughout, so no save in this process can replace
/// the file before that removal.
fn create_in_place(dir: &Dir, rel: &Path, name: &str, bytes: &[u8]) -> Result<(), Fault> {
let _writing = WRITE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut create_options = OpenOptions::new();
create_options.write(true).create_new(true);
let mut handle = match dir.open_with(rel, &create_options) {
Ok(handle) => handle,
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => return Err(Fault::Refused(format!("{name} already exists"))),
Err(error) => return Err(io_fault(&error)),
};
let written = write_new(&mut handle, bytes).and_then(|()| sync_new(&handle));
drop(handle);
#[cfg(test)]
tests::in_place_finished();
if written.is_err() {
let _ = dir.remove_file(rel);
}
written
}
/// Syncs a file [`create`] is making.
fn sync_new(handle: &cap_std::fs::File) -> Result<(), Fault> {
#[cfg(test)]
if tests::FAIL_CREATE_SYNC.with(|countdown| {
let left = countdown.get();
countdown.set(left.saturating_sub(1));
left == 1
}) {
return Err(Fault::Unreachable("no space left on device".to_owned()));
}
handle.sync_all().map_err(|error| io_fault(&error))
}
/// Writes the bytes of a file [`create`] is making.
fn write_new(handle: &mut cap_std::fs::File, bytes: &[u8]) -> Result<(), Fault> {
#[cfg(test)]
if tests::FAIL_CREATE_WRITE.with(|countdown| {
let left = countdown.get();
countdown.set(left.saturating_sub(1));
left == 1
}) {
let half = bytes.get(..bytes.len() / 2).unwrap_or_default();
handle.write_all(half).map_err(|error| io_fault(&error))?;
return Err(Fault::Unreachable("no space left on device".to_owned()));
}
handle.write_all(bytes).map_err(|error| io_fault(&error))
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::mpsc;
/// Run once by the next [`write`] to pass its etag check, then cleared.
type Hook = Box<dyn FnOnce() + Send>;
static AFTER_CHECK: Mutex<Option<Hook>> = Mutex::new(None);
pub(super) fn after_check() {
let hook = AFTER_CHECK.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take();
if let Some(hook) = hook {
hook();
}
}
/// Run once by the next [`write_replacing`] to finish its temporary file,
/// before it takes [`WRITE_LOCK`], then cleared.
static BEFORE_LOCK: Mutex<Option<Hook>> = Mutex::new(None);
pub(super) fn before_lock() {
let hook = BEFORE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take();
if let Some(hook) = hook {
hook();
}
}
fn entry_for(id: &str) -> Entry {
Entry {
room: format!("local:{id}"),
name: id.trim_start_matches('/').to_owned(),
kind: EntryKind::File,
size: None,
modified: None,
mime: None,
etag: None,
writable: true,
shared_by: None,
path: id.to_owned(),
id: id.to_owned(),
}
}
#[test]
fn two_saves_from_one_etag_cannot_both_pass_the_check() {
let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let root = tempfile::tempdir().unwrap();
std::fs::write(root.path().join("Note.txt"), b"original").unwrap();
let (read_entry, _) = read(root.path(), &entry_for("/Note.txt")).unwrap();
let (checked_tx, checked_rx) = mpsc::channel::<()>();
let (go_tx, go_rx) = mpsc::channel::<()>();
*AFTER_CHECK.lock().unwrap() = Some(Box::new(move || {
checked_tx.send(()).unwrap();
go_rx.recv().unwrap();
}));
let first = {
let (root, entry) = (root.path().to_owned(), read_entry.clone());
std::thread::spawn(move || write(&root, &entry, b"first save"))
};
checked_rx.recv().unwrap();
// The first save has passed its check and not yet renamed. A second
// save must not be able to reach its own check in between.
assert!(WRITE_LOCK.try_lock().is_err(), "the check and the rename must run under one lock");
// The second save passes its early check and writes its temporary
// file before the first one renames, so only the recheck under the
// lock can refuse it.
let (ready_tx, ready_rx) = mpsc::channel::<()>();
*BEFORE_LOCK.lock().unwrap() = Some(Box::new(move || ready_tx.send(()).unwrap()));
let second = {
let (root, entry) = (root.path().to_owned(), read_entry.clone());
std::thread::spawn(move || write(&root, &entry, b"second save"))
};
ready_rx.recv().unwrap();
go_tx.send(()).unwrap();
assert!(first.join().unwrap().is_ok());
assert!(matches!(second.join().unwrap(), Err(Fault::Conflict)), "the second save started from a stale etag");
assert_eq!(std::fs::read(root.path().join("Note.txt")).unwrap(), b"first save");
let left: Vec<_> = std::fs::read_dir(root.path()).unwrap().map(|item| item.unwrap().file_name()).collect();
assert_eq!(left, ["Note.txt"], "the refused save's temporary file is removed");
}
thread_local! {
/// When set to n, the nth [`write_new`] call on this thread from now
/// writes half its bytes and fails. 0 turns it off.
pub(super) static FAIL_CREATE_WRITE: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
/// Makes [`create`] on this thread take the path for a filesystem
/// without hard links.
pub(super) static NO_HARD_LINKS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Makes [`open_temp`] on this thread use 0 for its clock part.
pub(super) static FIXED_TEMP_CLOCK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// When set to n, the nth [`sync_new`] call on this thread from now
/// fails. 0 turns it off.
pub(super) static FAIL_CREATE_SYNC: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
/// Run once by [`create_in_place`] on this thread after its write and
/// sync, before it removes a failed file.
static IN_PLACE_FINISHED: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
}
pub(super) fn in_place_finished() {
if let Some(hook) = IN_PLACE_FINISHED.with(|hook| hook.borrow_mut().take()) {
hook();
}
}
#[test]
fn without_hard_links_a_failed_sync_leaves_no_file_and_keeps_a_concurrent_save() {
let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let root = tempfile::tempdir().unwrap();
let path = root.path().to_path_buf();
let held = std::rc::Rc::new(std::cell::Cell::new(false));
let saver = std::rc::Rc::new(std::cell::RefCell::new(None));
let (seen_held, seen_saver) = (held.clone(), saver.clone());
IN_PLACE_FINISHED.with(|hook| {
*hook.borrow_mut() = Some(Box::new(move || {
seen_held.set(WRITE_LOCK.try_lock().is_err());
// A save of the same name starts while the failed file is
// still there. It must not land before that file is removed.
*seen_saver.borrow_mut() = Some(std::thread::spawn(move || {
let dir = open_root(&path).unwrap();
write_replacing(&dir, Path::new("Minutes.txt"), b"saved meanwhile", || Ok(()))
}));
}));
});
NO_HARD_LINKS.with(|off| off.set(true));
// The temporary copy syncs, then the in-place file's sync fails.
FAIL_CREATE_SYNC.with(|fail| fail.set(2));
let failed = create(root.path(), "", "Minutes.txt", b"the whole document");
FAIL_CREATE_SYNC.with(|fail| fail.set(0));
NO_HARD_LINKS.with(|off| off.set(false));
assert!(matches!(failed, Err(Fault::Unreachable(_))), "a failed sync is a failed create: {failed:?}");
assert!(held.get(), "the in-place file is written and removed under the write lock");
let saver = saver.borrow_mut().take().unwrap();
saver.join().unwrap().unwrap();
let left: Vec<_> = std::fs::read_dir(root.path()).unwrap().map(|item| item.unwrap().file_name()).collect();
assert_eq!(left, ["Minutes.txt"]);
assert_eq!(std::fs::read(root.path().join("Minutes.txt")).unwrap(), b"saved meanwhile", "the removal took only the failed file");
}
/// Held by the tests that make temporary files, so the next value of
/// [`TEMP_SEQUENCE`] is known to the test that reads it.
static TEMP_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[test]
fn a_stale_temporary_file_is_skipped_and_kept() {
let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let root = tempfile::tempdir().unwrap();
let next = TEMP_SEQUENCE.load(Ordering::Relaxed);
let stale: Vec<_> = (next..next + 3).map(|n| temp_name(std::process::id(), 0, n)).collect();
for name in &stale {
std::fs::write(root.path().join(name), b"left by an earlier run").unwrap();
}
FIXED_TEMP_CLOCK.with(|fixed| fixed.set(true));
let made = create(root.path(), "", "Minutes.txt", b"minutes");
FIXED_TEMP_CLOCK.with(|fixed| fixed.set(false));
made.unwrap();
assert_eq!(std::fs::read(root.path().join("Minutes.txt")).unwrap(), b"minutes");
for name in &stale {
assert_eq!(std::fs::read(root.path().join(name)).unwrap(), b"left by an earlier run", "{name} is not this call's file");
}
}
#[test]
fn a_listing_leaves_out_a_temporary_file_a_stopped_save_left() {
let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let root = tempfile::tempdir().unwrap();
std::fs::create_dir(root.path().join("Archive")).unwrap();
std::fs::write(root.path().join("Minutes.txt"), b"minutes").unwrap();
std::fs::write(root.path().join(".craft-save-notes.tmp"), b"a person's own file").unwrap();
let folder = temp_name(1, 2, 3);
std::fs::create_dir(root.path().join(&folder)).unwrap();
let dir = open_root(root.path()).unwrap();
// A save stopped after its create and before its rename leaves the
// temporary file, at the root and inside a folder.
let (at_root, handle) = open_temp(&dir, Path::new("Minutes.txt")).unwrap();
drop(handle);
let (in_folder, handle) = open_temp(&dir, &Path::new("Archive").join("Agenda.txt")).unwrap();
drop(handle);
assert!(root.path().join(&at_root).exists() && root.path().join(&in_folder).exists());
let names: Vec<_> = list(root.path(), "").unwrap().into_iter().map(|entry| entry.name).collect();
assert_eq!(names, [".craft-save-1-2-3.tmp", "Archive", ".craft-save-notes.tmp", "Minutes.txt"], "a folder with the pattern stays listed");
assert!(list(root.path(), "/Archive").unwrap().is_empty());
}
#[test]
fn a_create_refuses_a_name_a_listing_would_leave_out() {
let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let root = tempfile::tempdir().unwrap();
let name = temp_name(1, 2, 3);
assert!(matches!(create(root.path(), "", &name, b"bytes"), Err(Fault::Refused(_))));
assert_eq!(std::fs::read_dir(root.path()).unwrap().count(), 0);
create(root.path(), "", ".craft-save-notes.tmp", b"bytes").unwrap();
}
#[test]
fn is_temp_name_matches_only_the_names_temp_name_makes() {
assert!(is_temp_name(&temp_name(4242, 0x1a2b, 7)));
assert!(is_temp_name(&temp_name(u32::MAX, u128::MAX, u64::MAX)));
for other in [
".craft-save-notes.tmp",
".craft-save-1-2.tmp",
".craft-save-1-2-3-4.tmp",
".craft-save--2-3.tmp",
".craft-save-1-xy-3.tmp",
"craft-save-1-2-3.tmp",
".craft-save-1-2-3.tmp.txt",
".craft-save-01-2-3.tmp",
".craft-save-1-2A-3.tmp",
".craft-save-+1-2-3.tmp",
] {
assert!(!is_temp_name(other), "{other} is not a temporary name");
}
}
#[test]
fn without_hard_links_a_create_still_refuses_a_taken_name_and_cleans_up() {
let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let root = tempfile::tempdir().unwrap();
NO_HARD_LINKS.with(|off| off.set(true));
let made = create(root.path(), "", "Minutes.txt", b"first");
let taken = create(root.path(), "", "Minutes.txt", b"second");
// The temporary copy is written, then the in-place write fails.
FAIL_CREATE_WRITE.with(|fail| fail.set(2));
let failed = create(root.path(), "", "Agenda.txt", b"the whole agenda");
FAIL_CREATE_WRITE.with(|fail| fail.set(0));
NO_HARD_LINKS.with(|off| off.set(false));
assert_eq!(made.unwrap().size, Some(5));
assert!(matches!(taken, Err(Fault::Refused(_))));
assert!(matches!(failed, Err(Fault::Unreachable(_))));
let left: Vec<_> = std::fs::read_dir(root.path()).unwrap().map(|item| item.unwrap().file_name()).collect();
assert_eq!(left, ["Minutes.txt"], "only the finished file is left");
assert_eq!(std::fs::read(root.path().join("Minutes.txt")).unwrap(), b"first");
}
#[test]
fn a_create_whose_write_fails_leaves_no_file_behind() {
let _serial = TEMP_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let root = tempfile::tempdir().unwrap();
FAIL_CREATE_WRITE.with(|fail| fail.set(1));
let failed = create(root.path(), "", "Minutes.txt", b"the whole document");
FAIL_CREATE_WRITE.with(|fail| fail.set(0));
assert!(matches!(failed, Err(Fault::Unreachable(_))));
assert_eq!(std::fs::read_dir(root.path()).unwrap().count(), 0, "no partial or temporary file is left");
let retried = create(root.path(), "", "Minutes.txt", b"the whole document").unwrap();
assert_eq!(retried.size, Some(18));
assert_eq!(std::fs::read(root.path().join("Minutes.txt")).unwrap(), b"the whole document");
}
#[test]
fn a_parent_segment_cannot_walk_out_of_root() {
+17 -8
View File
@@ -70,6 +70,9 @@ pub enum Event {
},
}
/// An answer with the account generation its job was issued in.
pub(crate) type Stamped = (u64, Event);
/// Where a worker's answers go.
///
/// Handed to [`CloudBackend::submit`] with the job it belongs to. A worker is
@@ -77,7 +80,10 @@ pub enum Event {
/// sign-in reports the URL it wants a browser pointed at and then reports that
/// the user finished there. A send after the window closed is not a failure.
pub struct Post {
tx: Sender<Event>,
/// Each event goes with the generation its job was issued in, so
/// [`super::pump`] can drop one that waited in the channel across a
/// sign-out or a new sign-in.
tx: Sender<Stamped>,
/// The window's account generation as of the moment the job this answers
/// was issued, beside a handle to what it is now. A sign-out or a new
/// sign-in bumps the live value; a reply that arrives after is for a
@@ -87,7 +93,7 @@ pub struct Post {
}
impl Post {
pub(crate) fn new(tx: Sender<Event>, generation: Arc<AtomicU64>) -> Post {
pub(crate) fn new(tx: Sender<Stamped>, generation: Arc<AtomicU64>) -> Post {
let issued = generation.load(Ordering::Relaxed);
Post { tx, generation, issued }
}
@@ -99,16 +105,19 @@ impl Post {
Post { tx: self.tx.clone(), generation: self.generation.clone(), issued: self.issued }
}
/// Delivers the event, unless the window has signed out or signed in
/// again since the job this answers was issued. Silently dropping it
/// there, rather than delivering it, is what keeps a late reply from
/// restoring the previous session's account, files or busy state on top
/// of whatever replaced it.
/// Queues the event with the generation its job was issued in.
///
/// [`super::pump`] holds the check that keeps a late reply from restoring
/// the previous session's account, files or busy state on top of whatever
/// replaced it: it drops every event whose generation is not the current
/// one, including an event sent here just before a sign-out or a new
/// sign-in. This method only skips the send when the generation has
/// already moved on, so an answer that `pump` would drop is not queued.
pub fn send(&self, event: Event) {
if self.generation.load(Ordering::Relaxed) != self.issued {
return;
}
let _ = self.tx.send(event);
let _ = self.tx.send((self.issued, event));
}
}
@@ -214,6 +214,53 @@ fn sign_out_recovers_save_after_a_backend_job_never_replies() {
assert!(saved.is_ok(), "after sign-out and sign-in, Save is still refused: {saved:?}; busy={:?}", app.cloud.busy.as_ref().map(Busy::text));
}
/// While a sign-in waits on the browser, the previous account may still be the one the service
/// answers for. No folder is listed until the sign-in answers, and then both are listed again,
/// so a listing from before the sign-in does not stay on screen as the new account's files.
#[test]
fn folders_are_listed_again_only_after_a_sign_in_answers() {
let (mut app, held, _log) = two_tabs();
let ctx = egui::Context::default();
start(&mut app);
held.take(|j| matches!(j, Job::Account)).unwrap().1.send(Event::Account(Ok(account("Ada"))));
held.take(|j| matches!(j, Job::List(_))).unwrap().1.send(Event::Listed { path: String::new(), entries: Ok(vec![entry("/Ada.note", "a1")]) });
drain(&mut app, &ctx);
assert!(app.cloud.mine.loaded);
sign_in(&mut app);
start(&mut app);
drain(&mut app, &ctx);
assert!(held.take(|j| matches!(j, Job::List(_))).is_none(), "a folder is listed before the sign-in says who is signed in");
assert!(report(&app)["entries"].as_array().is_some_and(Vec::is_empty), "the previous account's files stay on screen during sign-in");
held.take(|j| matches!(j, Job::SignIn)).unwrap().1.send(Event::Account(Ok(account("Grace"))));
drain(&mut app, &ctx);
assert!(!app.cloud.mine.loading && !app.cloud.mine.loaded && !app.cloud.shared.loading && !app.cloud.shared.loaded);
start(&mut app);
let (_, list_post) = held.take(|j| matches!(j, Job::List(_))).expect("the root folder is listed again once the sign-in answers");
list_post.send(Event::Listed { path: String::new(), entries: Ok(vec![entry("/Grace.note", "g1")]) });
drain(&mut app, &ctx);
assert_eq!(report(&app)["entries"], serde_json::json!(["Grace.note"]));
}
/// A sign-in empties the folder the Save As page was showing. Until it answers, a save would go
/// to the root rather than the folder the user picked, so Save As refuses.
#[test]
fn save_as_waits_for_a_sign_in_to_answer() {
let (mut app, held, _log) = two_tabs();
browse(&mut app, "/Projects");
sign_in(&mut app);
let folder = app.cloud.mine.path.clone();
let refused = save_as(&mut app, &folder, "B");
assert!(refused.is_err(), "Save As went ahead during sign-in: {refused:?}");
assert!(held.take(|j| matches!(j, Job::Create { .. })).is_none());
held.take(|j| matches!(j, Job::SignIn)).unwrap().1.send(Event::Account(Ok(account("Ada"))));
drain(&mut app, &egui::Context::default());
assert!(save_as(&mut app, "", "B").is_ok());
assert!(held.take(|j| matches!(j, Job::Create { .. })).is_some());
}
/// An account and a listing answer a job issued before sign-out. Landing after it, they must
/// not put the previous session's account and file names on screen with nobody signed in.
#[test]
+47 -10
View File
@@ -178,7 +178,8 @@ pub struct Guest {
/// exists.
pub struct CloudFiles {
backend: Option<Box<dyn CloudBackend>>,
events: (Sender<Event>, Receiver<Event>),
/// Each answer with the account generation its job was issued in.
events: (Sender<backend::Stamped>, Receiver<backend::Stamped>),
/// The badge and its menu. Signing in is the only way into any of this.
/// The badge is the only control that offers it. It lives here. An
/// application declares no field for it.
@@ -215,9 +216,14 @@ pub struct CloudFiles {
/// stay set after a failed sign-in.
sign_in_from_menu: bool,
/// Bumped on sign-out and on a new sign-in. Stamped onto every [`Post`]
/// handed out by [`submit`] so a reply to a job issued before the bump is
/// dropped rather than applied to the session that replaced it.
/// handed out by [`submit`] and onto every answer it queues. [`pump`]
/// drops an answer to a job issued before the bump rather than applying
/// it to the session that replaced it.
account_generation: Arc<AtomicU64>,
/// Set by [`sign_in`] and cleared by the account answer that follows it.
/// While it is set both folders read as loading, so no listing is asked
/// for before the service says who is now signed in.
relist_after_sign_in: bool,
/// The document Save As must act on, when it is not the active one.
///
/// Set only by the conflict modal's "Save as a copy", so the copy it asks
@@ -256,6 +262,7 @@ impl CloudFiles {
guest: None,
sign_in_from_menu: false,
account_generation: Arc::new(AtomicU64::new(0)),
relist_after_sign_in: false,
save_as_target: None,
}
}
@@ -371,11 +378,17 @@ pub fn sign_in<A: CloudApp>(app: &mut A) {
cloud.link = None;
cloud.status = Some(working);
// A new session. A job the previous one left outstanding may never
// answer, and if it does, that answer is not about this account: see
// `Post::send`. Busy goes with it, or a stuck read from before this
// answer, and if it does, that answer is not about this account: `pump`
// drops it. Busy goes with it, or a stuck read from before this
// sign-in would leave Save refused for a session that never asked for it.
// A folder listing that was outstanding is dropped the same way. Both
// folders wait for the account answer, which empties them so the next
// frame lists them for the account that is now signed in.
cloud.account_generation.fetch_add(1, Ordering::Relaxed);
cloud.busy = None;
cloud.mine = Folder { loading: true, ..Folder::default() };
cloud.shared = Folder { loading: true, ..Folder::default() };
cloud.relist_after_sign_in = true;
submit(app, Job::SignIn);
}
@@ -396,26 +409,32 @@ pub fn sign_out<A: CloudApp>(app: &mut A) {
cloud.status = Some(signed_out);
// The session this window had ends here. A job it started may never
// answer, and a reply that does arrive late must not land on whatever
// comes next: see `Post::send`. Busy goes with it, so an open or a save
// comes next: `pump` drops it. Busy goes with it, so an open or a save
// that never heard back does not refuse every one after it forever.
cloud.account_generation.fetch_add(1, Ordering::Relaxed);
cloud.busy = None;
cloud.relist_after_sign_in = false;
cloud.save_as_target = None;
submit(app, Job::SignOut);
}
/// Lists one folder. An empty path is the user's root.
///
/// Nothing is sent while a sign-in waits for its answer. A listing sent then
/// can answer after the account does, and its files may be the previous
/// account's; the answer empties the folder so it is listed again.
pub fn browse<A: CloudApp>(app: &mut A, path: &str) {
if !available(app) {
if !available(app) || app.cloud().relist_after_sign_in {
return;
}
app.cloud_mut().mine.begin(path);
submit(app, Job::List(path.to_owned()));
}
/// Lists what other people have shared with this user.
/// Lists what other people have shared with this user. Like [`browse`], it
/// sends nothing while a sign-in waits for its answer.
pub fn load_shared<A: CloudApp>(app: &mut A) {
if !available(app) {
if !available(app) || app.cloud().relist_after_sign_in {
return;
}
app.cloud_mut().shared.begin("");
@@ -608,6 +627,9 @@ pub fn save_as<A: CloudApp>(app: &mut A, folder: &str, name: &str) -> Result<Jso
if app.cloud().busy.is_some() {
return Err("a cloud transfer is already running".to_owned());
}
if app.cloud().relist_after_sign_in {
return Err("wait for the sign-in to finish".to_owned());
}
// A document that does not exist yet has no content type to read. The
// name a person just typed is the whole of what was asked for.
let bytes = app.encode(uid, Destination::new(&name))?;
@@ -636,7 +658,13 @@ pub fn pump<A: CloudApp>(app: &mut A, ctx: &egui::Context) {
while let Ok(event) = app.cloud().events.1.try_recv() {
arrived.push(event);
}
for event in arrived {
for (issued, event) in arrived {
// A worker that sent just before a sign-out or a new sign-in passed
// `Post::send`'s check, and its answer waited here while the session
// changed. It is about the session that is gone.
if issued != app.cloud().account_generation.load(Ordering::Relaxed) {
continue;
}
apply(app, event);
}
poll_link(app);
@@ -649,6 +677,15 @@ pub fn pump<A: CloudApp>(app: &mut A, ctx: &egui::Context) {
fn apply<A: CloudApp>(app: &mut A, event: Event) {
let noun = app.kind().noun;
if matches!(event, Event::Account(_)) && app.cloud().relist_after_sign_in {
// The sign-in has answered, whether or not it succeeded. Both folders
// are emptied and not loading, so `start` and the Open page list them
// again for whoever is signed in now.
let cloud = app.cloud_mut();
cloud.relist_after_sign_in = false;
cloud.mine = Folder::default();
cloud.shared = Folder::default();
}
match event {
Event::Account(Ok(account)) => {
let linked = account.provider_linked;
+3 -1
View File
@@ -422,7 +422,9 @@ pub fn save_page<A: CloudApp>(app: &mut A, ui: &mut Ui) -> bool {
asked = typing.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
});
ui.add_space(10.0);
let ready = app.cloud().busy.is_none() && !document_name(&app.cloud().save_name, kind).is_empty();
// A sign-in in progress has emptied the folder, so the destination is not
// the one the user picked until the folders are listed again.
let ready = app.cloud().busy.is_none() && !app.cloud().relist_after_sign_in && !document_name(&app.cloud().save_name, kind).is_empty();
if ui.add_enabled(ready, egui::Button::new(save_label)).clicked() {
asked = true;
}
+82 -8
View File
@@ -197,6 +197,12 @@ fn pumped(app: &mut Notebook, ctx: &egui::Context) {
ctx.end_pass().textures_delta.clear();
}
/// Puts an answer in the channel as a worker for the current session would.
fn deliver(app: &Notebook, event: Event) {
let issued = app.cloud.account_generation.load(Ordering::Relaxed);
app.cloud.events.0.send((issued, event)).unwrap();
}
fn wired() -> (Notebook, Arc<Mutex<Vec<Job>>>, egui::Context) {
let mut app = Notebook::new();
let jobs = Arc::new(Mutex::new(Vec::new()));
@@ -339,7 +345,7 @@ fn a_refused_save_is_put_to_the_user_and_never_retried() {
pumped(&mut app, &ctx);
jobs.lock().unwrap().clear();
// What a service answers when somebody else saved first.
app.cloud.events.0.send(Event::Saved { uid: 1, entry: Err(Fault::Conflict) }).unwrap();
deliver(&app, Event::Saved { uid: 1, entry: Err(Fault::Conflict) });
pumped(&mut app, &ctx);
assert_eq!(report(&app)["conflict"]["name"], "Minutes.note", "the user is told, and asked what to do");
assert_eq!(app.did().dropped, vec![1], "the version that did not land is forgotten");
@@ -349,7 +355,7 @@ fn a_refused_save_is_put_to_the_user_and_never_retried() {
#[test]
fn no_account_yet_is_an_offer_to_link_and_never_an_error() {
let (mut app, _jobs, ctx) = wired();
app.cloud.events.0.send(Event::Account(Err(Fault::NotLinked))).unwrap();
deliver(&app, Event::Account(Err(Fault::NotLinked)));
pumped(&mut app, &ctx);
assert_eq!(report(&app)["link"], "offered");
assert_eq!(report(&app)["accountError"], serde_json::Value::Null, "not having linked an account yet is not a failure");
@@ -359,7 +365,7 @@ fn no_account_yet_is_an_offer_to_link_and_never_an_error() {
#[test]
fn a_browser_round_trip_is_polled_until_the_user_is_done() {
let (mut app, jobs, ctx) = wired();
app.cloud.events.0.send(Event::Browser { url: "https://cloud.example/link/abc".to_owned(), handle: Some("abc".to_owned()) }).unwrap();
deliver(&app, Event::Browser { url: "https://cloud.example/link/abc".to_owned(), handle: Some("abc".to_owned()) });
pumped(&mut app, &ctx);
assert_eq!(app.did().urls, vec!["https://cloud.example/link/abc".to_owned()], "the browser is opened for them");
assert_eq!(report(&app)["link"]["waiting"], "https://cloud.example/link/abc");
@@ -403,11 +409,10 @@ fn working_together_needs_somewhere_for_the_room_to_be_keyed_on() {
#[test]
fn a_conversation_uses_the_hosts_chat_opener() {
let (mut app, _, ctx) = wired();
app.cloud
.events
.0
.send(Event::Conversation(Ok(craft_cloud::Conversation { url: "https://cloud.example.net/call/room".to_owned(), name: "Talk".to_owned() })))
.unwrap();
deliver(
&app,
Event::Conversation(Ok(craft_cloud::Conversation { url: "https://cloud.example.net/call/room".to_owned(), name: "Talk".to_owned() })),
);
pumped(&mut app, &ctx);
@@ -430,6 +435,75 @@ fn signing_out_forgets_everything_this_window_knew() {
assert!(jobs.lock().unwrap().iter().any(|j| matches!(j, Job::SignOut)), "the service is told, so the saved token goes too");
}
#[test]
fn an_answer_queued_before_the_session_changed_is_dropped() {
let (mut app, _jobs, ctx) = wired();
let old = Account { display: "Ada Lovelace".to_owned(), capabilities: vec![Capability::Files], provider_linked: true };
// A worker answers, and the answers wait in the channel while the user
// signs out in the same frame.
let post = Post::new(app.cloud.events.0.clone(), app.cloud.account_generation.clone());
post.send(Event::Account(Ok(old)));
post.dup().send(Event::Listed { path: String::new(), entries: Ok(vec![file("/Minutes.note")]) });
sign_out(&mut app);
pumped(&mut app, &ctx);
let state = report(&app);
assert_eq!(state["account"], serde_json::Value::Null, "the previous session's account must not come back");
assert_eq!(state["entries"], serde_json::json!([]), "nor its files");
// The same across a new sign-in.
let post = Post::new(app.cloud.events.0.clone(), app.cloud.account_generation.clone());
post.send(Event::Listed { path: String::new(), entries: Ok(vec![file("/Stale.note")]) });
sign_in(&mut app);
pumped(&mut app, &ctx);
assert_eq!(report(&app)["entries"], serde_json::json!([]), "a listing for the signed-out session is not shown to the new one");
}
#[test]
fn a_sign_in_that_drops_a_listing_leaves_no_folder_loading() {
let (mut app, _jobs, ctx) = wired();
// Both listings are asked for, and the answer to the first waits in the
// channel while the user signs in again. The shared one never answers.
browse(&mut app, "");
load_shared(&mut app);
sign_in(&mut app);
pumped(&mut app, &ctx);
assert!(!app.cloud.mine.loading, "a dropped listing must not leave the folder loading forever");
assert!(!app.cloud.shared.loading, "nor the shared one, which would then never be asked for again");
// A listing the new session asks for still completes.
browse(&mut app, "");
pumped(&mut app, &ctx);
assert!(app.cloud.mine.loaded);
assert_eq!(report(&app)["entries"], serde_json::json!(["Minutes.note", "Archive"]));
}
#[test]
fn a_listing_asked_for_before_the_sign_in_answers_is_not_sent() {
let (mut app, jobs, ctx) = wired();
sign_in(&mut app);
jobs.lock().unwrap().clear();
// Asked for after the sign-in and before its answer. A listing sent now
// could answer after the account does, and its files may be the previous
// account's.
browse(&mut app, "");
load_shared(&mut app);
assert!(
!jobs.lock().unwrap().iter().any(|j| matches!(j, Job::List(_) | Job::SharedWithMe)),
"no listing goes out while the sign-in is outstanding"
);
pumped(&mut app, &ctx);
assert!(!app.cloud.mine.loaded && !app.cloud.mine.loading, "the folder waits to be listed for the new account");
assert!(!app.cloud.shared.loaded && !app.cloud.shared.loading, "and so does the shared one");
// Once the sign-in has answered, a listing goes through.
browse(&mut app, "");
pumped(&mut app, &ctx);
assert!(app.cloud.mine.loaded);
}
#[test]
fn bytes_are_said_the_way_a_person_reads_them() {
assert_eq!(size_text(None), "");
+12 -7
View File
@@ -675,14 +675,17 @@ impl ShareDialog {
}
}
Answer::Granted { shared, failed } => {
// A link was asked for in order to be handed out, so it goes
// to the clipboard without a second click.
if let Some(url) = shared.iter().find_map(|s| s.url.clone()) {
ctx.copy_text(url);
}
if let Some(sheet) = &mut self.open
&& sheet.granting == Some(seq)
{
// A link was asked for in order to be handed out, so it
// goes to the clipboard without a second click. Only for
// the sheet that asked: a grant answered after the sheet
// closed or moved to another document leaves the
// clipboard alone.
if let Some(url) = shared.iter().find_map(|s| s.url.clone()) {
ctx.copy_text(url);
}
sheet.granting = None;
sheet.error = None;
// Recipients that went through leave the picker. The ones
@@ -918,9 +921,11 @@ fn draw(ui: &mut Ui, sheet: &mut Sheet, avatars: &HashMap<String, Avatar>, label
ui.add(egui::TextEdit::singleline(&mut sheet.link_key).hint_text(labels.key_hint.as_str()).password(true).desired_width(150.0));
}
// A key the server insists on cannot be skipped, so the control
// stays disabled until one is typed.
// stays disabled until one is typed. It also waits, as Send does,
// while a grant is in flight: the answer to that grant is the one
// the sheet takes, and an earlier link would be dropped.
let keyed = !sheet.link_key.trim().is_empty();
let ready = keyed || !allowed.key_required;
let ready = (keyed || !allowed.key_required) && sheet.granting.is_none();
if ui.add_enabled(ready, egui::Button::new(labels.create_link.as_str())).clicked() {
acts.push(Act::Grant(Grant {
id: sheet.id.clone(),
+79
View File
@@ -240,6 +240,85 @@ fn a_share_reaching_four_of_five_names_the_fifth() {
assert_eq!(left.chosen.first().map(|c| &c.target), Some(&ShareTarget::Email("nobody@@".into())));
}
fn copied(ctx: &Context) -> Vec<String> {
ctx.output(|o| o.commands.iter().filter_map(|c| if let egui::OutputCommand::CopyText(text) = c { Some(text.clone()) } else { None }).collect())
}
fn ask_for_link(dialog: &mut ShareDialog) -> u64 {
let granting = dialog.issue(Request::Grant(Grant {
id: "files/budget.xlsx".into(),
password: None,
targets: Vec::new(),
permission: Permission::View,
note: None,
notify: false,
}));
if let Some(sheet) = &mut dialog.open {
sheet.granting = Some(granting);
}
granting
}
fn link(url: &str) -> Answer {
let mut made = share("s1", ShareTarget::Email("anyone@example.com".into()));
made.url = Some(url.into());
Answer::Granted { shared: vec![made], failed: Vec::new() }
}
#[test]
fn a_granted_link_goes_to_the_clipboard() {
let (ctx, mut dialog, _) = ready();
let granting = ask_for_link(&mut dialog);
dialog.receive(&ctx, granting, Ok(link("https://cloud.example/l/budget")));
assert_eq!(copied(&ctx), ["https://cloud.example/l/budget"]);
}
#[test]
fn a_link_granted_after_the_sheet_moved_on_is_not_copied() {
let (ctx, mut dialog, _) = ready();
let granting = ask_for_link(&mut dialog);
dialog.close();
dialog.open("files/plan.docx", "Plan");
dialog.receive(&ctx, granting, Ok(link("https://cloud.example/l/budget")));
assert!(copied(&ctx).is_empty(), "the budget's link must not replace the clipboard while the plan is open");
let (ctx, mut dialog, _) = ready();
let granting = ask_for_link(&mut dialog);
dialog.close();
dialog.receive(&ctx, granting, Ok(link("https://cloud.example/l/budget")));
assert!(copied(&ctx).is_empty(), "nor after the sheet closed");
}
/// Whether one frame of the sheet offers "Get a link" as a button that can
/// be pressed, read off the accessibility tree.
fn link_button_enabled(dialog: &mut ShareDialog) -> Option<bool> {
let ctx = Context::default();
ctx.enable_accesskit();
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 900.0))), ..Default::default() };
let mut output = ctx.run_ui(raw, |ui| dialog.show_in(ui));
output.textures_delta.clear();
let tree = output.platform_output.accesskit_update?;
tree.nodes
.iter()
.find(|(_, node)| node.role() == egui::accesskit::Role::Button && node.label() == Some("Get a link"))
.map(|(_, node)| !node.is_disabled())
}
#[test]
fn get_a_link_waits_while_a_grant_is_in_flight() {
let ctx = Context::default();
let mut dialog = ShareDialog::new();
dialog.connect(Silent::default());
dialog.collect(&ctx);
dialog.receive(&ctx, 1, Ok(can(vec![Capability::Sharing, Capability::LinkShares])));
dialog.open("files/budget.xlsx", "Budget");
assert_eq!(link_button_enabled(&mut dialog), Some(true));
let granting = ask_for_link(&mut dialog);
assert_eq!(link_button_enabled(&mut dialog), Some(false), "a second grant would make the first one's link be dropped");
dialog.receive(&ctx, granting, Ok(link("https://cloud.example/l/budget")));
assert_eq!(link_button_enabled(&mut dialog), Some(true));
}
#[test]
fn a_refusal_that_stopped_the_whole_call_is_not_a_failed_recipient() {
let (ctx, mut dialog, _) = ready();
+444 -1
View File
@@ -44,13 +44,22 @@ impl Matrix {
_ => None,
}
}
/// The ISO/IEC 23091-2 `matrix_coefficients` code to write for this matrix.
/// [`Matrix::Bt601`] writes 6 (SMPTE 170M); code 5 has the same coefficients.
pub fn to_code(self) -> u8 {
match self {
Matrix::Bt709 => 1,
Matrix::Bt601 => 6,
Matrix::Bt2020Ncl => 9,
}
}
}
/// Transfer characteristics.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Transfer {
/// BT.709 display, approximated with the sRGB curve by this slim conversion layer.
/// This is not a pure-gamma BT.1886 decode.
/// This is not a pure-gamma BT.1886 decode; [`bt1886_eotf`] is.
#[default]
Bt709,
Srgb,
@@ -73,6 +82,17 @@ impl Transfer {
_ => None,
}
}
/// The ISO/IEC 23091-2 `transfer_characteristics` code to write for this transfer.
/// [`Transfer::Bt709`] writes 1; codes 6, 14 and 15 also read as it.
pub fn to_code(self) -> u8 {
match self {
Transfer::Bt709 => 1,
Transfer::Linear => 8,
Transfer::Srgb => 13,
Transfer::Pq => 16,
Transfer::Hlg => 18,
}
}
}
/// Chromaticity primaries.
@@ -86,6 +106,32 @@ pub enum Primaries {
P3D65,
}
impl Primaries {
/// From an ISO/IEC 23091-2 `colour_primaries` code.
pub fn from_code(c: u8) -> Option<Primaries> {
match c {
1 => Some(Primaries::Bt709),
5 => Some(Primaries::Bt601_625),
// SMPTE 240M (7) has the same primaries as SMPTE 170M (6).
6 | 7 => Some(Primaries::Bt601_525),
9 => Some(Primaries::Bt2020),
// H.273 table 2: code 11 is DCI-P3 with its own white point, not D65.
12 => Some(Primaries::P3D65),
_ => None,
}
}
/// The ISO/IEC 23091-2 `colour_primaries` code to write for these primaries.
pub fn to_code(self) -> u8 {
match self {
Primaries::Bt709 => 1,
Primaries::Bt601_625 => 5,
Primaries::Bt601_525 => 6,
Primaries::Bt2020 => 9,
Primaries::P3D65 => 12,
}
}
}
/// Quantisation range of integer Y'CbCr samples.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Range {
@@ -192,6 +238,144 @@ pub fn normalize_c(v: u32, bits: u32, range: Range) -> Result<f32, InvalidBitDep
})
}
/// Quantize a luma signal in 0..1 to an integer code value: the inverse of [`normalize_y`].
///
/// Limited range follows ITU-R BT.709 and BT.2100 (`round((219 * E + 16) * 2^(bits - 8))`), full
/// range follows BT.2100 (`round((2^bits - 1) * E)`). Values outside the signal range are clamped
/// to the codes `0..=2^bits - 1`, and NaN is treated as 0.
pub fn quantize_y(e: f32, bits: u32, range: Range) -> Result<u16, InvalidBitDepth> {
if !(8..=16).contains(&bits) {
return Err(InvalidBitDepth(bits));
}
let e = if e.is_nan() { 0.0 } else { f64::from(e) };
let scale = f64::from(1u32 << (bits - 8));
let code = match range {
Range::Limited => (219.0 * e + 16.0) * scale,
Range::Full => f64::from((1u32 << bits) - 1) * e,
};
Ok(clamp_code(code, bits))
}
/// Quantize a chroma signal in −0.5..0.5 to an integer code value: the inverse of
/// [`normalize_c`].
///
/// Limited range is `round((224 * E + 128) * 2^(bits - 8))`, full range is
/// `round((2^bits - 1) * E + 2^(bits - 1))` (BT.2100). Values outside the signal range are
/// clamped to the codes `0..=2^bits - 1`, and NaN is treated as 0 (no chroma).
pub fn quantize_c(e: f32, bits: u32, range: Range) -> Result<u16, InvalidBitDepth> {
if !(8..=16).contains(&bits) {
return Err(InvalidBitDepth(bits));
}
let e = if e.is_nan() { 0.0 } else { f64::from(e) };
let scale = f64::from(1u32 << (bits - 8));
let code = match range {
Range::Limited => (224.0 * e + 128.0) * scale,
Range::Full => f64::from((1u32 << bits) - 1) * e + f64::from(1u32 << (bits - 1)),
};
Ok(clamp_code(code, bits))
}
#[inline]
fn clamp_code(code: f64, bits: u32) -> u16 {
// `bits` is at most 16, so the maximum fits in u16.
code.round().clamp(0.0, f64::from((1u32 << bits) - 1)) as u16
}
/// Convert non-linear R'G'B' (0..1) to integer Y'CbCr code values at a bit depth and range.
pub fn rgb_to_ycbcr_codes(r: f32, g: f32, b: f32, m: Matrix, bits: u32, range: Range) -> Result<[u16; 3], InvalidBitDepth> {
let [y, cb, cr] = rgb_to_ycbcr(r, g, b, m);
Ok([quantize_y(y, bits, range)?, quantize_c(cb, bits, range)?, quantize_c(cr, bits, range)?])
}
/// Convert integer Y'CbCr code values at a bit depth and range to non-linear R'G'B'.
///
/// The result is not clamped: codes outside the nominal range (limited-range footroom and
/// headroom) give values below 0 or above 1.
pub fn ycbcr_codes_to_rgb(y: u32, cb: u32, cr: u32, m: Matrix, bits: u32, range: Range) -> Result<[f32; 3], InvalidBitDepth> {
Ok(ycbcr_to_rgb(normalize_y(y, bits, range)?, normalize_c(cb, bits, range)?, normalize_c(cr, bits, range)?, m))
}
/// Fixed-point conversion between 8-bit R'G'B' and 8-bit Y'CbCr for one matrix and range.
///
/// The coefficients are computed once by [`Ycbcr8::new`]; each conversion is integer
/// multiply-adds with 16 fractional bits, for per-pixel loops over camera or encoder frames.
/// Results stay within one code of [`rgb_to_ycbcr_codes`] and [`ycbcr_codes_to_rgb`], and
/// neutral grays keep chroma at exactly 128.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Ycbcr8 {
y_offset: i32,
// R'G'B' to Y'CbCr.
y_rgb: [i32; 3],
cb_rgb: [i32; 3],
cr_rgb: [i32; 3],
// Y'CbCr to R'G'B'.
rgb_y: i32,
r_cr: i32,
g_cb: i32,
g_cr: i32,
b_cb: i32,
}
const FIXED_ONE: f64 = 65536.0;
const FIXED_HALF: i32 = 1 << 15;
impl Ycbcr8 {
/// Coefficients for matrix `m` and range `range`.
pub fn new(m: Matrix, range: Range) -> Ycbcr8 {
let (kr, kb) = m.kr_kb();
let (kr, kb) = (f64::from(kr), f64::from(kb));
let kg = 1.0 - kr - kb;
let (y_offset, y_scale, c_scale) = match range {
Range::Limited => (16, 219.0, 224.0),
Range::Full => (0, 255.0, 255.0),
};
let fixed = |v: f64| (v * FIXED_ONE).round() as i32;
// Luma: the green weight takes the rounding remainder so 255 gray reaches the top code.
let y_total = fixed(y_scale / 255.0);
let (y_r, y_b) = (fixed(kr * y_scale / 255.0), fixed(kb * y_scale / 255.0));
// Chroma: the green weight cancels the other two so every gray gives exactly 128.
let cb_scale = c_scale / 255.0 / (2.0 * (1.0 - kb));
let cr_scale = c_scale / 255.0 / (2.0 * (1.0 - kr));
let (cb_r, cb_b) = (fixed(-kr * cb_scale), fixed((1.0 - kb) * cb_scale));
let (cr_r, cr_b) = (fixed((1.0 - kr) * cr_scale), fixed(-kb * cr_scale));
let r_cr = 2.0 * (1.0 - kr) * 255.0 / c_scale;
let b_cb = 2.0 * (1.0 - kb) * 255.0 / c_scale;
Ycbcr8 {
y_offset,
y_rgb: [y_r, y_total - y_r - y_b, y_b],
cb_rgb: [cb_r, -cb_r - cb_b, cb_b],
cr_rgb: [cr_r, -cr_r - cr_b, cr_b],
rgb_y: fixed(255.0 / y_scale),
r_cr: fixed(r_cr),
g_cb: fixed(-kb * b_cb / kg),
g_cr: fixed(-kr * r_cr / kg),
b_cb: fixed(b_cb),
}
}
/// 8-bit R'G'B' to 8-bit Y'CbCr code values.
#[inline]
pub fn rgb_to_ycbcr(&self, r: u8, g: u8, b: u8) -> [u8; 3] {
let rgb = [i32::from(r), i32::from(g), i32::from(b)];
let dot = |k: &[i32; 3]| k[0] * rgb[0] + k[1] * rgb[1] + k[2] * rgb[2];
[to_u8(dot(&self.y_rgb) + (self.y_offset << 16)), to_u8(dot(&self.cb_rgb) + (128 << 16)), to_u8(dot(&self.cr_rgb) + (128 << 16))]
}
/// 8-bit Y'CbCr code values to 8-bit R'G'B', clamped to 0..=255.
#[inline]
pub fn ycbcr_to_rgb(&self, y: u8, cb: u8, cr: u8) -> [u8; 3] {
let y = self.rgb_y * (i32::from(y) - self.y_offset);
let (cb, cr) = (i32::from(cb) - 128, i32::from(cr) - 128);
[to_u8(y + self.r_cr * cr), to_u8(y + self.g_cb * cb + self.g_cr * cr), to_u8(y + self.b_cb * cb)]
}
}
/// Round a 16.16 fixed-point value to the nearest integer and clamp it to a u8.
#[inline]
fn to_u8(v: i32) -> u8 {
((v + FIXED_HALF) >> 16).clamp(0, 255) as u8
}
/// sRGB electro-optical transfer (encoded → linear).
#[inline]
pub fn srgb_to_linear(v: f32) -> f32 {
@@ -255,6 +439,41 @@ pub fn hlg_inverse_oetf(e: f32) -> f32 {
if e <= 0.5 { e * e / 3.0 } else { (((e - c) / a).exp() + b) / 12.0 }
}
/// The BT.1886 exponent.
const BT1886_GAMMA: f64 = 2.4;
/// BT.1886 constants `a` and `b` for a display's white and black luminance, or `None` when white
/// is not measurably above black, or is NaN or infinite. A black below 0, or NaN, is taken as 0.
/// The constants are in `f64`, so a black close to white keeps the curve's endpoints.
fn bt1886_ab(white: f32, black: f32) -> Option<(f64, f64)> {
let (white, black) = (f64::from(white), f64::from(black.max(0.0)));
let (w, k) = (white.powf(1.0 / BT1886_GAMMA), black.powf(1.0 / BT1886_GAMMA));
let d = w - k;
if d.is_finite() && d > 0.0 { Some((d.powf(BT1886_GAMMA), k / d)) } else { None }
}
/// ITU-R BT.1886 reference display EOTF: a BT.709 signal (0..1) to screen luminance, for a
/// display with the given white and black luminance (any unit, e.g. cd/m²). With `white` 1 and
/// `black` 0 it is a pure 2.4 gamma. [`to_linear`] with [`Transfer::Bt709`] uses the sRGB curve
/// instead. A `black` below 0, or NaN, is taken as 0. When `white` is not measurably above
/// `black`, or is NaN or infinite, the result is `black`.
pub fn bt1886_eotf(v: f32, white: f32, black: f32) -> f32 {
match bt1886_ab(white, black) {
Some((a, b)) => (a * (f64::from(v) + b).max(0.0).powf(BT1886_GAMMA)) as f32,
None => black.max(0.0),
}
}
/// Inverse of [`bt1886_eotf`]: screen luminance to a BT.709 signal. Luminance at or below
/// `black` gives 0. When `white` is not measurably above `black`, or is NaN or infinite, the
/// result is 0.
pub fn bt1886_inverse_eotf(l: f32, white: f32, black: f32) -> f32 {
match bt1886_ab(white, black) {
Some((a, b)) if l > black.max(0.0) => ((f64::from(l) / a).powf(1.0 / BT1886_GAMMA) - b).max(0.0) as f32,
_ => 0.0,
}
}
/// 256-entry table: sRGB-encoded u8 → linear f32.
pub fn srgb_u8_to_linear_table() -> &'static [f32; 256] {
static T: OnceLock<[f32; 256]> = OnceLock::new();
@@ -402,6 +621,108 @@ mod tests {
assert_eq!(linear_to_srgb_u8(srgb_u8_to_linear_table()[128]), 128);
}
/// SMPTE ST 2084 inverse EOTF in `f64`, with the constants as exact fractions from
/// Recommendation ITU-R BT.2100 Table 4.
fn st2084_inverse_eotf(y: f64) -> f64 {
let (m1, m2) = (2610.0 / 16384.0, 2523.0 / 4096.0 * 128.0);
let (c1, c2, c3) = (3424.0 / 4096.0, 2413.0 / 4096.0 * 32.0, 2392.0 / 4096.0 * 32.0);
let p = y.powf(m1);
((c1 + c2 * p) / (1.0 + c3 * p)).powf(m2)
}
#[test]
fn pq_matches_the_st_2084_equations() {
for nits in [0.01_f64, 0.1, 1.0, 10.0, 100.0, 203.0, 1000.0, 4000.0, 10_000.0] {
let want = st2084_inverse_eotf(nits / 10_000.0);
let got = pq_inverse_eotf((nits / 10_000.0) as f32) as f64;
assert!((got - want).abs() < 1e-5, "{nits} nits: {got} vs {want}");
let back = pq_eotf(want as f32) as f64 * 10_000.0;
assert!((back - nits).abs() <= nits * 1e-4, "{want}: {back} vs {nits} nits");
}
assert!((pq_inverse_eotf(1.0) - 1.0).abs() < 1e-6);
assert!((pq_eotf(1.0) - 1.0).abs() < 1e-6);
}
/// Report ITU-R BT.2408-7 Table 1: display luminance in cd/m², then the nominal signal level in
/// whole percent for a PQ reference display and for a 1 000 cd/m² HLG display.
const BT2408_TABLE_1: [(f32, f32, f32); 4] = [(26.0, 38.0, 38.0), (162.0, 56.0, 71.0), (179.0, 57.0, 73.0), (203.0, 58.0, 75.0)];
#[test]
fn signal_levels_match_bt2408_table_1() {
for (nits, pq_percent, hlg_percent) in BT2408_TABLE_1 {
let pq = pq_inverse_eotf(nits / 10_000.0) * 100.0;
assert!((pq - pq_percent).abs() <= 0.5, "{nits} nits: PQ {pq}% vs {pq_percent}%");
// The BT.2100 HLG OOTF has a system gamma of 1.2 on a 1 000 cd/m² display, so a
// neutral gray shown at `nits` comes from scene light (nits / 1000)^(1 / 1.2).
let hlg = hlg_oetf((nits / 1000.0).powf(1.0 / 1.2)) * 100.0;
assert!((hlg - hlg_percent).abs() <= 0.5, "{nits} nits: HLG {hlg}% vs {hlg_percent}%");
}
}
#[test]
fn hlg_matches_the_bt2100_equations() {
// Recommendation ITU-R BT.2100 Table 5: a = 0.17883277, b = 1 - 4a, c = 0.5 - a ln(4a).
let a = 0.178_832_77_f64;
let b = 1.0 - 4.0 * a;
let c = 0.5 - a * (4.0 * a).ln();
let oetf = |e: f64| if e <= 1.0 / 12.0 { (3.0 * e).sqrt() } else { a * (12.0 * e - b).ln() + c };
for e in [0.0_f64, 0.001, 0.01, 1.0 / 12.0, 0.1, 0.25, 0.5, 0.75, 1.0] {
let want = oetf(e);
let got = hlg_oetf(e as f32) as f64;
assert!((got - want).abs() < 1e-6, "E = {e}: {got} vs {want}");
let back = hlg_inverse_oetf(want as f32) as f64;
assert!((back - e).abs() <= 1e-6 + e * 1e-5, "E' = {want}: {back} vs {e}");
}
assert!((hlg_oetf(1.0 / 12.0) - 0.5).abs() < 1e-6);
assert!((hlg_oetf(1.0) - 1.0).abs() < 1e-6);
}
/// The sRGB transfer of IEC 61966-2-1 (Amendment 1), as the ICC sRGB registry entry gives it.
#[test]
fn srgb_tables_match_the_iec_61966_2_1_equations() {
let decode = |v: f64| if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) };
let encode = |l: f64| if l <= 0.003_130_8 { l * 12.92 } else { 1.055 * l.powf(1.0 / 2.4) - 0.055 };
for (i, got) in srgb_u8_to_linear_table().iter().enumerate() {
let want = decode(i as f64 / 255.0);
assert!((*got as f64 - want).abs() <= 1e-6, "code {i}: {got} vs {want}");
}
for (i, got) in linear_to_srgb_u8_table().iter().enumerate() {
let want = (encode(i as f64 / 4095.0) * 255.0).round() as u8;
assert_eq!(*got, want, "linear {i}/4095");
}
}
#[test]
fn bt1886_follows_the_recommendation() {
// BT.1886 with Lw = 100 cd/m² and Lb = 0: L = 100 · V^2.4.
assert!((bt1886_eotf(0.5, 100.0, 0.0) - 100.0 * 0.5f32.powf(2.4)).abs() < 1e-3);
// A pure gamma has no linear toe, so near black it is darker than the sRGB curve.
assert!(bt1886_eotf(0.02, 1.0, 0.0) < to_linear(0.02, Transfer::Bt709) / 10.0);
// A black level lifts code 0 to the display's black and keeps code 1 at its white.
for (white, black) in [(100.0, 0.1), (300.0, 0.5), (1.0, 0.0)] {
assert!((bt1886_eotf(0.0, white, black) - black).abs() < 1e-4 * white);
assert!((bt1886_eotf(1.0, white, black) - white).abs() < 1e-4 * white);
for v in [0.0, 0.1, 0.5, 0.9, 1.0] {
let l = bt1886_eotf(v, white, black);
assert!((bt1886_inverse_eotf(l, white, black) - v).abs() < 1e-4, "{white} {black} {v}");
}
assert_eq!(bt1886_inverse_eotf(black / 2.0, white, black), 0.0);
}
assert!(bt1886_eotf(0.5, 100.0, 0.1) > bt1886_eotf(0.5, 100.0, 0.0));
// A black close to white keeps both endpoints of the inverse.
assert_eq!(bt1886_inverse_eotf(99.99, 100.0, 99.99), 0.0);
assert!((bt1886_inverse_eotf(100.0, 100.0, 99.99) - 1.0).abs() < 1e-3);
// A display whose white is not above its black.
assert_eq!(bt1886_eotf(0.5, 1.0, 1.0), 1.0);
assert_eq!(bt1886_inverse_eotf(0.5, 0.0, 0.0), 0.0);
assert_eq!(bt1886_inverse_eotf(0.5, f32::NAN, 0.0), 0.0);
assert_eq!(bt1886_eotf(0.5, 100.0, f32::NAN), bt1886_eotf(0.5, 100.0, 0.0));
for (white, black) in [(1.0, 0.999_999_94), (f32::INFINITY, 0.0)] {
assert!(bt1886_eotf(0.5, white, black).is_finite());
assert!(bt1886_inverse_eotf(0.5, white, black).is_finite());
}
}
#[test]
fn hsl_roundtrip() {
let c = [0.2, 0.6, 0.9];
@@ -428,6 +749,92 @@ mod tests {
assert_eq!(HdrMetadata { max_cll: Some(100.0), ..HdrMetadata::default() }.peak_nits(), Some(REFERENCE_WHITE_NITS as f32));
}
#[test]
fn code_values_match_published_levels() {
// The BT.709 and BT.2100 quantization levels: black, nominal peak and achromatic chroma.
assert_eq!(rgb_to_ycbcr_codes(0.0, 0.0, 0.0, Matrix::Bt709, 8, Range::Limited), Ok([16, 128, 128]));
assert_eq!(rgb_to_ycbcr_codes(1.0, 1.0, 1.0, Matrix::Bt709, 8, Range::Limited), Ok([235, 128, 128]));
assert_eq!(rgb_to_ycbcr_codes(1.0, 1.0, 1.0, Matrix::Bt2020Ncl, 10, Range::Limited), Ok([940, 512, 512]));
assert_eq!(rgb_to_ycbcr_codes(0.0, 0.0, 0.0, Matrix::Bt2020Ncl, 10, Range::Limited), Ok([64, 512, 512]));
assert_eq!(rgb_to_ycbcr_codes(1.0, 1.0, 1.0, Matrix::Bt2020Ncl, 12, Range::Full), Ok([4095, 2048, 2048]));
// 100% red: Y'CbCr of the BT.709 and BT.601 color bars.
assert_eq!(rgb_to_ycbcr_codes(1.0, 0.0, 0.0, Matrix::Bt709, 8, Range::Limited), Ok([63, 102, 240]));
assert_eq!(rgb_to_ycbcr_codes(1.0, 0.0, 0.0, Matrix::Bt601, 8, Range::Limited), Ok([81, 90, 240]));
// JFIF (ITU-T T.871) full-range BT.601: red is Y 76, Cb 85, Cr 255.5 clamped to 255.
assert_eq!(rgb_to_ycbcr_codes(1.0, 0.0, 0.0, Matrix::Bt601, 8, Range::Full), Ok([76, 85, 255]));
}
#[test]
fn quantize_inverts_normalize() {
for range in [Range::Limited, Range::Full] {
for bits in [8, 10, 12, 16] {
for v in [0, 1, 16, 64, 128, 235, 240, 255] {
let v = v << (bits - 8);
assert_eq!(u32::from(quantize_y(normalize_y(v, bits, range).unwrap(), bits, range).unwrap()), v, "{range:?} {bits} y {v}");
assert_eq!(u32::from(quantize_c(normalize_c(v, bits, range).unwrap(), bits, range).unwrap()), v, "{range:?} {bits} c {v}");
}
let top = (1u32 << bits) - 1;
assert_eq!(u32::from(quantize_y(f32::INFINITY, bits, range).unwrap()), top);
assert_eq!(quantize_c(f32::NEG_INFINITY, bits, range), Ok(0));
assert_eq!(quantize_c(f32::NAN, bits, range), quantize_c(0.0, bits, range));
assert_eq!(quantize_y(f32::NAN, bits, range), quantize_y(0.0, bits, range));
}
}
for bits in [0, 7, 17, u32::MAX] {
assert_eq!(quantize_y(0.5, bits, Range::Full), Err(InvalidBitDepth(bits)));
assert_eq!(quantize_c(0.0, bits, Range::Limited), Err(InvalidBitDepth(bits)));
assert_eq!(rgb_to_ycbcr_codes(0.5, 0.5, 0.5, Matrix::Bt709, bits, Range::Full), Err(InvalidBitDepth(bits)));
assert_eq!(ycbcr_codes_to_rgb(0, 0, 0, Matrix::Bt709, bits, Range::Full), Err(InvalidBitDepth(bits)));
}
}
#[test]
fn ycbcr_codes_roundtrip() {
for m in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] {
for range in [Range::Limited, Range::Full] {
let [y, cb, cr] = rgb_to_ycbcr_codes(0.8, 0.3, 0.1, m, 10, range).unwrap();
let back = ycbcr_codes_to_rgb(y.into(), cb.into(), cr.into(), m, 10, range).unwrap();
for (k, v) in [0.8, 0.3, 0.1].into_iter().enumerate() {
assert!((back[k] - v).abs() < 4e-3, "{m:?} {range:?} {back:?}");
}
}
}
}
#[test]
fn fixed_point_8_bit_matches_float() {
let close = |a: [u8; 3], b: [u16; 3]| a.iter().zip(b).all(|(&a, b)| (i32::from(a) - i32::from(b)).abs() <= 1);
for m in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] {
for range in [Range::Limited, Range::Full] {
let conv = Ycbcr8::new(m, range);
for r in (0..=255u8).step_by(5) {
for g in (0..=255u8).step_by(5) {
for b in (0..=255u8).step_by(5) {
let float = rgb_to_ycbcr_codes(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0, m, 8, range).unwrap();
let fixed = conv.rgb_to_ycbcr(r, g, b);
assert!(close(fixed, float), "{m:?} {range:?} {r} {g} {b}: {fixed:?} vs {float:?}");
let [y, cb, cr] = fixed;
let rgb = ycbcr_codes_to_rgb(y.into(), cb.into(), cr.into(), m, 8, range).unwrap();
let want = rgb.map(|v| (v * 255.0).round().clamp(0.0, 255.0) as u16);
assert!(close(conv.ycbcr_to_rgb(y, cb, cr), want), "{m:?} {range:?} {fixed:?}");
}
}
}
for v in 0..=255u8 {
let [_, cb, cr] = conv.rgb_to_ycbcr(v, v, v);
assert_eq!((cb, cr), (128, 128), "{m:?} {range:?} gray {v}");
}
// Out-of-range codes clamp instead of wrapping.
assert_eq!(conv.ycbcr_to_rgb(255, 255, 255)[0], 255);
assert_eq!(conv.ycbcr_to_rgb(0, 0, 0)[0], 0);
}
assert_eq!(Ycbcr8::new(m, Range::Limited).rgb_to_ycbcr(255, 255, 255), [235, 128, 128]);
assert_eq!(Ycbcr8::new(m, Range::Full).rgb_to_ycbcr(255, 255, 255), [255, 128, 128]);
assert_eq!(Ycbcr8::new(m, Range::Limited).ycbcr_to_rgb(235, 128, 128), [255, 255, 255]);
assert_eq!(Ycbcr8::new(m, Range::Limited).ycbcr_to_rgb(16, 128, 128), [0, 0, 0]);
}
}
#[test]
fn codes() {
assert_eq!(Matrix::from_code(9), Some(Matrix::Bt2020Ncl));
@@ -437,4 +844,40 @@ mod tests {
assert_eq!(Transfer::from_code(16), Some(Transfer::Pq));
assert_eq!(Transfer::from_code(99), None);
}
#[test]
fn codes_written_are_the_h273_values() {
assert_eq!([Matrix::Bt709, Matrix::Bt601, Matrix::Bt2020Ncl].map(Matrix::to_code), [1, 6, 9]);
assert_eq!([Transfer::Bt709, Transfer::Linear, Transfer::Srgb, Transfer::Pq, Transfer::Hlg].map(Transfer::to_code), [1, 8, 13, 16, 18]);
assert_eq!(
[Primaries::Bt709, Primaries::Bt601_625, Primaries::Bt601_525, Primaries::Bt2020, Primaries::P3D65].map(Primaries::to_code),
[1, 5, 6, 9, 12]
);
}
#[test]
fn primaries_codes() {
assert_eq!(Primaries::from_code(1), Some(Primaries::Bt709));
assert_eq!(Primaries::from_code(5), Some(Primaries::Bt601_625));
assert_eq!(Primaries::from_code(6), Some(Primaries::Bt601_525));
assert_eq!(Primaries::from_code(7), Some(Primaries::Bt601_525));
assert_eq!(Primaries::from_code(9), Some(Primaries::Bt2020));
assert_eq!(Primaries::from_code(12), Some(Primaries::P3D65));
for c in [0, 2, 3, 4, 8, 10, 11, 13, 22, 255] {
assert_eq!(Primaries::from_code(c), None, "{c}");
}
}
#[test]
fn written_codes_read_back() {
for m in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] {
assert_eq!(Matrix::from_code(m.to_code()), Some(m));
}
for t in [Transfer::Bt709, Transfer::Srgb, Transfer::Linear, Transfer::Pq, Transfer::Hlg] {
assert_eq!(Transfer::from_code(t.to_code()), Some(t));
}
for p in [Primaries::Bt709, Primaries::Bt601_625, Primaries::Bt601_525, Primaries::Bt2020, Primaries::P3D65] {
assert_eq!(Primaries::from_code(p.to_code()), Some(p));
}
}
}
+56 -8
View File
@@ -1,7 +1,7 @@
//! Authenticated JSON-lines request framing and dispatch for local control services.
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
use serde_json::{Value, json};
use std::io::{BufRead, BufReader, Read, Write};
use std::io::{BufRead, BufReader, BufWriter, Read, Write};
use subtle::ConstantTimeEq;
/// Whether a session token has the control protocol's 64 hexadecimal character form.
@@ -72,12 +72,14 @@ pub enum ReadFailure {
Rejected(String),
}
/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped).
/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped, and a `\r`
/// before it). The `\r\n` or `\n` does not count toward `max`.
/// `Ok(false)` at end of stream; `Err` when the line is too long or the read fails.
pub fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -> Result<bool, ReadFailure> {
buf.clear();
// `take` bounds the bytes buffered for one line: a peer can't make us allocate more than `max`.
let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1);
// `take` bounds the bytes buffered for one line: a peer can't make us allocate more than
// `max + 2`, the line and its `\r\n`.
let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(2);
let n = reader.take(limit).read_until(b'\n', buf).map_err(|e| match e.kind() {
std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock => ReadFailure::Timeout,
_ => ReadFailure::Rejected(e.to_string()),
@@ -90,12 +92,11 @@ pub fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usiz
if buf.last() == Some(&b'\r') {
buf.pop();
}
return Ok(true);
}
if buf.len() > max {
return Err(ReadFailure::Rejected(format!("request line longer than {max} bytes; closing the connection")));
}
// Last line without a newline, then end of stream.
// A complete line, or the last line without a newline, then end of stream.
Ok(true)
}
@@ -120,18 +121,30 @@ pub fn serve_lines<R: Read, W: Write>(read: R, mut out: W, token: &str, max_line
if let Some(o) = r.as_object_mut() {
o.insert("id".into(), id);
}
if writeln!(out, "{r}").and_then(|()| out.flush()).is_err() {
if write_line(&mut out, &r).is_err() {
return;
}
continue;
}
},
};
let _ = writeln!(out, "{}", json!({"ok": false, "error": reject})).and_then(|()| out.flush());
let _ = write_line(&mut out, &json!({"ok": false, "error": reject}));
return;
}
}
/// Write `reply` and its newline to `out` through a buffer, then flush. `writeln!` with a JSON
/// value writes each string, number and separator separately, which is one system call apiece on
/// an unbuffered socket. The buffer holds at most `REPLY_BUFFER` bytes, so a large reply is not
/// copied whole before it is sent.
fn write_line(out: &mut impl Write, reply: &Value) -> std::io::Result<()> {
const REPLY_BUFFER: usize = 64 * 1024;
let mut buffered = BufWriter::with_capacity(REPLY_BUFFER, out);
serde_json::to_writer(&mut buffered, reply).map_err(std::io::Error::other)?;
buffered.write_all(b"\n")?;
buffered.flush()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -193,6 +206,36 @@ mod tests {
assert_eq!(calls, 1);
}
#[test]
fn replies_reach_the_writer_in_few_bounded_writes() {
struct Writes(Vec<Vec<u8>>);
impl Write for Writes {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.push(buf.to_vec());
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let input = b"{\"id\":1,\"method\":\"tree\",\"token\":\"s\"}\n{\"id\":2,\"method\":\"tree\"}\n";
let mut writes = Writes(Vec::new());
serve_lines(&input[..], &mut writes, "s", 1024, |_, _| Some(json!({"ok": true, "result": {"names": ["a", "b", "c"], "sizes": [1, 2, 3]}})));
assert_eq!(writes.0.len(), 2, "one write for the reply and one for the rejection");
for line in &writes.0 {
assert_eq!(line.last(), Some(&b'\n'));
serde_json::from_slice::<Value>(line).unwrap();
}
// A large reply goes out in a few buffer-sized writes, never as one whole copy.
let items: Vec<u32> = (0..100_000).collect();
let mut writes = Writes(Vec::new());
serve_lines(&b"{\"method\":\"tree\",\"token\":\"s\"}\n"[..], &mut writes, "s", 1024, |_, _| Some(json!({"ok": true, "result": items})));
let total: usize = writes.0.iter().map(Vec::len).sum();
assert!(writes.0.len() < items.len() / 100);
assert!(writes.0.iter().all(|w| w.len() < total));
let reply: Value = serde_json::from_slice(&writes.0.concat()).unwrap();
assert_eq!(reply["result"].as_array().map(Vec::len), Some(items.len()));
}
#[test]
fn client_request_and_reply_keep_optional_fields() {
let line = request_line(7, None, "status", &json!({"a": 1}));
assert_eq!(serde_json::from_str::<Value>(&line).unwrap(), json!({"id": 7, "token": null, "method": "status", "params": {"a": 1}}));
@@ -226,6 +269,11 @@ mod tests {
assert_eq!(read_bounded_line(&mut &b"abc"[..], &mut buf, 3), Ok(true));
assert_eq!(buf, b"abc");
assert!(matches!(read_bounded_line(&mut &b"abcd"[..], &mut buf, 3), Err(ReadFailure::Rejected(_))));
// The cap counts the line without its `\r\n` or `\n`.
assert_eq!(read_bounded_line(&mut &b"abc\r\n"[..], &mut buf, 3), Ok(true));
assert_eq!(buf, b"abc");
assert!(matches!(read_bounded_line(&mut &b"abcd\n"[..], &mut buf, 3), Err(ReadFailure::Rejected(_))));
assert!(matches!(read_bounded_line(&mut &b"abcd\r\n"[..], &mut buf, 3), Err(ReadFailure::Rejected(_))));
let mut out = Vec::new();
serve_lines(&b"{broken}\n"[..], &mut out, "secret", 1024, |_, _| panic!("must not dispatch"));
let reply: Value = serde_json::from_slice(&out).unwrap();
+2
View File
@@ -24,6 +24,8 @@ serde_json = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# The per-launch control token: 32 random bytes from the operating system (MIT OR Apache-2.0).
getrandom = "0.3"
# The request-line reader and the reply's result, shared with servers built on it (MIT OR Apache-2.0, ours).
craft-control-protocol = { workspace = true }
# The launcher's app list, read in one place for the launcher, the gateway and every app (MIT OR Apache-2.0, ours).
craft-ai-agents = { workspace = true, optional = true }
craft-atomic = { workspace = true, optional = true }
+3 -6
View File
@@ -117,13 +117,10 @@ impl Request {
}
}
/// A control reply as a call's result: its `result`, or its `error`.
/// A control reply as a call's result: its `result`, or its `error`
/// ([`craft_control_protocol::reply_result`]).
pub fn outcome(v: &Value) -> Result<Value, String> {
if v.get("ok").and_then(Value::as_bool) == Some(true) {
Ok(v.get("result").cloned().unwrap_or(Value::Null))
} else {
Err(v.get("error").and_then(Value::as_str).unwrap_or("error").to_string())
}
craft_control_protocol::reply_result(v)
}
/// A request the app said is still running. Its reply will come on this connection, through
+79 -28
View File
@@ -10,6 +10,7 @@ use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};
use craft_control_protocol::ReadFailure;
use serde_json::{Value, json};
use crate::Effect;
@@ -215,35 +216,19 @@ pub fn new_token() -> Option<String> {
Some(bytes.iter().map(|b| format!("{b:02x}")).collect())
}
/// One line without its newline, or `None` at the end of the stream. A client that sends
/// gigabytes with no newline would otherwise make this thread allocate until the process is
/// killed, so the line is refused as soon as it passes `max`.
/// One line without its newline (and a `\r` before it), or `None` at the end of the stream, read
/// with [`craft_control_protocol::read_bounded_line`]. A line of more than `max` bytes, not
/// counting its `\r\n` or `\n`, is refused with `InvalidData`, and at most `max + 2` bytes of it
/// are buffered, so a client that sends gigabytes with no newline cannot make this thread
/// allocate until the process is killed. A read that times out (the token deadline) fails with
/// `TimedOut`.
fn read_line(r: &mut impl BufRead, max: usize) -> std::io::Result<Option<Vec<u8>>> {
let mut line = Vec::new();
loop {
let (done, used) = {
let available = r.fill_buf()?;
if available.is_empty() {
return Ok((!line.is_empty()).then_some(line));
}
match available.iter().position(|b| *b == b'\n') {
Some(i) => {
line.extend_from_slice(available.get(..i).unwrap_or(&[]));
(true, i + 1)
}
None => {
line.extend_from_slice(available);
(false, available.len())
}
}
};
r.consume(used);
if done {
return Ok(Some(line));
}
if line.len() > max {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "request too large"));
}
match craft_control_protocol::read_bounded_line(r, &mut line, max) {
Ok(true) => Ok(Some(line)),
Ok(false) => Ok(None),
Err(ReadFailure::Timeout) => Err(std::io::ErrorKind::TimedOut.into()),
Err(ReadFailure::Rejected(e)) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e)),
}
}
@@ -1335,7 +1320,73 @@ mod tests {
let mut r = BufReader::new(flood.as_slice());
let e = read_line(&mut r, MAX_LINE).unwrap_err();
assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
assert!(e.to_string().contains("request too large"), "{e}");
assert!(e.to_string().contains(&format!("longer than {MAX_LINE} bytes")), "{e}");
}
/// The cap is exact: a line of `max` bytes is read, and one byte more is refused even when its
/// newline arrives in the same read as the rest of it. The `\r\n` or `\n` after the line does
/// not count toward the cap.
#[test]
fn the_cap_holds_for_a_line_read_at_once() {
for end in [&b"\n"[..], &b"\r\n"[..]] {
let mut fits = vec![b'A'; 1000];
fits.extend_from_slice(end);
assert_eq!(read_line(&mut BufReader::new(fits.as_slice()), 1000).unwrap().unwrap().len(), 1000);
let mut over = vec![b'A'; 1001];
over.extend_from_slice(end);
let e = read_line(&mut BufReader::new(over.as_slice()), 1000).unwrap_err();
assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
}
}
/// The cap holds when the line arrives a few bytes at a time, and at the end of the stream:
/// a `\r\n` split across two reads does not count toward it, and a last line of one byte
/// more than the cap with no newline is refused.
#[test]
fn the_cap_holds_across_reads() {
let mut fits = vec![b'A'; 1000];
fits.extend_from_slice(b"\r\n");
assert_eq!(read_line(&mut BufReader::with_capacity(7, fits.as_slice()), 1000).unwrap().unwrap().len(), 1000);
let last = vec![b'A'; 1001];
let e = read_line(&mut BufReader::with_capacity(7, last.as_slice()), 1000).unwrap_err();
assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
}
/// A read interrupted by a signal is tried again instead of ending the connection, and a
/// `\r` before the newline is not part of the line.
#[test]
fn interrupted_reads_are_retried() {
struct Interrupting(Vec<&'static [u8]>);
impl std::io::Read for Interrupting {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if self.0.is_empty() {
return Ok(0);
}
let chunk = self.0.remove(0);
if chunk.is_empty() {
return Err(std::io::ErrorKind::Interrupted.into());
}
buf[..chunk.len()].copy_from_slice(chunk);
Ok(chunk.len())
}
}
let mut r = BufReader::new(Interrupting(vec![b"", b"{\"a\"", b"", b":1}\r\n"]));
assert_eq!(read_line(&mut r, MAX_LINE).unwrap().unwrap(), b"{\"a\":1}");
assert!(read_line(&mut r, MAX_LINE).unwrap().is_none());
}
/// A read that times out before the token is shown fails with `TimedOut`, which closes the
/// connection without a reply.
#[test]
fn timed_out_reads_report_timed_out() {
struct Slow;
impl std::io::Read for Slow {
fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
Err(std::io::ErrorKind::WouldBlock.into())
}
}
let e = read_line(&mut BufReader::new(Slow), MAX_LINE).unwrap_err();
assert_eq!(e.kind(), std::io::ErrorKind::TimedOut);
}
/// Ordinary framing: lines split on newlines, blank lines kept, no trailing newline needed.
+17
View File
@@ -34,6 +34,7 @@ craft-draw = { workspace = true, optional = true }
craft-ecproj-format = { workspace = true, optional = true }
craft-font-catalog = { workspace = true, optional = true }
craft-font-manager = { workspace = true, optional = true }
craft-font-os-windows = { workspace = true, optional = true }
craft-font-store = { workspace = true, optional = true }
craft-font-subset = { workspace = true, optional = true }
craft-imaging = { workspace = true, optional = true }
@@ -228,6 +229,9 @@ craft-ppt-binary = { workspace = true, optional = true }
craft-sqlite = { workspace = true, optional = true }
craft-audio-dsp = { workspace = true, optional = true }
craft-sbs = { workspace = true, optional = true }
craft-ease = { workspace = true, optional = true }
craft-i18n-build = { workspace = true, optional = true }
craft-pbr = { workspace = true, optional = true }
[features]
ui = [
@@ -441,6 +445,9 @@ dwg = ["dep:craft-dwg"]
dxf = ["dep:craft-dxf"]
ease = ["dep:craft-ease"]
ease-serde = ["ease", "craft-ease/serde"]
ecproj-format = ["dep:craft-ecproj-format"]
elf = ["dep:craft-elf"]
@@ -500,6 +507,8 @@ font-catalog-system = ["font-catalog", "craft-font-catalog/system"]
font-manager = ["dep:craft-font-manager"]
font-os-windows = ["dep:craft-font-os-windows"]
font-store = ["dep:craft-font-store"]
font-store-bundled-index = ["font-store", "craft-font-store/bundled-index"]
@@ -554,6 +563,8 @@ http-url = ["dep:craft-http-url"]
i18n-collate = ["craft-i18n/collate"]
i18n-build = ["dep:craft-i18n-build"]
ical = ["dep:craft-ical"]
idml = ["dep:craft-idml"]
@@ -561,6 +572,7 @@ idml = ["dep:craft-idml"]
image-codecs = ["dep:craft-image-codecs"]
image-codecs-avif = ["image-codecs", "craft-image-codecs/avif"]
image-codecs-avif-decode = ["image-codecs", "craft-image-codecs/avif-decode"]
image-codecs-cms = ["image-codecs", "craft-image-codecs/cms"]
image-codecs-corpus = ["image-codecs", "craft-image-codecs/corpus"]
image-codecs-heif = ["image-codecs", "craft-image-codecs/heif"]
image-codecs-jxl = ["image-codecs", "craft-image-codecs/jxl"]
@@ -663,6 +675,7 @@ odf = ["dep:craft-odf"]
odf-text = ["odf", "craft-odf/text"]
ods = ["dep:craft-ods"]
ods-test-support = ["ods", "craft-ods/test-support"]
offcrypto = ["dep:craft-offcrypto"]
@@ -677,6 +690,9 @@ pages = ["dep:craft-pages", "keymap", "text"]
palette = ["dep:craft-palette"]
pbr = ["dep:craft-pbr"]
pbr-parallel = ["pbr", "craft-pbr/parallel"]
pcap = ["dep:craft-pcap"]
pcraft-bundle = ["dep:craft-pcraft-bundle"]
@@ -939,6 +955,7 @@ ui-system_fonts = ["ui", "craft-ui/system_fonts"]
ui-testing = ["ui", "craft-ui/testing"]
update = ["dep:craft-update"] # native only: downloads and installs through getrandom without wasm support
update-local-mirror = ["update", "craft-update/local-mirror"]
update-oci_migration = ["update", "craft-update/oci_migration"]
usd = ["dep:craft-usd"]
+1 -1
View File
@@ -3,7 +3,7 @@
/// The egui fork the library is built and tested with. Apps patch egui to exactly this.
pub const GIT: &str = "https://github.com/storytold/egui.git";
/// The commit of [`GIT`].
pub const REV: &str = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec";
pub const REV: &str = "b9770908e0f304896f9658d239a7b29cf8af1564";
/// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]).
pub const PACKAGES: &[&str] = &[
+8
View File
@@ -103,6 +103,8 @@ pub use craft_drawingml as drawingml;
pub use craft_dwg as dwg;
#[cfg(feature = "dxf")]
pub use craft_dxf as dxf;
#[cfg(feature = "ease")]
pub use craft_ease as ease;
#[cfg(feature = "ecproj-format")]
pub use craft_ecproj_format as ecproj_format;
#[cfg(feature = "elf")]
@@ -139,6 +141,8 @@ pub use craft_flow as flow;
pub use craft_font_catalog as font_catalog;
#[cfg(feature = "font-manager")]
pub use craft_font_manager as font_manager;
#[cfg(feature = "font-os-windows")]
pub use craft_font_os_windows as font_os_windows;
#[cfg(feature = "font-store")]
pub use craft_font_store as font_store;
#[cfg(feature = "font-subset")]
@@ -179,6 +183,8 @@ pub use craft_html as html;
#[cfg(feature = "http-url")]
pub use craft_http_url as http_url;
pub use craft_i18n as i18n;
#[cfg(feature = "i18n-build")]
pub use craft_i18n_build as i18n_build;
#[cfg(feature = "ical")]
pub use craft_ical as ical;
#[cfg(feature = "idml")]
@@ -265,6 +271,8 @@ pub use craft_ora as ora;
pub use craft_pages as pages;
#[cfg(feature = "palette")]
pub use craft_palette as palette;
#[cfg(feature = "pbr")]
pub use craft_pbr as pbr;
#[cfg(feature = "pcap")]
pub use craft_pcap as pcap;
#[cfg(feature = "pcraft-bundle")]
+2
View File
@@ -34,6 +34,8 @@ impl Reader<'_> {
"w:linkStyles" => s.link_styles = on_off(k),
"w:removePersonalInformation" => s.remove_personal_info = on_off(k),
"w:removeDateAndTime" => s.remove_date_time = on_off(k),
"w:hideSpellingErrors" => s.hide_spelling_errors = on_off(k),
"w:hideGrammaticalErrors" => s.hide_grammar_errors = on_off(k),
"w:compat" => {
s.allow_space_of_same_style_in_table = k.child("w:allowSpaceOfSameStyleInTable").is_some_and(on_off);
// Only Word's own setting: another `w:uri` names a different application's.
+7
View File
@@ -54,6 +54,13 @@ pub(super) fn settings_xml(doc: &Document, footnotes: bool, endnotes: bool, temp
if s.gutter_at_top {
w.empty("w:gutterAtTop", &[]);
}
// After `w:gutterAtTop` and before `w:proofState` in CT_Settings.
if s.hide_spelling_errors {
w.empty("w:hideSpellingErrors", &[]);
}
if s.hide_grammar_errors {
w.empty("w:hideGrammaticalErrors", &[]);
}
if let Some(id) = template_rel {
w.empty("w:attachedTemplate", &[("r:id", id)]);
}
+2
View File
@@ -20,6 +20,8 @@ const OWNED: &[&str] = &[
"w:displayBackgroundShape",
"w:mirrorMargins",
"w:gutterAtTop",
"w:hideSpellingErrors",
"w:hideGrammaticalErrors",
"w:attachedTemplate",
"w:linkStyles",
"w:mailMerge",
+47
View File
@@ -204,3 +204,50 @@ fn do_not_track_moves_round_trips() {
assert!(s.contains("<w:doNotTrackMoves/>"), "{s}");
assert!(!craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap().settings.track_moves);
}
/// Hide spelling errors and Hide grammar errors in this document only (`w:hideSpellingErrors`,
/// `w:hideGrammaticalErrors`) are read, written once each (before `w:proofState` in a merged
/// part), written in a generated part, and left out when they are turned off.
#[test]
fn hidden_proofing_errors_round_trip() {
let original = SETTINGS.replace("<w:proofState", r#"<w:hideSpellingErrors/><w:hideGrammaticalErrors w:val="1"/><w:proofState"#);
let mut doc = craft_docx::read(&with_settings(&original)).unwrap();
assert!(doc.settings.hide_spelling_errors && doc.settings.hide_grammar_errors);
let s = text(&save(&doc), "word/settings.xml");
assert_eq!(s.matches("hideSpellingErrors").count(), 1, "{s}");
assert_eq!(s.matches("hideGrammaticalErrors").count(), 1, "{s}");
assert!(pos(&s, "<w:hideSpellingErrors/>") < pos(&s, "<w:hideGrammaticalErrors/>"));
assert!(pos(&s, "<w:hideGrammaticalErrors/>") < pos(&s, "<w:proofState"), "{s}");
assert!(s.contains("ClauseSet"), "a merged part: {s}");
doc.settings.hide_spelling_errors = false;
doc.settings.hide_grammar_errors = false;
let s = text(&save(&doc), "word/settings.xml");
assert!(!s.contains("hideSpellingErrors") && !s.contains("hideGrammaticalErrors"), "{s}");
// Turned on in a part that lacks them: inserted once each, before `w:proofState`.
let mut doc = craft_docx::read(&with_settings(SETTINGS)).unwrap();
assert!(!doc.settings.hide_spelling_errors && !doc.settings.hide_grammar_errors);
doc.settings.hide_spelling_errors = true;
doc.settings.hide_grammar_errors = true;
let s = text(&save(&doc), "word/settings.xml");
assert_eq!(s.matches("hideSpellingErrors").count(), 1, "{s}");
assert_eq!(s.matches("hideGrammaticalErrors").count(), 1, "{s}");
assert!(pos(&s, "removeDateAndTime") < pos(&s, "<w:hideSpellingErrors/>"), "{s}");
assert!(pos(&s, "<w:hideGrammaticalErrors/>") < pos(&s, "<w:proofState"), "{s}");
// `w:val="false"` and `w:val="0"` show them.
let off = SETTINGS.replace("<w:proofState", r#"<w:hideSpellingErrors w:val="false"/><w:hideGrammaticalErrors w:val="0"/><w:proofState"#);
let read = craft_docx::read(&with_settings(&off)).unwrap();
assert!(!read.settings.hide_spelling_errors && !read.settings.hide_grammar_errors);
let s = text(&save(&read), "word/settings.xml");
assert!(!s.contains("hideSpellingErrors") && !s.contains("hideGrammaticalErrors"), "{s}");
// A document of our own: absent by default, written when on, and read back.
let mut doc = craft_wordmodel::Document::new();
assert!(!text(&save(&doc), "word/settings.xml").contains("hideSpellingErrors"));
doc.settings.hide_grammar_errors = true;
let s = text(&save(&doc), "word/settings.xml");
assert!(s.contains("<w:hideGrammaticalErrors/>") && !s.contains("hideSpellingErrors"), "{s}");
let back = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap();
assert!(back.settings.hide_grammar_errors && !back.settings.hide_spelling_errors);
}
+1 -1
View File
@@ -13,7 +13,7 @@ startup and call `serve_if_asked()` before normal argument handling. Subsequent
is contained to that child. The worker has no operating-system memory limit yet. Without a
configured worker, conversions are refused rather than run in the current process: call
`allow_in_process()` only for input that is known to be trusted (tests, or bytes this process
produced itself). Coordinates, once a worker is configured but cannot start, also fail closed.
produced itself). Conversions, once a worker is configured but cannot start, also fail closed.
The bridge is not built for `wasm32` or FreeBSD/aarch64. Those targets retain the public API and
return a clear unsupported-build error. The `acadrust` 0.6.6 dependency is used unmodified under
+8 -4
View File
@@ -6,8 +6,9 @@
//! that reads one request from standard input and writes one reply to standard output. A file that
//! kills the worker then costs that one open or save, and every other open drawing stays safe.
//!
//! Without a worker [`decode`] and [`encode_as`] refuse rather than run the conversion in the
//! calling process, because the third-party code is the part that can end a process.
//! Without a worker [`decode`], [`encode_as`], [`encode_noted`] and [`encode_kept_noted`] refuse
//! rather than run the conversion in the calling process, because the third-party code is the part
//! that can end a process.
//! [`allow_in_process`] is the explicit exception, for input the caller knows is trusted (tests, or
//! bytes this process produced itself). There's no memory limit on the worker yet: that takes
//! per-platform system calls, which `unsafe_code = "forbid"` keeps out of this crate.
@@ -62,7 +63,9 @@ pub fn use_worker(program: PathBuf, args: Vec<OsString>) {
}
/// Use a copy of this program as the worker, started with [`WORKER_ARG`]. If its path can't be
/// found, the reader and writer stay in this process.
/// found, the worker setting does not change. When no worker was set before, [`decode`],
/// [`encode_as`], [`encode_noted`] and [`encode_kept_noted`] then refuse unless
/// [`allow_in_process`] was called.
pub fn use_own_worker() {
match std::env::current_exe() {
Ok(program) => use_worker(program, vec![WORKER_ARG.into()]),
@@ -70,7 +73,8 @@ pub fn use_own_worker() {
}
}
/// Let [`decode`] and [`encode_as`] run the conversion in this process when no worker is set.
/// Let [`decode`], [`encode_as`], [`encode_noted`] and [`encode_kept_noted`] run the conversion in
/// this process when no worker is set.
///
/// This opts out of the isolation the crate exists for: the third-party code allocates from sizes
/// a hostile file declares, and a failed allocation ends the process. Call it for input the caller
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "craft-ease"
description = "Easing curves, keyed tracks, motion paths and springs for animation: named eases, cubic Bezier and speed/influence eases, editable custom curves, sampled tables, hold keys, constant-speed Bezier paths and an O(1) damped spring"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
[lints]
workspace = true
[features]
default = ["serde"]
# Reading and writing eases (spring eases included) and tracks with serde.
serde = ["dep:serde"]
[dependencies]
serde = { workspace = true, features = ["rc"], optional = true }
[dev-dependencies]
serde_json = { workspace = true }
+102
View File
@@ -0,0 +1,102 @@
# craft-ease
Easing curves, keyed tracks, constant-speed motion paths and damped springs for animation in the
Craft apps. The crate depends only on the standard library, with `serde` as an optional feature
(on by default). It builds for `wasm32-unknown-unknown`.
Its parts come from AniCraft and EffectCraft:
- `Easing`, `CustomEase`, `SampledEase` and the curve editing came from AniCraft's `anicraft-doc`
(`crates/doc/src/easing.rs`). They now use `f64` and the crate's own `Vec2`, the Back and
Elastic In Out curves follow the published equations, and `Hold` and `Spring` are new
variants.
- Speed and influence eases, hold keys and the constant-speed motion paths came from
EffectCraft's `effectcraft-keyframe` (`crates/keyframe/src/lib.rs`). `Track` takes any
`Animatable` value instead of the app's value type, and `MotionPath` continues in a straight
line past either end.
- `Spring` replaces AniCraft's stepped spring (`crates/doc/src/spring.rs`) with the exact
solution of the damped spring equation, so a step costs O(1) and any step length is stable.
Licensed under MIT OR Apache-2.0.
## Contents
- `Easing` maps linear progress `t` in `0..=1` to eased progress. The variants are no ease
(`Linear`), `Hold`, the Classic slider (−100 to +100), nine named families (Quad, Cubic, Quart,
Quint, Sine, Back, Circ, Bounce, Elastic) each In, Out and In Out, `CubicBezier` as the CSS
Easing Functions specification defines `cubic-bezier()`, an editable `CustomEase`, a
`SampledEase` table and a physical `SpringEase`. `Easing::apply(t)` returns exactly 0 for
`t <= 0` and NaN, and exactly 1 for `t >= 1`. It does not allocate.
- `Easing::from_temporal` builds the cubic Bezier for a segment from the speed and influence of
its two sides (`TemporalEase`), as keyframe velocity dialogs give them. `Easing::temporal`
reads them back.
- `Track<T>` holds keys of any `Animatable` value (`f32`, `f64`, `Vec2`, `[f32; N]`,
`[f64; N]`), each with the ease to the next key. `Track::sample` is a binary search and does
not allocate.
- `MotionPath` is a chain of cubic Bezier segments with an arc-length table per segment, built
once. `point_at` and `point_at_length` move at constant speed along it and continue in a
straight line past either end. `MotionPath::through` sets the handles of a smooth path through
a list of anchors.
- `Spring` and `SpringState` move a value toward a target. `SpringState::step` applies the exact
solution of the damped spring equation over the step, so a step costs O(1), any step length is
stable, and many short steps give the same value as one long one.
## Checked and lenient constructors
Every type has a checked constructor that returns `EaseError` for a value that is not finite or
is out of range: `Easing::cubic_bezier`, `Easing::from_temporal`, `Easing::spring`,
`CustomEase::try_new`, `SampledEase::try_new`, `Track::from_keys`, `MotionPath::new`,
`Spring::new` and `Spring::from_physical`. `CustomEase::new` and `SampledEase::new` repair what
they are given instead, and files are read through the same repairs. Reading a track refuses a
file with more than `MAX_TRACK_KEYS` keys while it reads.
## Limits
| Constant | Value |
| --- | --- |
| `MAX_EASE_Y` | 10 (eased values stay within ±10) |
| `MAX_EASE_POINTS` | 64 points in a custom ease |
| `MAX_EASE_SAMPLES` | 1,025 samples in a sampled ease |
| `MAX_TRACK_KEYS` | 100,000 keys in a track |
| `MAX_PATH_SEGMENTS` | 10,000 segments in a motion path |
| `MAX_SPRING_HZ` | 10,000 swings a second |
| `MAX_DAMPING_RATIO` | 1,000,000 |
| `MIN_INFLUENCE` | 0.001 |
## Sources
- The named families are the easing equations published by Robert Penner. Back In Out and
Elastic In Out use the published In Out equations, which scale Back's overshoot by 1.525 and
give Elastic a longer period.
- `CubicBezier` follows the CSS Easing Functions Level 1 specification.
## Details
- Values are `f64` throughout.
- The `serde` feature reads and writes `Easing` (spring eases included) and `Track`.
`MotionPath`, `Spring` and `SpringState` are not serialized.
- Serialized eases keep their form: presets are strings such as `"QuadIn"`, and `Classic`,
`CubicBezier`, `Custom` and `Sampled` are one-key objects. `Hold` and `Spring` are the last
variants. A track is read from its fields by name or in order.
- `Easing::apply` returns exactly 0 and 1 at the ends for every variant, and `+∞` gives 1.
- `CubicBezier` keeps y1 and y2 within ±10 when it is evaluated. Its solver inverts the curve
with both handles at full reach in closed form, and otherwise stops within 1e-12 of the span
in at most 64 steps.
- A sampled ease's name drops control characters, bidirectional overrides and invisible format
characters such as zero-width spaces. A sampled ease with no name left is named "Sampled ease".
Reading a file keeps the first 65,536 entries of a custom ease's points or a sampled ease's
values and skips the rest.
- Without the `serde` feature the crate has no dependencies, and its tests that read and write
files are left out.
- `Track` takes `Easing::Hold` for held keys and treats −0 and +0 as one time. It samples keys
at opposite ends of the `f64` range without overflow, and returns `EaseError::Overflow` when
an overshooting ease carries a value past what its type holds.
- Speed and influence become a `CubicBezier` (`Easing::from_temporal`), with the influence
allowed from 0.001 to 1 on each side, including a sum above 1.
- Motion paths are measured by Gauss-Legendre quadrature per table cell with Newton refinement.
`MotionPath::through` sets each handle to a sixth of the line between the anchor's neighbors.
A segment whose handles lie on its chord is treated as a straight line.
- `Spring::from_physical(mass, stiffness, damping)` takes a mass, a stiffness and a damping
coefficient. A spring ease that is still moving after 10 seconds has the distance it is still
off taken out evenly over the ease, so it reaches 1 without a jump. Any other spring ease is
within about 0.1 % of 1 just before it reaches 1.
+450
View File
@@ -0,0 +1,450 @@
//! [`CustomEase`]: an editable curve of several Bezier segments from (0, 0) to (1, 1).
use crate::{EaseError, Vec2, bez, solve_monotonic};
/// Most points (anchors) a custom ease keeps; longer curves are thinned evenly.
pub const MAX_EASE_POINTS: usize = 64;
/// Values a custom ease (and its handles) may reach: overshoot well past 0..1, never unbounded.
pub const MAX_EASE_Y: f64 = 10.0;
/// Most points read from a file or a caller before thinning (bounds the sort).
const MAX_EASE_INPUT: usize = 65_536;
/// A point of a custom ease: where it is (x = time, y = progress), its handles as offsets from
/// it (in toward the previous point, out toward the next), and whether it is smooth (handles in
/// line, moved together) or a corner. In files the in handle is `"in"`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EasePoint {
pub at: Vec2,
#[cfg_attr(feature = "serde", serde(rename = "in", default))]
pub h_in: Vec2,
#[cfg_attr(feature = "serde", serde(default))]
pub out: Vec2,
#[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "is_false"))]
pub smooth: bool,
}
#[cfg(feature = "serde")]
fn is_false(b: &bool) -> bool {
!*b
}
/// Which handle of a point.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Handle {
In,
Out,
}
/// A custom ease: Bezier segments through its points, from (0, 0) to (1, 1).
///
/// Always valid, however it was made: 2 to [`MAX_EASE_POINTS`] finite points sorted by x, the
/// ends fixed at (0, 0) and (1, 1), every handle reaching toward its neighbor in x and every
/// segment's x running forwards (so time never runs backwards), and every value within
/// ±[`MAX_EASE_Y`]. A handle whose x lies between its point and that neighbor always keeps x
/// running forwards; a handle may reach past the neighbor (as a piece of a split segment can)
/// only while its segment's x still runs forwards. Reading a file repairs a curve the way
/// [`CustomEase::new`] does.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(from = "CustomEaseFile"))]
pub struct CustomEase {
points: Vec<EasePoint>,
}
#[cfg(feature = "serde")]
#[derive(serde::Deserialize)]
struct CustomEaseFile {
#[serde(default, deserialize_with = "read_points")]
points: Vec<EasePoint>,
}
/// The first [`MAX_EASE_INPUT`] points of a file's list, the way [`CustomEase::new`] keeps them.
#[cfg(feature = "serde")]
fn read_points<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<EasePoint>, D::Error> {
crate::read_first(d, MAX_EASE_INPUT)
}
#[cfg(feature = "serde")]
impl From<CustomEaseFile> for CustomEase {
fn from(f: CustomEaseFile) -> CustomEase {
CustomEase::new(f.points)
}
}
impl Default for CustomEase {
fn default() -> CustomEase {
CustomEase::linear()
}
}
impl CustomEase {
/// The straight line, its handles a third of the way along.
pub fn linear() -> CustomEase {
CustomEase::linear_points()
}
/// One segment with handles `(x1, y1)` and `(x2, y2)` in the unit box (x is clamped to
/// `0..=1`).
pub fn from_bezier(x1: f64, y1: f64, x2: f64, y2: f64) -> CustomEase {
let (x1, x2) = (x1.clamp(0.0, 1.0), x2.clamp(0.0, 1.0));
CustomEase::new(vec![
EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::new(x1, y1), smooth: false },
EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(x2 - 1.0, y2 - 1.0), out: Vec2::ZERO, smooth: false },
])
}
/// The curve of absolute points `[p0, c1, c2, p1, c3, c4, p2, …]` (3n + 1 of them): `None`
/// when the count is wrong.
pub fn from_flat(pts: &[Vec2]) -> Option<CustomEase> {
if pts.len() < 4 || pts.len() % 3 != 1 || pts.len() > MAX_EASE_INPUT {
return None;
}
let mut out: Vec<EasePoint> = Vec::with_capacity(pts.len() / 3 + 1);
for (i, at) in pts.iter().enumerate().step_by(3) {
let h_in = if i == 0 { Vec2::ZERO } else { pts.get(i - 1).map_or(Vec2::ZERO, |c| *c - *at) };
let h_out = pts.get(i + 1).map_or(Vec2::ZERO, |c| *c - *at);
// Handles in line (opposite ways) make a smooth point, as an editor would draw it.
let smooth = h_in.length() > 1e-6 && h_out.length() > 1e-6 && (h_in.normalized().dot(h_out.normalized()) + 1.0).abs() < 1e-3;
out.push(EasePoint { at: *at, h_in, out: h_out, smooth });
}
Some(CustomEase::new(out))
}
/// A curve from points a caller supplies, checked: an error for a point or handle that is
/// not finite, fewer than 2 points or more than [`MAX_EASE_POINTS`]. The points are then
/// sorted, the ends pinned and the handles brought within reach as [`CustomEase::new`] does.
pub fn try_new(pts: Vec<EasePoint>) -> Result<CustomEase, EaseError> {
if pts.iter().any(|p| !(p.at.is_finite() && p.h_in.is_finite() && p.out.is_finite())) {
return Err(EaseError::NotFinite("ease point"));
}
if pts.len() < 2 {
return Err(EaseError::TooFew { what: "a custom ease", need: 2 });
}
if pts.len() > MAX_EASE_POINTS {
return Err(EaseError::Full(MAX_EASE_POINTS));
}
Ok(CustomEase::new(pts))
}
/// A valid curve from any points, as a file holds them (see the type's docs): non-finite
/// points are dropped and non-finite handles zeroed, the rest sorted by x, a curve longer
/// than [`MAX_EASE_POINTS`] thinned evenly, the ends pinned and every handle brought within
/// reach. Fewer than two points make the straight line.
pub fn new(mut pts: Vec<EasePoint>) -> CustomEase {
pts.truncate(MAX_EASE_INPUT);
pts.retain(|p| p.at.is_finite());
for p in pts.iter_mut() {
p.at = Vec2::new(p.at.x.clamp(0.0, 1.0), p.at.y.clamp(-MAX_EASE_Y, MAX_EASE_Y));
if !p.h_in.is_finite() {
p.h_in = Vec2::ZERO;
}
if !p.out.is_finite() {
p.out = Vec2::ZERO;
}
}
pts.sort_by(|a, b| a.at.x.total_cmp(&b.at.x));
if pts.len() > MAX_EASE_POINTS {
let n = pts.len();
let keep: Vec<usize> = (0..MAX_EASE_POINTS).map(|k| k * (n - 1) / (MAX_EASE_POINTS - 1)).collect();
pts = keep.into_iter().filter_map(|i| pts.get(i).copied()).collect();
}
if pts.len() < 2 {
return CustomEase::linear_points();
}
if let Some(p) = pts.first_mut() {
p.at = Vec2::ZERO;
}
if let Some(p) = pts.last_mut() {
p.at = Vec2::new(1.0, 1.0);
}
let mut c = CustomEase { points: pts };
// A point marked smooth whose handles are not in line is a corner: it loses the mark
// before the handles are brought within reach, so they are clipped as a corner's, and
// again if bringing them within reach put them out of line.
c.clear_broken_smooth();
c.clamp_handles();
c.clear_broken_smooth();
c
}
/// Clears the smooth mark of every end and of every point whose handles are not in line.
fn clear_broken_smooth(&mut self) {
let n = self.points.len();
for (i, p) in self.points.iter_mut().enumerate() {
if p.smooth && (i == 0 || i + 1 == n || !handles_in_line(p.h_in, p.out)) {
p.smooth = false;
}
}
}
/// [`CustomEase::linear`] built directly (so [`CustomEase::new`] does not recurse).
fn linear_points() -> CustomEase {
let third = 1.0 / 3.0;
CustomEase {
points: vec![
EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::new(third, third), smooth: false },
EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(-third, -third), out: Vec2::ZERO, smooth: false },
],
}
}
/// Brings every handle within reach (see the type's docs): each handle toward its neighbor
/// in x and within ±[`MAX_EASE_Y`], then, in a segment whose x would run backwards, each
/// handle that reaches past the neighbor back to it. A smooth point's handles are shortened
/// along their own line, so they stay in line; a corner's are clipped.
fn clamp_handles(&mut self) {
let n = self.points.len();
for (i, p) in self.points.iter_mut().enumerate() {
let (lo, hi) = (-MAX_EASE_Y - p.at.y, MAX_EASE_Y - p.at.y);
p.h_in = if i == 0 { Vec2::ZERO } else { fit_y(Vec2::new(p.h_in.x.min(0.0), p.h_in.y), lo, hi, p.smooth) };
p.out = if i + 1 == n { Vec2::ZERO } else { fit_y(Vec2::new(p.out.x.max(0.0), p.out.y), lo, hi, p.smooth) };
}
for i in 1..n {
let (Some(a), Some(b)) = (self.points.get(i - 1).copied(), self.points.get(i).copied()) else { continue };
let span = b.at.x - a.at.x;
if runs_forwards(span, a.out.x, -b.h_in.x) {
continue;
}
if let Some(p) = self.points.get_mut(i - 1) {
p.out = fit_x(p.out, span, p.smooth);
}
if let Some(p) = self.points.get_mut(i) {
p.h_in = fit_x(p.h_in, span, p.smooth);
}
}
}
pub fn points(&self) -> &[EasePoint] {
&self.points
}
/// The control points of segment `i` (from point `i` to point `i + 1`), absolute; x runs
/// forwards along it (see the type's docs).
pub fn segment(&self, i: usize) -> Option<[Vec2; 4]> {
let (a, b) = (self.points.get(i)?, self.points.get(i.checked_add(1)?)?);
Some([a.at, a.at + a.out, b.at + b.h_in, b.at])
}
/// The segment that time `t` falls in.
fn segment_at(&self, t: f64) -> usize {
self.points.partition_point(|p| p.at.x <= t).saturating_sub(1).min(self.points.len().saturating_sub(2))
}
/// The eased value at time `t` (0 at the start, 1 at the end, anything between, overshoot
/// included). `t` outside `0..=1` is clamped, and NaN reads as 0.
pub fn apply(&self, t: f64) -> f64 {
if t.is_nan() || t <= 0.0 {
return 0.0;
}
if t >= 1.0 {
return 1.0;
}
let Some([p0, p1, p2, p3]) = self.segment(self.segment_at(t)) else { return t };
if p3.x <= p0.x {
return p3.y;
}
let s = solve_monotonic(t, [p0.x, p1.x, p2.x, p3.x]);
bez(s, [p0.y, p1.y, p2.y, p3.y])
}
/// Adds a point on the curve at time `t`, leaving its shape as it was (the segment is split
/// in two): the new curve and the point's index. `None` at the ends, on an existing point,
/// where the split cannot be placed at `t` (on a curve so flat there that its time cannot be
/// solved closely enough), or when the curve is full.
pub fn insert_at(&self, t: f64) -> Option<(CustomEase, usize)> {
if !(t > 0.0 && t < 1.0) || self.points.len() >= MAX_EASE_POINTS || self.points.iter().any(|p| p.at.x == t) {
return None;
}
let i = self.segment_at(t);
let [p0, p1, p2, p3] = self.segment(i)?;
let s = solve_monotonic(t, [p0.x, p1.x, p2.x, p3.x]);
// de Casteljau at s.
let (a, b, c) = (p0.lerp(p1, s), p1.lerp(p2, s), p2.lerp(p3, s));
let (d, e) = (a.lerp(b, s), b.lerp(c, s));
let m = d.lerp(e, s);
// Refused when the split cannot be placed at `t`: it lands on an anchor, or farther from
// `t` than a millionth of the way to the nearer anchor.
if !(m.x > p0.x && m.x < p3.x && (m.x - t).abs() <= 1e-6 * (t - p0.x).min(p3.x - t)) {
return None;
}
let mut pts = self.points.clone();
if let Some(q) = pts.get_mut(i) {
q.out = a - p0;
}
if let Some(q) = pts.get_mut(i + 1) {
q.h_in = c - p3;
}
pts.insert(i + 1, EasePoint { at: m, h_in: d - m, out: e - m, smooth: true });
Some((CustomEase::new(pts), i + 1))
}
/// Moves point `i` (not an end) to `to`, its handles with it; its x stays between its
/// neighbors' so time keeps running forwards. `None` for an end, a missing point or a
/// non-finite `to`.
pub fn move_point(&self, i: usize, to: Vec2) -> Option<CustomEase> {
if i == 0 || i >= self.points.len().saturating_sub(1) || !to.is_finite() {
return None;
}
let (lo, hi) = (self.points.get(i - 1)?.at.x, self.points.get(i + 1)?.at.x);
let mut c = self.clone();
let p = c.points.get_mut(i)?;
p.at = Vec2::new(to.x.clamp(lo, hi), to.y.clamp(-MAX_EASE_Y, MAX_EASE_Y));
c.clamp_handles();
Some(c)
}
/// Moves handle `which` of point `i` to `to` (absolute); a smooth point's other handle turns
/// to stay in line, keeping its length. `None` for a handle the point does not have (the
/// first point's in, the last's out) or a non-finite `to`.
pub fn move_handle(&self, i: usize, which: Handle, to: Vec2) -> Option<CustomEase> {
let n = self.points.len();
if !to.is_finite() || i >= n || (which == Handle::In && i == 0) || (which == Handle::Out && i + 1 == n) {
return None;
}
let mut c = self.clone();
let p = c.points.get_mut(i)?;
let off = to - p.at;
match which {
Handle::In => p.h_in = off,
Handle::Out => p.out = off,
}
c.clamp_handles();
if i > 0 && i + 1 < n {
let (prev, next) = (c.points.get(i - 1)?.at.x, c.points.get(i + 1)?.at.x);
if let Some(p) = c.points.get_mut(i).filter(|p| p.smooth) {
let at = p.at;
let (moved, other, x_reach) = match which {
Handle::In => (p.h_in, &mut p.out, next - at.x),
Handle::Out => (p.out, &mut p.h_in, prev - at.x),
};
let dir = -moved.normalized();
if dir != Vec2::ZERO {
// Shortened to stay within reach along `dir`, so the clamp below does not
// turn it out of line.
// A handle with no length is given one, so the point stays smooth.
let mut len = other.length();
if len <= 0.0 {
len = 1e-3;
}
if dir.x != 0.0 {
len = len.min((x_reach / dir.x).max(0.0));
}
if dir.y != 0.0 {
let y_reach = if dir.y > 0.0 { MAX_EASE_Y - at.y } else { -MAX_EASE_Y - at.y };
len = len.min((y_reach / dir.y).max(0.0));
}
*other = dir * len;
}
}
}
c.clamp_handles();
Some(c)
}
/// Removes point `i` (not an end). `None` for an end or a missing point.
pub fn remove(&self, i: usize) -> Option<CustomEase> {
if i == 0 || i >= self.points.len().saturating_sub(1) {
return None;
}
let mut pts = self.points.clone();
pts.remove(i);
Some(CustomEase::new(pts))
}
/// Makes point `i` smooth (its handles in line with its neighbors' chord, a third of the way
/// to each) or a corner (its handles on the point, so the curve turns sharply there).
pub fn set_smooth(&self, i: usize, smooth: bool) -> Option<CustomEase> {
let n = self.points.len();
let prev = if i == 0 { None } else { self.points.get(i - 1).map(|p| p.at) };
let next = i.checked_add(1).and_then(|j| self.points.get(j)).map(|p| p.at);
let mut c = self.clone();
let p = c.points.get_mut(i)?;
p.smooth = smooth && i > 0 && i + 1 < n;
if smooth {
let (a, b) = (prev.unwrap_or(p.at), next.unwrap_or(p.at));
let chord = b - a;
let dir = if chord.x > 1e-6 { chord * (1.0 / chord.x) } else { Vec2::new(1.0, 0.0) };
if prev.is_some() {
p.h_in = -dir * ((p.at.x - a.x) / 3.0);
}
if next.is_some() {
p.out = dir * ((b.x - p.at.x) / 3.0);
}
} else {
p.h_in = Vec2::ZERO;
p.out = Vec2::ZERO;
}
c.clamp_handles();
Some(c)
}
/// The flat list of absolute points `[p0, c1, c2, p1, …]` (see [`CustomEase::from_flat`]).
pub fn to_flat(&self) -> Vec<Vec2> {
let mut out = Vec::with_capacity(self.points.len() * 3);
for (i, p) in self.points.iter().enumerate() {
if i > 0 {
out.push(p.at + p.h_in);
}
out.push(p.at);
if i + 1 < self.points.len() {
out.push(p.at + p.out);
}
}
out
}
}
/// Whether a segment `span` wide in x whose out handle reaches `a` forwards and whose in handle
/// reaches `c` backwards (both at least 0) runs forwards in x. Its x′ is the quadratic with
/// Bernstein coefficients `a`, `span − a − c` and `c`, which is never negative when the middle
/// one is at least −√(ac); that always holds while neither handle reaches past the other end,
/// and never holds when one reaches past 4/3 of the span. The test is made on reaches divided by
/// the span, so squaring them does not underflow on a very narrow segment.
fn runs_forwards(span: f64, a: f64, c: f64) -> bool {
if a <= span && c <= span {
return true;
}
if a > 2.0 * span || c > 2.0 * span {
return false;
}
// Here span > 0: a handle reaches past it, and no more than twice it.
let (a, c) = (a / span, c / span);
let b = 1.0 - a - c;
b >= 0.0 || b * b <= a * c * (1.0 + 1e-12)
}
/// Whether handles `a` and `b` point opposite ways along one line (as a smooth point's do), or
/// one of them has no length.
fn handles_in_line(a: Vec2, b: Vec2) -> bool {
a.length() <= 1e-9 || b.length() <= 1e-9 || (a.normalized().dot(b.normalized()) + 1.0).abs() < 1e-3
}
/// Handle `h` (an offset) with its y within `lo..=hi`: a smooth point's shortened along its line,
/// a corner's clipped.
fn fit_y(h: Vec2, lo: f64, hi: f64, smooth: bool) -> Vec2 {
let k = if h.y > hi {
hi / h.y
} else if h.y < lo {
lo / h.y
} else {
return h;
};
if smooth { Vec2::new(h.x * k, (h.y * k).clamp(lo, hi)) } else { Vec2::new(h.x, h.y.clamp(lo, hi)) }
}
/// Handle `h` (an offset) reaching at most `span` in x: a smooth point's shortened along its line,
/// a corner's clipped.
fn fit_x(h: Vec2, span: f64, smooth: bool) -> Vec2 {
let reach = h.x.abs();
if reach <= span {
return h;
}
let span = span.max(0.0);
if smooth {
let k = span / reach;
Vec2::new((h.x * k).clamp(-span, span), h.y * k)
} else {
Vec2::new(span.copysign(h.x), h.y)
}
}
+655
View File
@@ -0,0 +1,655 @@
//! [`Easing`]: maps linear progress to eased progress.
use std::sync::Arc;
use crate::custom::{CustomEase, EasePoint, MAX_EASE_Y};
use crate::sampled::SampledEase;
use crate::spring::Spring;
use crate::{EaseError, Vec2, bez, finite, solve_monotonic, within};
/// The Back family's overshoot (about 10 %).
const BACK: f64 = 1.701_58;
/// Back In Out's overshoot, as the published equation scales it.
const BACK_IN_OUT: f64 = BACK * 1.525;
/// The smallest influence a [`TemporalEase`] may have.
pub const MIN_INFLUENCE: f64 = 0.001;
/// The families of named eases.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EaseFamily {
Quad,
Cubic,
Quart,
Quint,
Sine,
Back,
Circ,
Bounce,
Elastic,
}
impl EaseFamily {
pub const ALL: [EaseFamily; 9] = [
EaseFamily::Quad,
EaseFamily::Cubic,
EaseFamily::Quart,
EaseFamily::Quint,
EaseFamily::Sine,
EaseFamily::Back,
EaseFamily::Circ,
EaseFamily::Bounce,
EaseFamily::Elastic,
];
/// The family's English name.
pub fn label(self) -> &'static str {
match self {
EaseFamily::Quad => "Quad",
EaseFamily::Cubic => "Cubic",
EaseFamily::Quart => "Quart",
EaseFamily::Quint => "Quint",
EaseFamily::Sine => "Sine",
EaseFamily::Back => "Back",
EaseFamily::Circ => "Circ",
EaseFamily::Bounce => "Bounce",
EaseFamily::Elastic => "Elastic",
}
}
/// The ease in, `In(t)`. With `in_out` set, the curve whose halves make In Out: the
/// published In Out equations scale Back's overshoot by 1.525 and give Elastic a longer
/// period (4.5 instead of 3 per unit) and its own phase; the other families use `In(t)`.
fn ease_in(self, t: f64, in_out: bool) -> f64 {
use std::f64::consts::PI;
match self {
EaseFamily::Quad => t * t,
EaseFamily::Cubic => t * t * t,
EaseFamily::Quart => t * t * t * t,
EaseFamily::Quint => t * t * t * t * t,
EaseFamily::Sine => 1.0 - (t * PI * 0.5).cos(),
EaseFamily::Back => {
let c = if in_out { BACK_IN_OUT } else { BACK };
(c + 1.0) * t * t * t - c * t * t
}
EaseFamily::Circ => 1.0 - (1.0 - t * t).max(0.0).sqrt(),
EaseFamily::Bounce => 1.0 - bounce_out(1.0 - t),
EaseFamily::Elastic => {
if t <= 0.0 {
0.0
} else if t >= 1.0 {
1.0
} else if in_out {
-(2f64.powf(10.0 * t - 10.0)) * ((10.0 * t - 11.125) * (2.0 * PI / 4.5)).sin()
} else {
-(2f64.powf(10.0 * t - 10.0)) * ((10.0 * t - 10.75) * (2.0 * PI / 3.0)).sin()
}
}
}
}
/// Where the ease in changes formula (other than 0 and 1): Bounce is four parabolas.
fn breaks_in(self) -> &'static [f64] {
match self {
// 1 − the Out breakpoints (1/2.75, 2/2.75, 2.5/2.75), in order.
EaseFamily::Bounce => &[0.25 / 2.75, 0.75 / 2.75, 1.75 / 2.75],
_ => &[],
}
}
/// Bezier segments per ease in that draw it to within a hair (see [`Easing::to_custom`]);
/// cubic polynomials (Quad, Cubic, Back) and the parabolas of Bounce are exact with one.
fn pieces_in(self) -> usize {
match self {
EaseFamily::Quad | EaseFamily::Cubic | EaseFamily::Back | EaseFamily::Bounce | EaseFamily::Circ => 1,
EaseFamily::Quart | EaseFamily::Quint | EaseFamily::Sine => 4,
EaseFamily::Elastic => 24,
}
}
}
fn bounce_out(t: f64) -> f64 {
const N: f64 = 7.5625;
const D: f64 = 2.75;
if t < 1.0 / D {
N * t * t
} else if t < 2.0 / D {
let u = t - 1.5 / D;
N * u * u + 0.75
} else if t < 2.5 / D {
let u = t - 2.25 / D;
N * u * u + 0.9375
} else {
let u = t - 2.625 / D;
N * u * u + 0.984_375
}
}
/// Which way a named ease eases.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EaseDir {
In,
Out,
InOut,
}
impl EaseDir {
pub const ALL: [EaseDir; 3] = [EaseDir::In, EaseDir::Out, EaseDir::InOut];
pub fn label(self) -> &'static str {
match self {
EaseDir::In => "In",
EaseDir::Out => "Out",
EaseDir::InOut => "In Out",
}
}
}
/// One side of a segment's ease as a keyframe velocity dialog gives it: `speed` normalized
/// (speed × segment duration ÷ value change, so 1 is the straight line's speed) and
/// `influence` the fraction of the segment its handle reaches.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TemporalEase {
pub speed: f64,
pub influence: f64,
}
impl TemporalEase {
/// A side that leaves at rest with a third of the segment's influence.
pub const EASY: TemporalEase = TemporalEase { speed: 0.0, influence: 1.0 / 3.0 };
/// A linear side next to an eased one: the segment's average speed with a sixth of its
/// influence.
pub const LINEAR: TemporalEase = TemporalEase { speed: 1.0, influence: 1.0 / 6.0 };
}
/// A damped spring as an ease: a mass on a spring with damping, released from 0 toward 1 and
/// played over the time it takes to stay within 0.1 % of 1 (at most 10 seconds of its motion).
/// Values outside the ranges [`Spring::from_physical`] accepts are brought into them when the
/// ease is evaluated.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SpringEase {
pub mass: f64,
pub stiffness: f64,
pub damping: f64,
}
impl SpringEase {
/// A gentle spring with a small overshoot (mass 1, stiffness 100, damping 15).
pub const GENTLE: SpringEase = SpringEase { mass: 1.0, stiffness: 100.0, damping: 15.0 };
fn apply(self, t: f64) -> f64 {
Spring::physical_lenient(self.mass, self.stiffness, self.damping).ease(t)
}
}
/// Maps linear progress `t ∈ [0, 1]` to eased progress.
///
/// The unit variants are the named presets; their names are the file format and the names
/// commands use. [`Easing::apply`] returns exactly 0 for `t <= 0` (and for NaN) and exactly 1
/// for `t >= 1`, whatever the variant holds.
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Easing {
#[default]
Linear,
QuadIn,
QuadOut,
QuadInOut,
CubicIn,
CubicOut,
CubicInOut,
/// The traditional single-slider ease: −100 (ease in) … 0 (linear) … +100 (ease out).
Classic(f64),
/// A cubic Bezier through (0, 0), (x1, y1), (x2, y2), (1, 1), as the CSS Easing Functions
/// specification defines `cubic-bezier()`. Evaluation keeps x1 and x2 within `0..=1` and
/// y1 and y2 within ±[`MAX_EASE_Y`].
CubicBezier(f64, f64, f64, f64),
QuartIn,
QuartOut,
QuartInOut,
QuintIn,
QuintOut,
QuintInOut,
SineIn,
SineOut,
SineInOut,
BackIn,
BackOut,
BackInOut,
CircIn,
CircOut,
CircInOut,
BounceIn,
BounceOut,
BounceInOut,
ElasticIn,
ElasticOut,
ElasticInOut,
/// A curve of several Bezier segments, shared when copied.
Custom(Arc<CustomEase>),
/// A table of values, read between samples by straight lines.
Sampled(Arc<SampledEase>),
/// A damped spring.
Spring(SpringEase),
/// Stays at the start until the end, then jumps: 0 for `t < 1`.
Hold,
}
impl Easing {
pub const LINEAR_LABEL: &'static str = "Linear";
/// The `smooth` alias's curve.
pub const SMOOTH: Easing = Easing::CubicBezier(0.25, 0.1, 0.25, 1.0);
/// A cubic Bezier ease, checked: every value finite, `x1` and `x2` within `0..=1` (so time
/// runs forwards), `y1` and `y2` within ±[`MAX_EASE_Y`].
pub fn cubic_bezier(x1: f64, y1: f64, x2: f64, y2: f64) -> Result<Easing, EaseError> {
within(x1, 0.0, 1.0, "x1")?;
within(x2, 0.0, 1.0, "x2")?;
within(y1, -MAX_EASE_Y, MAX_EASE_Y, "y1")?;
within(y2, -MAX_EASE_Y, MAX_EASE_Y, "y2")?;
Ok(Easing::CubicBezier(x1, y1, x2, y2))
}
/// The ease of a segment from its two sides: `out` leaving the first key, `into` arriving at
/// the second. Each influence must be within [`MIN_INFLUENCE`] to 1 and each speed finite.
/// The result is the cubic Bezier with handles `(i0, s0 × i0)` and `(1 − i1, 1 − s1 × i1)`.
pub fn from_temporal(out: TemporalEase, into: TemporalEase) -> Result<Easing, EaseError> {
finite(out.speed, "out speed")?;
finite(into.speed, "in speed")?;
let i0 = within(out.influence, MIN_INFLUENCE, 1.0, "out influence")?;
let i1 = within(into.influence, MIN_INFLUENCE, 1.0, "in influence")?;
let (y1, y2) = (out.speed * i0, 1.0 - into.speed * i1);
if !(y1.abs() <= MAX_EASE_Y && y2.abs() <= MAX_EASE_Y) {
return Err(EaseError::OutOfRange { what: "speed × influence", min: -MAX_EASE_Y, max: MAX_EASE_Y });
}
Ok(Easing::CubicBezier(i0, y1, 1.0 - i1, y2))
}
/// The two sides of an ease that one cubic Bezier draws (see [`Easing::from_temporal`] and
/// [`Easing::as_bezier`]). A handle with no reach has speed 0. `None` when a handle's reach
/// is so short that its speed is too large to represent.
pub fn temporal(&self) -> Option<(TemporalEase, TemporalEase)> {
let (x1, y1, x2, y2) = self.as_bezier()?;
let (i0, i1) = (x1.clamp(0.0, 1.0), (1.0 - x2).clamp(0.0, 1.0));
let s0 = if i0 > 0.0 { y1 / i0 } else { 0.0 };
let s1 = if i1 > 0.0 { (1.0 - y2) / i1 } else { 0.0 };
if !(s0.is_finite() && s1.is_finite()) {
return None;
}
Some((TemporalEase { speed: s0, influence: i0 }, TemporalEase { speed: s1, influence: i1 }))
}
/// A spring ease, checked as [`Spring::from_physical`] checks its values.
pub fn spring(mass: f64, stiffness: f64, damping: f64) -> Result<Easing, EaseError> {
Spring::from_physical(mass, stiffness, damping)?;
Ok(Easing::Spring(SpringEase { mass, stiffness, damping }))
}
/// The named ease of `family` easing `dir`.
pub fn preset(family: EaseFamily, dir: EaseDir) -> Easing {
use EaseDir::*;
use EaseFamily::*;
match (family, dir) {
(Quad, In) => Easing::QuadIn,
(Quad, Out) => Easing::QuadOut,
(Quad, InOut) => Easing::QuadInOut,
(Cubic, In) => Easing::CubicIn,
(Cubic, Out) => Easing::CubicOut,
(Cubic, InOut) => Easing::CubicInOut,
(Quart, In) => Easing::QuartIn,
(Quart, Out) => Easing::QuartOut,
(Quart, InOut) => Easing::QuartInOut,
(Quint, In) => Easing::QuintIn,
(Quint, Out) => Easing::QuintOut,
(Quint, InOut) => Easing::QuintInOut,
(Sine, In) => Easing::SineIn,
(Sine, Out) => Easing::SineOut,
(Sine, InOut) => Easing::SineInOut,
(Back, In) => Easing::BackIn,
(Back, Out) => Easing::BackOut,
(Back, InOut) => Easing::BackInOut,
(Circ, In) => Easing::CircIn,
(Circ, Out) => Easing::CircOut,
(Circ, InOut) => Easing::CircInOut,
(Bounce, In) => Easing::BounceIn,
(Bounce, Out) => Easing::BounceOut,
(Bounce, InOut) => Easing::BounceInOut,
(Elastic, In) => Easing::ElasticIn,
(Elastic, Out) => Easing::ElasticOut,
(Elastic, InOut) => Easing::ElasticInOut,
}
}
/// The family and direction of a named ease.
pub fn family(&self) -> Option<(EaseFamily, EaseDir)> {
use EaseDir::*;
use EaseFamily::*;
Some(match self {
Easing::QuadIn => (Quad, In),
Easing::QuadOut => (Quad, Out),
Easing::QuadInOut => (Quad, InOut),
Easing::CubicIn => (Cubic, In),
Easing::CubicOut => (Cubic, Out),
Easing::CubicInOut => (Cubic, InOut),
Easing::QuartIn => (Quart, In),
Easing::QuartOut => (Quart, Out),
Easing::QuartInOut => (Quart, InOut),
Easing::QuintIn => (Quint, In),
Easing::QuintOut => (Quint, Out),
Easing::QuintInOut => (Quint, InOut),
Easing::SineIn => (Sine, In),
Easing::SineOut => (Sine, Out),
Easing::SineInOut => (Sine, InOut),
Easing::BackIn => (Back, In),
Easing::BackOut => (Back, Out),
Easing::BackInOut => (Back, InOut),
Easing::CircIn => (Circ, In),
Easing::CircOut => (Circ, Out),
Easing::CircInOut => (Circ, InOut),
Easing::BounceIn => (Bounce, In),
Easing::BounceOut => (Bounce, Out),
Easing::BounceInOut => (Bounce, InOut),
Easing::ElasticIn => (Elastic, In),
Easing::ElasticOut => (Elastic, Out),
Easing::ElasticInOut => (Elastic, InOut),
Easing::Linear
| Easing::Classic(_)
| Easing::CubicBezier(..)
| Easing::Custom(_)
| Easing::Sampled(_)
| Easing::Spring(_)
| Easing::Hold => return None,
})
}
/// Every named preset: no ease, then each family In, Out, In Out.
pub fn named() -> impl Iterator<Item = Easing> {
std::iter::once(Easing::Linear).chain(EaseFamily::ALL.into_iter().flat_map(|f| EaseDir::ALL.into_iter().map(move |d| Easing::preset(f, d))))
}
/// The preset's name in commands and files (`"QuadIn"`, `"ElasticInOut"`, `"Hold"`), `None`
/// for eases with values.
pub fn name(&self) -> Option<String> {
match self {
Easing::Linear => Some("Linear".into()),
Easing::Hold => Some("Hold".into()),
_ => self.family().map(|(f, d)| format!("{}{}", f.label(), d.label().replace(' ', ""))),
}
}
/// The preset named `name`, ignoring case, spaces, `-` and `_` (`"back in out"`), with the
/// aliases `none`, `easein`, `easeout`, `easeinout` and `smooth`.
pub fn from_name(name: &str) -> Option<Easing> {
// No preset or alias is longer than this, so a longer name is unknown and is not copied
// past it.
const LONGEST: usize = 12;
let key: String = name.chars().filter(|c| !matches!(c, '-' | '_' | ' ')).flat_map(char::to_lowercase).take(LONGEST + 1).collect();
if key.chars().count() > LONGEST {
return None;
}
match key.as_str() {
"none" | "noease" => return Some(Easing::Linear),
"hold" => return Some(Easing::Hold),
"easein" => return Some(Easing::QuadIn),
"easeout" => return Some(Easing::QuadOut),
"easeinout" => return Some(Easing::QuadInOut),
"smooth" => return Some(Easing::SMOOTH),
_ => {}
}
Easing::named().find(|e| e.name().is_some_and(|n| n.to_lowercase() == key))
}
/// An English label for menus and reports.
pub fn label(&self) -> String {
match self {
Easing::Linear => Easing::LINEAR_LABEL.to_string(),
Easing::Hold => "Hold".to_string(),
Easing::Classic(s) => format!("Classic {s:+.0}"),
Easing::CubicBezier(..) if *self == Easing::SMOOTH => "Smooth (bezier)".to_string(),
Easing::CubicBezier(a, b, c, d) => format!("Bezier({a:.2}, {b:.2}, {c:.2}, {d:.2})"),
Easing::Custom(_) => "Custom".to_string(),
Easing::Sampled(s) => s.name().to_string(),
Easing::Spring(s) => format!("Spring {:.0}, {:.0}, {:.0}", s.mass, s.stiffness, s.damping),
other => other.family().map_or_else(|| "Custom".to_string(), |(f, d)| format!("{} {}", f.label(), d.label())),
}
}
/// The single cubic Bezier `(x1, y1, x2, y2)` that draws this ease: exact for linear, the
/// Classic slider, the Quad, Cubic and Back eases in and out, and a custom ease of one
/// segment; the Quad and Cubic in-outs get their usual one-curve approximations. `None` for
/// eases one curve cannot draw (Bounce, Elastic, the other families, hold, springs, sampled
/// tables, custom eases of several segments, and a custom ease of one segment whose handle
/// reaches past the unit box in x).
pub fn as_bezier(&self) -> Option<(f64, f64, f64, f64)> {
const THIRD: f64 = 1.0 / 3.0;
Some(match self {
Easing::Linear => (THIRD, THIRD, 2.0 * THIRD, 2.0 * THIRD),
// t², t³ and (c+1)t³ − ct² and their mirrors, with x(s) = s.
Easing::QuadIn => (THIRD, 0.0, 2.0 * THIRD, THIRD),
Easing::QuadOut => (THIRD, 2.0 * THIRD, 2.0 * THIRD, 1.0),
Easing::CubicIn => (THIRD, 0.0, 2.0 * THIRD, 0.0),
Easing::CubicOut => (THIRD, 1.0, 2.0 * THIRD, 1.0),
Easing::BackIn => (THIRD, 0.0, 2.0 * THIRD, -BACK * THIRD),
Easing::BackOut => (THIRD, 1.0 + BACK * THIRD, 2.0 * THIRD, 1.0),
Easing::QuadInOut => (0.45, 0.0, 0.55, 1.0),
Easing::CubicInOut => (0.65, 0.0, 0.35, 1.0),
Easing::Classic(strength) => {
// The quadratic 2(1 − t)t·c + t², raised to a cubic.
let c = 0.5 + 0.5 * classic_strength(*strength);
(THIRD, 2.0 * c * THIRD, 2.0 * THIRD, (2.0 * c + 1.0) * THIRD)
}
Easing::CubicBezier(a, b, c, d) => bezier_handles(*a, *b, *c, *d),
Easing::Custom(c) => match c.points() {
[a, b] if a.out.x <= 1.0 && b.h_in.x >= -1.0 => (a.out.x, a.out.y, b.at.x + b.h_in.x, b.at.y + b.h_in.y),
_ => return None,
},
_ => return None,
})
}
/// Eased progress at `t`: exactly 0 for `t <= 0` or NaN, exactly 1 for `t >= 1`.
pub fn apply(&self, t: f64) -> f64 {
if t.is_nan() || t <= 0.0 {
return 0.0;
}
if t >= 1.0 {
return 1.0;
}
let v = match self {
Easing::Linear => t,
Easing::Hold => 0.0,
Easing::Classic(strength) => {
// Quadratic Bezier with the middle control point moved by `strength`.
let c = 0.5 + 0.5 * classic_strength(*strength);
2.0 * (1.0 - t) * t * c + t * t
}
Easing::CubicBezier(x1, y1, x2, y2) => {
let (x1, y1, x2, y2) = bezier_handles(*x1, *y1, *x2, *y2);
bez(solve_monotonic(t, [0.0, x1, x2, 1.0]), [0.0, y1, y2, 1.0])
}
Easing::Custom(c) => c.apply(t),
Easing::Sampled(s) => s.apply(t),
Easing::Spring(s) => s.apply(t),
named => match named.family() {
Some((f, d)) => eval_named(f, d, t),
None => t,
},
};
if v.is_finite() { v } else { t }
}
/// This ease as a custom curve for a graph editor: exact for linear, Classic, a Bezier,
/// the Quad, Cubic, Back and Bounce families and custom eases; Circ is two circular arcs,
/// and Quart, Quint, Sine and Elastic are fitted by matching values and slopes at a few
/// points (all within 0.5 % of the range everywhere). A sampled ease or a spring becomes the
/// straight segments through [`crate::POLYLINE_POINTS`] of its values, and a hold a corner
/// at the end.
pub fn to_custom(&self) -> CustomEase {
match self {
Easing::Custom(c) => (**c).clone(),
Easing::Sampled(s) => s.to_polyline(),
Easing::Spring(_) => {
let n = crate::MAX_EASE_SAMPLES;
let values = (0..n).map(|i| self.apply(i as f64 / (n - 1) as f64)).collect();
SampledEase::new("Spring", "", "", values).to_polyline()
}
Easing::Hold => {
// Flat at 0 across the segment, then straight up to 1 at the end.
let third = 1.0 / 3.0;
CustomEase::new(vec![
EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::new(third, 0.0), smooth: false },
EasePoint { at: Vec2::new(1.0, 0.0), h_in: Vec2::new(-third, 0.0), out: Vec2::ZERO, smooth: false },
EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::ZERO, out: Vec2::ZERO, smooth: false },
])
}
Easing::Linear => CustomEase::linear(),
Easing::Classic(_) | Easing::CubicBezier(..) => {
let Some((x1, y1, x2, y2)) = self.as_bezier() else { return CustomEase::linear() };
CustomEase::from_bezier(x1, y1, x2, y2)
}
named => match named.family() {
Some((f, d)) => fit_named(f, d),
None => CustomEase::linear(),
},
}
}
/// The custom curve, when this is one.
pub fn custom(&self) -> Option<&CustomEase> {
match self {
Easing::Custom(c) => Some(c),
_ => None,
}
}
/// The sampled curve, when this is one.
pub fn sampled(&self) -> Option<&SampledEase> {
match self {
Easing::Sampled(s) => Some(s),
_ => None,
}
}
}
/// A cubic Bezier's handles as evaluation uses them: x within `0..=1`, y within ±[`MAX_EASE_Y`],
/// and the straight line for a handle that is not finite.
fn bezier_handles(x1: f64, y1: f64, x2: f64, y2: f64) -> (f64, f64, f64, f64) {
if ![x1, y1, x2, y2].iter().all(|v| v.is_finite()) {
return (1.0 / 3.0, 1.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0);
}
(x1.clamp(0.0, 1.0), y1.clamp(-MAX_EASE_Y, MAX_EASE_Y), x2.clamp(0.0, 1.0), y2.clamp(-MAX_EASE_Y, MAX_EASE_Y))
}
fn classic_strength(s: f64) -> f64 {
if s.is_finite() { s.clamp(-100.0, 100.0) / 100.0 } else { 0.0 }
}
fn eval_named(f: EaseFamily, d: EaseDir, t: f64) -> f64 {
match d {
EaseDir::In => f.ease_in(t, false),
EaseDir::Out => 1.0 - f.ease_in(1.0 - t, false),
EaseDir::InOut => {
if t < 0.5 {
0.5 * f.ease_in(2.0 * t, true)
} else {
1.0 - 0.5 * f.ease_in(2.0 - 2.0 * t, true)
}
}
}
}
/// The slope of `y` at `x`, from inside `[lo, hi]`: one-sided, a step in from `x` (so a value
/// pinned at an end, as Elastic's are, does not count), exact for parabolas but for that step.
fn slope(y: &dyn Fn(f64) -> f64, x: f64, lo: f64, hi: f64) -> f64 {
const H: f64 = 1e-6;
let s = if x + 3.0 * H <= hi {
let d = (-3.0 * y(x + H) + 4.0 * y(x + 2.0 * H) - y(x + 3.0 * H)) / (2.0 * H);
let d2 = (y(x + H) - 2.0 * y(x + 2.0 * H) + y(x + 3.0 * H)) / (H * H);
d - d2 * H
} else if x - 3.0 * H >= lo {
let d = (3.0 * y(x - H) - 4.0 * y(x - 2.0 * H) + y(x - 3.0 * H)) / (2.0 * H);
let d2 = (y(x - H) - 2.0 * y(x - 2.0 * H) + y(x - 3.0 * H)) / (H * H);
d + d2 * H
} else {
0.0
};
if s.is_finite() { s } else { 0.0 }
}
/// The ease in of `f` (its In Out form with `in_out`) as Bezier points: Hermite segments (value
/// and slope matched at each end, so exact for cubic polynomials and for each parabola of
/// Bounce), except Circ, whose quarter circle is two 45° arcs (within 4·10⁻⁶ of the circle).
fn fit_in(f: EaseFamily, in_out: bool) -> Vec<EasePoint> {
let pt = |x: f64, y: f64, i: (f64, f64), o: (f64, f64)| EasePoint {
at: Vec2::new(x, y),
h_in: Vec2::new(i.0, i.1),
out: Vec2::new(o.0, o.1),
smooth: false,
};
if f == EaseFamily::Circ {
// The circle about (0, 1) from (0, 0) to (1, 1); each arc's handles are k = 4/3·tan(φ/4)
// long along the tangents.
let k = 4.0 / 3.0 * (std::f64::consts::PI / 16.0).tan();
let c = std::f64::consts::FRAC_1_SQRT_2;
return vec![pt(0.0, 0.0, (0.0, 0.0), (k, 0.0)), pt(c, 1.0 - c, (-k * c, -k * c), (k * c, k * c)), pt(1.0, 1.0, (0.0, -k), (0.0, 0.0))];
}
let y = move |t: f64| f.ease_in(t, in_out);
let mut xs: Vec<f64> = Vec::new();
let pieces = f.pieces_in();
let bounds: Vec<f64> = std::iter::once(0.0).chain(f.breaks_in().iter().copied()).chain(std::iter::once(1.0)).collect();
for w in bounds.windows(2) {
if let [a, c] = w {
xs.extend((0..pieces).map(|k| a + (c - a) * k as f64 / pieces as f64));
}
}
xs.push(1.0);
let mut pts: Vec<EasePoint> = xs.iter().map(|&x| pt(x, y(x), (0.0, 0.0), (0.0, 0.0))).collect();
for i in 0..xs.len().saturating_sub(1) {
let (Some(&a), Some(&b)) = (xs.get(i), xs.get(i + 1)) else { continue };
let h = (b - a) / 3.0;
let (sa, sb) = (slope(&y, a, a, b), slope(&y, b, a, b));
if let Some(p) = pts.get_mut(i) {
p.out = Vec2::new(h, sa * h);
}
if let Some(p) = pts.get_mut(i + 1) {
p.h_in = Vec2::new(-h, -sb * h);
}
}
pts
}
/// The curve turned half a turn about (½, ½): an ease in becomes the ease out.
fn mirrored(pts: &[EasePoint]) -> Vec<EasePoint> {
pts.iter().rev().map(|p| EasePoint { at: Vec2::new(1.0 - p.at.x, 1.0 - p.at.y), h_in: -p.out, out: -p.h_in, smooth: p.smooth }).collect()
}
fn scaled(pts: &[EasePoint], by: f64, from: Vec2) -> Vec<EasePoint> {
pts.iter().map(|p| EasePoint { at: from + p.at * by, h_in: p.h_in * by, out: p.out * by, smooth: p.smooth }).collect()
}
/// A named ease as a custom curve (see [`Easing::to_custom`]).
fn fit_named(f: EaseFamily, d: EaseDir) -> CustomEase {
let mut pts = match d {
EaseDir::In => fit_in(f, false),
EaseDir::Out => mirrored(&fit_in(f, false)),
EaseDir::InOut => {
let half = fit_in(f, true);
let mut a = scaled(&half, 0.5, Vec2::ZERO);
let b = scaled(&mirrored(&half), 0.5, Vec2::new(0.5, 0.5));
// The two halves meet at (½, ½): one point, the first half's in, the second's out.
if let (Some(last), Some(first)) = (a.last_mut(), b.first()) {
last.out = first.out;
}
a.extend(b.into_iter().skip(1));
a
}
};
// Points where the slope carries on are smooth (Bounce's floor hits are corners).
let n = pts.len();
for (i, p) in pts.iter_mut().enumerate() {
p.smooth =
i > 0 && i + 1 < n && p.h_in.length() > 1e-9 && p.out.length() > 1e-9 && (p.h_in.normalized().dot(p.out.normalized()) + 1.0).abs() < 1e-3;
}
CustomEase::new(pts)
}
+228
View File
@@ -0,0 +1,228 @@
//! Easing curves, keyed tracks, motion paths and springs.
//!
//! * [`Easing`] maps linear progress `t` in `0..=1` to eased progress: no ease, hold, the
//! Classic slider, nine named families (Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce,
//! Elastic), each In, Out and In Out, one cubic Bezier (also built from speed and influence,
//! [`TemporalEase`]), an editable multi-segment [`CustomEase`], a [`SampledEase`] table and a
//! [`SpringEase`]. [`Easing::apply`] is a pure function that does not allocate, and it returns
//! exactly 0 at the start and exactly 1 at the end.
//! * [`Track`] holds keys of any [`Animatable`] value (`f32`, `f64`, [`Vec2`], `[f32; N]`,
//! `[f64; N]`) at times in seconds, each easing into the next. Sampling is a binary search and
//! does not allocate for these value types; for another [`Animatable`] type it allocates
//! whatever that type's `Clone` and `Animatable` implementations allocate.
//! * [`MotionPath`] is a chain of cubic Bezier segments with arc-length tables built once, for
//! constant-speed motion along a curve.
//! * [`Spring`] and [`SpringState`] move a value toward a target as a damped spring. Each step
//! uses the exact solution of the spring equation, so a step costs the same at any frame rate
//! and length.
//!
//! The named families are the classic public easing equations published by Robert Penner.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod custom;
mod easing;
mod path;
mod sampled;
mod spring;
mod track;
mod vec2;
pub use custom::{CustomEase, EasePoint, Handle, MAX_EASE_POINTS, MAX_EASE_Y};
pub use easing::{EaseDir, EaseFamily, Easing, MIN_INFLUENCE, SpringEase, TemporalEase};
pub use path::{MAX_PATH_SEGMENTS, MotionPath};
pub use sampled::{MAX_EASE_SAMPLES, POLYLINE_POINTS, SampledEase};
pub use spring::{MAX_DAMPING_RATIO, MAX_SPRING_HZ, Spring, SpringState};
pub use track::{Animatable, Key, MAX_TRACK_KEYS, Track};
pub use vec2::Vec2;
/// Why a value was refused.
#[derive(Clone, Debug, PartialEq)]
pub enum EaseError {
/// The named input is NaN or infinite.
NotFinite(&'static str),
/// The named input is outside the range it must lie in.
OutOfRange { what: &'static str, min: f64, max: f64 },
/// A track or path holds as many entries as it may.
Full(usize),
/// A path or curve needs more points than it was given.
TooFew { what: &'static str, need: usize },
/// The track has no keys.
Empty,
/// Two keys are at this time.
SameTime(f64),
/// The result is too large to represent.
Overflow,
}
impl std::fmt::Display for EaseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
EaseError::NotFinite(what) => write!(f, "{what} is not a finite number"),
EaseError::OutOfRange { what, min, max } => write!(f, "{what} must be between {min} and {max}"),
EaseError::Full(n) => write!(f, "at most {n} entries are allowed"),
EaseError::TooFew { what, need } => write!(f, "{what} needs at least {need} points"),
EaseError::Empty => write!(f, "the track has no keys"),
EaseError::SameTime(t) => write!(f, "two keys are at {t} s"),
EaseError::Overflow => write!(f, "the result is too large"),
}
}
}
impl std::error::Error for EaseError {}
/// `v` itself when it is finite.
pub(crate) fn finite(v: f64, what: &'static str) -> Result<f64, EaseError> {
if v.is_finite() { Ok(v) } else { Err(EaseError::NotFinite(what)) }
}
/// `v` itself when it is finite and within `min..=max`.
pub(crate) fn within(v: f64, min: f64, max: f64, what: &'static str) -> Result<f64, EaseError> {
let v = finite(v, what)?;
if (min..=max).contains(&v) { Ok(v) } else { Err(EaseError::OutOfRange { what, min, max }) }
}
/// The value `t` of the way from `a` to `b`. When a step on the way is too large to represent
/// (`a` and `b` near opposite ends of the `f64` range, or an overshooting `t`), it is worked
/// out at half scale, so only a result too large to represent is infinite. `t` of exactly 0 or
/// 1 returns `a` or `b` itself.
pub(crate) fn lerp(a: f64, b: f64, t: f64) -> f64 {
if t == 0.0 {
return a;
}
if t == 1.0 {
return b;
}
let r = a + (b - a) * t;
if r.is_finite() { r } else { 2.0 * (0.5 * a + (0.5 * b - 0.5 * a) * t) }
}
/// Reads a list, keeping its first `max` entries and skipping the rest without storing them.
#[cfg(feature = "serde")]
pub(crate) fn read_first<'de, D, T>(d: D, max: usize) -> Result<Vec<T>, D::Error>
where
D: serde::Deserializer<'de>,
T: serde::Deserialize<'de>,
{
use serde::de::{IgnoredAny, SeqAccess, Visitor};
struct V<T>(usize, std::marker::PhantomData<T>);
impl<'de, T: serde::Deserialize<'de>> Visitor<'de> for V<T> {
type Value = Vec<T>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "a list")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<T>, A::Error> {
let mut out = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(self.0).min(1024));
while out.len() < self.0 {
match seq.next_element()? {
Some(v) => out.push(v),
None => return Ok(out),
}
}
while seq.next_element::<IgnoredAny>()?.is_some() {}
Ok(out)
}
}
d.deserialize_seq(V(max, std::marker::PhantomData))
}
/// Reads a string and keeps only what `clean` makes of it, so a long string in a file is never
/// copied whole into the value.
///
/// This bounds the memory the value keeps. A format that has to decode escapes may still build
/// the whole string in a temporary buffer first; that buffer is no larger than the input, so the
/// caller bounds it by limiting the size of the file it reads.
#[cfg(feature = "serde")]
pub(crate) fn read_cleaned<'de, D: serde::Deserializer<'de>>(d: D, clean: fn(&str) -> String) -> Result<String, D::Error> {
struct V(fn(&str) -> String);
impl serde::de::Visitor<'_> for V {
type Value = String;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "a string")
}
fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<String, E> {
Ok((self.0)(s))
}
}
d.deserialize_str(V(clean))
}
/// Cubic Bezier in one dimension.
pub(crate) fn bez(t: f64, p: [f64; 4]) -> f64 {
let mt = 1.0 - t;
mt * mt * mt * p[0] + 3.0 * mt * mt * t * p[1] + 3.0 * mt * t * t * p[2] + t * t * t * p[3]
}
/// The derivative of [`bez`].
pub(crate) fn dbez(t: f64, p: [f64; 4]) -> f64 {
let mt = 1.0 - t;
3.0 * mt * mt * (p[1] - p[0]) + 6.0 * mt * t * (p[2] - p[1]) + 3.0 * t * t * (p[3] - p[2])
}
/// Most steps [`solve_monotonic`] takes.
pub(crate) const SOLVE_STEPS: u32 = 64;
/// How close [`solve_monotonic`] brings `bez(s)` to `x`, relative to the curve's span.
pub(crate) const SOLVE_TOLERANCE: f64 = 1e-12;
/// The parameter where the Bezier `p` (non-decreasing, as it is when its inner points lie
/// between its ends) reaches `x`: Newton steps kept inside a shrinking bracket, halving when a step leaves it, to
/// within [`SOLVE_TOLERANCE`] of the span in at most [`SOLVE_STEPS`] steps. The curve is solved
/// shifted to start at 0 and scaled to a span of 1, so a narrow segment far from 0 is solved as
/// precisely as a wide one. The curve with both handles at full reach (`p1 = p3`, `p2 = p0`),
/// whose slope is zero halfway, is inverted in closed form.
pub(crate) fn solve_monotonic(x: f64, p: [f64; 4]) -> f64 {
solve_counted(x, p).0
}
/// [`solve_monotonic`] and the number of steps it took.
pub(crate) fn solve_counted(x: f64, p: [f64; 4]) -> (f64, u32) {
let span = p[3] - p[0];
if span.is_nan() || span <= 0.0 {
return (0.5, 0);
}
if x <= p[0] {
return (0.0, 0);
}
if x >= p[3] {
return (1.0, 0);
}
let u = (x - p[0]) / span;
if p[1] == p[3] && p[2] == p[0] {
// x(s) = 0.5 + 4 (s − 0.5)³ on the unit span.
return ((0.5 + ((u - 0.5) * 0.25).cbrt()).clamp(0.0, 1.0), 0);
}
let q = [0.0, (p[1] - p[0]) / span, (p[2] - p[0]) / span, 1.0];
let (mut lo, mut hi) = (0.0f64, 1.0f64);
let mut s = u.clamp(0.0, 1.0);
for step in 1..=SOLVE_STEPS {
let err = bez(s, q) - u;
if err.abs() <= SOLVE_TOLERANCE {
return (s, step);
}
if err < 0.0 {
lo = s;
} else {
hi = s;
}
let d = dbez(s, q);
let next = if d.abs() > 1e-300 { s - err / d } else { f64::NAN };
s = if next > lo && next < hi { next } else { 0.5 * (lo + hi) };
}
(s, SOLVE_STEPS)
}
#[cfg(test)]
#[path = "tests/easing_tests.rs"]
mod easing_tests;
#[cfg(test)]
#[path = "tests/track_tests.rs"]
mod track_tests;
#[cfg(test)]
#[path = "tests/path_tests.rs"]
mod path_tests;
#[cfg(test)]
#[path = "tests/spring_tests.rs"]
mod spring_tests;
+355
View File
@@ -0,0 +1,355 @@
//! [`MotionPath`]: constant-speed motion along a chain of cubic Bezier segments.
use crate::{EaseError, Vec2, bez, dbez};
/// Most segments one path holds.
pub const MAX_PATH_SEGMENTS: usize = 10_000;
/// Cells in each segment's arc-length table.
const ARC_N: usize = 32;
/// Most steps `Segment::param_at` takes; halving a table cell this often reaches the smallest
/// step an `f64` parameter can take.
const PARAM_STEPS: u32 = 64;
/// 5-point Gauss-Legendre nodes and weights on −1..1.
const GAUSS: [(f64, f64); 5] = [
(0.0, 0.568_888_888_888_888_9),
(-0.538_469_310_105_683_1, 0.478_628_670_499_366_5),
(0.538_469_310_105_683_1, 0.478_628_670_499_366_5),
(-0.906_179_845_938_664, 0.236_926_885_056_189_1),
(0.906_179_845_938_664, 0.236_926_885_056_189_1),
];
#[derive(Clone, Debug, PartialEq)]
struct Segment {
p: [Vec2; 4],
/// Arc length from the segment's start at `u = i / ARC_N`.
table: [f64; ARC_N + 1],
/// Both handles on the chord: the segment is the straight line between its ends.
straight: bool,
/// The parameters inside `0..1` where the x or y derivative is zero, in order, with the
/// unused entries set to 1. Arc lengths are integrated in pieces split there, since the
/// speed has a kink where the curve stops and turns back.
stops: [f64; 4],
/// Arc length from the path's start to this segment's start.
start: f64,
}
impl Segment {
fn new(p: [Vec2; 4], start: f64) -> Segment {
let straight = on_chord(p[0], p[1], p[3]) && on_chord(p[0], p[2], p[3]);
let stops = stationary(&p);
let mut table = [0.0; ARC_N + 1];
if straight {
let len = p[0].distance(p[3]);
for (i, v) in table.iter_mut().enumerate() {
*v = len * (i as f64 / ARC_N as f64);
}
} else {
let mut acc = 0.0;
for i in 1..=ARC_N {
acc += arc(&p, &stops, (i - 1) as f64 / ARC_N as f64, i as f64 / ARC_N as f64);
if let Some(v) = table.get_mut(i) {
*v = acc;
}
}
}
Segment { p, table, straight, stops, start }
}
fn length(&self) -> f64 {
self.table[ARC_N]
}
fn point(&self, u: f64) -> Vec2 {
let p = &self.p;
Vec2::new(bez(u, [p[0].x, p[1].x, p[2].x, p[3].x]), bez(u, [p[0].y, p[1].y, p[2].y, p[3].y]))
}
/// The parameter at arc length `s` from the segment's start (`0..=length`): the table
/// cell's straight-line guess refined with Newton steps on the true arc length, kept inside
/// a shrinking bracket and halving it when a step would leave it (where the curve stands
/// still, for one), until the arc length is within 1e-12 of the segment's length of `s`, in
/// at most [`PARAM_STEPS`] steps.
fn param_at(&self, s: f64) -> f64 {
let len = self.length();
if len <= 0.0 {
return 0.0;
}
let s = s.clamp(0.0, len);
if self.straight {
return s / len;
}
let i = self.table.partition_point(|&v| v < s).clamp(1, ARC_N);
let (Some(&a), Some(&b)) = (self.table.get(i - 1), self.table.get(i)) else { return s / len };
let (u0, u1) = ((i - 1) as f64 / ARC_N as f64, i as f64 / ARC_N as f64);
let mut u = u0 + if b > a { (s - a) / (b - a) } else { 0.0 } * (u1 - u0);
let (mut lo, mut hi) = (u0, u1);
for _ in 0..PARAM_STEPS {
let e = a + arc(&self.p, &self.stops, u0, u) - s;
if e.abs() <= 1e-12 * len {
break;
}
if e < 0.0 {
lo = u;
} else {
hi = u;
}
let d = speed(&self.p, u);
let next = if d > 0.0 { u - e / d } else { f64::NAN };
u = if next > lo && next < hi { next } else { 0.5 * (lo + hi) };
}
u
}
/// The direction of travel at `u`, or the chord's where the curve's derivative vanishes.
fn direction(&self, u: f64) -> Vec2 {
let p = &self.p;
let d = Vec2::new(dbez(u, [p[0].x, p[1].x, p[2].x, p[3].x]), dbez(u, [p[0].y, p[1].y, p[2].y, p[3].y])).normalized();
if d != Vec2::ZERO {
return d;
}
// At an end whose handle sits on it, the curve leaves toward the next control point.
let toward = if u < 0.5 {
[p[1], p[2], p[3]].into_iter().find(|q| *q != p[0]).map(|q| q - p[0])
} else {
[p[2], p[1], p[0]].into_iter().find(|q| *q != p[3]).map(|q| p[3] - q)
};
toward.unwrap_or(Vec2::ZERO).normalized()
}
}
/// |dB/du|.
fn speed(p: &[Vec2; 4], u: f64) -> f64 {
Vec2::new(dbez(u, [p[0].x, p[1].x, p[2].x, p[3].x]), dbez(u, [p[0].y, p[1].y, p[2].y, p[3].y])).length()
}
/// Arc length between parameters `a` and `b` (Gauss-Legendre; exact enough on one table cell),
/// in pieces split at the parameters `stops` that lie between them.
fn arc(p: &[Vec2; 4], stops: &[f64; 4], a: f64, b: f64) -> f64 {
let mut from = a;
let mut total = 0.0;
for &r in stops.iter().filter(|&&r| r > a && r < b) {
total += gauss(p, from, r);
from = r;
}
total + gauss(p, from, b)
}
/// [`arc`] over one piece. Each term is scaled by the interval before they are added, so a
/// length near the largest `f64` does not overflow on the way.
fn gauss(p: &[Vec2; 4], a: f64, b: f64) -> f64 {
let (m, h) = ((a + b) * 0.5, (b - a) * 0.5);
GAUSS.iter().map(|(x, w)| w * h * speed(p, m + h * x)).sum::<f64>()
}
/// The parameters inside `0..1` where the x or y derivative of the segment `p` is zero, sorted
/// and padded with 1 (see `Segment::stops`).
fn stationary(p: &[Vec2; 4]) -> [f64; 4] {
let mut out = [1.0; 4];
let mut n = 0;
for k in [[p[0].x, p[1].x, p[2].x, p[3].x], [p[0].y, p[1].y, p[2].y, p[3].y]] {
for r in quadratic_roots(k[1] - k[0], k[2] - k[1], k[3] - k[2]) {
if let Some(slot) = out.get_mut(n) {
*slot = r;
n += 1;
}
}
}
out.sort_by(f64::total_cmp);
out
}
/// The roots inside `0..1` of the quadratic with Bernstein coefficients `k0`, `k1` and `k2`
/// (a cubic's derivative, up to a factor of 3). The coefficients are scaled to the largest
/// first, so coordinates near the ends of the `f64` range do not overflow when squared.
fn quadratic_roots(k0: f64, k1: f64, k2: f64) -> impl Iterator<Item = f64> {
let m = k0.abs().max(k1.abs()).max(k2.abs());
let (k0, k1, k2) = if m.is_finite() && m > 0.0 { (k0 / m, k1 / m, k2 / m) } else { (0.0, 0.0, 0.0) };
// a u² + b u + c in powers of u.
let (a, b, c) = (k0 - 2.0 * k1 + k2, 2.0 * (k1 - k0), k0);
let roots = if a.abs() < 1e-12 {
[if b != 0.0 { -c / b } else { f64::NAN }, f64::NAN]
} else {
let disc = b * b - 4.0 * a * c;
if disc < 0.0 {
[f64::NAN, f64::NAN]
} else {
// The root of larger size first, then the other from their product, without
// cancellation.
let q = -0.5 * (b + disc.sqrt().copysign(b));
[q / a, if q != 0.0 { c / q } else { f64::NAN }]
}
};
roots.into_iter().filter(|r| *r > 0.0 && *r < 1.0)
}
/// Whether control point `c` lies on the segment `a`–`b` (within rounding).
fn on_chord(a: Vec2, c: Vec2, b: Vec2) -> bool {
let (mut d, mut v) = (b - a, c - a);
// Scaled to the largest component first, so squaring coordinates near 1e154 and above does
// not overflow and make a curve look straight.
let scale = d.x.abs().max(d.y.abs()).max(v.x.abs()).max(v.y.abs());
if scale.is_finite() && scale > 0.0 {
(d, v) = (Vec2::new(d.x / scale, d.y / scale), Vec2::new(v.x / scale, v.y / scale));
}
let dd = d.dot(d);
if dd <= 0.0 {
// A segment of zero length is straight when its handles sit on its point.
return v == Vec2::ZERO;
}
let t = v.dot(d) / dd;
let off = v - d * t;
(0.0..=1.0).contains(&t) && off.dot(off) <= dd * 1e-28
}
/// A path of cubic Bezier segments with an arc-length table per segment, built once, so a point
/// at a distance along it costs a binary search and a few curve evaluations and does not
/// allocate.
///
/// A distance before the start or past the end continues in a straight line along the path's
/// direction there, so an ease that overshoots carries the motion past the end the same way on
/// curved and straight paths.
#[derive(Clone, Debug, PartialEq)]
pub struct MotionPath {
segments: Vec<Segment>,
length: f64,
/// The first and last segments that have length (the first and last when none has), so the
/// ends' directions skip anchors repeated at an end.
ends: (usize, usize),
}
impl MotionPath {
/// A path from the absolute points `[p0, c1, c2, p1, c3, c4, p2, …]` (3n + 1 of them, n from
/// 1 to [`MAX_PATH_SEGMENTS`]). An error for a wrong count, a point that is not finite, or
/// a path too long to measure.
pub fn new(points: &[Vec2]) -> Result<MotionPath, EaseError> {
if points.len() < 4 {
return Err(EaseError::TooFew { what: "a motion path", need: 4 });
}
if points.len() % 3 != 1 {
return Err(EaseError::OutOfRange { what: "the point count (3n + 1)", min: 4.0, max: (3 * MAX_PATH_SEGMENTS + 1) as f64 });
}
if points.len() > 3 * MAX_PATH_SEGMENTS + 1 {
return Err(EaseError::Full(MAX_PATH_SEGMENTS));
}
if points.iter().any(|p| !p.is_finite()) {
return Err(EaseError::NotFinite("path point"));
}
let mut segments = Vec::with_capacity(points.len() / 3);
let mut start = 0.0;
for w in points.windows(4).step_by(3) {
let [a, b, c, d] = w else { continue };
let s = Segment::new([*a, *b, *c, *d], start);
start += s.length();
segments.push(s);
}
if !start.is_finite() {
return Err(EaseError::Overflow);
}
let first = segments.iter().position(|g| g.length() > 0.0).unwrap_or(0);
let last = segments.iter().rposition(|g| g.length() > 0.0).unwrap_or(segments.len().saturating_sub(1));
Ok(MotionPath { segments, length: start, ends: (first, last) })
}
/// A smooth path through `anchors` (at least 2), its handles set automatically: each inner
/// anchor's handles point along the line from the anchor before it to the anchor after it,
/// a sixth of that line long, and an end anchor's handle points a sixth of the way toward
/// its neighbor. A side that faces an anchor at the same place has no handle, so two equal
/// anchors make a segment of zero length.
pub fn through(anchors: &[Vec2]) -> Result<MotionPath, EaseError> {
if anchors.len() < 2 {
return Err(EaseError::TooFew { what: "a motion path", need: 2 });
}
if anchors.len() > MAX_PATH_SEGMENTS + 1 {
return Err(EaseError::Full(MAX_PATH_SEGMENTS));
}
if anchors.iter().any(|p| !p.is_finite()) {
return Err(EaseError::NotFinite("path point"));
}
let n = anchors.len();
let at = |i: usize| anchors.get(i).copied().unwrap_or(Vec2::ZERO);
let handles = |i: usize| -> (Vec2, Vec2) {
let (a, p, c) = (at(i.saturating_sub(1)), at(i), at((i + 1).min(n - 1)));
let out = (c - a) * (1.0 / 6.0);
let h_in = if i > 0 && a == p { Vec2::ZERO } else { -out };
let h_out = if i + 1 < n && c == p { Vec2::ZERO } else { out };
(h_in, h_out)
};
let mut points = Vec::with_capacity(3 * n - 2);
for i in 0..n {
let (h_in, h_out) = handles(i);
if i > 0 {
points.push(at(i) + h_in);
}
points.push(at(i));
if i + 1 < n {
points.push(at(i) + h_out);
}
}
MotionPath::new(&points)
}
/// The path's length.
pub fn length(&self) -> f64 {
self.length
}
/// How many segments the path has.
pub fn segments(&self) -> usize {
self.segments.len()
}
/// The segment holding distance `s` (clamped to the path) and the distance into it.
fn locate(&self, s: f64) -> Option<(&Segment, f64)> {
let i = self.segments.partition_point(|g| g.start <= s).saturating_sub(1);
let g = self.segments.get(i)?;
Some((g, s - g.start))
}
/// The segments at the ends (see the `ends` field).
fn ends(&self) -> Option<(&Segment, &Segment)> {
Some((self.segments.get(self.ends.0)?, self.segments.get(self.ends.1)?))
}
/// The point `s` along the path. Before the start and past the end it continues along the
/// path's direction there; NaN and −∞ give the start, and +∞ the end.
pub fn point_at_length(&self, s: f64) -> Vec2 {
let Some((first, last)) = self.ends() else { return Vec2::ZERO };
if s.is_nan() || s <= 0.0 {
let s = if s.is_finite() { s } else { 0.0 };
return first.p[0] + first.direction(0.0) * s;
}
if s >= self.length {
let past = if s.is_finite() { s - self.length } else { 0.0 };
return last.p[3] + last.direction(1.0) * past;
}
match self.locate(s) {
Some((g, into)) if g.straight => {
let len = g.length();
if len > 0.0 { g.p[0].lerp(g.p[3], into / len) } else { g.p[0] }
}
Some((g, into)) => g.point(g.param_at(into)),
None => first.p[0],
}
}
/// The point `progress` of the way along the path (0 the start, 1 the end).
pub fn point_at(&self, progress: f64) -> Vec2 {
self.point_at_length(progress * self.length)
}
/// The unit direction of travel `s` along the path (zero for a path of zero length).
pub fn direction_at_length(&self, s: f64) -> Vec2 {
let Some((first, last)) = self.ends() else { return Vec2::ZERO };
if s.is_nan() || s <= 0.0 {
return first.direction(0.0);
}
if s >= self.length {
return last.direction(1.0);
}
match self.locate(s) {
Some((g, into)) => g.direction(g.param_at(into)),
None => Vec2::ZERO,
}
}
}
+203
View File
@@ -0,0 +1,203 @@
//! [`SampledEase`]: an ease kept as a table of values.
use crate::Vec2;
use crate::custom::{CustomEase, EasePoint, MAX_EASE_Y};
/// Most samples a sampled ease keeps (longer tables are thinned evenly).
pub const MAX_EASE_SAMPLES: usize = 1025;
/// Points of the custom curve a sampled ease becomes when edited (of [`crate::MAX_EASE_POINTS`]).
pub const POLYLINE_POINTS: usize = 48;
/// Longest source or ease id a sampled ease keeps.
const MAX_EASE_ID: usize = 64;
/// Longest name a sampled ease keeps.
const MAX_EASE_NAME: usize = 64;
/// An ease as a table: `values[i]` is the eased progress at `t = i / (n - 1)`, read between
/// samples by linear interpolation, so evaluation is a constant-time function of `t`. It keeps
/// a name and where it came from (a source id, such as a plug-in's, and the ease's id there).
///
/// Always valid, however it was made: 2 to [`MAX_EASE_SAMPLES`] finite values within
/// ±[`MAX_EASE_Y`], starting at exactly 0 and ending at exactly 1.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(from = "SampledEaseFile"))]
pub struct SampledEase {
name: String,
plugin: String,
ease: String,
values: Vec<f64>,
}
#[cfg(feature = "serde")]
#[derive(serde::Deserialize)]
struct SampledEaseFile {
#[serde(default, deserialize_with = "read_name")]
name: String,
#[serde(default, deserialize_with = "read_id")]
plugin: String,
#[serde(default, deserialize_with = "read_id")]
ease: String,
#[serde(default, deserialize_with = "read_values")]
values: Vec<f64>,
}
/// Most values read from a file's list; the rest are skipped.
#[cfg(feature = "serde")]
const MAX_SAMPLE_INPUT: usize = 65_536;
#[cfg(feature = "serde")]
fn read_name<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
crate::read_cleaned(d, |s| ease_name(s).unwrap_or_default())
}
#[cfg(feature = "serde")]
fn read_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
crate::read_cleaned(d, ease_id)
}
#[cfg(feature = "serde")]
fn read_values<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<f64>, D::Error> {
crate::read_first(d, MAX_SAMPLE_INPUT)
}
#[cfg(feature = "serde")]
impl From<SampledEaseFile> for SampledEase {
fn from(f: SampledEaseFile) -> SampledEase {
SampledEase::new(&f.name, &f.plugin, &f.ease, f.values)
}
}
/// An id as a sampled ease keeps it: `[A-Za-z0-9._-]`, at most [`MAX_EASE_ID`] characters.
fn ease_id(s: &str) -> String {
s.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')).take(MAX_EASE_ID).collect()
}
/// A name as kept: control characters, bidirectional overrides and invisible format characters
/// (zero-width spaces and joiners, word joiners, the byte-order mark, soft hyphens) removed,
/// trimmed, at most [`MAX_EASE_NAME`] characters; `None` when nothing is left.
fn ease_name(name: &str) -> Option<String> {
let n: String = name
.chars()
.filter(|c| {
!c.is_control()
&& !matches!(
c,
'\u{ad}' | '\u{180e}' | '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2060}'..='\u{2069}' | '\u{feff}'
)
})
.skip_while(|c| c.is_whitespace())
.take(MAX_EASE_NAME)
.collect();
let n = n.trim().to_string();
(!n.is_empty()).then_some(n)
}
/// The index of the `k`th of [`MAX_EASE_SAMPLES`] samples spread evenly over `n` values,
/// computed in 128 bits so a long table cannot overflow a 32-bit `usize`.
pub(crate) fn thinned(k: usize, n: usize) -> usize {
let i = (k as u128) * (n.saturating_sub(1) as u128) / ((MAX_EASE_SAMPLES - 1) as u128);
usize::try_from(i).unwrap_or(usize::MAX)
}
impl SampledEase {
/// A valid table from any values (see the type's docs): a longer table is thinned evenly, a
/// value that is not finite becomes the straight line's, values are clamped, the ends pinned;
/// fewer than two values make the straight line.
pub fn new(name: &str, plugin: &str, ease: &str, mut values: Vec<f64>) -> SampledEase {
if values.len() > MAX_EASE_SAMPLES {
let n = values.len();
values = (0..MAX_EASE_SAMPLES).filter_map(|k| values.get(thinned(k, n)).copied()).collect();
}
if values.len() < 2 {
values = vec![0.0, 1.0];
}
let last = (values.len() - 1) as f64;
for (i, v) in values.iter_mut().enumerate() {
*v = if v.is_finite() { v.clamp(-MAX_EASE_Y, MAX_EASE_Y) } else { i as f64 / last };
}
if let Some(v) = values.first_mut() {
*v = 0.0;
}
if let Some(v) = values.last_mut() {
*v = 1.0;
}
SampledEase { name: ease_name(name).unwrap_or_else(|| "Sampled ease".to_string()), plugin: ease_id(plugin), ease: ease_id(ease), values }
}
/// The name an ease menu shows.
pub fn name(&self) -> &str {
&self.name
}
/// The id of the source it came from.
pub fn plugin(&self) -> &str {
&self.plugin
}
/// Its id within that source.
pub fn ease(&self) -> &str {
&self.ease
}
pub fn values(&self) -> &[f64] {
&self.values
}
/// A table a caller supplies, checked: an error for a value that is not finite or outside
/// ±[`MAX_EASE_Y`], fewer than 2 values or more than [`MAX_EASE_SAMPLES`]. The ends are then
/// pinned to 0 and 1 as [`SampledEase::new`] does.
pub fn try_new(name: &str, plugin: &str, ease: &str, values: Vec<f64>) -> Result<SampledEase, crate::EaseError> {
for v in &values {
crate::within(*v, -MAX_EASE_Y, MAX_EASE_Y, "sample")?;
}
if values.len() < 2 {
return Err(crate::EaseError::TooFew { what: "a sampled ease", need: 2 });
}
if values.len() > MAX_EASE_SAMPLES {
return Err(crate::EaseError::Full(MAX_EASE_SAMPLES));
}
Ok(SampledEase::new(name, plugin, ease, values))
}
/// The eased value at time `t`, between the two nearest samples. `t` outside `0..=1` is
/// clamped, and NaN reads as 0.
pub fn apply(&self, t: f64) -> f64 {
let t = if t.is_finite() {
t.clamp(0.0, 1.0)
} else if t > 0.0 {
1.0
} else {
0.0
};
let last = self.values.len().saturating_sub(1);
if last == 0 {
return t;
}
let x = t * last as f64;
let i = (x.floor() as usize).min(last - 1);
let f = x - i as f64;
let (a, b) = (self.values.get(i).copied().unwrap_or(0.0), self.values.get(i + 1).copied().unwrap_or(1.0));
a + (b - a) * f
}
/// The custom curve of straight segments through [`POLYLINE_POINTS`] of its samples, for a
/// graph editor: editing a sampled ease makes it a custom ease drawn like it, with room left
/// to add points.
pub fn to_polyline(&self) -> CustomEase {
let n = self.values.len();
let m = POLYLINE_POINTS.min(n).max(2);
let at: Vec<Vec2> = (0..m)
.map(|k| {
let i = k * (n - 1) / (m - 1);
Vec2::new(i as f64 / (n - 1).max(1) as f64, self.values.get(i).copied().unwrap_or(0.0))
})
.collect();
let pts = at
.iter()
.enumerate()
.map(|(k, p)| {
let prev = if k == 0 { *p } else { at.get(k - 1).copied().unwrap_or(*p) };
let next = at.get(k + 1).copied().unwrap_or(*p);
EasePoint { at: *p, h_in: (prev - *p) * (1.0 / 3.0), out: (next - *p) * (1.0 / 3.0), smooth: false }
})
.collect();
CustomEase::new(pts)
}
}
+247
View File
@@ -0,0 +1,247 @@
//! Damped springs: [`Spring`] and [`SpringState`].
//!
//! A spring pulls a value `x` toward a target with
//!
//! ```text
//! x'' = −ω² (x − target) − 2ζω x'
//! ```
//!
//! where `ω` is the natural angular frequency and `ζ` the damping ratio (below 1 the value
//! overshoots and swings back, at 1 it arrives as fast as it can without overshooting, above 1
//! it creeps in). [`SpringState::step`] moves the value by the exact solution of that equation
//! over the step, so a step costs O(1), any step length is stable, and many short steps give the
//! same value as one long one.
use crate::{EaseError, within};
/// Highest natural frequency a spring may have, in swings per second.
pub const MAX_SPRING_HZ: f64 = 10_000.0;
/// Highest damping ratio a spring may have.
pub const MAX_DAMPING_RATIO: f64 = 1e6;
/// The ranges [`Spring::from_physical`] accepts: mass, stiffness and damping coefficient.
const MASS: (f64, f64) = (0.01, 1e4);
const STIFFNESS: (f64, f64) = (0.01, 1e6);
const DAMPING: (f64, f64) = (0.0, 1e6);
/// Longest motion a spring ease plays, in seconds of the spring's own time.
const MAX_SETTLE: f64 = 10.0;
/// A damped spring's constants.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Spring {
omega: f64,
zeta: f64,
}
impl Spring {
/// A spring that would swing `frequency` times a second without damping, with damping ratio
/// `damping`. `frequency` must be above 0 and at most [`MAX_SPRING_HZ`], `damping` within 0
/// to [`MAX_DAMPING_RATIO`].
pub fn new(frequency: f64, damping: f64) -> Result<Spring, EaseError> {
let f = within(frequency, 0.0, MAX_SPRING_HZ, "frequency")?;
if f <= 0.0 {
return Err(EaseError::OutOfRange { what: "frequency", min: f64::MIN_POSITIVE, max: MAX_SPRING_HZ });
}
let z = within(damping, 0.0, MAX_DAMPING_RATIO, "damping")?;
Ok(Spring::raw(f, z))
}
/// A spring from two `0..=1` controls: `strength` sets the frequency from 0.5 to 10 swings a
/// second, evenly spread in pitch, and `damping` the ratio (0 swings on, 2/3 is critical,
/// 1 gives [`MAX_DAMPING_RATIO`]).
pub fn from_controls(strength: f64, damping: f64) -> Result<Spring, EaseError> {
let s = within(strength, 0.0, 1.0, "strength")?;
let d = within(damping, 0.0, 1.0, "damping")?;
let zeta = if d >= 1.0 { MAX_DAMPING_RATIO } else { (0.5 * d / (1.0 - d)).min(MAX_DAMPING_RATIO) };
Ok(Spring::raw(0.5 * 20f64.powf(s), zeta))
}
/// A mass on a spring with damping: `mass` within 0.01 to 10,000, `stiffness` within 0.01
/// to 1,000,000 and the damping coefficient `damping` within 0 to 1,000,000. An error when
/// the three give a damping ratio above [`MAX_DAMPING_RATIO`].
pub fn from_physical(mass: f64, stiffness: f64, damping: f64) -> Result<Spring, EaseError> {
let m = within(mass, MASS.0, MASS.1, "mass")?;
let k = within(stiffness, STIFFNESS.0, STIFFNESS.1, "stiffness")?;
let c = within(damping, DAMPING.0, DAMPING.1, "damping")?;
if c / (2.0 * (k * m).sqrt()) > MAX_DAMPING_RATIO {
return Err(EaseError::OutOfRange { what: "damping ratio", min: 0.0, max: MAX_DAMPING_RATIO });
}
Ok(Spring::physical(m, k, c))
}
/// [`Spring::from_physical`] with each value brought into its range (a value that is not
/// finite takes the default: mass 1, stiffness 100, damping 15).
pub(crate) fn physical_lenient(mass: f64, stiffness: f64, damping: f64) -> Spring {
let ok = |v: f64, (lo, hi): (f64, f64), d: f64| if v.is_finite() { v.clamp(lo, hi) } else { d };
Spring::physical(ok(mass, MASS, 1.0), ok(stiffness, STIFFNESS, 100.0), ok(damping, DAMPING, 15.0))
}
fn physical(m: f64, k: f64, c: f64) -> Spring {
Spring { omega: (k / m).sqrt(), zeta: (c / (2.0 * (k * m).sqrt())).min(MAX_DAMPING_RATIO) }
}
/// A spring from values already in range.
pub(crate) fn raw(frequency: f64, damping: f64) -> Spring {
Spring { omega: std::f64::consts::TAU * frequency, zeta: damping }
}
/// Seconds until a spring released from rest stays within about 0.1 % of its target, at
/// least 0.05 and at most 10.
pub fn settle_time(&self) -> f64 {
let (w, z) = (self.omega, self.zeta);
// The slowest mode's decay rate; e^−6.9 is 0.1 %, and a critically or over-damped
// spring's larger lead factor needs about 9.2. Released from rest, an under-damped
// spring's offset stays within e^−ζωt · min(1/√(1 − ζ²), 1 + ζωt), so its lead factor
// grows by ln(1/√(1 − ζ²)) up to the critical spring's 9.2.
let (rate, k) = if z < 1.0 { (z * w, (6.9 - 0.5 * (1.0 - z * z).ln()).min(9.2)) } else { (w / (z + (z * z - 1.0).sqrt()), 9.2) };
let settle = if rate > 1e-6 { (k / rate).clamp(0.05, MAX_SETTLE) } else { MAX_SETTLE };
if settle.is_finite() { settle } else { MAX_SETTLE }
}
/// The spring as an ease: released from rest at 0 toward 1, `t` of the way through its
/// [`Spring::settle_time`]. Exactly 0 at `t <= 0` and exactly 1 at `t >= 1`. A spring with
/// so little damping that it is still moving after 10 seconds has the distance it is still
/// off at that point taken out evenly over the ease, so it reaches 1 without a jump.
pub fn ease(&self, t: f64) -> f64 {
if t.is_nan() || t <= 0.0 {
return 0.0;
}
if t >= 1.0 {
return 1.0;
}
let settle = self.settle_time();
let mut x = 1.0 + self.response(-1.0, 0.0, t * settle).0;
if settle >= MAX_SETTLE {
x -= t * self.response(-1.0, 0.0, settle).0;
}
if x.is_finite() { x } else { 1.0 }
}
/// The natural angular frequency `ω`, in radians a second.
pub fn omega(&self) -> f64 {
self.omega
}
/// The damping ratio `ζ`.
pub fn damping(&self) -> f64 {
self.zeta
}
/// Offset and velocity `(y, v)` after `t` seconds, from offset `y0` (value minus target) and
/// velocity `v0`: the exact solution of the spring equation.
pub(crate) fn response(&self, y0: f64, v0: f64, t: f64) -> (f64, f64) {
let (w, z) = (self.omega, self.zeta);
if t <= 0.0 {
return (y0, v0);
}
// Past this much decay e^(−decay) is below the smallest f64: the spring has settled.
const SETTLED: f64 = 800.0;
// Damping ratios near 1 use the under- and over-damped solutions below, which stay
// precise there, so every ratio is solved as given; only exactly 1 is critical.
if z == 1.0 {
if w * t > SETTLED {
return (0.0, 0.0);
}
let b = v0 + w * y0;
let e = (-w * t).exp();
// The velocity is e^−ωt (v0 − ω b t), written so v0 is not recovered by subtracting
// the rounded position terms.
return (e * (y0 + b * t), e * (v0 - w * (b * t)));
}
if z < 1.0 {
if z * w * t > SETTLED {
return (0.0, 0.0);
}
// 1 − ζ² as (1 − ζ)(1 + ζ), precise for ζ near 1.
let wd = w * ((1.0 - z) * (1.0 + z)).sqrt();
let q = v0 + z * w * y0;
let e = (-z * w * t).exp();
// A step so long that the phase overflows (a spring with little or no damping) is
// reduced by whole periods first.
let reduced = !(wd * t).is_finite();
let phase = if reduced { wd * (t % (std::f64::consts::TAU / wd)) } else { wd * t };
let (s, c) = phase.sin_cos();
// sin(phase) / ωd is at most t, so it stays finite for a spring of any low frequency,
// where q / ωd alone would overflow. A small unreduced phase uses t · sin(phase) / phase
// from its series, which is t when ωd or the phase rounds to 0.
let sw = if !reduced && phase < 1e-4 {
let p2 = phase * phase;
t * (1.0 - p2 / 6.0 * (1.0 - p2 / 20.0))
} else {
s / wd
};
return (e * (y0 * c + q * sw), e * (v0 * c - (y0 * wd * s + z * w * q * sw)));
}
// ζ² − 1 as (ζ − 1)(ζ + 1), precise for ζ near 1.
let root = ((z - 1.0) * (z + 1.0)).sqrt();
// r1 = −ω(ζ − √(ζ² − 1)), written without the cancellation for large ζ.
let (r1, r2) = (-w / (z + root), -w * (z + root));
if -r1 * t > SETTLED {
return (0.0, 0.0);
}
// Written with the divided difference q = (e1 − e2) / (r1 − r2) rather than the two modes'
// coefficients, which overflow (in opposite signs) when r1 − r2 is tiny.
let (e1, e2) = ((r1 * t).exp(), (r2 * t).exp());
let x = (r1 - r2) * t;
let q = if x <= 1.0 {
// e2 · t · (e^x − 1) / x, with its series where x is too small for expm1's quotient.
let g = if x < 1e-5 { 1.0 + x * (0.5 + x / 6.0) } else { x.exp_m1() / x };
e2 * t * g
} else {
(e1 - e2) / (r1 - r2)
};
(y0 * (e1 - r1 * q) + v0 * q, v0 * (e2 + r1 * q) - y0 * (w * w) * q)
}
}
/// A value moved by a spring: where it is and how fast it moves.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct SpringState {
pub value: f64,
pub velocity: f64,
}
impl SpringState {
/// A value at rest at `value`.
pub fn at(value: f64) -> SpringState {
SpringState { value, velocity: 0.0 }
}
/// Moves the value `dt` seconds toward `target` (which holds still over the step) and
/// returns the new value. An error, with the state unchanged, for a `target` or `dt` that is
/// not finite, a negative `dt`, or a result too large to represent. A state whose value or
/// velocity is not finite is refused with [`EaseError::Overflow`] at every step length, and
/// stays as it is.
pub fn step(&mut self, spring: &Spring, target: f64, dt: f64) -> Result<f64, EaseError> {
let target = crate::finite(target, "target")?;
let dt = within(dt, 0.0, f64::MAX, "step")?;
if !(self.value.is_finite() && self.velocity.is_finite()) {
return Err(EaseError::Overflow);
}
if dt == 0.0 {
return Ok(self.value);
}
let (y, v) = spring.response(self.value - target, self.velocity, dt);
let (mut value, mut v) = (target + y, v);
if !(value.is_finite() && v.is_finite()) {
// The motion is linear in the offset and velocity, so they are moved again scaled by
// a power of two to at most 2, for a value and target near opposite ends of the f64
// range whose step overflowed on the way.
let (hy, hv) = (0.5 * self.value - 0.5 * target, 0.5 * self.velocity);
let m = hy.abs().max(hv.abs());
let scale = if m > 0.0 && m.is_finite() { 2f64.powi((m.log2().ceil() as i32).min(1023)) } else { 1.0 };
let (y, w) = spring.response(hy / scale, hv / scale, dt);
(value, v) = (2.0 * (0.5 * target + y * scale), 2.0 * (w * scale));
}
if !(value.is_finite() && v.is_finite()) {
return Err(EaseError::Overflow);
}
*self = SpringState { value, velocity: v };
Ok(value)
}
/// Whether the value is within `tolerance` of `target` and moves slower than `tolerance`
/// a second.
pub fn settled(&self, target: f64, tolerance: f64) -> bool {
(self.value - target).abs() <= tolerance && self.velocity.abs() <= tolerance
}
}
File diff suppressed because it is too large. Load diff
+227
View File
@@ -0,0 +1,227 @@
use crate::*;
/// A quarter circle of radius 100 about the origin, from (100, 0) to (0, 100).
fn quarter() -> MotionPath {
let k = 4.0 / 3.0 * (std::f64::consts::PI / 8.0).tan() * 100.0;
MotionPath::new(&[Vec2::new(100.0, 0.0), Vec2::new(100.0, k), Vec2::new(k, 100.0), Vec2::new(0.0, 100.0)]).unwrap()
}
/// The length of the curve through `n` evenly spaced points along it.
fn polyline_length(p: &MotionPath, n: usize) -> f64 {
(1..=n).map(|i| p.point_at_length(p.length() * i as f64 / n as f64).distance(p.point_at_length(p.length() * (i - 1) as f64 / n as f64))).sum()
}
/// A tiny curve is walked at constant speed like the same curve at full size.
#[test]
fn a_tiny_curve_is_walked_at_constant_speed() {
let r = 1e-15;
let k = 4.0 / 3.0 * (std::f64::consts::PI / 8.0).tan() * r;
let tiny = MotionPath::new(&[Vec2::new(r, 0.0), Vec2::new(r, k), Vec2::new(k, r), Vec2::new(0.0, r)]).unwrap();
let big = quarter();
for i in 1..20 {
let t = i as f64 / 20.0;
let (a, b) = (tiny.point_at(t), big.point_at(t));
assert!((a.x / r - b.x / 100.0).abs() < 1e-9 && (a.y / r - b.y / 100.0).abs() < 1e-9, "{t}: {a:?} vs {b:?}");
}
}
#[test]
fn a_curve_is_measured_and_walked_at_constant_speed() {
let p = quarter();
// The Bezier quarter circle is within 0.03 % of the circle's length.
assert!((p.length() - 50.0 * std::f64::consts::PI).abs() < 0.05, "{}", p.length());
assert!((polyline_length(&p, 20_000) - p.length()).abs() < 1e-6, "{} vs {}", polyline_length(&p, 20_000), p.length());
// Equal steps of distance are equal chords.
let n = 200;
let steps: Vec<f64> = (1..=n).map(|i| p.point_at(i as f64 / n as f64).distance(p.point_at((i - 1) as f64 / n as f64))).collect();
let (lo, hi) = steps.iter().fold((f64::MAX, f64::MIN), |(lo, hi), s| (lo.min(*s), hi.max(*s)));
assert!(hi - lo < 1e-6, "{lo}..{hi}");
assert_eq!(p.point_at(0.0), Vec2::new(100.0, 0.0));
let end = p.point_at(1.0);
assert!(end.distance(Vec2::new(0.0, 100.0)) < 1e-9, "{end:?}");
// Each point is on the curve: about 100 from the center.
for i in 0..=50 {
let r = p.point_at(i as f64 / 50.0).length();
assert!((r - 100.0).abs() < 0.03, "{r}");
}
}
#[test]
fn a_straight_segment_with_uneven_handles_still_moves_evenly() {
// Handles on the chord but bunched near the start: the curve's own parameter speeds up.
let p = MotionPath::new(&[Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::new(2.0, 0.0), Vec2::new(100.0, 0.0)]).unwrap();
assert_eq!(p.length(), 100.0);
for i in 0..=10 {
assert_eq!(p.point_at(i as f64 / 10.0), Vec2::new(i as f64 * 10.0, 0.0));
}
}
#[test]
fn past_the_ends_the_motion_continues_along_the_path() {
let p = quarter();
// At the end the circle heads in −x; past it the point keeps going that way.
let past = p.point_at_length(p.length() + 10.0);
assert!(past.distance(Vec2::new(-10.0, 100.0)) < 1e-6, "{past:?}");
let before = p.point_at_length(-5.0);
assert!(before.distance(Vec2::new(100.0, -5.0)) < 1e-6, "{before:?}");
// A track's overshooting ease drives the same distance through point_at.
let over = Easing::BackOut;
let peak = (1..100).map(|i| over.apply(i as f64 / 100.0)).fold(f64::MIN, f64::max);
let beyond = p.point_at(peak);
assert!(beyond.x < 0.0 && (beyond.y - 100.0).abs() < 1e-6, "{beyond:?}");
let d = p.direction_at_length(p.length() * 2.0);
assert!(d.distance(Vec2::new(-1.0, 0.0)) < 1e-9, "{d:?}");
assert_eq!(p.point_at_length(f64::INFINITY), p.point_at(1.0));
assert_eq!(p.point_at_length(f64::NAN), Vec2::new(100.0, 0.0));
assert_eq!(p.point_at_length(f64::NEG_INFINITY), Vec2::new(100.0, 0.0));
let flat = MotionPath::new(&[Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::new(2.0, 0.0), Vec2::new(3.0, 0.0)]).unwrap();
assert_eq!(flat.point_at_length(f64::NEG_INFINITY), Vec2::ZERO);
}
/// Moving a handle off the chord by a rounding error does not change where an overshoot goes.
#[test]
fn an_overshoot_goes_the_same_way_on_a_straight_and_an_almost_straight_path() {
let straight = MotionPath::new(&[Vec2::ZERO, Vec2::new(30.0, 0.0), Vec2::new(70.0, 0.0), Vec2::new(100.0, 0.0)]).unwrap();
let bent = MotionPath::new(&[Vec2::ZERO, Vec2::new(30.0, 1e-6), Vec2::new(70.0, 0.0), Vec2::new(100.0, 0.0)]).unwrap();
for progress in [-0.2, 1.1, 1.25] {
let (a, b) = (straight.point_at(progress), bent.point_at(progress));
assert!(a.distance(b) < 0.01, "{progress}: {a:?} vs {b:?}");
}
assert!(straight.point_at(1.25).distance(Vec2::new(125.0, 0.0)) < 1e-9);
}
#[test]
fn a_path_through_anchors_passes_through_each_one() {
let anchors = [Vec2::new(0.0, 0.0), Vec2::new(100.0, 50.0), Vec2::new(200.0, 0.0), Vec2::new(300.0, 80.0)];
let p = MotionPath::through(&anchors).unwrap();
assert_eq!(p.segments(), 3);
// Each anchor is reached at some distance along it.
for a in anchors {
let nearest = (0..=4000).map(|i| p.point_at(i as f64 / 4000.0).distance(a)).fold(f64::MAX, f64::min);
assert!(nearest < 0.1, "{a:?}: {nearest}");
}
// Smooth through the inner anchors: no turn in direction across them.
let mut prev = p.direction_at_length(0.0);
for i in 1..=2000 {
let d = p.direction_at_length(p.length() * i as f64 / 2000.0);
assert!(d.dot(prev) > 0.99, "a corner at {i}");
prev = d;
}
// Two anchors at one place make a segment of zero length, which is skipped over.
let q = MotionPath::through(&[Vec2::ZERO, Vec2::new(10.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(20.0, 0.0)]).unwrap();
assert!((q.length() - 20.0).abs() < 1e-9, "{}", q.length());
assert!(q.point_at(0.75).distance(Vec2::new(15.0, 0.0)) < 1e-6);
// Anchors repeated at either end still let the motion continue past it.
let r = MotionPath::through(&[Vec2::ZERO, Vec2::ZERO, Vec2::new(10.0, 0.0), Vec2::new(10.0, 0.0)]).unwrap();
assert!(r.point_at(1.2).distance(Vec2::new(12.0, 0.0)) < 1e-6, "{:?}", r.point_at(1.2));
assert!(r.point_at(-0.1).distance(Vec2::new(-1.0, 0.0)) < 1e-6, "{:?}", r.point_at(-0.1));
assert!(r.direction_at_length(20.0).distance(Vec2::new(1.0, 0.0)) < 1e-9);
assert!(r.direction_at_length(-1.0).distance(Vec2::new(1.0, 0.0)) < 1e-9);
}
#[test]
fn bad_paths_are_refused() {
assert_eq!(MotionPath::new(&[Vec2::ZERO; 3]), Err(EaseError::TooFew { what: "a motion path", need: 4 }));
assert!(matches!(MotionPath::new(&[Vec2::ZERO; 5]), Err(EaseError::OutOfRange { .. })));
assert_eq!(MotionPath::new(&[Vec2::ZERO, Vec2::new(f64::NAN, 0.0), Vec2::ZERO, Vec2::ZERO]), Err(EaseError::NotFinite("path point")));
assert_eq!(MotionPath::new(&vec![Vec2::ZERO; 3 * MAX_PATH_SEGMENTS + 4]), Err(EaseError::Full(MAX_PATH_SEGMENTS)));
assert_eq!(MotionPath::through(&[Vec2::ZERO]), Err(EaseError::TooFew { what: "a motion path", need: 2 }));
assert_eq!(MotionPath::through(&[Vec2::ZERO, Vec2::new(0.0, f64::INFINITY)]), Err(EaseError::NotFinite("path point")));
// A path too long to measure.
assert_eq!(
MotionPath::new(&[Vec2::new(-f64::MAX, 0.0), Vec2::new(-f64::MAX, 0.0), Vec2::new(f64::MAX, 0.0), Vec2::new(f64::MAX, 0.0)]),
Err(EaseError::Overflow)
);
// A path of one point stands still.
let still = MotionPath::new(&[Vec2::new(3.0, 4.0); 4]).unwrap();
assert_eq!((still.length(), still.point_at(0.5), still.direction_at_length(1.0)), (0.0, Vec2::new(3.0, 4.0), Vec2::ZERO));
}
/// A curve with huge coordinates (whose squares overflow) is walked as the same curve scaled,
/// not taken for a straight line.
#[test]
fn a_huge_curve_is_not_taken_for_a_straight_line() {
let shape = |k: f64| MotionPath::new(&[Vec2::ZERO, Vec2::new(0.0, k), Vec2::new(0.0, k), Vec2::new(2.0 * k, 0.0)]).unwrap();
let (small, huge) = (shape(1.0), shape(1e154));
for i in 0..=10 {
let t = i as f64 / 10.0;
let (a, b) = (small.point_at(t), huge.point_at(t));
assert!((b.x / 1e154 - a.x).abs() < 1e-9 && (b.y / 1e154 - a.y).abs() < 1e-9, "{t}: {a:?} vs {b:?}");
}
assert!(huge.point_at(0.5).y > 5e153, "{:?}", huge.point_at(0.5));
// A long chord with handles a small distance off it still bends.
let long = MotionPath::new(&[Vec2::ZERO, Vec2::new(1e12 / 3.0, 1000.0), Vec2::new(2e12 / 3.0, 1000.0), Vec2::new(1e12, 0.0)]).unwrap();
let mid = long.point_at_length(long.length() / 2.0);
assert!((mid.y - 750.0).abs() < 1.0, "{mid:?}");
}
/// Paths whose length is representable are measured even when their scale is near the f64 limit.
#[test]
fn a_path_near_the_largest_length_is_measured() {
let straight = MotionPath::new(&[Vec2::ZERO, Vec2::new(1e307 / 3.0, 0.0), Vec2::new(2e307 / 3.0, 0.0), Vec2::new(1e307, 0.0)]).unwrap();
assert_eq!(straight.length(), 1e307);
assert!((straight.point_at(0.5).x / 5e306 - 1.0).abs() < 1e-12, "{:?}", straight.point_at(0.5));
let curved = MotionPath::new(&[Vec2::ZERO, Vec2::ZERO, Vec2::new(0.0, 1e306), Vec2::new(5e307, 0.0)]).unwrap();
assert!(curved.length() > 5e307 && curved.length() < 5.2e307, "{}", curved.length());
assert!(curved.point_at(1.0).distance(Vec2::new(5e307, 0.0)) < 1e295);
}
/// A distance close to a start where the curve stands still is found on the curve, not where a
/// few Newton steps from the table's guess happen to stop.
#[test]
fn a_short_distance_from_a_still_start_is_found() {
let p = MotionPath::new(&[Vec2::ZERO, Vec2::ZERO, Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0)]).unwrap();
for s in [1e-10, 1e-8, 1e-6] {
let q = p.point_at_length(s);
// The curve leaves the start straight up, so the point is `s` above it.
assert!((q.y - s).abs() < 1e-11 && q.x.abs() < 1e-9, "{s}: {q:?}");
}
}
#[test]
fn a_vector_of_any_finite_size_has_a_unit_direction() {
let h = std::f64::consts::FRAC_1_SQRT_2;
let big = Vec2::new(f64::MAX, f64::MAX).normalized();
assert!((big.x - h).abs() < 1e-15 && (big.y - h).abs() < 1e-15, "{big:?}");
assert_eq!(Vec2::new(-f64::MAX, 0.0).normalized(), Vec2::new(-1.0, 0.0));
let tiny = Vec2::new(f64::from_bits(1), f64::from_bits(1)).normalized();
assert!((tiny.x - h).abs() < 1e-15 && (tiny.y - h).abs() < 1e-15, "{tiny:?}");
let odd = Vec2::new(3.0 * f64::from_bits(1), -4.0 * f64::from_bits(1)).normalized();
assert!((odd.x - 0.6).abs() < 1e-15 && (odd.y + 0.8).abs() < 1e-15, "{odd:?}");
assert_eq!(Vec2::ZERO.normalized(), Vec2::ZERO);
assert_eq!(Vec2::new(f64::INFINITY, 1.0).normalized(), Vec2::ZERO);
assert_eq!(Vec2::new(1.0, f64::NAN).normalized(), Vec2::ZERO);
}
/// The ends of an interpolation are the end values themselves, even where the difference
/// between them rounds.
#[test]
fn interpolating_returns_the_exact_ends() {
let (a, b) = (Vec2::new(1e20, -3.0), Vec2::new(1.0, 1e-30));
assert_eq!(a.lerp(b, 0.0), a);
assert_eq!(a.lerp(b, 1.0), b);
assert_eq!(Vec2::new(-f64::MAX, 0.0).lerp(Vec2::new(f64::MAX, 0.0), 1.0), Vec2::new(f64::MAX, 0.0));
}
/// A curve that stops and turns back inside one table cell is measured to its true length: x
/// runs out to 4/9 at u = 1/3 and back to 0, so the length is 8/9.
#[test]
fn a_curve_that_turns_back_is_measured_exactly() {
let p = MotionPath::new(&[Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::ZERO, Vec2::ZERO]).unwrap();
assert!((p.length() - 8.0 / 9.0).abs() < 1e-12, "{}", p.length());
let turn = p.point_at_length(4.0 / 9.0);
assert!((turn.x - 4.0 / 9.0).abs() < 1e-9 && turn.y == 0.0, "{turn:?}");
for (s, x) in [(0.2, 0.2), (0.6, 4.0 / 9.0 - (0.6 - 4.0 / 9.0)), (0.8, 4.0 / 9.0 - (0.8 - 4.0 / 9.0))] {
let q = p.point_at_length(s);
assert!((q.x - x).abs() < 1e-9, "{s}: {q:?} vs {x}");
}
}
#[test]
fn a_long_path_finds_its_segment_by_binary_search() {
let anchors: Vec<Vec2> = (0..=MAX_PATH_SEGMENTS).map(|i| Vec2::new(i as f64, ((i as f64) * 0.1).sin())).collect();
let p = MotionPath::through(&anchors).unwrap();
assert_eq!(p.segments(), MAX_PATH_SEGMENTS);
let mid = p.point_at(0.5);
assert!(mid.x > 4000.0 && mid.x < 6000.0, "{mid:?}");
}
+347
View File
@@ -0,0 +1,347 @@
use crate::*;
/// A spring released from 0 toward 1, `t` seconds in, from the closed forms written out
/// separately: under-damped, critically damped and over-damped.
fn released(w: f64, z: f64, t: f64) -> f64 {
if z < 1.0 {
let wd = w * (1.0 - z * z).sqrt();
1.0 - (-z * w * t).exp() * ((wd * t).cos() + z * w / wd * (wd * t).sin())
} else if (z - 1.0).abs() < 1e-9 {
1.0 - (-w * t).exp() * (1.0 + w * t)
} else {
let s = (z * z - 1.0).sqrt();
let (r1, r2) = (-w / (z + s), -w * (z + s));
1.0 - (r2 * (r1 * t).exp() - r1 * (r2 * t).exp()) / (r2 - r1)
}
}
const PRESETS: [(f64, f64, f64); 5] = [(1.0, 100.0, 15.0), (1.0, 300.0, 20.0), (1.0, 600.0, 15.0), (1.0, 80.0, 20.0), (2.5, 40.0, 2.0)];
#[test]
fn a_physical_spring_ease_matches_the_closed_form() {
for (m, k, c) in PRESETS {
let spring = Spring::from_physical(m, k, c).unwrap();
let (w, z) = ((k / m).sqrt(), c / (2.0 * (k * m).sqrt()));
assert!((spring.omega() - w).abs() < 1e-12 && (spring.damping() - z).abs() < 1e-12);
let rate = if z < 1.0 { z * w } else { w / (z + (z * z - 1.0).sqrt()) };
let lead = if z < 1.0 { (6.9 - 0.5 * (1.0 - z * z).ln()).min(9.2) } else { 9.2 };
let settle = (lead / rate).clamp(0.05, 10.0);
assert!((spring.settle_time() - settle).abs() < 1e-12);
let ease = Easing::Spring(SpringEase { mass: m, stiffness: k, damping: c });
// A spring cut short at 10 seconds has what it is still off taken out evenly.
let rest = if settle < 10.0 { 0.0 } else { 1.0 - released(w, z, settle) };
for i in 1..1000 {
let t = i as f64 / 1000.0;
let want = released(w, z, t * settle) + t * rest;
assert!((ease.apply(t) - want).abs() < 1e-12, "{m} {k} {c} at {t}: {} vs {want}", ease.apply(t));
}
// It ends within 0.1 % (0.2 % for the slower lead factor) of 1 before the jump to 1.
assert!((ease.apply(0.999_999) - 1.0).abs() < 2e-3, "{m} {k} {c}");
}
}
/// A step of no time returns the value unchanged, even when its distance to the target is too
/// large to represent.
#[test]
fn a_zero_length_step_keeps_a_far_value() {
let spring = Spring::new(1.0, 0.5).unwrap();
let mut s = SpringState::at(1e308);
assert_eq!(s.step(&spring, -1e308, 0.0), Ok(1e308));
assert_eq!(s, SpringState::at(1e308));
// A state that is not finite is still refused.
let mut bad = SpringState::at(f64::NAN);
assert_eq!(bad.step(&spring, 0.0, 0.0), Err(EaseError::Overflow));
}
/// A value and target at opposite ends of the f64 range move like any others.
#[test]
fn a_step_across_the_whole_range_does_not_overflow() {
let spring = Spring::new(1.0, 1.0).unwrap();
let mut s = SpringState::at(f64::MAX);
let v = s.step(&spring, -f64::MAX, 10.0).unwrap();
assert!(v.is_finite() && v < 0.0 && s.velocity.is_finite(), "{s:?}");
}
/// The smallest positive target is reached.
#[test]
fn a_spring_reaches_a_subnormal_target() {
let spring = Spring::new(1.0, 1.0).unwrap();
let mut s = SpringState::at(0.0);
assert_eq!(s.step(&spring, f64::from_bits(1), 1000.0), Ok(f64::from_bits(1)));
}
/// A spring of the lowest frequency still moves at its velocity over a step.
#[test]
fn a_very_slow_spring_steps_without_overflow() {
let spring = Spring::new(1e-320, 0.0).unwrap();
let mut s = SpringState { value: 0.0, velocity: 1.0 };
let v = s.step(&spring, 0.0, 1.0).unwrap();
assert!((v - 1.0).abs() < 1e-12 && (s.velocity - 1.0).abs() < 1e-12, "{s:?}");
// The same over-damped.
let spring = Spring::new(1e-320, 2.0).unwrap();
let mut s = SpringState { value: 0.0, velocity: 1.0 };
let v = s.step(&spring, 0.0, 1.0).unwrap();
assert!((v - 1.0).abs() < 1e-12 && (s.velocity - 1.0).abs() < 1e-12, "{s:?}");
}
/// Physical values whose damping ratio is above the limit are refused, not changed.
#[test]
fn physical_values_past_the_damping_ratio_limit_are_refused() {
assert_eq!(
Spring::from_physical(0.01, 0.01, 1_000_000.0),
Err(EaseError::OutOfRange { what: "damping ratio", min: 0.0, max: MAX_DAMPING_RATIO })
);
assert!(Spring::from_physical(0.01, 0.01, 19.0).is_ok());
}
/// A spring just under critical damping is within about 0.1 % of 1 just before the end, so the
/// ease does not jump when it reaches 1.
#[test]
fn a_nearly_critical_spring_ease_ends_without_a_jump() {
for z in [0.5, 0.9, 0.99, 0.999, 0.9999, 1.0 - 2e-4] {
let s = Spring::new(1.0, z).unwrap();
let end = s.ease(1.0 - 1e-9);
assert!((end - 1.0).abs() < 1.1e-3, "ζ {z}: {end}");
// The bound holds after the settle time too, not only at it.
let late = 1.0 + s.response(-1.0, 0.0, 1.5 * s.settle_time()).0;
assert!((late - 1.0).abs() < 1.1e-3, "ζ {z} later: {late}");
}
}
/// An undamped or barely damped spring ease still arrives at 1 without a jump.
#[test]
fn a_spring_that_never_settles_still_ends_at_one() {
for (m, k, c) in [(1.0, 100.0, 0.0), (1.0, 100.0, 0.01), (10.0, 0.5, 0.0)] {
let e = Easing::Spring(SpringEase { mass: m, stiffness: k, damping: c });
assert!((e.apply(1.0 - 1e-9) - 1.0).abs() < 1e-6, "{m} {k} {c}: {}", e.apply(1.0 - 1e-9));
assert!((1..1000).all(|i| e.apply(i as f64 / 1000.0).is_finite()));
}
}
/// Stepping a spring from rest toward 1 frame by frame traces its ease.
#[test]
fn stepping_from_rest_traces_the_spring_ease() {
// Springs that settle within 10 seconds (the others have their ease adjusted to end at 1).
for (m, k, c) in PRESETS.into_iter().filter(|&(m, k, c)| Spring::from_physical(m, k, c).unwrap().settle_time() < 10.0) {
let s = Spring::from_physical(m, k, c).unwrap();
let ease = Easing::Spring(SpringEase { mass: m, stiffness: k, damping: c });
let (settle, frames) = (s.settle_time(), 600);
let mut st = SpringState::at(0.0);
for f in 1..frames {
let v = st.step(&s, 1.0, settle / frames as f64).unwrap();
let want = ease.apply(f as f64 / frames as f64);
assert!((v - want).abs() < 1e-9, "{m} {k} {c} frame {f}: {v} vs {want}");
}
}
}
/// The spring equation integrated with small fourth-order Runge-Kutta steps, from 0 at rest
/// toward 1: value and velocity after `t` seconds.
fn integrated(w: f64, z: f64, t: f64) -> (f64, f64) {
let n = 100_000;
let h = t / n as f64;
let f = |x: f64, v: f64| (v, -w * w * (x - 1.0) - 2.0 * z * w * v);
let (mut x, mut v) = (0.0, 0.0);
for _ in 0..n {
let (a1, b1) = f(x, v);
let (a2, b2) = f(x + 0.5 * h * a1, v + 0.5 * h * b1);
let (a3, b3) = f(x + 0.5 * h * a2, v + 0.5 * h * b2);
let (a4, b4) = f(x + h * a3, v + h * b3);
x += h / 6.0 * (a1 + 2.0 * a2 + 2.0 * a3 + a4);
v += h / 6.0 * (b1 + 2.0 * b2 + 2.0 * b3 + b4);
}
(x, v)
}
/// Damping ratios just off 1 are solved with the ratio given, not the critical one.
#[test]
fn a_nearly_critical_spring_steps_with_its_own_damping_ratio() {
let w = 10.0;
for t in [0.1, 0.3, 1.0] {
let crit = released(w, 1.0, t);
for z in [1.0 - 5e-5, 1.0 + 5e-5, 1.0 - 1e-9, 1.0 + 1e-9] {
let s = Spring::new(w / std::f64::consts::TAU, z).unwrap();
let mut st = SpringState::at(0.0);
st.step(&s, 1.0, t).unwrap();
let (x, v) = integrated(w, z, t);
assert!((st.value - x).abs() < 1e-10 && (st.velocity - v).abs() < 1e-9, "ζ {z} at {t}: {st:?} vs {x}, {v}");
if (z - 1.0).abs() > 1e-6 {
// The two differ by far more than the tolerance above.
assert!((x - crit).abs() > 1e-7, "ζ {z} at {t}: {x} vs {crit}");
}
}
}
}
/// A critically damped step keeps the velocity a tiny step leaves, beside a huge offset.
#[test]
fn a_critical_step_keeps_its_velocity_beside_a_huge_offset() {
let s = Spring::from_physical(1.0, 1.0, 2.0).unwrap();
assert_eq!(s.damping(), 1.0);
let mut st = SpringState { value: 1e20, velocity: 1.0 };
st.step(&s, 0.0, 1e-22).unwrap();
assert!((st.velocity - 0.99).abs() < 1e-12, "{st:?}");
}
/// A spring whose damped frequency rounds to 0 moves at its velocity over a step.
#[test]
fn a_spring_whose_damped_frequency_rounds_to_zero_still_steps() {
let s = Spring::new(f64::from_bits(1), 0.9998).unwrap();
let mut st = SpringState { value: 0.0, velocity: 1.0 };
let v = st.step(&s, 0.0, 1.0).unwrap();
assert!((v - 1.0).abs() < 1e-12 && (st.velocity - 1.0).abs() < 1e-12, "{st:?}");
}
/// A spring whose damped frequency is above 0 but whose phase over a short step rounds to 0
/// still moves at its velocity over the step.
#[test]
fn a_step_whose_phase_rounds_to_zero_still_moves() {
let s = Spring::new(1e-320, 0.99995).unwrap();
let mut st = SpringState { value: 0.0, velocity: 1.0 };
let v = st.step(&s, 0.0, 0.001).unwrap();
assert!((v - 0.001).abs() < 1e-15 && (st.velocity - 1.0).abs() < 1e-12, "{st:?}");
}
/// A state that is not finite is refused at every step length and in every damping regime,
/// and stays as it is.
#[test]
fn a_state_that_is_not_finite_is_refused_at_any_step_length() {
for z in [0.5, 1.0, 2.0] {
let s = Spring::new(1.0, z).unwrap();
for start in [SpringState::at(f64::NAN), SpringState { value: 0.0, velocity: f64::INFINITY }] {
for dt in [0.0, 0.1, 200.0, 1e300] {
let mut st = start;
assert_eq!(st.step(&s, 1.0, dt), Err(EaseError::Overflow), "ζ {z}, {dt}");
assert_eq!((st.value.to_bits(), st.velocity.to_bits()), (start.value.to_bits(), start.velocity.to_bits()));
}
}
}
}
#[test]
fn the_three_damping_regimes_agree_near_critical_damping() {
// Either side of critical damping, the solutions meet the critically damped one.
let w = 10.0;
for t in [0.01, 0.1, 0.3, 1.0] {
let crit = released(w, 1.0, t);
for z in [1.0 - 2e-4, 1.0 - 5e-5, 1.0, 1.0 + 5e-5, 1.0 + 2e-4] {
let s = Spring::new(w / std::f64::consts::TAU, z).unwrap();
let mut st = SpringState::at(0.0);
let v = st.step(&s, 1.0, t).unwrap();
assert!((v - crit).abs() < 1e-3, "ζ {z} at {t}: {v} vs {crit}");
}
}
}
#[test]
fn a_spring_settles_on_its_target() {
for (f, z) in [(2.0, 0.2), (1.0, 1.0), (0.5, 3.0), (8.0, 0.05)] {
let s = Spring::new(f, z).unwrap();
let mut st = SpringState::at(0.0);
for _ in 0..60 * 120 {
st.step(&s, 10.0, 1.0 / 60.0).unwrap();
}
assert!(st.settled(10.0, 1e-6), "{f} Hz ζ {z}: {st:?}");
}
// An undamped spring keeps swinging, its energy kept.
let s = Spring::new(1.0, 0.0).unwrap();
let mut st = SpringState::at(0.0);
for _ in 0..60 * 100 {
st.step(&s, 1.0, 1.0 / 60.0).unwrap();
}
let w = s.omega();
let energy = (st.value - 1.0).powi(2) + (st.velocity / w).powi(2);
assert!((energy - 1.0).abs() < 1e-9, "{energy}");
}
/// Many short steps land where one long step does: the step is exact, not an integrator.
#[test]
fn many_small_steps_equal_one_long_step() {
for (f, z) in [(3.0, 0.3), (1.0, 1.0), (1.0, 4.0), (0.7, 0.0)] {
let s = Spring::new(f, z).unwrap();
let mut one = SpringState { value: -2.0, velocity: 5.0 };
let mut many = one;
one.step(&s, 1.0, 2.0).unwrap();
for _ in 0..240 {
many.step(&s, 1.0, 2.0 / 240.0).unwrap();
}
assert!((one.value - many.value).abs() < 1e-9 && (one.velocity - many.velocity).abs() < 1e-8, "{f} {z}: {one:?} {many:?}");
}
// Variable frame lengths too.
let s = Spring::new(2.0, 0.4).unwrap();
let (mut a, mut b) = (SpringState::at(0.0), SpringState::at(0.0));
a.step(&s, 1.0, 0.5).unwrap();
for dt in [0.1, 0.016, 0.05, 0.034, 0.2, 0.1] {
b.step(&s, 1.0, dt).unwrap();
}
assert!((a.value - b.value).abs() < 1e-9);
}
#[test]
fn huge_steps_land_on_the_target() {
for (f, z) in [(MAX_SPRING_HZ, 0.0001), (1e-6, 0.5), (1.0, MAX_DAMPING_RATIO), (5.0, 1.0)] {
let s = Spring::new(f, z).unwrap();
for dt in [1e6, 1e300, f64::MAX] {
let mut st = SpringState { value: 5.0, velocity: -3.0 };
let v = st.step(&s, 2.0, dt).unwrap();
assert!(v.is_finite() && st.velocity.is_finite(), "{f} {z} {dt}");
}
}
let s = Spring::new(4.0, 0.5).unwrap();
let mut st = SpringState { value: 5.0, velocity: -3.0 };
assert_eq!(st.step(&s, 2.0, 1e300).unwrap(), 2.0);
assert_eq!(st.velocity, 0.0);
// An undamped spring keeps its energy over any finite step, the longest included.
let s = Spring::new(MAX_SPRING_HZ, 0.0).unwrap();
let w = s.omega();
for dt in [1e300, f64::MAX] {
let mut st = SpringState { value: 5.0, velocity: -3.0 };
st.step(&s, 2.0, dt).unwrap();
let energy = (st.value - 2.0).powi(2) + (st.velocity / w).powi(2);
assert!((energy - (9.0 + (3.0 / w).powi(2))).abs() < 1e-9, "{dt}: {st:?}");
}
let s = Spring::new(4.0, 0.5).unwrap();
// A zero step changes nothing.
let mut st = SpringState { value: 5.0, velocity: -3.0 };
assert_eq!(st.step(&s, 2.0, 0.0).unwrap(), 5.0);
assert_eq!(st.velocity, -3.0);
}
#[test]
fn bad_inputs_are_refused_and_leave_the_state_alone() {
assert_eq!(Spring::new(f64::NAN, 0.5), Err(EaseError::NotFinite("frequency")));
assert!(matches!(Spring::new(0.0, 0.5), Err(EaseError::OutOfRange { what: "frequency", .. })));
assert!(matches!(Spring::new(MAX_SPRING_HZ * 2.0, 0.5), Err(EaseError::OutOfRange { what: "frequency", .. })));
assert!(matches!(Spring::new(1.0, -0.1), Err(EaseError::OutOfRange { what: "damping", .. })));
assert_eq!(Spring::new(1.0, f64::INFINITY), Err(EaseError::NotFinite("damping")));
assert!(matches!(Spring::from_controls(1.5, 0.5), Err(EaseError::OutOfRange { what: "strength", .. })));
assert!(matches!(Spring::from_physical(1.0, 0.0, 1.0), Err(EaseError::OutOfRange { what: "stiffness", .. })));
let s = Spring::new(1.0, 0.5).unwrap();
let start = SpringState { value: 1.0, velocity: 2.0 };
for (target, dt, err) in [
(f64::NAN, 0.1, EaseError::NotFinite("target")),
(f64::INFINITY, 0.1, EaseError::NotFinite("target")),
(0.0, f64::NAN, EaseError::NotFinite("step")),
(0.0, f64::INFINITY, EaseError::NotFinite("step")),
] {
let mut st = start;
assert_eq!(st.step(&s, target, dt), Err(err));
assert_eq!(st, start);
}
let mut st = start;
assert!(matches!(st.step(&s, 0.0, -0.1), Err(EaseError::OutOfRange { what: "step", .. })));
assert_eq!(st, start);
// A value too far from the target to measure is refused, not turned into NaN.
let mut far = SpringState { value: f64::MAX, velocity: 0.0 };
assert_eq!(far.step(&s, -f64::MAX, 0.1), Err(EaseError::Overflow));
assert_eq!(far, SpringState { value: f64::MAX, velocity: 0.0 });
}
#[test]
fn the_controls_map_onto_frequency_and_damping() {
let s = Spring::from_controls(0.0, 0.0).unwrap();
assert!((s.omega() - std::f64::consts::TAU * 0.5).abs() < 1e-12 && s.damping() == 0.0);
let s = Spring::from_controls(1.0, 2.0 / 3.0).unwrap();
assert!((s.omega() - std::f64::consts::TAU * 10.0).abs() < 1e-9 && (s.damping() - 1.0).abs() < 1e-12);
assert_eq!(Spring::from_controls(0.5, 1.0).unwrap().damping(), MAX_DAMPING_RATIO);
}
+162
View File
@@ -0,0 +1,162 @@
use crate::*;
fn key<T>(time: f64, value: T, ease: Easing) -> Key<T> {
Key { time, value, ease }
}
#[test]
fn a_track_eases_between_its_keys_and_holds_outside_them() {
let t = Track::from_keys(vec![
key(2.0, 10.0f64, Easing::QuadIn),
key(0.0, 0.0, Easing::Linear),
key(4.0, 0.0, Easing::Hold),
key(6.0, 50.0, Easing::Linear),
])
.unwrap();
assert_eq!(t.keys().iter().map(|k| k.time).collect::<Vec<_>>(), [0.0, 2.0, 4.0, 6.0]);
assert_eq!(t.sample(-1.0), Ok(0.0));
assert_eq!(t.sample(1.0), Ok(5.0));
assert_eq!(t.sample(2.0), Ok(10.0));
// Quad in: a quarter of the way at half time.
assert_eq!(t.sample(3.0), Ok(7.5));
// Hold keeps the value until the next key.
assert_eq!(t.sample(4.0), Ok(0.0));
assert_eq!(t.sample(5.999), Ok(0.0));
assert_eq!(t.sample(6.0), Ok(50.0));
assert_eq!(t.sample(1e300), Ok(50.0));
}
#[test]
fn an_overshooting_ease_carries_the_value_past_its_keys() {
let t = Track::from_keys(vec![key(0.0, 0.0f64, Easing::BackOut), key(1.0, 100.0, Easing::Linear)]).unwrap();
let peak = (1..100).map(|i| t.sample(i as f64 / 100.0).unwrap()).fold(f64::MIN, f64::max);
assert!(peak > 105.0 && peak < 115.0, "{peak}");
}
#[test]
fn tracks_hold_any_animatable_value() {
let p = Track::from_keys(vec![key(0.0, Vec2::new(0.0, 0.0), Easing::Linear), key(1.0, Vec2::new(10.0, -20.0), Easing::Linear)]).unwrap();
assert_eq!(p.sample(0.5), Ok(Vec2::new(5.0, -10.0)));
let c = Track::from_keys(vec![key(0.0, [0.0f32, 1.0, 0.5, 1.0], Easing::Linear), key(2.0, [1.0, 0.0, 0.5, 0.0], Easing::Linear)]).unwrap();
assert_eq!(c.sample(1.0), Ok([0.5, 0.5, 0.5, 0.5]));
let s = Track::from_keys(vec![key(0.0, 1.0f32, Easing::Linear), key(1.0, 3.0, Easing::Linear)]).unwrap();
assert_eq!(s.sample(0.25), Ok(1.5));
let d = Track::from_keys(vec![key(0.0, [0.0f64; 3], Easing::Linear), key(1.0, [3.0, 6.0, 9.0], Easing::Linear)]).unwrap();
assert_eq!(d.sample(1.0 / 3.0).map(|v| v.map(|x| (x * 1e9).round() / 1e9)), Ok([1.0, 2.0, 3.0]));
}
#[test]
fn bad_keys_and_times_are_refused() {
assert_eq!(Track::<f64>::new().sample(0.0), Err(EaseError::Empty));
let t = Track::from_keys(vec![key(0.0, 1.0f64, Easing::Linear)]).unwrap();
assert_eq!(t.sample(f64::NAN), Err(EaseError::NotFinite("time")));
assert_eq!(t.sample(f64::INFINITY), Err(EaseError::NotFinite("time")));
assert_eq!(t.sample(5.0), Ok(1.0));
assert_eq!(Track::from_keys(vec![key(f64::NAN, 1.0f64, Easing::Linear)]), Err(EaseError::NotFinite("time")));
assert_eq!(Track::from_keys(vec![key(0.0, f64::NAN, Easing::Linear)]), Err(EaseError::NotFinite("value")));
assert_eq!(Track::from_keys(vec![key(0.0, Vec2::new(0.0, f64::INFINITY), Easing::Linear)]), Err(EaseError::NotFinite("value")));
assert_eq!(Track::from_keys(vec![key(1.0, 1.0f64, Easing::Linear), key(1.0, 2.0, Easing::Linear)]), Err(EaseError::SameTime(1.0)));
// −0 and +0 are one time.
assert_eq!(Track::from_keys(vec![key(-0.0, 1.0f64, Easing::Linear), key(0.0, 2.0, Easing::Linear)]), Err(EaseError::SameTime(0.0)));
let mut z = Track::from_keys(vec![key(-0.0, 1.0f64, Easing::Linear), key(1.0, 2.0, Easing::Linear)]).unwrap();
assert_eq!(z.key_at(0.0), Some(0));
assert_eq!(z.key_at(-0.0), Some(0));
assert_eq!(z.insert(0.0, 5.0), Ok(0));
assert_eq!(z.len(), 2);
let too_many: Vec<Key<f32>> = (0..=MAX_TRACK_KEYS).map(|i| key(i as f64, 0.0, Easing::Linear)).collect();
assert_eq!(Track::from_keys(too_many), Err(EaseError::Full(MAX_TRACK_KEYS)));
}
#[test]
fn inserting_splits_a_segment_with_its_ease() {
let mut t = Track::from_keys(vec![key(0.0, 0.0f64, Easing::CubicIn), key(2.0, 8.0, Easing::Linear)]).unwrap();
assert_eq!(t.insert(1.0, 1.0), Ok(1));
assert_eq!(t.keys()[1].ease, Easing::CubicIn);
// Setting an existing key keeps its ease.
t.set_ease(1, Easing::Hold).unwrap();
assert_eq!(t.insert(1.0, 3.0), Ok(1));
assert_eq!((t.keys()[1].value, &t.keys()[1].ease), (3.0, &Easing::Hold));
assert_eq!(t.insert(-0.0, 7.0), Ok(0));
assert_eq!(t.len(), 3);
assert_eq!(t.key_at(0.0), Some(0));
assert_eq!(t.insert(5.0, f64::NAN), Err(EaseError::NotFinite("value")));
assert_eq!(t.insert(f64::NEG_INFINITY, 1.0), Err(EaseError::NotFinite("time")));
assert_eq!(t.remove(1).map(|k| k.value), Some(3.0));
assert!(t.remove(9).is_none() && t.set_ease(9, Easing::Linear).is_none());
// Before the first key, a new key eases linearly.
assert_eq!(t.insert(-1.0, 0.0), Ok(0));
assert_eq!(t.keys()[0].ease, Easing::Linear);
}
#[test]
fn keys_at_the_ends_of_the_number_range_sample_without_overflow() {
let t = Track::from_keys(vec![key(-f64::MAX, -1.0f64, Easing::Linear), key(f64::MAX, 1.0, Easing::Linear)]).unwrap();
assert_eq!(t.sample(0.0), Ok(0.0));
let v = t.sample(f64::MAX / 2.0).unwrap();
assert!((v - 0.5).abs() < 1e-12, "{v}");
// Keys a hair apart.
let near = Track::from_keys(vec![key(1.0, 0.0f64, Easing::Linear), key(1.0 + f64::EPSILON, 1.0, Easing::Linear)]).unwrap();
assert!(near.sample(1.0 + f64::EPSILON / 2.0).unwrap().is_finite());
// Values at opposite ends of the range interpolate without overflowing their difference.
let wide = Track::from_keys(vec![key(0.0, f64::MAX, Easing::Linear), key(1.0, -f64::MAX, Easing::Linear)]).unwrap();
assert_eq!(wide.sample(0.5), Ok(0.0));
let v =
Track::from_keys(vec![key(0.0, Vec2::new(-f64::MAX, 1e308), Easing::Linear), key(1.0, Vec2::new(f64::MAX, -1e308), Easing::Linear)]).unwrap();
assert_eq!(v.sample(0.5), Ok(Vec2::ZERO));
let a = Track::from_keys(vec![key(0.0, [f64::MAX; 2], Easing::Linear), key(1.0, [-f64::MAX; 2], Easing::Linear)]).unwrap();
assert!(a.sample(0.25).unwrap().iter().all(|x| x.is_finite()));
// Keys a subnormal step either side of 0 still interpolate between them.
let tiny = Track::from_keys(vec![key(-f64::from_bits(1), 0.0f64, Easing::Linear), key(f64::from_bits(1), 1.0, Easing::Linear)]).unwrap();
assert_eq!(tiny.sample(0.0), Ok(0.5));
// An overshoot past the largest f32 is refused, not returned as infinity.
let over = Track::from_keys(vec![key(0.0, -f32::MAX, Easing::BackOut), key(1.0, f32::MAX, Easing::Linear)]).unwrap();
assert_eq!(over.sample(0.6), Err(EaseError::Overflow));
// An overshoot whose step past the far key is too large to represent, with a result that
// is not.
let r = crate::lerp(-1e308, 5e307, 1.25);
assert!((r / 8.75e307 - 1.0).abs() < 1e-12, "{r}");
let back = Track::from_keys(vec![key(0.0, -f64::MAX, Easing::BackOut), key(1.0, -1e300, Easing::Linear)]).unwrap();
assert!(back.sample(0.6).unwrap() > 0.0);
}
#[cfg(feature = "serde")]
#[test]
fn tracks_round_trip_through_files_and_bad_files_are_refused() {
let t = Track::from_keys(vec![key(0.0, 1.0f64, Easing::Linear), key(1.5, 2.0, Easing::Hold), key(3.0, 0.5, Easing::QuadOut)]).unwrap();
let text = serde_json::to_string(&t).unwrap();
assert_eq!(
text,
r#"{"keys":[{"time":0.0,"value":1.0,"ease":"Linear"},{"time":1.5,"value":2.0,"ease":"Hold"},{"time":3.0,"value":0.5,"ease":"QuadOut"}]}"#
);
assert_eq!(serde_json::from_str::<Track<f64>>(&text).unwrap(), t);
// Keys out of order are sorted; a missing ease is linear.
let r: Track<f64> = serde_json::from_str(r#"{"keys":[{"time":2,"value":1},{"time":1,"value":0}]}"#).unwrap();
assert_eq!((r.keys()[0].time, &r.keys()[1].ease), (1.0, &Easing::Linear));
// Two keys at one time, or a time that is not a number, are a broken file.
assert!(serde_json::from_str::<Track<f64>>(r#"{"keys":[{"time":1,"value":1},{"time":1,"value":0}]}"#).is_err());
assert!(serde_json::from_str::<Track<f64>>(r#"{"keys":[{"time":"x","value":1}]}"#).is_err());
// More keys than a track holds are refused while reading, before the rest are read.
let mut big = String::from(r#"{"keys":["#);
for i in 0..=MAX_TRACK_KEYS {
if i > 0 {
big.push(',');
}
big.push_str(&format!(r#"{{"time":{i},"value":0}}"#));
}
big.push_str("]}");
let err = serde_json::from_str::<Track<f32>>(&big).unwrap_err().to_string();
assert!(err.contains("more than 100000 keys"), "{err}");
}
/// Formats that write a struct as its fields in order (rather than by name) read a track too,
/// through the same checks.
#[cfg(feature = "serde")]
#[test]
fn tracks_read_from_formats_that_write_fields_in_order() {
let t: Track<f64> = serde_json::from_str(r#"[[{"time":2,"value":1},{"time":1,"value":0,"ease":"QuadIn"}]]"#).unwrap();
assert_eq!(t.keys().iter().map(|k| (k.time, k.value)).collect::<Vec<_>>(), [(1.0, 0.0), (2.0, 1.0)]);
assert_eq!(t.keys()[0].ease, Easing::QuadIn);
assert!(serde_json::from_str::<Track<f64>>(r#"[[{"time":1,"value":1},{"time":1,"value":0}]]"#).is_err());
assert!(serde_json::from_str::<Track<f64>>("[]").is_err());
assert!(serde_json::from_str::<Track<f64>>("[[], 1]").is_err());
}
+269
View File
@@ -0,0 +1,269 @@
//! [`Track`]: keyed values with an ease between each key and the next.
use crate::{EaseError, Easing, Vec2, finite};
/// Most keys one track holds.
pub const MAX_TRACK_KEYS: usize = 100_000;
/// A value a track can animate: interpolated in a straight line between keys, the ease giving
/// how far along. Eases that overshoot pass `t` outside `0..=1`, which extrapolates.
pub trait Animatable: Clone {
/// The value `t` of the way from `self` to `to`.
fn lerp(&self, to: &Self, t: f64) -> Self;
/// Whether every component is finite.
fn is_finite(&self) -> bool;
}
impl Animatable for f32 {
fn lerp(&self, to: &f32, t: f64) -> f32 {
crate::lerp(f64::from(*self), f64::from(*to), t) as f32
}
fn is_finite(&self) -> bool {
f32::is_finite(*self)
}
}
impl Animatable for f64 {
fn lerp(&self, to: &f64, t: f64) -> f64 {
crate::lerp(*self, *to, t)
}
fn is_finite(&self) -> bool {
f64::is_finite(*self)
}
}
impl Animatable for Vec2 {
fn lerp(&self, to: &Vec2, t: f64) -> Vec2 {
Vec2::lerp(*self, *to, t)
}
fn is_finite(&self) -> bool {
Vec2::is_finite(*self)
}
}
impl<const N: usize> Animatable for [f32; N] {
fn lerp(&self, to: &[f32; N], t: f64) -> [f32; N] {
let mut out = *self;
for (o, b) in out.iter_mut().zip(to) {
*o = Animatable::lerp(&*o, b, t);
}
out
}
fn is_finite(&self) -> bool {
self.iter().all(|v| v.is_finite())
}
}
impl<const N: usize> Animatable for [f64; N] {
fn lerp(&self, to: &[f64; N], t: f64) -> [f64; N] {
let mut out = *self;
for (o, b) in out.iter_mut().zip(to) {
*o = crate::lerp(*o, *b, t);
}
out
}
fn is_finite(&self) -> bool {
self.iter().all(|v| v.is_finite())
}
}
/// A key: a value at a time (seconds), and the ease to the next key ([`Easing::Hold`] keeps the
/// value until the next key).
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Key<T> {
pub time: f64,
pub value: T,
#[cfg_attr(feature = "serde", serde(default))]
pub ease: Easing,
}
/// Keys sorted by time, one per time, at most [`MAX_TRACK_KEYS`], every time and value finite.
///
/// Before the first key a track gives the first key's value, after the last key the last's.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Track<T> {
keys: Vec<Key<T>>,
}
impl<T> Default for Track<T> {
fn default() -> Self {
Track { keys: Vec::new() }
}
}
impl<T: Animatable> Track<T> {
pub fn new() -> Self {
Track::default()
}
/// A track from keys a caller or a file supplies: an error for a time or value that is not
/// finite, two keys at one time, or more than [`MAX_TRACK_KEYS`]. The keys may come in any
/// order.
pub fn from_keys(mut keys: Vec<Key<T>>) -> Result<Self, EaseError> {
if keys.len() > MAX_TRACK_KEYS {
return Err(EaseError::Full(MAX_TRACK_KEYS));
}
for k in &mut keys {
check(k.time, &k.value)?;
// -0.0 and 0.0 are one time.
if k.time == 0.0 {
k.time = 0.0;
}
}
keys.sort_by(|a, b| a.time.total_cmp(&b.time));
if let Some(w) = keys.windows(2).find(|w| matches!(w, [a, b] if a.time == b.time)) {
return Err(EaseError::SameTime(w.first().map_or(0.0, |k| k.time)));
}
Ok(Track { keys })
}
pub fn keys(&self) -> &[Key<T>] {
&self.keys
}
pub fn is_empty(&self) -> bool {
self.keys.is_empty()
}
pub fn len(&self) -> usize {
self.keys.len()
}
/// Sets the value at `time`, keeping that key's ease, or adds a key there that eases like
/// the segment it splits. Returns the key's index. An error for a time or value that is not
/// finite, or a full track.
pub fn insert(&mut self, time: f64, value: T) -> Result<usize, EaseError> {
check(time, &value)?;
// -0.0 and 0.0 are one time.
let time = if time == 0.0 { 0.0 } else { time };
match self.keys.binary_search_by(|k| k.time.total_cmp(&time)) {
Ok(i) => {
if let Some(k) = self.keys.get_mut(i) {
k.value = value;
}
Ok(i)
}
Err(i) => {
if self.keys.len() >= MAX_TRACK_KEYS {
return Err(EaseError::Full(MAX_TRACK_KEYS));
}
let ease = i.checked_sub(1).and_then(|p| self.keys.get(p)).map_or_else(Easing::default, |k| k.ease.clone());
self.keys.insert(i, Key { time, value, ease });
Ok(i)
}
}
}
/// Sets the ease from key `i` to the next one. `None` for a missing key.
pub fn set_ease(&mut self, i: usize, ease: Easing) -> Option<()> {
self.keys.get_mut(i)?.ease = ease;
Some(())
}
/// Removes key `i`, returning it.
pub fn remove(&mut self, i: usize) -> Option<Key<T>> {
(i < self.keys.len()).then(|| self.keys.remove(i))
}
/// The index of the key at exactly `time` (−0 and +0 are one time).
pub fn key_at(&self, time: f64) -> Option<usize> {
let time = if time == 0.0 { 0.0 } else { time };
self.keys.binary_search_by(|k| k.time.total_cmp(&time)).ok()
}
/// The value at `time`. An error for an empty track, a `time` that is not finite, or an
/// overshooting ease that carries the value past what the type can hold.
pub fn sample(&self, time: f64) -> Result<T, EaseError> {
let time = finite(time, "time")?;
let (Some(first), Some(last)) = (self.keys.first(), self.keys.last()) else { return Err(EaseError::Empty) };
if time <= first.time {
return Ok(first.value.clone());
}
if time >= last.time {
return Ok(last.value.clone());
}
let i = self.keys.partition_point(|k| k.time <= time);
let (Some(a), Some(b)) = (i.checked_sub(1).and_then(|j| self.keys.get(j)), self.keys.get(i)) else { return Ok(last.value.clone()) };
if a.ease == Easing::Hold {
return Ok(a.value.clone());
}
// Keys at opposite ends of the f64 range overflow the span; halving both sides keeps it.
let span = b.time - a.time;
let t = if span.is_finite() { (time - a.time) / span } else { (time * 0.5 - a.time * 0.5) / (b.time * 0.5 - a.time * 0.5) };
let v = a.value.lerp(&b.value, a.ease.apply(t.clamp(0.0, 1.0)));
if v.is_finite() { Ok(v) } else { Err(EaseError::Overflow) }
}
}
fn check<T: Animatable>(time: f64, value: &T) -> Result<(), EaseError> {
finite(time, "time")?;
if value.is_finite() { Ok(()) } else { Err(EaseError::NotFinite("value")) }
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::{Animatable, Key, MAX_TRACK_KEYS, Track};
use serde::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor};
use std::marker::PhantomData;
/// The key list, read one key at a time and refused once it passes [`MAX_TRACK_KEYS`], so a
/// hostile file cannot make it allocate more.
struct Keys<T>(Vec<Key<T>>);
impl<'de, T: Deserialize<'de>> Deserialize<'de> for Keys<T> {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct V<T>(PhantomData<T>);
impl<'de, T: Deserialize<'de>> Visitor<'de> for V<T> {
type Value = Keys<T>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "a list of at most {MAX_TRACK_KEYS} keys")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Keys<T>, A::Error> {
let mut keys = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(1024));
while let Some(k) = seq.next_element()? {
if keys.len() >= MAX_TRACK_KEYS {
return Err(A::Error::custom(format!("more than {MAX_TRACK_KEYS} keys")));
}
keys.push(k);
}
Ok(Keys(keys))
}
}
d.deserialize_seq(V(PhantomData))
}
}
impl<'de, T: Animatable + Deserialize<'de>> Deserialize<'de> for Track<T> {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct V<T>(PhantomData<T>);
impl<'de, T: Animatable + Deserialize<'de>> Visitor<'de> for V<T> {
type Value = Track<T>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "a track")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Track<T>, A::Error> {
let mut keys: Option<Vec<Key<T>>> = None;
while let Some(name) = map.next_key::<String>()? {
if name == "keys" {
keys = Some(map.next_value::<Keys<T>>()?.0);
} else {
map.next_value::<serde::de::IgnoredAny>()?;
}
}
Track::from_keys(keys.unwrap_or_default()).map_err(A::Error::custom)
}
/// Formats that write a struct as its fields in order.
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Track<T>, A::Error> {
let keys = seq.next_element::<Keys<T>>()?.ok_or_else(|| A::Error::invalid_length(0, &self))?.0;
if seq.next_element::<serde::de::IgnoredAny>()?.is_some() {
return Err(A::Error::invalid_length(2, &self));
}
Track::from_keys(keys).map_err(A::Error::custom)
}
}
d.deserialize_struct("Track", &["keys"], V(PhantomData))
}
}
}
+83
View File
@@ -0,0 +1,83 @@
//! A 2D point or vector, for ease curve points and motion paths.
use std::ops::{Add, Mul, Neg, Sub};
/// A 2D point or vector. In files it is `{"x": …, "y": …}`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Vec2 {
pub x: f64,
pub y: f64,
}
impl Vec2 {
pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 };
pub const fn new(x: f64, y: f64) -> Self {
Vec2 { x, y }
}
pub fn dot(self, o: Vec2) -> f64 {
self.x * o.x + self.y * o.y
}
/// The length. Large components do not overflow on the way, so the length is finite whenever
/// it is at most `f64::MAX`; a longer vector, such as `(f64::MAX, f64::MAX)`, has an infinite
/// length. [`Vec2::normalized`] still gives such a vector's direction.
pub fn length(self) -> f64 {
self.x.hypot(self.y)
}
/// The vector scaled to length 1, or zero for a zero (or non-finite) vector. The components
/// are divided by the larger one first, so a vector near the largest or smallest `f64` still
/// gives a unit vector.
pub fn normalized(self) -> Vec2 {
let m = self.x.abs().max(self.y.abs());
if !(self.is_finite() && m > 0.0) {
return Vec2::ZERO;
}
let (x, y) = (self.x / m, self.y / m);
let l = x.hypot(y);
Vec2::new(x / l, y / l)
}
pub fn lerp(self, o: Vec2, t: f64) -> Vec2 {
Vec2::new(crate::lerp(self.x, o.x, t), crate::lerp(self.y, o.y, t))
}
pub fn distance(self, o: Vec2) -> f64 {
(o - self).length()
}
pub fn is_finite(self) -> bool {
self.x.is_finite() && self.y.is_finite()
}
}
impl Add for Vec2 {
type Output = Vec2;
fn add(self, o: Vec2) -> Vec2 {
Vec2::new(self.x + o.x, self.y + o.y)
}
}
impl Sub for Vec2 {
type Output = Vec2;
fn sub(self, o: Vec2) -> Vec2 {
Vec2::new(self.x - o.x, self.y - o.y)
}
}
impl Mul<f64> for Vec2 {
type Output = Vec2;
fn mul(self, s: f64) -> Vec2 {
Vec2::new(self.x * s, self.y * s)
}
}
impl Neg for Vec2 {
type Output = Vec2;
fn neg(self) -> Vec2 {
Vec2::new(-self.x, -self.y)
}
}
+116 -42
View File
@@ -12,8 +12,9 @@
//!
//! The `exr` crate sizes buffers from headers before it reads pixels, so everything that reaches
//! it is checked first: preview attributes against their own size, each part's samples against
//! [`Limits`], all parts together against the budget, and the samples against what a file of
//! this size can decompress to.
//! [`Limits`], all parts together against the budget, the samples against what a file of this
//! size can decompress to, and the packed length of each chunk of the part being read against the
//! rest of the file and the budget.
use std::io::Cursor;
@@ -456,7 +457,11 @@ pub fn decode_display_part(
if pixels > limits.max_pixels {
return Err(Error::LimitExceeded(format!("display window of {pixels} pixels exceeds {}", limits.max_pixels)));
}
let kept = info.channels.iter().filter(|channel| keep(&part_channel_name(info.name.as_deref(), &channel.name))).count();
let header = meta.headers.get(index).ok_or_else(|| malformed(format!("part {index}")))?;
let prefix = header.own_attributes.layer_name.as_ref().map(|name| name.to_string()).filter(|name| !name.is_empty());
let kept_names = kept_channel_names(header, prefix.as_deref(), keep);
let kept =
header.channels.list.iter().filter(|channel| kept_names.contains(&part_channel_name(prefix.as_deref(), &channel.name.to_string()))).count();
let bytes_needed = pixels
.checked_mul(4)
.and_then(|bytes_per_channel| bytes_per_channel.checked_mul(kept as u64))
@@ -464,16 +469,18 @@ pub fn decode_display_part(
if bytes_needed > limits.max_bytes || usize::try_from(bytes_needed).is_err() {
return Err(Error::LimitExceeded(format!("{bytes_needed} display-window bytes exceed {}", limits.max_bytes)));
}
let recorded = |name: &str| kept_names.contains(name);
let keep: &dyn Fn(&str) -> bool = &recorded;
let block_limit = std::cell::Cell::new(None);
let select = DisplaySelect { index, keep, fill, limits, seen: std::cell::Cell::new(0), block_limit: &block_limit };
let exr_error = |error| block_limit.take().map(Error::LimitExceeded).unwrap_or_else(|| map_exr(error));
let planes = if meta.headers.iter().any(|header| header.deep) {
let header = meta.headers.get(index).ok_or_else(|| malformed(format!("part {index}")))?;
select.seen.set(index);
let mut reader = select.create_channels_reader(header).map_err(exr_error)?;
read_flat_part_chunks(bytes, &meta, index, &mut reader, limits)?;
reader.into_channels()
} else {
check_flat_packed_lengths(bytes, &meta, index, kept > 0, limits)?;
ReadImage::new(ReadAllLayers { read_channels: select }, |_| {})
.from_buffered(Cursor::new(bytes))
.map_err(exr_error)?
@@ -822,6 +829,104 @@ pub(super) fn flat_block_ordinal(header: &Header, tile: TileCoordinates) -> Resu
Err(malformed("flat tile names a missing level"))
}
/// Part `index`'s offset table (one `u64` per chunk) and where the last offset table ends. The
/// tables follow the headers, one per part in header order, and must all lie inside the file.
fn part_offset_table<'a>(bytes: &'a [u8], meta: &MetaData, index: usize) -> Result<(&'a [u8], u64)> {
let header = meta.headers.get(index).ok_or_else(|| malformed(format!("part {index}")))?;
let truncated = || malformed("the offset tables run past the end of the file");
let (mut table, mut tables_end) = (0u64, tables_start(bytes)?);
for (i, h) in meta.headers.iter().enumerate() {
if i == index {
table = tables_end;
}
let len = u64::try_from(h.chunk_count).ok().and_then(|n| n.checked_mul(8)).ok_or_else(truncated)?;
tables_end = tables_end.checked_add(len).filter(|end| *end <= bytes.len() as u64).ok_or_else(truncated)?;
}
let offsets = usize::try_from(table)
.ok()
.and_then(|start| bytes.get(start..start.checked_add(header.chunk_count.checked_mul(8)?)?))
.ok_or_else(truncated)?;
Ok((offsets, tables_end))
}
/// The bytes from `offset` to the end of the file, and the packed length the flat chunk there
/// declares. The chunk must start past the last offset table and inside the file, carry part
/// number `index` in a multipart file, and declare no more bytes than the file has left after its
/// length field.
fn flat_chunk_at<'a>(bytes: &'a [u8], header: &Header, multipart: bool, index: usize, offset: u64, tables_end: u64) -> Result<(&'a [u8], usize)> {
let chunk = usize::try_from(offset)
.ok()
.filter(|_| offset >= tables_end)
.and_then(|start| bytes.get(start..))
.filter(|rest| !rest.is_empty())
.ok_or_else(|| malformed(format!("chunk offset {offset} is outside the chunk area of the file")))?;
if multipart {
let part = chunk.get(..4).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(i32::from_le_bytes);
let part = part.ok_or_else(|| malformed(format!("the chunk at offset {offset} is cut off")))?;
if usize::try_from(part).ok() != Some(index) {
return Err(malformed(format!("the chunk at offset {offset} belongs to part {part}, not part {index}")));
}
}
// The crate allocates a chunk's declared payload before it reads it, so the payload must
// fit in the rest of the file. The length follows the part number and the block's y, or
// its four tile coordinates.
let fields = if matches!(header.blocks, exr::meta::BlockDescription::Tiles(_)) { 16 } else { 4 };
let size_at = if multipart { 4 } else { 0 } + fields;
let size = chunk.get(size_at..size_at + 4).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(i32::from_le_bytes);
let size = size.ok_or_else(|| malformed(format!("the chunk at offset {offset} is cut off")))?;
let left = chunk.len() - (size_at + 4);
if usize::try_from(size).is_ok_and(|size| size > left) {
return Err(malformed(format!("the chunk at offset {offset} declares {size} bytes, but {left} remain in the file")));
}
let size = usize::try_from(size).map_err(|_| malformed("negative packed chunk length"))?;
Ok((chunk, size))
}
/// The names of `header`'s channels that `keep` accepts, named as the channel readers name them
/// (behind `prefix`, the part's name, when there is one). `keep` is asked once per channel, and
/// the readers and the packed-length check use this one answer.
fn kept_channel_names(header: &Header, prefix: Option<&str>, keep: &dyn Fn(&str) -> bool) -> std::collections::HashSet<String> {
let names = header.channels.list.iter().map(|channel| part_channel_name(prefix, &channel.name.to_string()));
names.filter(|name| keep(name)).collect()
}
/// Checks every chunk of flat part `index` before the `exr` crate's image reader reads the part.
/// That reader reserves a chunk's declared packed length, up to the part's nominal block size,
/// before it reads the payload, so each chunk is checked as [`flat_chunk_at`] describes. The
/// reader picks the chunks it reads by their place in the offset table, which follows the
/// part's blocks in increasing y order, and reads only the blocks of the largest resolution
/// level, and none when the decode keeps no channel (`reads_any` false). The packed length of
/// each chunk the reader reads must also fit in [`Limits::max_bytes`].
///
/// The table has one entry per block (`header.chunk_count`). Every block of a scan-line part is
/// at the largest level. In a tiled part the largest level's tiles come first, so an entry is at
/// that level when its place is below that level's tile count. The check works from these counts
/// and does not list the blocks, so its memory does not grow with the size of the offset table.
fn check_flat_packed_lengths(bytes: &[u8], meta: &MetaData, index: usize, reads_any: bool, limits: &Limits) -> Result<()> {
let header = meta.headers.get(index).ok_or_else(|| malformed(format!("part {index}")))?;
let multipart = meta.requirements.is_multilayer();
let (offsets, tables_end) = part_offset_table(bytes, meta, index)?;
let largest_level_blocks = match &header.blocks {
exr::meta::BlockDescription::Tiles(tiles) => {
let (tile_w, tile_h) = (tiles.tile_size.width(), tiles.tile_size.height());
if tile_w == 0 || tile_h == 0 {
return Err(malformed("flat block has a zero dimension"));
}
header.layer_size.width().div_ceil(tile_w).saturating_mul(header.layer_size.height().div_ceil(tile_h))
}
exr::meta::BlockDescription::ScanLines => header.chunk_count,
};
let read_count = if reads_any { largest_level_blocks } else { 0 };
for (place, &entry) in offsets.as_chunks::<8>().0.iter().enumerate() {
let (_, size) = flat_chunk_at(bytes, header, multipart, index, u64::from_le_bytes(entry), tables_end)?;
let read = place < read_count;
if read && size as u64 > limits.max_bytes {
return Err(Error::LimitExceeded("packed flat block exceeds the byte budget".into()));
}
}
Ok(())
}
/// Reads the chunks of flat part `index` of a file that also holds deep parts into `reader`.
///
/// The `exr` crate's image reader validates every header before it reads a chunk and refuses
@@ -839,19 +944,7 @@ fn read_flat_part_chunks(bytes: &[u8], meta: &MetaData, index: usize, reader: &m
for flat in meta.headers.iter().filter(|h| !h.deep) {
flat.validate(multipart, &mut long_names, false).map_err(map_exr)?;
}
let truncated = || malformed("the offset tables run past the end of the file");
let (mut table, mut tables_end) = (0u64, tables_start(bytes)?);
for (i, h) in meta.headers.iter().enumerate() {
if i == index {
table = tables_end;
}
let len = u64::try_from(h.chunk_count).ok().and_then(|n| n.checked_mul(8)).ok_or_else(truncated)?;
tables_end = tables_end.checked_add(len).filter(|end| *end <= bytes.len() as u64).ok_or_else(truncated)?;
}
let offsets = usize::try_from(table)
.ok()
.and_then(|start| bytes.get(start..start.checked_add(header.chunk_count.checked_mul(8)?)?))
.ok_or_else(truncated)?;
let (offsets, tables_end) = part_offset_table(bytes, meta, index)?;
// One bit per block, not a Vec/HashSet of every coordinate. A cropped display must not
// permit unbounded bookkeeping for an enormous data window of tiny tiles.
let tracking_bytes = header.chunk_count.div_ceil(8);
@@ -863,31 +956,7 @@ fn read_flat_part_chunks(bytes: &[u8], meta: &MetaData, index: usize, reader: &m
seen.resize(tracking_bytes, 0u8);
for &entry in offsets.as_chunks::<8>().0 {
let offset = u64::from_le_bytes(entry);
let chunk = usize::try_from(offset)
.ok()
.filter(|_| offset >= tables_end)
.and_then(|start| bytes.get(start..))
.filter(|rest| !rest.is_empty())
.ok_or_else(|| malformed(format!("chunk offset {offset} is outside the chunk area of the file")))?;
if multipart {
let part = chunk.get(..4).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(i32::from_le_bytes);
let part = part.ok_or_else(|| malformed(format!("the chunk at offset {offset} is cut off")))?;
if usize::try_from(part).ok() != Some(index) {
return Err(malformed(format!("the chunk at offset {offset} belongs to part {part}, not part {index}")));
}
}
// The crate allocates a chunk's declared payload before it reads it, so the payload must
// fit in the rest of the file. The length follows the part number and the block's y, or
// its four tile coordinates.
let fields = if matches!(header.blocks, exr::meta::BlockDescription::Tiles(_)) { 16 } else { 4 };
let size_at = if multipart { 4 } else { 0 } + fields;
let size = chunk.get(size_at..size_at + 4).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(i32::from_le_bytes);
let size = size.ok_or_else(|| malformed(format!("the chunk at offset {offset} is cut off")))?;
let left = chunk.len() - (size_at + 4);
if usize::try_from(size).is_ok_and(|size| size > left) {
return Err(malformed(format!("the chunk at offset {offset} declares {size} bytes, but {left} remain in the file")));
}
let size = usize::try_from(size).map_err(|_| malformed("negative packed chunk length"))?;
let (chunk, size) = flat_chunk_at(bytes, header, multipart, index, offset, tables_end)?;
// Read coordinates without allocating the payload. Validate their real clipped block
// and budgets before Chunk::read uses the nominal (possibly huge) tile dimensions.
let coordinate_at = if multipart { 4 } else { 0 };
@@ -959,6 +1028,10 @@ pub fn decode_part(bytes: &[u8], index: usize, keep: &dyn Fn(&str) -> bool, limi
return Err(Error::Unsupported("HTJ2K compression".into()));
}
let info = part_info(index, header);
let kept_names = kept_channel_names(header, None, keep);
let keeps_any = !kept_names.is_empty();
let recorded = |name: &str| kept_names.contains(name);
let keep: &dyn Fn(&str) -> bool = &recorded;
let select = Select { index, keep, seen: std::cell::Cell::new(0) };
let planes = if meta.headers.iter().any(|header| header.deep) {
select.seen.set(index);
@@ -966,6 +1039,7 @@ pub fn decode_part(bytes: &[u8], index: usize, keep: &dyn Fn(&str) -> bool, limi
read_flat_part_chunks(bytes, &meta, index, &mut reader, limits)?;
reader.into_channels()
} else {
check_flat_packed_lengths(bytes, &meta, index, keeps_any, limits)?;
let image = ReadImage::new(ReadAllLayers { read_channels: select }, |_| {}).from_buffered(Cursor::new(bytes)).map_err(map_exr)?;
image.layer_data.into_iter().nth(index).map(|l| l.channel_data).ok_or_else(|| malformed("the part was not read"))?
};
+127
View File
@@ -179,6 +179,133 @@ fn decoded_display_part_rejects_kept_subsampled_channels() {
assert!(matches!(decode_display_part(&bytes, 0, &|name| name == "R", &|_| 0.0, &Limits::default()), Err(Error::Unsupported(_))));
}
#[test]
fn a_flat_chunk_s_packed_length_is_checked_before_the_crate_reads_it() {
// One 9 × 7 tile of a 1024 × 1024 tile size: the crate would reserve up to the nominal tile
// (1024 × 1024 pixels of three f32 channels, 12 MiB) for the chunk's declared length.
let list = ["B", "G", "R"].iter().map(|n| AnyChannel::new(*n, FlatSamples::F32(ramp(63, 1.0)))).collect();
let encoding = Encoding {
compression: exr::prelude::Compression::Uncompressed,
blocks: Blocks::Tiles(exr::math::Vec2(1024, 1024)),
line_order: LineOrder::Increasing,
};
let mut bytes = file(vec![Layer::new((9, 7), LayerAttributes::default(), encoding, AnyChannels::sort(list))], (9, 7));
assert_eq!(decode_part(&bytes, 0, &all, &Limits::default()).unwrap().channels.len(), 3);
let mut cursor = std::io::Cursor::new(&bytes[..]);
exr::meta::MetaData::read_from_buffered(&mut cursor, false).unwrap();
let table = cursor.position() as usize;
let chunk = u64::from_le_bytes(bytes[table..table + 8].try_into().unwrap()) as usize;
// The packed length follows the four tile coordinates.
let size_at = chunk + 16;
bytes.extend_from_slice(&[0; 2000]);
let limits = Limits { max_bytes: 1000, ..Limits::default() };
let r = |name: &str| name == "R";
// More bytes than the file has left after the length.
bytes[size_at..size_at + 4].copy_from_slice(&i32::MAX.to_le_bytes());
assert!(matches!(decode_part(&bytes, 0, &all, &limits), Err(Error::Malformed(m)) if m.contains("remain in the file")));
assert!(matches!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &limits), Err(Error::Malformed(m)) if m.contains("remain in the file")));
// Inside the file, but over the byte budget.
bytes[size_at..size_at + 4].copy_from_slice(&1001i32.to_le_bytes());
assert!(matches!(decode_part(&bytes, 0, &all, &limits), Err(Error::LimitExceeded(_))));
assert!(matches!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &limits), Err(Error::LimitExceeded(_))));
// A decode that keeps no channel reads no chunk.
let none = |_: &str| false;
assert!(decode_part(&bytes, 0, &none, &limits).unwrap().channels.is_empty());
assert!(decode_display_part(&bytes, 0, &none, &|_| 0.0, &limits).unwrap().channels.is_empty());
}
#[test]
fn a_skipped_flat_chunk_s_packed_length_is_not_held_to_the_budget() {
use exr::math::RoundingMode;
use exr::prelude::Levels;
// 9 × 7 in 4 × 4 tiles with mip levels. The reader reads only the six tiles of level 0, so a
// smaller level's chunk may declare more than the budget while it fits in the file.
let sizes: Vec<usize> = exr::meta::mip_map_levels(RoundingMode::Down, exr::math::Vec2(9, 7)).map(|(_, size)| size.area()).collect();
let levels = Levels::Mip { rounding_mode: RoundingMode::Down, level_data: sizes.iter().map(|n| FlatSamples::F32(ramp(*n, 1.0))).collect() };
let encoding = Encoding {
compression: exr::prelude::Compression::Uncompressed,
blocks: Blocks::Tiles(exr::math::Vec2(4, 4)),
line_order: LineOrder::Increasing,
};
let channels = AnyChannels::sort(vec![AnyChannel::new("R", levels)].into());
let layers = vec![Layer::new((9, 7), LayerAttributes::default(), encoding, channels)];
let image = exr::image::Image::from_layers(ImageAttributes::new(IntegerBounds::new((0, 0), (9, 7))), layers);
let mut out = std::io::Cursor::new(Vec::new());
image.write().to_buffered(&mut out).unwrap();
let mut bytes = out.into_inner();
let mut cursor = std::io::Cursor::new(&bytes[..]);
let meta = exr::meta::MetaData::read_from_buffered(&mut cursor, false).unwrap();
let table = cursor.position() as usize;
let count = meta.headers[0].chunk_count;
assert!(count > 6, "the part has chunks beyond level 0");
// The last chunk in the table holds the smallest level: its tile coordinates, then its level.
let last = table + (count - 1) * 8;
let chunk = u64::from_le_bytes(bytes[last..last + 8].try_into().unwrap()) as usize;
let level_x = i32::from_le_bytes(bytes[chunk + 8..chunk + 12].try_into().unwrap());
let level_y = i32::from_le_bytes(bytes[chunk + 12..chunk + 16].try_into().unwrap());
assert_ne!((level_x, level_y), (0, 0));
bytes.extend_from_slice(&[0; 2000]);
bytes[chunk + 16..chunk + 20].copy_from_slice(&1500i32.to_le_bytes());
let limits = Limits { max_bytes: 1000, ..Limits::default() };
let r = |name: &str| name == "R";
assert_eq!(decode_part(&bytes, 0, &all, &limits).unwrap().channels.len(), 1);
assert_eq!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &limits).unwrap().channels.len(), 1);
// The reader picks chunks by their place in the table, so a level-0 entry that points at the
// smaller level's chunk is read, and that chunk's length is held to the budget.
let entry = bytes[last..last + 8].to_vec();
bytes[table..table + 8].copy_from_slice(&entry);
assert!(matches!(decode_part(&bytes, 0, &all, &limits), Err(Error::LimitExceeded(_))));
assert!(matches!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &limits), Err(Error::LimitExceeded(_))));
}
#[test]
fn the_packed_length_check_finds_the_end_of_level_0_among_many_small_tiles() {
use exr::math::RoundingMode;
use exr::prelude::Levels;
// 64 × 48 in 1 × 1 tiles with mip levels: the 3,072 tiles of level 0 fill the first places of
// the offset table, and the smaller levels follow.
let (w, h) = (64, 48);
let sizes: Vec<usize> = exr::meta::mip_map_levels(RoundingMode::Down, exr::math::Vec2(w, h)).map(|(_, size)| size.area()).collect();
let levels = Levels::Mip { rounding_mode: RoundingMode::Down, level_data: sizes.iter().map(|n| FlatSamples::F32(ramp(*n, 1.0))).collect() };
let encoding = Encoding {
compression: exr::prelude::Compression::Uncompressed,
blocks: Blocks::Tiles(exr::math::Vec2(1, 1)),
line_order: LineOrder::Increasing,
};
let channels = AnyChannels::sort(vec![AnyChannel::new("R", levels)].into());
let layers = vec![Layer::new((w, h), LayerAttributes::default(), encoding, channels)];
let image = exr::image::Image::from_layers(ImageAttributes::new(IntegerBounds::new((0, 0), (w, h))), layers);
let mut out = std::io::Cursor::new(Vec::new());
image.write().to_buffered(&mut out).unwrap();
let mut bytes = out.into_inner();
let mut cursor = std::io::Cursor::new(&bytes[..]);
let meta = exr::meta::MetaData::read_from_buffered(&mut cursor, false).unwrap();
let table = cursor.position() as usize;
let level_0 = w * h;
assert!(meta.headers[0].chunk_count > level_0, "the part has chunks beyond level 0");
let chunk_at = |bytes: &[u8], place: usize| u64::from_le_bytes(bytes[table + place * 8..table + place * 8 + 8].try_into().unwrap()) as usize;
let level_of = |bytes: &[u8], chunk: usize| {
let x = i32::from_le_bytes(bytes[chunk + 8..chunk + 12].try_into().unwrap());
let y = i32::from_le_bytes(bytes[chunk + 12..chunk + 16].try_into().unwrap());
(x, y)
};
let (last_read, first_skipped) = (chunk_at(&bytes, level_0 - 1), chunk_at(&bytes, level_0));
assert_eq!(level_of(&bytes, last_read), (0, 0));
assert_ne!(level_of(&bytes, first_skipped), (0, 0));
// The decoded part takes 12,288 bytes, inside the budget; a declared length of 30,000 is not.
bytes.extend_from_slice(&[0; 40_000]);
let limits = Limits { max_bytes: 20_000, ..Limits::default() };
let r = |name: &str| name == "R";
// The first chunk past level 0 is not read, so its length is not held to the budget.
bytes[first_skipped + 16..first_skipped + 20].copy_from_slice(&30_000i32.to_le_bytes());
assert_eq!(decode_part(&bytes, 0, &all, &limits).unwrap().channels.len(), 1);
assert_eq!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &limits).unwrap().channels.len(), 1);
// The last chunk of level 0 is read, so its length is.
bytes[last_read + 16..last_read + 20].copy_from_slice(&30_000i32.to_le_bytes());
assert!(matches!(decode_part(&bytes, 0, &all, &limits), Err(Error::LimitExceeded(_))));
assert!(matches!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &limits), Err(Error::LimitExceeded(_))));
}
/// A 2x2 single-part file whose layer carries a 2x1 preview.
fn with_preview() -> Vec<u8> {
let mut attrs = LayerAttributes::named("rgb");
+3 -1
View File
@@ -54,7 +54,9 @@ Each face (`FaceInfo`) has its family and style, legacy family and style, family
- `family(name)` and `resolve(name, style)` accept any name of a family: its own name ignoring ASCII case, its names in other languages and its legacy names ignoring case and anything but letters and digits. `resolve` also accepts a legacy family with its legacy style (`Roboto Light` / `Regular`), a full name, and a PostScript name.
- Within a family, `resolve` matches the style by name (any of its names). Otherwise it picks the nearest weight, with italic differing counting as 1000, then the nearest width. It returns `Match::Exact` or `Match::NearestStyle`, so the app decides about substitutes.
- `by_postscript_name(name)`.
- These list each face once, from the first file that has it: added faces first, then installed files by path. `versions(face)` gives the face from every file that has it (the same family, style, PostScript name and variations), for an app that offers another version of a font.
- `generic_family(Generic::SansSerif)` (also `Serif`, `Monospace` and `SystemUi`) names the installed family to use when a document names no family or one that is not installed. With the `system` feature it takes the first family the font service lists for it that the catalog has (fontconfig's configured aliases on Linux and FreeBSD). Otherwise, or when the catalog has none of those, it takes the first installed family of a fixed list for the catalog's platform (`Arial` for sans-serif on Windows, `Helvetica` on macOS, `DejaVu Sans` on Linux), then of the other platforms' lists. `SystemUi` tries the platform's sans-serif families before the other platforms' lists. It returns `None` when none of them is installed.
- `faces()`, `families()` and the lookups list each face once: of faces with the same family, style, PostScript name and variations they keep the first (added faces, then installed files by path), except that the font store's face wins over a scanned copy elsewhere, such as one in the OS font folder. `versions(face)` gives the face from every file that has it, for an app that offers another version of a font. `scanned_faces()` lists every face the scan found, the same font in two places included, for telling copies apart (craft-font-store's conflict check).
- `read_faces(path, source)` reads one file's faces, named instances included, as a scan does, without a catalog.
## Loading and threads
+4 -1
View File
@@ -8,7 +8,7 @@
use std::time::{Duration, Instant};
use craft_font_catalog::{Catalog, font_dirs, font_store_dir};
use craft_font_catalog::{Catalog, Generic, font_dirs, font_store_dir};
fn main() {
let catalog = Catalog::global();
@@ -18,6 +18,9 @@ fn main() {
let faces = catalog.faces();
println!("{} families, {} faces, first scan {:?}", families.len(), faces.len(), start.elapsed());
println!("font store: {:?}", font_store_dir(catalog.env()));
for generic in Generic::ALL {
println!("{}: {:?}", generic.css_name(), catalog.generic_family(generic));
}
for dir in font_dirs(catalog.env()).iter().filter(|d| d.is_dir()) {
println!("folder: {}", dir.display());
}
+50 -9
View File
@@ -139,22 +139,44 @@ struct Index {
impl Index {
/// Added faces first: a document's or the app's own face wins over an installed face of the
/// same family and style.
/// same family and style. Among scanned duplicates the font store's face wins, so a store
/// font copied into the OS font folder stays the store's wherever the folders sort.
fn build(added: &[Face], scanned: &[Face]) -> Self {
let mut faces: Vec<Face> = Vec::new();
let mut listed = HashMap::new();
let mut versions: HashMap<usize, Vec<FaceInfo>> = HashMap::new();
for f in added.iter().chain(scanned) {
let all: Vec<&Face> = added.iter().chain(scanned).collect();
// The positions in `all` of each face's versions, the listed one first.
let mut groups: HashMap<_, Vec<usize>> = HashMap::new();
for (i, f) in all.iter().enumerate() {
let variations: Vec<(u32, u32)> = f.info.variations.iter().map(|(t, v)| (u32::from_be_bytes(*t), v.to_bits())).collect();
let key = (f.info.family.to_ascii_lowercase(), norm(&f.info.style), f.keys.postscript.first().cloned(), variations);
match listed.entry(key) {
Entry::Occupied(e) => versions.entry(*e.get()).or_default().push(f.info.clone()),
match groups.entry(key) {
Entry::Vacant(e) => {
e.insert(faces.len());
faces.push(f.clone());
e.insert(vec![i]);
}
Entry::Occupied(mut e) => {
let group = e.get_mut();
let store_first =
group.first().is_some_and(|held| *held >= added.len() && all.get(*held).is_some_and(|h| h.info.source != Source::Store));
if store_first && f.info.source == Source::Store {
group.insert(0, i);
} else {
group.push(i);
}
}
}
}
let mut groups: Vec<Vec<usize>> = groups.into_values().collect();
groups.sort_unstable();
let mut faces: Vec<Face> = Vec::new();
let mut versions: HashMap<usize, Vec<FaceInfo>> = HashMap::new();
for group in &groups {
let mut group = group.iter().filter_map(|i| all.get(*i));
let Some(listed) = group.next() else { continue };
let others: Vec<FaceInfo> = group.map(|f| f.info.clone()).collect();
if !others.is_empty() {
versions.insert(faces.len(), others);
}
faces.push((*listed).clone());
}
let mut by_family: HashMap<String, Vec<usize>> = HashMap::new();
let mut aliases: HashMap<String, Vec<Alias>> = HashMap::new();
let mut postscript: HashMap<String, usize> = HashMap::new();
@@ -469,6 +491,12 @@ fn modified(path: &Path) -> Option<SystemTime> {
std::fs::metadata(path).and_then(|m| m.modified()).ok()
}
/// The faces of the font file at `path` as a scan reads them, named instances included, with
/// `source` as their source. Empty when it isn't a font.
pub fn read_faces(path: &Path, source: Source) -> Vec<FaceInfo> {
scan::file_faces(path, MAX_SCAN_READ, source).into_iter().map(|f| f.info).collect()
}
impl Catalog {
/// A catalog of the fonts installed on the system `env` describes, the font store, and the
/// files the platform's font service lists (with the `system` feature).
@@ -546,6 +574,11 @@ impl Catalog {
self.config.read().unwrap_or_else(PoisonError::into_inner)
}
/// Whether scans ask the platform's font service ([`Catalog::with_font_service`]).
pub(crate) fn uses_font_service(&self) -> bool {
self.read_config().font_service
}
/// The environment the catalog was made for.
pub fn env(&self) -> &FontEnv {
&self.env
@@ -728,6 +761,14 @@ impl Catalog {
history.record(generation, &old, &new);
}
/// Every face the last scan found, in path order, with the faces [`Catalog::faces`] drops as
/// duplicates of another of the same family, style and PostScript name. Faces added from
/// files or bytes aren't in it. For telling apart copies of one font in different places.
pub fn scanned_faces(&self) -> Vec<FaceInfo> {
self.ensure();
self.scanned().iter().map(|f| f.info.clone()).collect()
}
/// The family names, sorted ignoring case. Private system families are among them ([`is_private_family`]): a
/// document may name one, while font lists leave them out.
pub fn families(&self) -> Arc<[String]> {
+124
View File
@@ -0,0 +1,124 @@
//! Generic families: the installed family to use for sans-serif, serif, monospace or interface
//! text when a caller has no family name, or the name it has is not installed.
use crate::{Catalog, Os};
/// A generic family ([`Catalog::generic_family`]), as CSS names them.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Generic {
/// `sans-serif`.
SansSerif,
/// `serif`.
Serif,
/// `monospace`.
Monospace,
/// `system-ui`: the face the platform draws its own interface with.
SystemUi,
}
impl Generic {
/// Every generic family.
pub const ALL: [Generic; 4] = [Generic::SansSerif, Generic::Serif, Generic::Monospace, Generic::SystemUi];
/// The CSS keyword (`sans-serif`, `serif`, `monospace`, `system-ui`).
pub fn css_name(self) -> &'static str {
match self {
Generic::SansSerif => "sans-serif",
Generic::Serif => "serif",
Generic::Monospace => "monospace",
Generic::SystemUi => "system-ui",
}
}
}
/// The platforms in the order their lists are tried after the catalog's own.
const OSES: [Os; 4] = [Os::Windows, Os::MacOs, Os::Unix, Os::Haiku];
/// The families tried for `generic` on `os`, most likely first.
fn names(generic: Generic, os: Os) -> &'static [&'static str] {
match (generic, os) {
(Generic::SansSerif, Os::Windows) => &["Arial", "Segoe UI", "Tahoma", "Verdana"],
(Generic::SansSerif, Os::MacOs) => &["Helvetica", "Helvetica Neue", "Arial"],
(Generic::SansSerif, Os::Unix) => &["DejaVu Sans", "Noto Sans", "Liberation Sans", "Cantarell", "Ubuntu", "FreeSans"],
(Generic::SansSerif, Os::Haiku) => &["Noto Sans", "DejaVu Sans"],
(Generic::Serif, Os::Windows) => &["Times New Roman", "Cambria", "Georgia"],
(Generic::Serif, Os::MacOs) => &["Times", "Times New Roman", "New York"],
(Generic::Serif, Os::Unix) => &["DejaVu Serif", "Noto Serif", "Liberation Serif", "FreeSerif"],
(Generic::Serif, Os::Haiku) => &["Noto Serif", "DejaVu Serif"],
(Generic::Monospace, Os::Windows) => &["Consolas", "Cascadia Mono", "Courier New"],
(Generic::Monospace, Os::MacOs) => &["Menlo", "SF Mono", "Monaco", "Courier", "Courier New"],
(Generic::Monospace, Os::Unix) => &["DejaVu Sans Mono", "Noto Sans Mono", "Liberation Mono", "FreeMono"],
(Generic::Monospace, Os::Haiku) => &["Noto Sans Mono", "DejaVu Sans Mono"],
(Generic::SystemUi, Os::Windows) => &["Segoe UI", "Tahoma"],
(Generic::SystemUi, Os::MacOs) => &[".SF NS", "SF Pro", "SF Pro Text", "Helvetica Neue", "Lucida Grande"],
(Generic::SystemUi, Os::Unix) => &["Cantarell", "Ubuntu", "Noto Sans", "DejaVu Sans"],
(Generic::SystemUi, Os::Haiku) => &["Noto Sans"],
(_, Os::None) => &[],
}
}
/// The names [`Catalog::generic_family`] tries, in order: the font service's (`service`) and the
/// list for `os`, then the other platforms' lists. For [`Generic::SystemUi`], the font service's
/// and `os`'s sans-serif names (`sans_service`) come before the other platforms' lists, and their
/// sans-serif lists come last.
fn candidates<'a>(generic: Generic, os: Os, service: &'a [String], sans_service: &'a [String]) -> Vec<&'a str> {
let others = |generic: Generic| OSES.into_iter().filter(move |o| *o != os).flat_map(move |o| names(generic, o).iter().copied());
let mut out: Vec<&str> = service.iter().map(String::as_str).chain(names(generic, os).iter().copied()).collect();
if generic == Generic::SystemUi {
out.extend(sans_service.iter().map(String::as_str).chain(names(Generic::SansSerif, os).iter().copied()));
out.extend(others(generic).chain(others(Generic::SansSerif)));
} else {
out.extend(others(generic));
}
out
}
impl Catalog {
/// The installed family for `generic`, as the catalog names it.
///
/// With the font service on ([`Catalog::with_font_service`]), the families the platform's
/// service lists for `generic` come first (fontconfig's configured aliases on Linux and
/// FreeBSD, fixed names on macOS and Windows). A fixed list for the catalog's platform
/// ([`crate::FontEnv::os`]) follows, then the other platforms' lists. [`Generic::SystemUi`]
/// tries the service's and the platform's sans-serif families before the other platforms'
/// lists. The first of these names that [`Catalog::resolve`] finds wins, so a legacy family
/// name finds its family. Faces added with [`Catalog::add_bytes`] or [`Catalog::add_file`]
/// count as installed. Returns `None` when none of the names is installed. Pass the family
/// to [`Catalog::resolve`] for a face in a style.
pub fn generic_family(&self, generic: Generic) -> Option<String> {
let service = |generic| if self.uses_font_service() { crate::system::generic_family_names(generic) } else { Vec::new() };
let (own, sans) = (service(generic), if generic == Generic::SystemUi { service(Generic::SansSerif) } else { Vec::new() });
candidates(generic, self.env().os, &own, &sans).into_iter().find_map(|name| self.resolve(name, "").map(|(face, _)| face.family))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn candidates_put_the_service_first_then_this_platform_then_the_others() {
let service = ["Configured Sans".to_string()];
let tried = candidates(Generic::SansSerif, Os::Unix, &service, &[]);
assert_eq!(&tried[..3], ["Configured Sans", "DejaVu Sans", "Noto Sans"]);
let windows = tried.iter().position(|n| *n == "Arial");
let mac = tried.iter().position(|n| *n == "Helvetica");
assert!(windows.is_some() && mac.is_some() && windows < mac, "the other platforms' lists follow in a fixed order");
let ui = candidates(Generic::SystemUi, Os::Windows, &[], &service);
assert_eq!(&ui[..4], ["Segoe UI", "Tahoma", "Configured Sans", "Arial"], "this platform's sans-serif names follow its system-ui names");
let (cantarell, dejavu) = (ui.iter().position(|n| *n == "Cantarell"), ui.iter().rposition(|n| *n == "DejaVu Sans"));
assert!(cantarell < dejavu, "the other platforms' system-ui names come before their sans-serif names");
assert!(candidates(Generic::Serif, Os::None, &[], &[]).contains(&"Times New Roman"));
}
#[test]
fn every_generic_has_names_on_every_platform_with_font_folders() {
for generic in Generic::ALL {
for os in OSES {
assert!(!names(generic, os).is_empty(), "{generic:?} on {os:?}");
}
assert!(names(generic, Os::None).is_empty());
}
assert_eq!(Generic::ALL.map(Generic::css_name), ["sans-serif", "serif", "monospace", "system-ui"]);
}
}
+3 -1
View File
@@ -27,6 +27,7 @@ mod env;
mod face_data;
mod fallback;
mod fontconfig;
mod generic;
mod ligature;
mod line_break;
mod outline;
@@ -41,12 +42,13 @@ mod suitcase;
pub mod system;
mod visual_order;
pub use catalog::{Catalog, Changes, FontData, FontFileError, Limits, Lister, LoadedFace, Match, Watch, is_private_family};
pub use catalog::{Catalog, Changes, FontData, FontFileError, Limits, Lister, LoadedFace, Match, Watch, is_private_family, read_faces};
pub use embedding::{SubsetEmbedding, subset_embedding};
pub use env::{FontEnv, Os, font_dirs, font_store_dir, office_font_dirs};
pub use face_data::FaceData;
pub use fallback::{cluster_face, drawable_characters};
pub use fontconfig::fontconfig_dirs;
pub use generic::Generic;
pub use ligature::ligature_caret_stops;
pub use line_break::settle_line_break;
pub use outline::{FontOutline, GlyphPen, OutlineError};
+24 -1
View File
@@ -13,7 +13,7 @@ mod imp {
use std::path::{Path, PathBuf};
use std::sync::{Mutex, PoisonError};
use fontique::{Collection, CollectionOptions, SourceKind};
use fontique::{Collection, CollectionOptions, GenericFamily, SourceKind};
use crate::{FontEnv, font_store_dir};
@@ -160,6 +160,19 @@ mod imp {
})
}
pub fn generic_family_names(generic: crate::Generic) -> Vec<String> {
let generic = match generic {
crate::Generic::SansSerif => GenericFamily::SansSerif,
crate::Generic::Serif => GenericFamily::Serif,
crate::Generic::Monospace => GenericFamily::Monospace,
crate::Generic::SystemUi => GenericFamily::SystemUi,
};
with(false, |s| {
let ids: Vec<_> = s.collection.generic_families(generic).collect();
ids.into_iter().filter_map(|id| s.collection.family_name(id).map(str::to_owned)).collect()
})
}
#[cfg(test)]
mod tests {
use super::*;
@@ -241,6 +254,10 @@ mod imp {
pub fn font_files(_refresh: bool) -> Vec<PathBuf> {
Vec::new()
}
pub fn generic_family_names(_generic: crate::Generic) -> Vec<String> {
Vec::new()
}
}
#[cfg(all(feature = "system", not(target_arch = "wasm32")))]
@@ -269,3 +286,9 @@ pub fn refresh() {
pub(crate) fn font_files(refresh: bool) -> Vec<std::path::PathBuf> {
imp::font_files(refresh)
}
/// The families the platform's font service lists for `generic`, most preferred first; none
/// without the `system` feature.
pub(crate) fn generic_family_names(generic: crate::Generic) -> Vec<String> {
imp::generic_family_names(generic)
}
+50
View File
@@ -259,6 +259,23 @@ fn lookup_by_every_name_kind() {
assert_eq!(cat.by_postscript_name("Missing-Regular"), None);
}
#[test]
fn the_stores_face_wins_over_its_copy_in_the_os_folder() {
// A Flatpak's store sits under ~/.var/app, which sorts after the host's ~/.local/share/fonts
// the store copies its fonts into.
let root = temp("store-copy");
let bytes = font(&spec("Copied Sans", "Regular", 400));
write(&root.join("home/.local/share/fonts/Craft/Copied Sans/CopiedSans-Regular.ttf"), &bytes);
let store = root.join("home/.var/app/org.example.Fonts/data/craft-fonts");
write(&store.join("Copied Sans/CopiedSans-Regular.ttf"), &bytes);
let cat = Catalog::new(FontEnv { font_store: Some(store), ..linux_env(&root) }).with_font_service(false);
cat.rescan();
let styles = cat.styles("Copied Sans");
assert_eq!(styles.len(), 1);
assert_eq!(styles[0].source, Source::Store);
assert_eq!(cat.scanned_faces().iter().filter(|f| f.family == "Copied Sans").count(), 2);
}
#[test]
fn installed_and_removed_fonts_are_seen_without_a_restart() {
let root = temp("rescan");
@@ -373,6 +390,39 @@ fn a_family_loads_once_for_every_thread() {
assert!(cat.load_family("Missing").is_empty());
}
#[test]
fn generic_families_follow_the_platforms_list_then_the_others() {
let root = temp("generic");
let dir = root.join("listed");
write(&dir.join("Arial.ttf"), font(&spec("Arial", "Regular", 400)));
write(&dir.join("NotoSans.ttf"), font(&spec("Noto Sans", "Regular", 400)));
write(&dir.join("Mono.ttf"), font(&spec("DEJAVU SANS MONO", "Regular", 400)));
write(&dir.join("Times.ttf"), font(&Spec { legacy: Some(("Times New Roman", "Regular")), ..spec("Times New Roman Pro", "Regular", 400) }));
write(&dir.join("DejaVuSans.ttf"), font(&Spec { outlines: false, ..spec("DejaVu Sans", "Regular", 400) }));
let catalog = |os: Os| {
let listed = dir.clone();
Catalog::new(FontEnv { os, ..linux_env(&root) }).with_font_service(false).with_lister(Arc::new(move || vec![listed.clone()]))
};
// Linux: DejaVu Sans has no outlines, so Noto Sans; the family's own spelling comes back.
let linux = catalog(Os::Unix);
assert_eq!(linux.generic_family(Generic::SansSerif).as_deref(), Some("Noto Sans"));
assert_eq!(linux.generic_family(Generic::Monospace).as_deref(), Some("DEJAVU SANS MONO"));
// A legacy family name finds its family.
assert_eq!(linux.generic_family(Generic::Serif).as_deref(), Some("Times New Roman Pro"));
assert_eq!(linux.generic_family(Generic::SystemUi).as_deref(), Some("Noto Sans"));
// Windows tries Arial before the Linux names.
let windows = catalog(Os::Windows);
assert_eq!(windows.generic_family(Generic::SansSerif).as_deref(), Some("Arial"));
// Nothing of macOS's system-ui list: sans-serif's answer.
assert_eq!(catalog(Os::MacOs).generic_family(Generic::SystemUi).as_deref(), Some("Arial"));
// An added face counts; with nothing installed there is no answer.
let empty = Catalog::new(linux_env(&root.join("empty"))).with_font_service(false);
assert_eq!(empty.generic_family(Generic::Monospace), None);
empty.add_bytes(font(&spec("Liberation Mono", "Regular", 400)), Source::Document, &Limits::default()).unwrap();
assert_eq!(empty.generic_family(Generic::Monospace).as_deref(), Some("Liberation Mono"));
assert_eq!(empty.generic_family(Generic::Serif), None);
}
#[test]
fn repeated_name_records_are_bounded_before_pairing() {
// Thousands of legacy family and style records in one language: pairing them all would
+1
View File
@@ -11,6 +11,7 @@ repository.workspace = true
reads = [
"crates/ui-contract/fonts/inter/Inter-Regular.ttf",
"crates/ui-contract/fonts/inter/Inter-SemiBold.ttf",
"crates/font-subset/tests/data/orbitron/Orbitron[wght].ttf",
"crates/font-subset/tests/data/sarabun/Sarabun-Regular.ttf",
"crates/ui-contract/tests/fonts/NotoSansCJKsc-test.otf",
]
+40 -12
View File
@@ -10,7 +10,7 @@ Fonts tab; the standalone app
| `filter` | always | Search over the index: family names ignoring case and accents, category, language (English name, autonym or id) and script |
| `index` | always | The pinned built-in indexes (Google Fonts and Noto) compiled into [`craft-font-store`](../font-store/README.md) (`bundled`), each family's source (`source_label`: its name and whether it is curated), and the categories |
| `installed` | always | The installed fonts [`craft-font-catalog`](../font-catalog/README.md) sees, grouped by family and source |
| `store` | always | `Installer`, what the interface needs from the font store: the download consent, install, remove, downloads for a preview, the indexes (`indexes`, `fetch_indexes`) and the sources the user added (`user_sources`, `add_user_source`, `remove_user_source`). `SuiteStore` is craft-font-store's store (native only), `FakeStore` a stand-in for tests, `NoStore` one for when the store folder is unknown. What the preview pool (craft-font-store's `preview`) reads is the `PreviewStore` part |
| `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`), the sources the user added (`user_sources`, `add_user_source`, `remove_user_source`), and a family's copies in the OS user font folder (`available_to_all_supported`, `is_available_to_all`, `not_yet_available`, `make_available`, `withdraw`) with its recorded choice (`available_to_all_choice`, `set_available_to_all_choice`, the default `craft_apps_only`, and `shares` for the two together). `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 |
@@ -28,15 +28,26 @@ The layout follows Adobe Fonts' and Google Fonts' browse pages.
English name or its own, "Japanese · 日本語"), script, source, and installed or not; each option
with its count.
- **Family cards**, one per row: the name, style count, category and source on one line with the
card's state at its end (Install and Preview, Installed, a progress bar while downloading,
card's state at its end (Install, whose menu installs for all apps or for Craft apps only, and
Preview, Installed, a progress bar while downloading,
Couldn't install with Retry, "Not curated" for a source the user added), and a large sample in
the face below. The list is virtual: only the cards on screen are laid out, and their faces load
as they come into view. The arrow keys step through the cards and Enter opens one.
- **Sample toolbar**: a preset (a sentence in the language filtered by, or in the family's own
script when it has no Latin; the alphabet; numerals), the sample text, and the size.
as they come into view. With a preview service set, families that aren't installed draw from
small subsets of their face: the sample for the cards on screen, then one screen above and two
below, then ASCII for the Latin cards on screen; typed text outside those asks for its own
characters once typing pauses. A card the service draws offers no Preview; one whose subset
failed does, and so does its details sheet. The arrow keys step through the cards and Enter
opens one.
- **Sample toolbar**: a preset (a sentence in the language filtered by, else the family's own
sample from the index, by its `sample_script`; the alphabet; numerals), the sample text, and the
size.
- **Details sheet** over the list: every style in its own face with Install or Remove for each,
Install all and Remove all, the source, designer, licence, scripts and languages, and what a
preview downloads.
Install all (with the same menu) and Remove all, whether the family is available to all apps
with the switch that changes it, the source, designer, licence, scripts and languages, and what a
preview downloads. With a preview service, styles not installed draw with its subsets: a static
file's sample, and one subset of each variable file with every axis kept, drawn at each named
instance and at the values of its axis sliders. The copyright and the upstream link, and
an Apache family's NOTICE and, on request, the licence text, read through the store.
- **Installed**: system and font store fonts as the same cards, filtered by source. Only font
store families can be removed; system fonts are removed with the system's own tools.
- **Sources** (`sources_ui`, for a host's settings page): the built-in sources, the index URLs the
@@ -79,6 +90,10 @@ panel.ui(ui);
| `set_look(look)` | The host's palettes (dark and light) and font families, and whether labels are set in capitals |
| `settings()` | The panel's `FontsPanelSettings`: the sample text, preset and size, and whether the downloads note was closed. The panel reads them from the Host's `fonts_panel` section on its first frame and writes the section when they change; without a Host they stay in memory |
| `downloads_allowed()`, `set_downloads_allowed(on)` | The download consent, for a host's settings page. It is the font store's own setting, shared by every Craft app |
| `use_default_filters(language)` | Starts the catalogue on sans-serif families in the host's interface language (English when the index has none for it). Called once, after building the panel |
| `with_previews(previews)` | The preview service's client (craft-font-store's `preview::Previews`), for a host that builds its own (native only) |
| `reload_preview_settings()` | Reads the preview service and the previews setting again, after a host's settings page changed them. The panel also reads them when it first shows and when its window regains focus |
| `loading_previews()` | Whether previews are being fetched |
| `show_downloads_switch(false)` | For a host with the switch in its own settings |
| `sources_ui(ui)` | The font sources, for a host's settings page |
| `set_index(index)` | The indexes, after the host fetched them |
@@ -86,17 +101,30 @@ panel.ui(ui);
## Network use
Nothing is downloaded until the user allows it. Downloads are off by default; the first Install or
Preview asks first. Files come from each source's repositories at the commit or tag its index
No font is installed or downloaded whole until the user allows it. Downloads are off by default; the
first Install or Preview asks first. With a preview service set and previews on (a user setting, on by
default), the panel fetches the small preview subsets of the fonts it shows without asking; with
previews off it uses only those in the disk cache. Files come from each source's repositories at the commit or tag its index
records, through jsDelivr (raw GitHub as the fallback), and each is checked against the index's
size and sha256 before use. Previews stay in memory and are never installed. A source the user
adds is an index at an https URL; its families are never curated.
## Strings
Every interface string goes through craft-i18n with the English text as the key. The panel embeds
its own Japanese and Arabic catalogs (`src/panel/catalogs/`) until its rows are part of
craft-i18n; style and weight names, licence names and product names stay in English.
Every interface string is a word of the Host's `I18n` (`craft_ui::words!`), so the panel is in the Host's
language when the app's catalogs have its rows and in English where they have none. `CATALOGS` holds the
Japanese and Arabic rows, until they are part of craft-i18n's shared catalog, as data the app passes to
its Host's `I18n`:
```rust
// An app with no shared catalog of its own; one with a shared catalog joins the rows to it for
// `I18n::from_owned`.
let (i18n, problems) = craft_i18n::I18n::new(craft_font_manager::CATALOGS, &["ja", "ar"]);
let lang = i18n.match_tag(language).unwrap_or(craft_i18n::Lang::EN);
Host::builder(app).i18n(Arc::new(i18n)).lang(lang).install(ctx);
```
Style and weight names, licence names and product names stay in English.
## Testing
+35 -9
View File
@@ -25,13 +25,14 @@ craft_ui::words! {
width: "axisSliders.width" = "Width";
slant: "axisSliders.slant" = "Slant";
italic: "axisSliders.italic" = "Italic";
optical_size: "axisSliders.opticalSize" = "Optical size";
style: "axisSliders.style" = "Style";
custom: "axisSliders.custom" = "Custom";
}
}
/// The label of an axis: its name when the font gives one, else the registered tag's
/// (`Weight`, `Width`, `Slant`, `Italic`), else the tag itself.
/// (`Weight`, `Width`, `Slant`, `Italic`, `Optical size`), else the tag itself.
pub fn axis_label(axis: &FontAxis) -> String {
label_in(axis, &AxisSlidersWords::default())
}
@@ -45,6 +46,7 @@ fn label_in(axis: &FontAxis, labels: &AxisSlidersWords) -> String {
b"wdth" => labels.width.as_str().to_owned(),
b"slnt" => labels.slant.as_str().to_owned(),
b"ital" => labels.italic.as_str().to_owned(),
b"opsz" => labels.optical_size.as_str().to_owned(),
tag => Tag::new(tag).to_string(),
}
}
@@ -70,9 +72,21 @@ fn set_value(values: &mut AxisValues, tag: [u8; 4], value: f32) {
}
}
/// The axes the sliders show: not hidden, not `opsz`, with a finite, non-empty range.
fn shown_axes(axes: &[FontAxis]) -> impl Iterator<Item = &FontAxis> {
axes.iter().filter(|a| !a.hidden && a.tag != *b"opsz" && a.min.is_finite() && a.max.is_finite() && a.min < a.max)
/// Where the optical size axis (`opsz`) takes its value from.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum OpticalSize {
/// The text layout sets it from the font size: it has no slider.
#[default]
FontSize,
/// Its own slider, as any axis: for text drawn only to look at the face.
Slider,
}
/// The axes the sliders show: not hidden, `opsz` only where it has a slider, with a finite, non-empty range.
pub(crate) fn shown_axes(axes: &[FontAxis], optical_size: OpticalSize) -> impl Iterator<Item = &FontAxis> {
let slides = move |a: &FontAxis| a.tag != *b"opsz" || optical_size == OpticalSize::Slider;
axes.iter().filter(move |a| !a.hidden && slides(a) && a.min.is_finite() && a.max.is_finite() && a.min < a.max)
}
/// What changed in the sliders this pass.
@@ -108,8 +122,8 @@ struct Drawn {
}
/// One slider field per visible axis (label, slider, number field with the axis's range), plus a `Select` of named
/// instances above them when the face has any. Hidden axes, `opsz` (the text layout sets the optical size from the
/// font size) and axes with an empty or non-finite range are left out. Values are the current coordinates; an axis
/// instances above them when the face has any. Hidden axes, `opsz` ([`OpticalSize::FontSize`]) and axes with an empty or
/// non-finite range are left out. Values are the current coordinates; an axis
/// without one shows what the layout draws (its style's weight and italic; else its default). Axes whose range is 10 wide
/// or more step by whole units, the others by hundredths. A drag is one edit; an instance sets every axis in one
/// edit.
@@ -128,6 +142,9 @@ pub struct AxisSliders<'a> {
/// Whether the style is italic: an unset `ital` axis then shows its maximum, once a weight is given.
#[prop]
italic: bool,
/// Whether the `opsz` axis has a slider.
#[prop]
optical_size: OpticalSize,
/// The axes (by tag) the selection mixes: each shows `Mixed` and is left out of the edit's held values.
#[prop]
#[allow(dead_code)] // P3(type-w3): ty.X21a
@@ -137,12 +154,21 @@ pub struct AxisSliders<'a> {
impl<'a> AxisSliders<'a> {
/// Sliders named `label` over the `axes` of a face, editing the coordinates `values`.
pub fn new(label: impl Into<Label>, axes: &'a [FontAxis], values: Bind<'a, AxisValues>) -> Self {
AxisSliders { label: label.into(), axes, values, instances: &[], weight: None, italic: false, mixed: &[] }
AxisSliders {
label: label.into(),
axes,
values,
instances: &[],
weight: None,
italic: false,
optical_size: OpticalSize::default(),
mixed: &[],
}
}
/// Draws the sliders (and the instance list, if any) and reports the edit made this pass.
pub fn show(self, ui: &mut Ui) -> AxisSlidersOutput {
let AxisSliders { label, axes, mut values, instances, weight, italic, mixed: _ } = self;
let AxisSliders { label, axes, mut values, instances, weight, italic, optical_size, mixed: _ } = self;
let drawn = Drawn { weight, italic };
let env = Env::of(ui);
let words = env.words::<AxisSlidersWords>();
@@ -172,7 +198,7 @@ impl<'a> AxisSliders<'a> {
instance = Some(chosen.clone());
}
}
for axis in shown_axes(axes) {
for axis in shown_axes(axes, optical_size) {
let held = read_bind(&mut values, cx).unwrap_or_default();
let wide = axis.max - axis.min >= 10.0;
let mut value = f64::from(value_of(&held, axis, drawn));
@@ -3,7 +3,7 @@
use craft_ui::testing::{Drive, StoryData, StoryOutput, ValueAt, story};
use egui::Ui;
use super::{AxisSliders, AxisValues};
use super::{AxisSliders, AxisValues, OpticalSize};
use crate::axes::{FontAxis, NamedInstance};
const WGHT: [u8; 4] = *b"wght";
@@ -20,3 +20,11 @@ fn axis_sliders(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let (values, values_at): (&mut AxisValues, ValueAt<'_>) = data.value_at("values", vec![(WGHT, 400.0), (WDTH, 100.0)]);
AxisSliders::new("Axes", &axes, values_at.bind(values)).instances(&instances).show(ui).into()
}
/// Sliders that also set the optical size, for text drawn only to look at the face.
#[story(AxisSliders<'static>, covers = [], drive = Drive::Never)]
fn axis_sliders_optical_size(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let axes = [FontAxis::new(WGHT, "", 100.0, 400.0, 900.0), FontAxis::new(*b"opsz", "", 8.0, 14.0, 144.0)];
let (values, values_at): (&mut AxisValues, ValueAt<'_>) = data.value_at("values", vec![(WGHT, 400.0)]);
AxisSliders::new("Axes", &axes, values_at.bind(values)).optical_size(OpticalSize::Slider).show(ui).into()
}
+1 -1
View File
@@ -33,7 +33,7 @@ pub use craft_font_catalog;
pub use craft_font_catalog::{Catalog, FaceInfo, FontEnv, Source};
#[cfg(feature = "ui")]
pub use panel::{
FontSources, FontSourcesOutput, FontsBrowseWords, FontsCommand, FontsPanel, FontsPanelOutput, FontsPanelSettings, FontsPanelView,
CATALOGS, FontSources, FontSourcesOutput, FontsBrowseWords, FontsCommand, FontsPanel, FontsPanelOutput, FontsPanelSettings, FontsPanelView,
FontsPanelWords, Options, Preset, Tab, install_interface_fonts,
};
+197 -22
View File
@@ -5,19 +5,20 @@
pub(crate) mod stories;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use crate::craft_font_catalog::{FontEnv, Limits, Os};
use crate::filter::{Query, Search};
use crate::index::{Category, Family, Index, categories, source_label};
use crate::index::{Category, Family, FontFile, Index, categories, source_label};
use crate::installed::{InstalledFamily, group};
use crate::store::{Installer, RemoveRequest, StoreError};
use crate::store::{Conflict, Installer, MadeAvailable, RemoveRequest, StoreError};
use crate::{Catalog, FaceInfo, Source};
use craft_behavior::ColumnWidth;
use craft_host::{Host, Section, Wake};
use craft_i18n::Folder;
use craft_i18n::matcher::Matcher;
use craft_ui::contract::{NoValue, Outcome, Props as _, ShowContainer as _};
use craft_ui::contract::{Animate as _, NoValue, Outcome, Props as _, ShowContainer as _};
use craft_ui::dialog::Prompt;
use craft_ui::fonts::{EmbeddedFace, I18nScripts, UiFonts};
use craft_ui::layout_components::{Grid, Stack};
@@ -28,11 +29,14 @@ use craft_ui::runtime::words::CommonWords;
use craft_ui::sections::{DialogRole, FooterButton};
use egui::{Context, Response, Ui};
use crate::axes::AxisValues;
use crate::panel::browse::{FontsBrowseWords, Texts};
use crate::panel::details::DetailsSheet;
use crate::panel::i18n::LANGUAGES;
use crate::panel::jobs::{self, Finished, Jobs, Kind, Request};
use crate::panel::legal::LegalTexts;
use crate::panel::samples;
use crate::panel::subsets::Subsets;
/// Installs the standalone app's interface fonts in `ctx`: craft-ui's font stack for `language`, with `craft_faces`
/// (craft-fonts' faces the app embeds with craft-fonts-build, or none) and the system's fonts for every other
@@ -41,8 +45,11 @@ pub fn install_interface_fonts(ctx: &Context, language: &str, craft_faces: &[Emb
UiFonts::new(&I18nScripts).languages(LANGUAGES).ui_language(language).craft_faces(craft_faces).install(ctx);
}
/// The filters column takes the width of its widest section; the list and toolbar take the rest.
const PANES: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::fill(1.0)];
/// The filters column, whatever the list beside it shows; the list and toolbar take the rest.
const PANES: [ColumnWidth; 2] = [ColumnWidth::Fixed(248.0), ColumnWidth::fill(1.0)];
/// The panes of a panel less than [`WIDE_PANEL`] wide.
const NARROW_PANES: [ColumnWidth; 2] = [ColumnWidth::Fixed(212.0), ColumnWidth::fill(1.0)];
const WIDE_PANEL: f32 = 860.0;
/// Preview downloads: at most this much per file, and this many faces in a session.
const PREVIEW_LIMITS: Limits = Limits { max_file_bytes: 64 << 20, max_faces_per_file: 512, max_added_faces: 20_000 };
@@ -63,6 +70,8 @@ craft_ui::words! {
styles: count "fontsPanel.styles" = "{n} style" | "{n} styles";
families: count "fontsPanel.families" = "{n} family" | "{n} families";
setting_failed: template "fontsPanel.settingFailed" = "The download setting couldn't be saved: {error}";
craft_apps_only_failed: template "fontsPanel.craftAppsOnlyFailed" = "The Craft apps only setting couldn't be applied: {error}";
system_fonts_failed: template "fontsPanel.systemFontsFailed" = "Your system's fonts folder couldn't be updated: {error}";
consent_title: template "fontsPanel.consentTitle" = "Download from {source}?";
consent_text: template "fontsPanel.consentText" = "Craft Font Manager downloads {family} ({size}) from {source}, and checks every file before using it.";
consent_text_host: template "fontsPanel.consentTextHost" = "Craft Font Manager downloads {family} ({size}) from {host}, the server of {source}, a source you added, and checks every file before using it.";
@@ -175,7 +184,8 @@ impl Options {
/// A download, waiting for the user's consent or to be tried again.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Pending {
Install(usize),
/// A family, and whether to copy it into the OS user font folder ([`Request::Install`]).
Install(usize, Option<bool>),
/// One file of a family, by its path in the index.
InstallFile(usize, String),
Preview(usize),
@@ -184,7 +194,7 @@ pub(crate) enum Pending {
impl Pending {
pub(crate) fn family(&self) -> usize {
match self {
Pending::Install(i) | Pending::InstallFile(i, _) | Pending::Preview(i) => *i,
Pending::Install(i, _) | Pending::InstallFile(i, _) | Pending::Preview(i) => *i,
}
}
}
@@ -198,6 +208,37 @@ pub(crate) enum Detail {
Installed(String, Source),
}
/// Why a family installed here isn't in the OS user font folder.
#[derive(Clone, Debug)]
pub(crate) enum NotCopied {
/// Fonts already there have its PostScript names, or sit where its copies would go.
Refused(Vec<Conflict>),
Failed(String),
}
/// A problem that belongs to no family, with the error reported.
#[derive(Clone, Debug)]
pub(crate) enum Problem {
/// The download setting couldn't be saved.
DownloadSetting(String),
/// "Keep fonts in Craft apps only" couldn't be saved.
CraftAppsOnly(String),
/// A family couldn't be copied to or withdrawn from the OS user font folder.
SystemFonts(String),
}
impl Problem {
/// What the panel says about it.
pub(crate) fn text(&self, words: &FontsPanelWords) -> String {
let (template, error) = match self {
Problem::DownloadSetting(error) => (&words.setting_failed, error),
Problem::CraftAppsOnly(error) => (&words.craft_apps_only_failed, error),
Problem::SystemFonts(error) => (&words.system_fonts_failed, error),
};
template.fill(&[("error", error.as_str())])
}
}
/// Why the last job for a family failed, and what Retry runs.
#[derive(Clone, Debug)]
pub(crate) struct Failure {
@@ -254,12 +295,24 @@ pub struct FontsPanel {
/// Downloaded preview files, never installed.
pub(crate) previews: Arc<Catalog>,
pub(crate) previewed: HashMap<String, Vec<FaceInfo>>,
/// The previews from the font preview service.
pub(crate) subsets: Subsets,
/// The values the user set on the details sheet's axis sliders, by file sha256.
pub(crate) detail_axes: HashMap<String, AxisValues>,
/// Licence and NOTICE texts, by family, text and file.
pub(crate) legal: LegalTexts,
pub(crate) jobs: Jobs,
pub(crate) asking: Option<Pending>,
/// By lower-case family name.
pub(crate) failed: HashMap<String, Failure>,
/// A problem that belongs to no family: why the download setting couldn't be saved.
pub(crate) notice: Option<String>,
/// The last problem that belongs to no family.
pub(crate) notice: Option<Problem>,
/// Families an install couldn't copy into the OS user font folder, by lower-case name.
pub(crate) not_copied: HashMap<String, NotCopied>,
/// "Keep fonts in Craft apps only" as last read or set.
pub(crate) craft_apps_only: bool,
/// Whether the start-up copy of families whose choice is the OS user font folder was queued.
shared_at_start: bool,
/// The window had OS focus on the last pass.
window_active: bool,
/// The download consent as last read.
@@ -284,6 +337,11 @@ pub(crate) fn source_name(words: &FontsPanelWords, source: Source) -> &Label {
}
}
/// The file of the face the list shows for a family of the index: the one closest to an upright regular.
pub(crate) fn list_file(family: &Family) -> Option<&FontFile> {
family.files.iter().min_by_key(|f| (f.is_italic(), !f.has_weight(400, f.is_italic()), f.weight.abs_diff(400), !f.has_normal_width()))
}
/// The face closest to an upright regular.
pub(crate) fn regular(faces: &[FaceInfo]) -> Option<&FaceInfo> {
faces.iter().min_by_key(|f| (f.italic, ((f.weight - 400.0).abs() * 10.0) as i64, ((f.width - 100.0).abs() * 10.0) as i64))
@@ -316,6 +374,7 @@ impl FontsPanel {
pub fn new(options: Options) -> FontsPanel {
let catalogue = options.index.map(|index| Catalogue { search: Search::new(&index), index: Arc::new(index) });
let previews = Arc::new(Catalog::new(FontEnv { os: Os::None, ..FontEnv::default() }).with_font_service(false));
let subsets = Subsets::new(Arc::clone(&options.installer));
FontsPanel {
settings: FontsPanelSettings::default(),
saved: FontsPanelSettings::default(),
@@ -323,7 +382,9 @@ impl FontsPanel {
tab: Tab::Catalogue,
downloads_switch: true,
catalog: options.catalog,
craft_apps_only: options.installer.craft_apps_only(),
installer: options.installer,
shared_at_start: false,
catalogue,
query: Query::default(),
show: Show::All,
@@ -346,15 +407,38 @@ impl FontsPanel {
detail: None,
previews,
previewed: HashMap::new(),
subsets,
detail_axes: HashMap::new(),
legal: LegalTexts::new(),
jobs: Jobs::new(),
asking: None,
failed: HashMap::new(),
notice: None,
not_copied: HashMap::new(),
window_active: true,
consent: None,
}
}
/// Fetches the previews through `previews` instead of craft-font-store's client.
#[cfg(not(target_arch = "wasm32"))]
#[must_use]
pub fn with_previews(mut self, previews: craft_font_store::preview::Previews) -> FontsPanel {
self.subsets.replace(previews);
self
}
/// Reads the preview service and the previews setting again on the next pass, after a host's settings page changed
/// them. The panel also reads them when it first shows and when its window regains focus.
pub fn reload_preview_settings(&mut self) {
self.subsets.read_settings_soon();
}
/// Whether previews from the font preview service are being fetched.
pub fn loading_previews(&self) -> bool {
self.subsets.loading()
}
/// Shows `index` (after the host fetched the sources, say). The details sheet closes, as family positions
/// change.
pub fn set_index(&mut self, index: Result<Index, String>) {
@@ -416,6 +500,25 @@ impl FontsPanel {
}
}
/// Starts the catalogue filtered to sans-serif families and to the language of `language` (a tag such as `de` or
/// `pt-BR`; the most spoken language of the index with that ISO 639 code), or to English when the index has none for
/// it. A host calls it once, after building the panel; the user changes both filters from there.
pub fn use_default_filters(&mut self, language: &str) {
let Ok(c) = &self.catalogue else { return };
let code = language.split(['-', '_']).next().unwrap_or("").to_ascii_lowercase();
let best = |code: &str| {
c.index
.languages()
.iter()
.enumerate()
.filter(|(_, l)| !l.historical && l.id.split('_').next().is_some_and(|id| id.eq_ignore_ascii_case(code)))
.max_by_key(|(_, l)| l.population)
.map(|(i, _)| i)
};
self.query.category = Some(Category::SansSerif);
self.query.language = best(&code).or_else(|| best("en"));
}
/// Whether the panel shows its own "Allow downloads" switch. A host with the switch in its own settings turns it
/// off; the panel still offers to allow downloads where one is needed.
pub fn show_downloads_switch(&mut self, show: bool) {
@@ -468,7 +571,7 @@ impl FontsPanel {
pub fn set_downloads_allowed(&mut self, allowed: bool) -> Result<(), StoreError> {
let result = self.installer.allow_downloads(allowed);
self.consent = None;
self.notice = result.as_ref().err().map(|e| e.0.clone());
self.notice = result.as_ref().err().map(|e| Problem::DownloadSetting(e.0.clone()));
result
}
@@ -482,12 +585,14 @@ impl FontsPanel {
/// (read again when the window regains focus) and the results of the search.
fn prepare(&mut self, host: Option<&Arc<Host>>, window_active: bool) {
self.load_settings(host);
self.share_installed_at_start(host);
self.poll_jobs();
if window_active && !self.window_active {
if self.catalog.is_ready() {
self.catalog.rescan_if_changed();
}
self.consent = None;
self.subsets.read_settings_soon();
}
self.window_active = window_active;
self.refresh_installed();
@@ -519,9 +624,19 @@ impl FontsPanel {
for (job, result) in self.jobs.poll() {
let key = family_key(&job.source, &job.family);
match result {
Ok(Finished::Installed | Finished::Removed) => {
Ok(Finished::Installed(copied)) => {
self.failed.remove(&key);
self.record_copy(&job.family, copied);
}
Ok(Finished::Removed) => {
self.failed.remove(&key);
self.not_copied.remove(&job.family.to_lowercase());
}
Ok(Finished::Switched(copied)) => self.record_copy(&job.family, copied.map(Ok)),
Ok(Finished::SharedAtStart(refused)) => {
self.not_copied.extend(refused.into_iter().map(|(f, c)| (f.to_lowercase(), NotCopied::Refused(c))));
}
Err(e) if job.kind == Kind::SystemFonts => self.notice = Some(Problem::SystemFonts(e.0)),
Ok(Finished::Previewed(files)) => {
self.failed.remove(&key);
let mut faces = Vec::new();
@@ -539,9 +654,9 @@ impl FontsPanel {
c.index.families().iter().position(|f| f.source == job.source && f.family.eq_ignore_ascii_case(&job.family))
});
let retry = position.and_then(|i| match job.kind {
Kind::Install => Some(job.file.clone().map_or(Pending::Install(i), |path| Pending::InstallFile(i, path))),
Kind::Install => Some(job.file.clone().map_or(Pending::Install(i, job.share), |path| Pending::InstallFile(i, path))),
Kind::Preview => Some(Pending::Preview(i)),
Kind::Remove => None,
Kind::Remove | Kind::SystemFonts => None,
});
log::warn!("{} ({:?}): {e}", job.family, job.kind);
self.failed.insert(key, Failure { kind: job.kind, error: e.0, retry });
@@ -549,6 +664,45 @@ impl FontsPanel {
}
}
self.poll_sources();
self.poll_legal();
}
fn record_copy(&mut self, family: &str, copied: Option<Result<MadeAvailable, StoreError>>) {
let not_copied = match copied {
Some(Ok(MadeAvailable::Refused(conflicts))) => NotCopied::Refused(conflicts),
Some(Err(e)) => NotCopied::Failed(e.0),
Some(Ok(MadeAvailable::Done)) | None => {
self.not_copied.remove(&family.to_lowercase());
return;
}
};
self.not_copied.insert(family.to_lowercase(), not_copied);
}
/// Sets "Keep fonts in Craft apps only": what a plain Install does from now on. Installed families keep their
/// choice.
pub(crate) fn set_craft_apps_only(&mut self, on: bool) {
self.notice = self.installer.set_craft_apps_only(on).err().map(|e| Problem::CraftAppsOnly(e.0));
self.craft_apps_only = self.installer.craft_apps_only();
}
/// Makes a store family available to all apps or keeps it in Craft apps only, as a job, and records that as its
/// choice.
pub(crate) fn set_available_to_all(&mut self, host: Option<&Arc<Host>>, family: &str, files: Vec<PathBuf>, on: bool) {
self.notice = None;
let request = Request::AvailableToAll(family.to_owned(), files, on);
self.jobs.start(host, Arc::clone(&self.installer), Arc::clone(&self.catalog), request);
}
/// Once per start, copies the store families whose choice is the OS user font folder and that aren't all there
/// yet (installed before installs copied, say), as a job.
fn share_installed_at_start(&mut self, host: Option<&Arc<Host>>) {
if std::mem::replace(&mut self.shared_at_start, true) {
return;
}
if self.installer.available_to_all_supported() {
self.jobs.start(host, Arc::clone(&self.installer), Arc::clone(&self.catalog), Request::ShareAtStart);
}
}
fn refresh_installed(&mut self) {
@@ -638,8 +792,9 @@ impl FontsPanel {
self.installed_shown.0.clone()
}
/// The sample for a family with `scripts`: what the user typed, else the preset.
pub(crate) fn sample_for<'a>(&self, scripts: impl IntoIterator<Item = &'a str>) -> String {
/// The sample for a family with `scripts`, whose own sample in the index is `own`: what the user typed, else the
/// preset.
pub(crate) fn sample_for<'a>(&self, own: Option<&str>, scripts: impl IntoIterator<Item = &'a str>) -> String {
if !self.settings.sample.trim().is_empty() {
return self.settings.sample.clone();
}
@@ -648,7 +803,7 @@ impl FontsPanel {
Preset::Numerals => samples::NUMERALS.to_owned(),
Preset::Sentence => {
let language = self.catalogue.as_ref().ok().zip(self.query.language).and_then(|(c, l)| c.index.languages().get(l));
language.and_then(|l| samples::for_language(&l.id)).unwrap_or_else(|| samples::for_scripts(scripts)).to_owned()
language.and_then(|l| samples::for_language(&l.id)).or(own).unwrap_or_else(|| samples::for_scripts(scripts)).to_owned()
}
}
}
@@ -672,7 +827,7 @@ impl FontsPanel {
self.failed.remove(&family_key(&f.source, &f.family));
}
let request = match pending {
Pending::Install(i) => Request::Install(index, i),
Pending::Install(i, share) => Request::Install(index, i, share),
Pending::InstallFile(i, path) => Request::InstallFile(index, i, path),
Pending::Preview(i) => Request::Preview(index, i),
};
@@ -783,19 +938,39 @@ impl<'a> FontsPanelView<'a> {
panel.prepare(host.as_ref(), view.shell().window.active);
let search = ui.scope_id().with("search");
let folder = env.folder();
let shown = Stack::new().fill().label(words.panel.clone()).command_scope(FontsCommand::SCOPE).show(ui, |ui, root| {
let wake = panel.jobs.waker();
let panes = if ui.available_width() < WIDE_PANEL { &NARROW_PANES } else { &PANES };
let mut begun = false;
let mut shown = Stack::new().fill().label(words.panel.clone()).command_scope(FontsCommand::SCOPE).show(ui, |ui, root| {
if !std::mem::replace(&mut begun, true) {
panel.subsets.begin(root.now(), &wake);
}
while root.take_command::<FontsCommand>().is_some() {
focus::request(ui.ctx(), FocusTarget::Id(search));
}
root.publish(FontsCommand::Find, CommandState::new());
panel.top_bar(ui, &browse, texts.format, search);
Grid::new(&PANES).fill().show(ui, |ui, _| {
let shown = Grid::new(panes).fill().show(ui, |ui, _| {
panel.filters(ui, &texts);
panel.main(ui, &texts, &folder, host.as_ref());
panel.main(ui, &texts, &folder, host.as_ref())
});
shown.inner.flatten()
});
if panel.detail.is_some() && DetailsSheet::new(panel).show(ui).closed {
panel.detail = None;
// A measuring run has no rows on screen, and a pass that runs again may have the wrong ones.
let rerun = craft_ui::runtime::frame::will_rerun(ui.ctx());
let real = shown.settle(|_, visible| (!rerun).then(|| panel.request_subsets(visible.take()))).flatten().is_some();
if panel.detail.is_some() {
if DetailsSheet::new(panel).show(ui).closed {
panel.detail = None;
}
} else {
if real {
panel.subsets.request_detail(None, &[]);
}
panel.detail_axes.clear();
}
if let Some(seconds) = panel.subsets.next_wake() {
craft_ui::runtime::frame::request_repaint_after(ui.ctx(), seconds);
}
panel.consent_prompt(ui, &env, &words, host.as_ref());
panel.save_settings(host.as_ref());
+1 -1
View File
@@ -60,6 +60,6 @@ fn fonts_panel_no_results(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
fn fonts_panel_consent(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show(ui, data, Tab::Catalogue, |panel| {
let _ = panel.set_downloads_allowed(false);
panel.asking = Some(Pending::Install(0));
panel.asking = Some(Pending::Install(0, None));
})
}
+104 -36
View File
@@ -6,6 +6,7 @@ pub(crate) mod stories;
pub(crate) mod cards;
use std::borrow::Cow;
use std::ops::Range;
use std::sync::Arc;
use craft_behavior::{ColumnWidth, DisplayOrder, Flow, ItemSource, Metrics, Proposal, Selection, SelectionChange, SpanLayout};
@@ -33,14 +34,16 @@ use craft_ui::tabs::{Tab as TabItem, TabKind, TabStrip};
use craft_ui::text::TextField;
use egui::{Id, Pos2, Rect, Response, Ui, Vec2};
use crate::index::{Category, Index, source_label};
use crate::Source;
use crate::index::{Category, Family, Index, source_label};
use crate::panel::app::{
Detail, FontsPanel, FontsPanelWords, Origin, Pending, Preset, Show, Tab, category_label, family_key, regular, source_name, style_count,
};
use crate::panel::faces::Owner;
use crate::panel::jobs::Kind;
use crate::panel::specimen::{FontSample, SampleFace};
use crate::{Catalog, FaceInfo, Source};
use crate::panel::samples;
use crate::panel::specimen::{FontSample, HeldFace};
use crate::panel::subsets::{Row as SubsetRow, Subsets};
/// The language filter lists this many matches under its search field.
const LANGUAGE_MATCHES: usize = 8;
@@ -64,6 +67,9 @@ craft_ui::words! {
downloads: "fontsBrowse.downloads" = "Downloads";
allow_downloads: "fontsBrowse.allowDownloads" = "Allow downloads";
downloads_hint: "fontsBrowse.downloadsHint" = "From each font's source, only when you install or preview a font.";
system_fonts: "fontsBrowse.systemFonts" = "System fonts";
craft_apps_only: "fontsBrowse.craftAppsOnly" = "Keep fonts in Craft apps only";
craft_apps_only_hint: "fontsBrowse.craftAppsOnlyHint" = "Off: Install also copies fonts to your system's fonts folder, for all apps. Fonts already installed keep their own setting.";
category: "fontsBrowse.category" = "Category";
all_categories: "fontsBrowse.allCategories" = "All categories";
language: "fontsBrowse.language" = "Language";
@@ -87,6 +93,9 @@ craft_ui::words! {
sample_text: "fontsBrowse.sampleText" = "Sample text";
size: "fontsBrowse.size" = "Size";
downloads_off: "fontsBrowse.downloadsOff" = "Downloads are off";
installs_off_text: "fontsBrowse.installsOffText" = "Nothing is installed until you allow downloads.";
previews_unavailable: "fontsBrowse.previewsUnavailable" = "Font previews are unavailable";
previews_unreachable: template "fontsBrowse.previewsUnreachable" = "Can't reach the preview server {server}: {error}. Check the address in Settings → Advanced.";
downloads_off_text: "fontsBrowse.downloadsOffText" = "Fonts that aren't installed show a sample once you preview them. Nothing is downloaded until you allow it.";
cards: "fontsBrowse.cards" = "Families";
no_match: "fontsBrowse.noMatch" = "No fonts match";
@@ -103,14 +112,19 @@ craft_ui::words! {
installing: "fontsBrowse.installing" = "Installing";
removing: "fontsBrowse.removing" = "Removing";
downloading: "fontsBrowse.downloading" = "Downloading";
updating_system_fonts: "fontsBrowse.updatingSystemFonts" = "Updating system fonts";
progress: template "fontsBrowse.progress" = "{what} {percent} %";
working: template "fontsBrowse.working" = "{what}…";
retry: "fontsBrowse.retry" = "Retry";
failed_install: "fontsBrowse.failedInstall" = "Couldn't install";
failed_remove: "fontsBrowse.failedRemove" = "Couldn't remove";
failed_download: "fontsBrowse.failedDownload" = "Couldn't download";
failed_system_fonts: "fontsBrowse.failedSystemFonts" = "Couldn't update system fonts";
install: "fontsBrowse.install" = "Install";
install_family: template "fontsBrowse.installFamily" = "Install {family}";
install_options: "fontsBrowse.installOptions" = "More install options";
install_all_apps: "fontsBrowse.installAllApps" = "Install for all apps";
install_craft_apps: "fontsBrowse.installCraftApps" = "Install for Craft apps only";
preview: "fontsBrowse.preview" = "Preview";
preview_family: template "fontsBrowse.previewFamily" = "Preview {family}";
remove: "fontsBrowse.remove" = "Remove";
@@ -189,7 +203,7 @@ impl FontsPanel {
pub(crate) fn filters(&mut self, ui: &mut Ui, texts: &Texts<'_>) {
let browse = texts.browse;
Stack::new().scroll(Scroll::vertical()).label(browse.filters.clone()).show(ui, |ui, _| {
Stack::new().fill().scroll(Scroll::vertical()).label(browse.filters.clone()).show(ui, |ui, _| {
match self.tab {
Tab::Catalogue => self.catalogue_filters(ui, texts),
Tab::Installed => self.installed_filters(ui, texts),
@@ -205,6 +219,16 @@ impl FontsPanel {
Text::new(browse.downloads_hint.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
});
}
if self.installer.available_to_all_supported() {
Section::fixed(browse.system_fonts.clone()).id_salt("system-fonts").show(ui, |ui, _| {
let mut on = self.craft_apps_only;
Checkbox::new(Bind::bound(&mut on)).label(browse.craft_apps_only.clone()).show(ui);
if on != self.craft_apps_only {
self.set_craft_apps_only(on);
}
Text::new(browse.craft_apps_only_hint.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
});
}
});
}
@@ -247,7 +271,7 @@ impl FontsPanel {
.activate(ActivateOn::Click)
.allow_empty(false)
.header(false)
.sizing(Sizing::Content)
.sizing(Sizing::FillWidth)
.natural_height(true)
.selection(Bind::given(current))
.show_items(ui, &CardKeys::new(&rows, |_| None), &mut |key, _| {
@@ -317,20 +341,31 @@ impl FontsPanel {
});
}
pub(crate) fn main(&mut self, ui: &mut Ui, texts: &Texts<'_>, folder: &Folder, host: Option<&Arc<Host>>) {
Stack::new().fill().show(ui, |ui, _| {
/// The toolbar, the notices and the cards; the positions of the catalogue cards on screen, or `None` while it shows
/// none.
pub(crate) fn main(&mut self, ui: &mut Ui, texts: &Texts<'_>, folder: &Folder, host: Option<&Arc<Host>>) -> Option<Range<usize>> {
let shown = Stack::new().fill().show(ui, |ui, _| {
self.toolbar(ui, texts.browse);
if let Some(error) = self.notice.clone() {
Notice::new(Tone::Bad, Label::from(texts.panel.setting_failed.fill(&[("error", error.as_str())]))).show(ui);
self.subsets.typed(format!("{:?}\n{:?}\n{}", self.settings.preset, self.query.language, self.settings.sample));
if let Some(problem) = &self.notice {
Notice::new(Tone::Bad, Label::from(problem.text(texts.panel))).show(ui);
}
if let Some((server, error)) = self.subsets.unreachable() {
let text = texts.browse.previews_unreachable.fill(&[("server", server), ("error", error)]);
Notice::new(Tone::Warn, Label::from(text)).id_salt("previews").title(texts.browse.previews_unavailable.clone()).show(ui);
}
match self.tab {
Tab::Catalogue => {
self.download_note(ui, texts.browse);
self.catalogue_list(ui, texts, host);
self.catalogue_list(ui, texts, host)
}
Tab::Installed => {
self.installed_list(ui, texts, folder, host);
None
}
Tab::Installed => self.installed_list(ui, texts, folder, host),
}
});
shown.inner.flatten()
}
fn toolbar(&mut self, ui: &mut Ui, browse: &FontsBrowseWords) {
@@ -345,7 +380,9 @@ impl FontsPanel {
if self.settings.preset != before {
self.settings.sample.clear();
}
let hint = self.sample_for(["Latn"]);
let index = self.index();
let latin = index.as_ref().and_then(|index| index.sample("Latn")).map(|sample| sample.text.as_str());
let hint = self.sample_for(latin, ["Latn"]);
TextField::new(browse.sample_text.clone(), Bind::bound(&mut self.settings.sample)).placeholder(Label::from(hint)).show(ui);
let mut size = f64::from(self.settings.size);
SliderField::new(browse.size.clone(), Bind::bound(&mut size), 12.0..=120.0)
@@ -360,7 +397,9 @@ impl FontsPanel {
if self.allowed() || self.settings.hide_download_note {
return;
}
let out = Notice::new(Tone::Info, browse.downloads_off_text.clone())
// With a preview service, samples show without asking: the note is about installs only.
let text = if self.subsets.available() { &browse.installs_off_text } else { &browse.downloads_off_text };
let out = Notice::new(Tone::Info, text.clone())
.title(browse.downloads_off.clone())
.action(NoticeAction::new(browse.allow_downloads.clone()))
.dismiss()
@@ -373,31 +412,31 @@ impl FontsPanel {
}
}
fn catalogue_list(&mut self, ui: &mut Ui, texts: &Texts<'_>, host: Option<&Arc<Host>>) {
fn catalogue_list(&mut self, ui: &mut Ui, texts: &Texts<'_>, host: Option<&Arc<Host>>) -> Option<Range<usize>> {
let browse = texts.browse;
let index = match &self.catalogue {
Ok(c) => Arc::clone(&c.index),
Err(error) => {
Notice::new(Tone::Bad, Label::from(browse.indexes_unreadable.fill(&[("error", error.as_str())]))).show(ui);
return;
return None;
}
};
self.source_problems(ui, texts, &index, host);
Text::new(Label::from(texts.families(self.results.len()))).role(TypeRole::Caption).shade(Shade::Faint).show(ui);
if self.results.is_empty() {
self.empty(ui, browse, &browse.no_match, &browse.no_match_hint, true);
return;
return None;
}
let results = self.results.clone();
let events = {
let shown = {
let me = &*self;
let keys = CardKeys::new(&results, |i| index.families().get(i).map(|f| f.family.as_str()));
FamilyCards::new(browse.cards.clone()).show_items(ui, &keys, &mut |key, _| FamilyCard::new(me.catalogue_card(&index, *key, texts))).events
FamilyCards::new(browse.cards.clone()).show_items(ui, &keys, &mut |key, _| FamilyCard::new(me.catalogue_card(&index, *key, texts)))
};
for event in events {
for event in shown.events {
match event {
CollectionEvent::Activate(i) => self.detail = Some(Detail::Family(i)),
CollectionEvent::Item(i, CardEvent::Install) => self.ask(host, Pending::Install(i)),
CollectionEvent::Item(i, CardEvent::Install(share)) => self.ask(host, Pending::Install(i, share)),
CollectionEvent::Item(i, CardEvent::Preview) => self.ask(host, Pending::Preview(i)),
CollectionEvent::Item(i, CardEvent::Retry) => {
let retry = index
@@ -412,6 +451,42 @@ impl FontsPanel {
_ => {}
}
}
Some(shown.visible)
}
/// Asks the preview service for the subsets of the catalogue cards on screen, at the positions `visible` of the
/// results, and round them; cancels what the list asked for when it shows no card.
pub(crate) fn request_subsets(&mut self, visible: Option<Range<usize>>) {
let Some((visible, index)) = visible.zip(self.index()) else {
self.subsets.cancel_all();
return;
};
let window = Subsets::window(&visible, self.results.len());
let rows: Vec<Option<SubsetRow<'_>>> = window.clone().map(|n| self.subset_row(&index, *self.results.get(n)?)).collect();
self.subsets.request(&index, window.start, &rows, visible);
}
/// The family at `i` in the index as a row drawn with a subset: `None` when it is installed or previewed whole.
fn subset_row<'a>(&self, index: &'a Index, i: usize) -> Option<SubsetRow<'a>> {
let family = index.families().get(i)?;
if self.installed_by_name.contains_key(&family.family.to_lowercase())
|| self.previewed.contains_key(&family_key(&family.source, &family.family))
{
return None;
}
Some((family, self.family_sample(index, family)))
}
/// The sample a family of the index shows.
pub(crate) fn family_sample(&self, index: &Index, family: &Family) -> String {
self.sample_for(samples::of_family(index, family), family.scripts.iter().map(String::as_str))
}
/// The sample the installed family `name` shows: that of the index's family of the name, else the preset's.
pub(crate) fn installed_sample(&self, name: &str) -> String {
let index = self.index();
let family = index.as_deref().and_then(|index| Some((index, index.family(name)?)));
family.map_or_else(|| self.sample_for(None, []), |(index, family)| self.family_sample(index, family))
}
/// Sources that couldn't be loaded, one note each above the list; the others show as usual.
@@ -501,6 +576,8 @@ impl FontsPanel {
let key = family_key(&family.source, &family.family);
let installed = self.installed_by_name.get(&family.family.to_lowercase()).and_then(|f| regular(f)).cloned();
let previewed = self.previewed.get(&key).and_then(|f| regular(f)).cloned();
let row = self.subset_row(index, i);
let drawn = row.as_ref().is_some_and(|row| self.subsets.draws(index, row));
let state = if let Some(job) = self.jobs.of(&family.source, &family.family) {
CardState::Running(job.kind, job.fraction())
} else if let Some(failure) = self.failed.get(&key) {
@@ -508,24 +585,16 @@ impl FontsPanel {
} else if installed.is_some() {
CardState::Installed
} else {
CardState::Offer { preview: !self.previewed.contains_key(&key) }
CardState::Offer { preview: !drawn && !self.previewed.contains_key(&key), destinations: self.installer.available_to_all_supported() }
};
let (source, curated) = source_label(index, family);
let meta = [texts.styles(style_count(family)), category_label(texts.panel, family), source.to_owned()].join(" · ");
let face = match (installed, previewed) {
(Some(face), _) => Some((Owner::Installed, face, Arc::clone(&self.catalog))),
(None, Some(face)) => Some((Owner::Preview, face, Arc::clone(&self.previews))),
(None, None) => None,
(Some(face), _) => Some(HeldFace::local(Owner::Installed, face, &self.catalog)),
(None, Some(face)) => Some(HeldFace::local(Owner::Preview, face, &self.previews)),
(None, None) => row.as_ref().and_then(|row| self.subsets.font(index, row)).map(HeldFace::Subset),
};
CardData {
name: family.family.clone(),
meta,
sample: self.sample_for(family.scripts.iter().map(String::as_str)),
points: self.settings.size,
curated,
state,
face,
}
CardData { name: family.family.clone(), meta, sample: self.family_sample(index, family), points: self.settings.size, curated, state, face }
}
/// What an installed family's card shows.
@@ -540,15 +609,14 @@ impl FontsPanel {
None => CardState::System,
},
};
let scripts = self.index().and_then(|index| index.family(&family.name).map(|f| f.scripts.clone())).unwrap_or_default();
CardData {
name: family.name.clone(),
meta,
sample: self.sample_for(scripts.iter().map(String::as_str)),
sample: self.installed_sample(&family.name),
points: self.settings.size,
curated: true,
state,
face: regular(&family.faces).cloned().map(|face| (Owner::Installed, face, Arc::clone(&self.catalog))),
face: regular(&family.faces).cloned().map(|face| HeldFace::local(Owner::Installed, face, &self.catalog)),
}
}
}
+50 -26
View File
@@ -1,12 +1,13 @@
//! The family card and the collection of cards the panel lists.
use craft_ui::contract::{Props as _, Styled as _, clicked};
use craft_ui::buttons::{SplitButton, SplitOutput};
use craft_ui::contract::{ActivateOn, Entry, Props as _, Styled as _, clicked};
use super::{
Access, Arc, Badge, Button, Catalog, Collection, CollectionProps, CollectionResponse, Common, Component, ComponentStyle, ContainerProps, Cow, Cx,
DisplayOrder, Emphasis, FaceInfo, Flow, FontSample, FontsBrowseWords, Ink, ItemOutput, ItemSource, Kind, Label, Link, MeasureCx, Metrics, Name,
NoValue, Outcome, Owner, PartsCx, Pos2, Progress, Proposal, Rect, Response, Role, RuleKind, SampleFace, SelectMode, Selection, Shade, Sizing,
SpanLayout, Stateful, StyleCx, Text, TextLook, TextRun, Tone, TypeRole, Variant, Vec2,
Access, Badge, Button, Collection, CollectionProps, CollectionResponse, Common, Component, ComponentStyle, ContainerProps, Cow, Cx, DisplayOrder,
Emphasis, Flow, FontSample, FontsBrowseWords, HeldFace, Ink, ItemOutput, ItemSource, Kind, Label, Link, MeasureCx, Metrics, Name, NoValue,
Outcome, PartsCx, Pos2, Progress, Proposal, Rect, Response, Role, RuleKind, SelectMode, Selection, Shade, Sizing, SpanLayout, Stateful, StyleCx,
Text, TextLook, TextRun, Tone, TypeRole, Variant, Vec2,
};
use craft_ui::primitives::RectSide;
@@ -14,8 +15,9 @@ use craft_ui::primitives::RectSide;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CardEvent {
/// Install the family.
Install,
/// Install the family, for all apps (`true`), for Craft apps only (`false`), or as its recorded choice, else the
/// setting, says (`None`).
Install(Option<bool>),
/// Download the family for a preview.
Preview,
/// Remove the family from the font store.
@@ -43,6 +45,8 @@ pub enum CardState {
Offer {
/// Whether Preview is offered.
preview: bool,
/// Whether Install's menu offers installing for all apps or for Craft apps only.
destinations: bool,
},
}
@@ -62,8 +66,8 @@ pub struct CardData {
pub curated: bool,
/// What is at the reading end.
pub state: CardState,
/// The face the sample is drawn in, and whose catalog holds it.
pub face: Option<(Owner, FaceInfo, Arc<Catalog>)>,
/// The face the sample is drawn in.
pub(crate) face: Option<HeldFace>,
}
/// The pieces of a card at the reading end, in reading order.
@@ -75,6 +79,7 @@ enum End {
Installed,
Preview,
Install,
InstallMenu,
Remove,
RunningText,
RunningBar,
@@ -83,7 +88,7 @@ enum End {
impl End {
fn event(self) -> Option<CardEvent> {
match self {
End::Install => Some(CardEvent::Install),
End::Install | End::InstallMenu => Some(CardEvent::Install(None)),
End::Preview => Some(CardEvent::Preview),
End::Remove => Some(CardEvent::Remove),
End::Retry => Some(CardEvent::Retry),
@@ -92,6 +97,24 @@ impl End {
}
}
/// What the control of a piece reports.
trait EndOutput {
/// What the pressed control of `end` asks for.
fn event(&self, end: End) -> Option<CardEvent>;
}
impl EndOutput for Response {
fn event(&self, end: End) -> Option<CardEvent> {
clicked(self).then(|| end.event()).flatten()
}
}
impl EndOutput for SplitOutput<bool> {
fn event(&self, end: End) -> Option<CardEvent> {
self.chosen.map(|share| CardEvent::Install(Some(share))).or_else(|| self.activated.then(|| end.event()).flatten())
}
}
/// Builds the control for one piece of a card's end and runs `$body` on it as `$c`. A control is built where it is
/// measured and again where it is shown, so both come from this one list.
macro_rules! with_end {
@@ -123,6 +146,13 @@ macro_rules! with_end {
let $c = Button::new($words.install.clone()).description($words.install_family.fill(&[("family", $card.data.name.as_str())]));
$body
}
End::InstallMenu => {
let entries = [Entry::new(true, $words.install_all_apps.clone()), Entry::new(false, $words.install_craft_apps.clone())];
let $c = SplitButton::new($words.install.clone(), &entries)
.arrow_label($words.install_options.clone())
.description($words.install_family.fill(&[("family", $card.data.name.as_str())]));
$body
}
End::Remove => {
let $c = Button::new($words.remove.clone())
.variant(Variant::DANGER)
@@ -236,6 +266,7 @@ impl FamilyCard {
Kind::Install => words.installing.as_str(),
Kind::Remove => words.removing.as_str(),
Kind::Preview => words.downloading.as_str(),
Kind::SystemFonts => words.updating_system_fonts.as_str(),
};
match fraction {
Some(fraction) => words.progress.fill(&[("what", what), ("percent", &((fraction * 100.0).round() as u64).to_string())]),
@@ -251,6 +282,7 @@ impl FamilyCard {
Kind::Install => &words.failed_install,
Kind::Remove => &words.failed_remove,
Kind::Preview => &words.failed_download,
Kind::SystemFonts => &words.failed_system_fonts,
};
(what.clone(), error.clone())
}
@@ -276,26 +308,18 @@ impl FamilyCard {
CardState::Installed => ends.push(End::Installed),
CardState::Removable => ends.push(End::Remove),
CardState::System => {}
CardState::Offer { preview } => {
CardState::Offer { preview, destinations } => {
if *preview {
ends.push(End::Preview);
}
ends.push(End::Install);
ends.push(if *destinations { End::InstallMenu } else { End::Install });
}
}
ends
}
/// The face the sample is drawn in: the card's own, or none.
fn face(&self) -> SampleFace<'_> {
match &self.data.face {
Some((owner, face, catalog)) => SampleFace::Face { catalog, owner: *owner, face },
None => SampleFace::Missing,
}
}
fn sample<'a>(&'a self, words: &FontsBrowseWords) -> FontSample<'a> {
FontSample::new(words.card_sample.clone(), self.data.sample.as_str(), self.face(), self.data.points)
FontSample::new(words.card_sample.clone(), self.data.sample.as_str(), HeldFace::sample(self.data.face.as_ref()), self.data.points)
}
/// The sizes of the parts at `width`.
@@ -394,9 +418,9 @@ impl Component for FamilyCard {
draw.edge_rule(RuleKind::Divider, cx.rect, RectSide::Bottom);
}
for (piece, rect) in &placed.end {
let pressed = with_end!(self, words, *piece, |child| clicked(&ui.child(("end", *piece as u8), *rect, child)));
if pressed {
self.event = piece.event();
let event = with_end!(self, words, *piece, |child| ui.child(("end", *piece as u8), *rect, child).event(*piece));
if event.is_some() {
self.event = event;
}
}
let sample = self.sample(&words);
@@ -416,7 +440,7 @@ pub struct FamilyCardsStyle {
metrics: Metrics,
}
/// The family cards of one list: one Tab stop, Up and Down move the lead, Enter or a double click activates a card.
/// The family cards of one list: one Tab stop, Up and Down move the lead, Enter or a click activates a card.
#[derive(craft_ui::contract::Component)]
#[component(collection)]
pub struct FamilyCards {
@@ -433,7 +457,7 @@ impl FamilyCards {
FamilyCards {
common: Common::new(),
props: ContainerProps::new().sizing(Sizing::Fill),
items: CollectionProps::new().select(SelectMode::Single),
items: CollectionProps::new().select(SelectMode::Single).activate(ActivateOn::Click),
}
.label(label)
}
@@ -23,7 +23,12 @@ fn data(name: &str, state: CardState) -> CardData {
#[story(FamilyCard, covers = [Default], drive = Drive::Never)]
fn family_card_not_installed(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
show_as_only_item(ui, FamilyCard::new(data("Hack", CardState::Offer { preview: true }))).into()
show_as_only_item(ui, FamilyCard::new(data("Hack", CardState::Offer { preview: true, destinations: true }))).into()
}
#[story(FamilyCard, covers = [], drive = Drive::Never)]
fn family_card_craft_apps_only(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
show_as_only_item(ui, FamilyCard::new(data("Hack", CardState::Offer { preview: true, destinations: false }))).into()
}
#[story(FamilyCard, covers = [], drive = Drive::Never)]
@@ -43,7 +48,7 @@ fn family_card_installed(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
#[story(FamilyCard, covers = [], drive = Drive::Never)]
fn family_card_not_curated(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let mut card = data("Hack", CardState::Offer { preview: false });
let mut card = data("Hack", CardState::Offer { preview: false, destinations: true });
card.curated = false;
show_as_only_item(ui, FamilyCard::new(card)).into()
}
@@ -51,7 +56,7 @@ fn family_card_not_curated(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
fn cards(ui: &mut Ui, keys: &[usize]) -> StoryOutput {
FamilyCards::new("Families")
.show_items(ui, &CardKeys::new(keys, |_| None), &mut |key, _| {
let state = if key % 2 == 0 { CardState::Installed } else { CardState::Offer { preview: true } };
let state = if key % 2 == 0 { CardState::Installed } else { CardState::Offer { preview: true, destinations: true } };
FamilyCard::new(data(&format!("Family {key}"), state))
})
.into()
@@ -0,0 +1,123 @@
# Arabic (ar) rows of the Fonts panel's words, for an app's shared catalog.
# Format: context<TAB>source<TAB>translation; @id rows name a word by its id, @plural rows list the locale's plural forms.
# Style and weight names (Regular, Bold, Italic), licence names and product names stay in English.
@id fontsPanel.sansSerif بلا زوائد
@id fontsPanel.serif بزوائد
@id fontsPanel.display عرض
@id fontsPanel.handwriting خط اليد
@id fontsPanel.monospace أحادي المسافة
@id fontsPanel.fontStore متجر الخطوط
@id fontsPanel.system النظام
@id fontsPanel.settingFailed تعذّر حفظ إعداد التنزيل: {error}
@id fontsPanel.consentNote يبقى التنزيل مسموحًا حتى توقفه.
@id fontsPanel.consentAllow تنزيل
@id fontsBrowse.tabBrowse تصفّح
@id fontsBrowse.tabInstalled مثبّت
@id fontsBrowse.search بحث
@id fontsBrowse.searchCatalogue ابحث في الخطوط بالاسم
@id fontsBrowse.searchInstalled ابحث في الخطوط المثبّتة
@id fontsBrowse.downloads التنزيلات
@id fontsBrowse.allowDownloads السماح بالتنزيل
@id fontsBrowse.category الفئة
@id fontsBrowse.allCategories كل الفئات
@id fontsBrowse.language اللغة
@id fontsBrowse.anyLanguage أي لغة
@id fontsBrowse.languagePlaceholder الاسم بالإنجليزية أو باللغة نفسها
@id fontsBrowse.findLanguage ابحث عن لغة
@id fontsBrowse.script نظام الكتابة
@id fontsBrowse.anyScript أي نظام كتابة
@id fontsBrowse.source المصدر
@id fontsBrowse.allSources كل المصادر
@id fontsBrowse.show إظهار
@id fontsBrowse.allFonts كل الخطوط
@id fontsBrowse.installed مثبّت
@id fontsBrowse.notInstalled غير مثبّت
@id fontsBrowse.clearFilters مسح عوامل التصفية
@id fontsBrowse.installedNote تستخدم كل تطبيقات Craft الخطوط الموجودة في متجر الخطوط. تُضاف خطوط النظام وتُزال بأدوات الخطوط في نظامك.
@id fontsBrowse.sample العينة
@id fontsBrowse.sentence جملة
@id fontsBrowse.alphabet الأبجدية
@id fontsBrowse.numerals الأرقام والرموز
@id fontsBrowse.sampleText نص العينة
@id fontsBrowse.size الحجم
@id fontsBrowse.downloadsOff التنزيل متوقف
@id fontsBrowse.downloadsOffText تظهر عينة الخط غير المثبّت بعد معاينته. لا يُنزَّل شيء حتى تسمح بذلك.
@id fontsBrowse.noMatch لا توجد خطوط مطابقة
@id fontsBrowse.noMatchHint جرّب اسمًا آخر أو عوامل تصفية أقل.
@id fontsBrowse.clearSearch مسح البحث وعوامل التصفية
@id fontsBrowse.indexesUnreadable تتعذّر قراءة فهارس الخطوط: {error}
@id fontsBrowse.sourceError {source}: {error}
@id fontsBrowse.tryAgain إعادة المحاولة
@id fontsBrowse.looking جارٍ البحث عن الخطوط المثبّتة…
@id fontsBrowse.noInstalled لا توجد خطوط مثبّتة مطابقة
@id fontsBrowse.installedEmpty تظهر هنا الخطوط التي تثبّتها من «تصفّح»، لكل تطبيقات Craft.
@id fontsBrowse.tryName جرّب اسمًا آخر.
@id fontsBrowse.installing جارٍ التثبيت
@id fontsBrowse.removing جارٍ الإزالة
@id fontsBrowse.downloading جارٍ التنزيل
@id fontsBrowse.retry إعادة المحاولة
@id fontsBrowse.failedInstall تعذّر التثبيت
@id fontsBrowse.failedRemove تعذّرت الإزالة
@id fontsBrowse.failedDownload تعذّر التنزيل
@id fontsBrowse.install تثبيت
@id fontsBrowse.installFamily تثبيت {family}
@id fontsBrowse.preview معاينة
@id fontsBrowse.previewFamily معاينة {family}
@id fontsBrowse.remove إزالة
@id fontsBrowse.removeFamily إزالة {family}
@id fontsBrowse.notCurated غير مراجَع
@id fontsBrowse.notCuratedTip تأتي هذه العائلة من مصدر أضفته. لا يراجعها Craft.
@id fontsBrowse.cardSample العينة
@id fontDetails.designedBy تصميم {designer}
@id fontDetails.installing جارٍ التثبيت
@id fontDetails.removing جارٍ الإزالة
@id fontDetails.downloading جارٍ التنزيل
@id fontDetails.installed مثبّت
@id fontDetails.installedOnSystem مثبّت على هذا النظام
@id fontDetails.installAll تثبيت الكل
@id fontDetails.removeAll إزالة الكل
@id fontDetails.preview معاينة
@id fontDetails.install تثبيت
@id fontDetails.remove إزالة
@id fontDetails.installStyle تثبيت {style}
@id fontDetails.removeStyle إزالة {style}
@id fontDetails.downloadSizeLine تنزيل {size}
@id fontDetails.previewNote تنزّل المعاينة هذا الخط ({size}) لهذه الجلسة فقط دون تثبيته.
@id fontDetails.notCurated غير مراجَع
@id fontDetails.notCuratedNote تأتي هذه العائلة من مصدر أضفته ({url}). لا يراجع Craft خطوطه ولا تراخيصها.
@id fontDetails.couldntInstall تعذّر التثبيت
@id fontDetails.couldntRemove تعذّرت الإزالة
@id fontDetails.couldntDownload تعذّر التنزيل
@id fontDetails.retry إعادة المحاولة
@id fontDetails.systemFontsNote تُزال خطوط النظام بأدوات الخطوط في نظامك.
@id fontDetails.systemFontsRemoval يُزال بأدوات الخطوط في نظامك
@id fontDetails.source المصدر
@id fontDetails.designer المصمم
@id fontDetails.licence الترخيص
@id fontDetails.stylesFact الأنماط
@id fontDetails.filesFact الملفات
@id fontDetails.downloadSize حجم التنزيل
@id fontDetails.scripts أنظمة الكتابة
@id fontDetails.languages اللغات · {n}
@id fontDetails.languagesMore {list} و{n} غيرها
@id fontSources.remove إزالة
@id fontSources.removeSource إزالة {source}
@id fontSources.notCurated غير مراجَع
@id fontSources.changed تغيّر منذ إضافته
@id fontSources.changedNote الفهرس على هذا العنوان ليس الذي نُزِّل منه أول مرة. تحقّق من المصدر قبل التثبيت منه.
@id fontSources.addASource إضافة مصدر
@id fontSources.add إضافة
@id fontSources.indexAddress عنوان الفهرس
@id fontSources.addWarning المصدر الذي تضيفه لا يُراجَع: أضف فقط الفهارس التي تثق بها. يُتحقَّق من كل خط مقابل فهرسه قبل استخدامه.
@id fontSources.downloading جارٍ تنزيل المصادر…
@id fontSources.update تحديث المصادر
@id fontSources.allowToUpdate اسمح بالتنزيل للتحديث
@id fontSources.added أُضيف. يُنزَّل عند السماح بالتنزيل.
@id fontSources.couldntAdd تعذّرت إضافة المصدر: {error}
@id fontSources.couldntRemove تعذّرت إزالة المصدر: {error}
@id common.cancel إلغاء
@id common.close إغلاق
@plural {n} style|{n} styles {n} نمط|{n} نمط|{n} نمط|{n} أنماط|{n} نمطًا|{n} نمط
@plural {n} family|{n} families {n} عائلة|{n} عائلة|{n} عائلة|{n} عائلات|{n} عائلة|{n} عائلة
@plural {n} font source couldn't be loaded|{n} font sources couldn't be loaded تعذّر تحميل {n} مصدر خطوط|تعذّر تحميل {n} مصدر خطوط|تعذّر تحميل {n} مصدر خطوط|تعذّر تحميل {n} مصادر خطوط|تعذّر تحميل {n} مصدرًا للخطوط|تعذّر تحميل {n} مصدر خطوط
@plural {n} style installed|{n} styles installed {n} نمط مثبّت|{n} نمط مثبّت|{n} نمط مثبّت|{n} أنماط مثبّتة|{n} نمطًا مثبّتًا|{n} نمط مثبّت
1 # Arabic (ar) rows of the Fonts panel's words, for an app's shared catalog.
2 # Format: context<TAB>source<TAB>translation; @id rows name a word by its id, @plural rows list the locale's plural forms.
3 # Style and weight names (Regular, Bold, Italic), licence names and product names stay in English.
4 @id fontsPanel.sansSerif بلا زوائد
5 @id fontsPanel.serif بزوائد
6 @id fontsPanel.display عرض
7 @id fontsPanel.handwriting خط اليد
8 @id fontsPanel.monospace أحادي المسافة
9 @id fontsPanel.fontStore متجر الخطوط
10 @id fontsPanel.system النظام
11 @id fontsPanel.settingFailed تعذّر حفظ إعداد التنزيل: {error}
12 @id fontsPanel.consentNote يبقى التنزيل مسموحًا حتى توقفه.
13 @id fontsPanel.consentAllow تنزيل
14 @id fontsBrowse.tabBrowse تصفّح
15 @id fontsBrowse.tabInstalled مثبّت
16 @id fontsBrowse.search بحث
17 @id fontsBrowse.searchCatalogue ابحث في الخطوط بالاسم
18 @id fontsBrowse.searchInstalled ابحث في الخطوط المثبّتة
19 @id fontsBrowse.downloads التنزيلات
20 @id fontsBrowse.allowDownloads السماح بالتنزيل
21 @id fontsBrowse.category الفئة
22 @id fontsBrowse.allCategories كل الفئات
23 @id fontsBrowse.language اللغة
24 @id fontsBrowse.anyLanguage أي لغة
25 @id fontsBrowse.languagePlaceholder الاسم بالإنجليزية أو باللغة نفسها
26 @id fontsBrowse.findLanguage ابحث عن لغة
27 @id fontsBrowse.script نظام الكتابة
28 @id fontsBrowse.anyScript أي نظام كتابة
29 @id fontsBrowse.source المصدر
30 @id fontsBrowse.allSources كل المصادر
31 @id fontsBrowse.show إظهار
32 @id fontsBrowse.allFonts كل الخطوط
33 @id fontsBrowse.installed مثبّت
34 @id fontsBrowse.notInstalled غير مثبّت
35 @id fontsBrowse.clearFilters مسح عوامل التصفية
36 @id fontsBrowse.installedNote تستخدم كل تطبيقات Craft الخطوط الموجودة في متجر الخطوط. تُضاف خطوط النظام وتُزال بأدوات الخطوط في نظامك.
37 @id fontsBrowse.sample العينة
38 @id fontsBrowse.sentence جملة
39 @id fontsBrowse.alphabet الأبجدية
40 @id fontsBrowse.numerals الأرقام والرموز
41 @id fontsBrowse.sampleText نص العينة
42 @id fontsBrowse.size الحجم
43 @id fontsBrowse.downloadsOff التنزيل متوقف
44 @id fontsBrowse.downloadsOffText تظهر عينة الخط غير المثبّت بعد معاينته. لا يُنزَّل شيء حتى تسمح بذلك.
45 @id fontsBrowse.noMatch لا توجد خطوط مطابقة
46 @id fontsBrowse.noMatchHint جرّب اسمًا آخر أو عوامل تصفية أقل.
47 @id fontsBrowse.clearSearch مسح البحث وعوامل التصفية
48 @id fontsBrowse.indexesUnreadable تتعذّر قراءة فهارس الخطوط: {error}
49 @id fontsBrowse.sourceError {source}: {error}
50 @id fontsBrowse.tryAgain إعادة المحاولة
51 @id fontsBrowse.looking جارٍ البحث عن الخطوط المثبّتة…
52 @id fontsBrowse.noInstalled لا توجد خطوط مثبّتة مطابقة
53 @id fontsBrowse.installedEmpty تظهر هنا الخطوط التي تثبّتها من «تصفّح»، لكل تطبيقات Craft.
54 @id fontsBrowse.tryName جرّب اسمًا آخر.
55 @id fontsBrowse.installing جارٍ التثبيت
56 @id fontsBrowse.removing جارٍ الإزالة
57 @id fontsBrowse.downloading جارٍ التنزيل
58 @id fontsBrowse.retry إعادة المحاولة
59 @id fontsBrowse.failedInstall تعذّر التثبيت
60 @id fontsBrowse.failedRemove تعذّرت الإزالة
61 @id fontsBrowse.failedDownload تعذّر التنزيل
62 @id fontsBrowse.install تثبيت
63 @id fontsBrowse.installFamily تثبيت {family}
64 @id fontsBrowse.preview معاينة
65 @id fontsBrowse.previewFamily معاينة {family}
66 @id fontsBrowse.remove إزالة
67 @id fontsBrowse.removeFamily إزالة {family}
68 @id fontsBrowse.notCurated غير مراجَع
69 @id fontsBrowse.notCuratedTip تأتي هذه العائلة من مصدر أضفته. لا يراجعها Craft.
70 @id fontsBrowse.cardSample العينة
71 @id fontDetails.designedBy تصميم {designer}
72 @id fontDetails.installing جارٍ التثبيت
73 @id fontDetails.removing جارٍ الإزالة
74 @id fontDetails.downloading جارٍ التنزيل
75 @id fontDetails.installed مثبّت
76 @id fontDetails.installedOnSystem مثبّت على هذا النظام
77 @id fontDetails.installAll تثبيت الكل
78 @id fontDetails.removeAll إزالة الكل
79 @id fontDetails.preview معاينة
80 @id fontDetails.install تثبيت
81 @id fontDetails.remove إزالة
82 @id fontDetails.installStyle تثبيت {style}
83 @id fontDetails.removeStyle إزالة {style}
84 @id fontDetails.downloadSizeLine تنزيل {size}
85 @id fontDetails.previewNote تنزّل المعاينة هذا الخط ({size}) لهذه الجلسة فقط دون تثبيته.
86 @id fontDetails.notCurated غير مراجَع
87 @id fontDetails.notCuratedNote تأتي هذه العائلة من مصدر أضفته ({url}). لا يراجع Craft خطوطه ولا تراخيصها.
88 @id fontDetails.couldntInstall تعذّر التثبيت
89 @id fontDetails.couldntRemove تعذّرت الإزالة
90 @id fontDetails.couldntDownload تعذّر التنزيل
91 @id fontDetails.retry إعادة المحاولة
92 @id fontDetails.systemFontsNote تُزال خطوط النظام بأدوات الخطوط في نظامك.
93 @id fontDetails.systemFontsRemoval يُزال بأدوات الخطوط في نظامك
94 @id fontDetails.source المصدر
95 @id fontDetails.designer المصمم
96 @id fontDetails.licence الترخيص
97 @id fontDetails.stylesFact الأنماط
98 @id fontDetails.filesFact الملفات
99 @id fontDetails.downloadSize حجم التنزيل
100 @id fontDetails.scripts أنظمة الكتابة
101 @id fontDetails.languages اللغات · {n}
102 @id fontDetails.languagesMore {list} و{n} غيرها
103 @id fontSources.remove إزالة
104 @id fontSources.removeSource إزالة {source}
105 @id fontSources.notCurated غير مراجَع
106 @id fontSources.changed تغيّر منذ إضافته
107 @id fontSources.changedNote الفهرس على هذا العنوان ليس الذي نُزِّل منه أول مرة. تحقّق من المصدر قبل التثبيت منه.
108 @id fontSources.addASource إضافة مصدر
109 @id fontSources.add إضافة
110 @id fontSources.indexAddress عنوان الفهرس
111 @id fontSources.addWarning المصدر الذي تضيفه لا يُراجَع: أضف فقط الفهارس التي تثق بها. يُتحقَّق من كل خط مقابل فهرسه قبل استخدامه.
112 @id fontSources.downloading جارٍ تنزيل المصادر…
113 @id fontSources.update تحديث المصادر
114 @id fontSources.allowToUpdate اسمح بالتنزيل للتحديث
115 @id fontSources.added أُضيف. يُنزَّل عند السماح بالتنزيل.
116 @id fontSources.couldntAdd تعذّرت إضافة المصدر: {error}
117 @id fontSources.couldntRemove تعذّرت إزالة المصدر: {error}
118 @id common.cancel إلغاء
119 @id common.close إغلاق
120 @plural {n} style|{n} styles {n} نمط|{n} نمط|{n} نمط|{n} أنماط|{n} نمطًا|{n} نمط
121 @plural {n} family|{n} families {n} عائلة|{n} عائلة|{n} عائلة|{n} عائلات|{n} عائلة|{n} عائلة
122 @plural {n} font source couldn't be loaded|{n} font sources couldn't be loaded تعذّر تحميل {n} مصدر خطوط|تعذّر تحميل {n} مصدر خطوط|تعذّر تحميل {n} مصدر خطوط|تعذّر تحميل {n} مصادر خطوط|تعذّر تحميل {n} مصدرًا للخطوط|تعذّر تحميل {n} مصدر خطوط
123 @plural {n} style installed|{n} styles installed {n} نمط مثبّت|{n} نمط مثبّت|{n} نمط مثبّت|{n} أنماط مثبّتة|{n} نمطًا مثبّتًا|{n} نمط مثبّت
@@ -0,0 +1,123 @@
# Japanese (ja) rows of the Fonts panel's words, for an app's shared catalog.
# Format: context<TAB>source<TAB>translation; @id rows name a word by its id, @plural rows list the locale's plural forms.
# Style and weight names (Regular, Bold, Italic), licence names and product names stay in English.
@id fontsPanel.sansSerif サンセリフ
@id fontsPanel.serif セリフ
@id fontsPanel.display ディスプレイ
@id fontsPanel.handwriting 手書き
@id fontsPanel.monospace 等幅
@id fontsPanel.fontStore フォントストア
@id fontsPanel.system システム
@id fontsPanel.settingFailed ダウンロードの設定を保存できませんでした: {error}
@id fontsPanel.consentNote ダウンロードは、オフにするまで許可されたままです。
@id fontsPanel.consentAllow ダウンロード
@id fontsBrowse.tabBrowse 探す
@id fontsBrowse.tabInstalled インストール済み
@id fontsBrowse.search 検索
@id fontsBrowse.searchCatalogue フォントを名前で検索
@id fontsBrowse.searchInstalled インストール済みのフォントを検索
@id fontsBrowse.downloads ダウンロード
@id fontsBrowse.allowDownloads ダウンロードを許可
@id fontsBrowse.category カテゴリ
@id fontsBrowse.allCategories すべてのカテゴリ
@id fontsBrowse.language 言語
@id fontsBrowse.anyLanguage すべての言語
@id fontsBrowse.languagePlaceholder 英語名またはその言語での名前
@id fontsBrowse.findLanguage 言語を検索
@id fontsBrowse.script 文字体系
@id fontsBrowse.anyScript すべての文字体系
@id fontsBrowse.source 入手元
@id fontsBrowse.allSources すべての入手元
@id fontsBrowse.show 表示
@id fontsBrowse.allFonts すべてのフォント
@id fontsBrowse.installed インストール済み
@id fontsBrowse.notInstalled 未インストール
@id fontsBrowse.clearFilters 絞り込みを解除
@id fontsBrowse.installedNote フォントストアのフォントはすべての Craft アプリで使えます。システムフォントの追加と削除は、システムのフォント管理ツールで行います。
@id fontsBrowse.sample サンプル
@id fontsBrowse.sentence 文
@id fontsBrowse.alphabet アルファベット
@id fontsBrowse.numerals 数字と記号
@id fontsBrowse.sampleText サンプルテキスト
@id fontsBrowse.size サイズ
@id fontsBrowse.downloadsOff ダウンロードはオフです
@id fontsBrowse.downloadsOffText インストールしていないフォントは、プレビューするとサンプルが表示されます。許可するまで何もダウンロードされません。
@id fontsBrowse.noMatch 一致するフォントはありません
@id fontsBrowse.noMatchHint 別の名前を試すか、絞り込みを減らしてください。
@id fontsBrowse.clearSearch 検索と絞り込みを解除
@id fontsBrowse.indexesUnreadable フォントの一覧を読み込めません: {error}
@id fontsBrowse.sourceError {source}: {error}
@id fontsBrowse.tryAgain もう一度試す
@id fontsBrowse.looking インストール済みのフォントを探しています…
@id fontsBrowse.noInstalled 一致するインストール済みフォントはありません
@id fontsBrowse.installedEmpty 「探す」からインストールしたフォントがここに表示され、すべての Craft アプリで使えます。
@id fontsBrowse.tryName 別の名前を試してください。
@id fontsBrowse.installing インストール中
@id fontsBrowse.removing 削除中
@id fontsBrowse.downloading ダウンロード中
@id fontsBrowse.retry 再試行
@id fontsBrowse.failedInstall インストールできませんでした
@id fontsBrowse.failedRemove 削除できませんでした
@id fontsBrowse.failedDownload ダウンロードできませんでした
@id fontsBrowse.install インストール
@id fontsBrowse.installFamily {family} をインストール
@id fontsBrowse.preview プレビュー
@id fontsBrowse.previewFamily {family} をプレビュー
@id fontsBrowse.remove 削除
@id fontsBrowse.removeFamily {family} を削除
@id fontsBrowse.notCurated 未審査
@id fontsBrowse.notCuratedTip このファミリーは追加したソースのものです。Craft は審査していません。
@id fontsBrowse.cardSample サンプル
@id fontDetails.designedBy デザイン: {designer}
@id fontDetails.installing インストール中
@id fontDetails.removing 削除中
@id fontDetails.downloading ダウンロード中
@id fontDetails.installed インストール済み
@id fontDetails.installedOnSystem このシステムにインストール済み
@id fontDetails.installAll すべてインストール
@id fontDetails.removeAll すべて削除
@id fontDetails.preview プレビュー
@id fontDetails.install インストール
@id fontDetails.remove 削除
@id fontDetails.installStyle {style} をインストール
@id fontDetails.removeStyle {style} を削除
@id fontDetails.downloadSizeLine ダウンロード {size}
@id fontDetails.previewNote プレビューでは、このフォント ({size}) をこのセッションの間だけダウンロードし、インストールはしません。
@id fontDetails.notCurated 未審査
@id fontDetails.notCuratedNote このファミリーは追加したソース ({url}) のものです。Craft はフォントもライセンスも審査していません。
@id fontDetails.couldntInstall インストールできませんでした
@id fontDetails.couldntRemove 削除できませんでした
@id fontDetails.couldntDownload ダウンロードできませんでした
@id fontDetails.retry 再試行
@id fontDetails.systemFontsNote システムフォントは、システムのフォント管理ツールで削除します。
@id fontDetails.systemFontsRemoval システムのフォントツールで削除します
@id fontDetails.source 入手元
@id fontDetails.designer デザイナー
@id fontDetails.licence ライセンス
@id fontDetails.stylesFact スタイル
@id fontDetails.filesFact ファイル
@id fontDetails.downloadSize ダウンロードサイズ
@id fontDetails.scripts 文字体系
@id fontDetails.languages 言語 · {n}
@id fontDetails.languagesMore {list} ほか {n} 言語
@id fontSources.remove 削除
@id fontSources.removeSource {source} を削除
@id fontSources.notCurated 未審査
@id fontSources.changed 追加後に変更あり
@id fontSources.changedNote このアドレスの一覧は、最初にダウンロードしたものと異なります。インストールする前にソースを確認してください。
@id fontSources.addASource ソースを追加
@id fontSources.add 追加
@id fontSources.indexAddress 一覧のアドレス
@id fontSources.addWarning 追加したソースは審査されません。信頼できる一覧だけを追加してください。どのフォントも、使う前に一覧と照合されます。
@id fontSources.downloading ソースをダウンロードしています…
@id fontSources.update ソースを更新
@id fontSources.allowToUpdate 更新するにはダウンロードを許可してください
@id fontSources.added 追加しました。ダウンロードを許可するとダウンロードされます。
@id fontSources.couldntAdd ソースを追加できませんでした: {error}
@id fontSources.couldntRemove ソースを削除できませんでした: {error}
@id common.cancel キャンセル
@id common.close 閉じる
@plural {n} style|{n} styles {n} スタイル
@plural {n} family|{n} families {n} ファミリー
@plural {n} font source couldn't be loaded|{n} font sources couldn't be loaded {n} 件のフォントソースを読み込めませんでした
@plural {n} style installed|{n} styles installed インストール済み {n} スタイル
1 # Japanese (ja) rows of the Fonts panel's words, for an app's shared catalog.
2 # Format: context<TAB>source<TAB>translation; @id rows name a word by its id, @plural rows list the locale's plural forms.
3 # Style and weight names (Regular, Bold, Italic), licence names and product names stay in English.
4 @id fontsPanel.sansSerif サンセリフ
5 @id fontsPanel.serif セリフ
6 @id fontsPanel.display ディスプレイ
7 @id fontsPanel.handwriting 手書き
8 @id fontsPanel.monospace 等幅
9 @id fontsPanel.fontStore フォントストア
10 @id fontsPanel.system システム
11 @id fontsPanel.settingFailed ダウンロードの設定を保存できませんでした: {error}
12 @id fontsPanel.consentNote ダウンロードは、オフにするまで許可されたままです。
13 @id fontsPanel.consentAllow ダウンロード
14 @id fontsBrowse.tabBrowse 探す
15 @id fontsBrowse.tabInstalled インストール済み
16 @id fontsBrowse.search 検索
17 @id fontsBrowse.searchCatalogue フォントを名前で検索
18 @id fontsBrowse.searchInstalled インストール済みのフォントを検索
19 @id fontsBrowse.downloads ダウンロード
20 @id fontsBrowse.allowDownloads ダウンロードを許可
21 @id fontsBrowse.category カテゴリ
22 @id fontsBrowse.allCategories すべてのカテゴリ
23 @id fontsBrowse.language 言語
24 @id fontsBrowse.anyLanguage すべての言語
25 @id fontsBrowse.languagePlaceholder 英語名またはその言語での名前
26 @id fontsBrowse.findLanguage 言語を検索
27 @id fontsBrowse.script 文字体系
28 @id fontsBrowse.anyScript すべての文字体系
29 @id fontsBrowse.source 入手元
30 @id fontsBrowse.allSources すべての入手元
31 @id fontsBrowse.show 表示
32 @id fontsBrowse.allFonts すべてのフォント
33 @id fontsBrowse.installed インストール済み
34 @id fontsBrowse.notInstalled 未インストール
35 @id fontsBrowse.clearFilters 絞り込みを解除
36 @id fontsBrowse.installedNote フォントストアのフォントはすべての Craft アプリで使えます。システムフォントの追加と削除は、システムのフォント管理ツールで行います。
37 @id fontsBrowse.sample サンプル
38 @id fontsBrowse.sentence 文
39 @id fontsBrowse.alphabet アルファベット
40 @id fontsBrowse.numerals 数字と記号
41 @id fontsBrowse.sampleText サンプルテキスト
42 @id fontsBrowse.size サイズ
43 @id fontsBrowse.downloadsOff ダウンロードはオフです
44 @id fontsBrowse.downloadsOffText インストールしていないフォントは、プレビューするとサンプルが表示されます。許可するまで何もダウンロードされません。
45 @id fontsBrowse.noMatch 一致するフォントはありません
46 @id fontsBrowse.noMatchHint 別の名前を試すか、絞り込みを減らしてください。
47 @id fontsBrowse.clearSearch 検索と絞り込みを解除
48 @id fontsBrowse.indexesUnreadable フォントの一覧を読み込めません: {error}
49 @id fontsBrowse.sourceError {source}: {error}
50 @id fontsBrowse.tryAgain もう一度試す
51 @id fontsBrowse.looking インストール済みのフォントを探しています…
52 @id fontsBrowse.noInstalled 一致するインストール済みフォントはありません
53 @id fontsBrowse.installedEmpty 「探す」からインストールしたフォントがここに表示され、すべての Craft アプリで使えます。
54 @id fontsBrowse.tryName 別の名前を試してください。
55 @id fontsBrowse.installing インストール中
56 @id fontsBrowse.removing 削除中
57 @id fontsBrowse.downloading ダウンロード中
58 @id fontsBrowse.retry 再試行
59 @id fontsBrowse.failedInstall インストールできませんでした
60 @id fontsBrowse.failedRemove 削除できませんでした
61 @id fontsBrowse.failedDownload ダウンロードできませんでした
62 @id fontsBrowse.install インストール
63 @id fontsBrowse.installFamily {family} をインストール
64 @id fontsBrowse.preview プレビュー
65 @id fontsBrowse.previewFamily {family} をプレビュー
66 @id fontsBrowse.remove 削除
67 @id fontsBrowse.removeFamily {family} を削除
68 @id fontsBrowse.notCurated 未審査
69 @id fontsBrowse.notCuratedTip このファミリーは追加したソースのものです。Craft は審査していません。
70 @id fontsBrowse.cardSample サンプル
71 @id fontDetails.designedBy デザイン: {designer}
72 @id fontDetails.installing インストール中
73 @id fontDetails.removing 削除中
74 @id fontDetails.downloading ダウンロード中
75 @id fontDetails.installed インストール済み
76 @id fontDetails.installedOnSystem このシステムにインストール済み
77 @id fontDetails.installAll すべてインストール
78 @id fontDetails.removeAll すべて削除
79 @id fontDetails.preview プレビュー
80 @id fontDetails.install インストール
81 @id fontDetails.remove 削除
82 @id fontDetails.installStyle {style} をインストール
83 @id fontDetails.removeStyle {style} を削除
84 @id fontDetails.downloadSizeLine ダウンロード {size}
85 @id fontDetails.previewNote プレビューでは、このフォント ({size}) をこのセッションの間だけダウンロードし、インストールはしません。
86 @id fontDetails.notCurated 未審査
87 @id fontDetails.notCuratedNote このファミリーは追加したソース ({url}) のものです。Craft はフォントもライセンスも審査していません。
88 @id fontDetails.couldntInstall インストールできませんでした
89 @id fontDetails.couldntRemove 削除できませんでした
90 @id fontDetails.couldntDownload ダウンロードできませんでした
91 @id fontDetails.retry 再試行
92 @id fontDetails.systemFontsNote システムフォントは、システムのフォント管理ツールで削除します。
93 @id fontDetails.systemFontsRemoval システムのフォントツールで削除します
94 @id fontDetails.source 入手元
95 @id fontDetails.designer デザイナー
96 @id fontDetails.licence ライセンス
97 @id fontDetails.stylesFact スタイル
98 @id fontDetails.filesFact ファイル
99 @id fontDetails.downloadSize ダウンロードサイズ
100 @id fontDetails.scripts 文字体系
101 @id fontDetails.languages 言語 · {n}
102 @id fontDetails.languagesMore {list} ほか {n} 言語
103 @id fontSources.remove 削除
104 @id fontSources.removeSource {source} を削除
105 @id fontSources.notCurated 未審査
106 @id fontSources.changed 追加後に変更あり
107 @id fontSources.changedNote このアドレスの一覧は、最初にダウンロードしたものと異なります。インストールする前にソースを確認してください。
108 @id fontSources.addASource ソースを追加
109 @id fontSources.add 追加
110 @id fontSources.indexAddress 一覧のアドレス
111 @id fontSources.addWarning 追加したソースは審査されません。信頼できる一覧だけを追加してください。どのフォントも、使う前に一覧と照合されます。
112 @id fontSources.downloading ソースをダウンロードしています…
113 @id fontSources.update ソースを更新
114 @id fontSources.allowToUpdate 更新するにはダウンロードを許可してください
115 @id fontSources.added 追加しました。ダウンロードを許可するとダウンロードされます。
116 @id fontSources.couldntAdd ソースを追加できませんでした: {error}
117 @id fontSources.couldntRemove ソースを削除できませんでした: {error}
118 @id common.cancel キャンセル
119 @id common.close 閉じる
120 @plural {n} style|{n} styles {n} スタイル
121 @plural {n} family|{n} families {n} ファミリー
122 @plural {n} font source couldn't be loaded|{n} font sources couldn't be loaded {n} 件のフォントソースを読み込めませんでした
123 @plural {n} style installed|{n} styles installed インストール済み {n} スタイル
+440 -117
View File
@@ -1,33 +1,50 @@
//! The details sheet: a family's every style in its own face, its facts and languages, and
//! installing or removing it whole or a style at a time.
//!
//! With a preview service, the styles not installed draw with its subsets: a static file's own, and one subset of each
//! variable file with every axis kept, drawn at each named instance and at the values of the file's axis sliders. The
//! axis values go with the text drawn, not with the face registered, so the sliders never register the face again.
pub(crate) mod rows;
#[cfg(feature = "suite")]
pub(crate) mod stories;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use craft_behavior::ColumnWidth;
use craft_host::Host;
use craft_theme::variant::{Emphasis, Tone};
use craft_ui::buttons::Button;
use craft_ui::buttons::{Button, Link, SplitButton};
use craft_ui::contract::overlay::Outside;
use craft_ui::contract::{Bind, CollectionEvent, NoValue, Outcome, Props as _, Show as _, ShowCollection as _, ShowContainer as _, clicked};
use craft_ui::contract::{
Bind, CollectionEvent, Entry, NoValue, Outcome, Props as _, Show as _, ShowCollection as _, ShowContainer as _, Sizing, clicked,
};
use craft_ui::dialog::Dialog;
use craft_ui::display::{Badge, Progress, Shade, Text};
use craft_ui::layout_components::{Grid, Row, Stack};
use craft_ui::notices::{Notice, NoticeAction};
use craft_ui::primitives::Wrap;
use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::focus::Initial;
use craft_ui::style::Variant;
use craft_ui::text::TextField;
use egui::{Response, Ui};
use self::rows::{Action, Lines, StyleLine, StyleList, StyleRow};
use crate::axes::{AxisSliders, AxisValues, FontAxis, OpticalSize, read_axes, shown_axes};
use crate::index::{Family, FontFile, Index, script_name, source_label};
use crate::panel::app::{Detail, FontsPanel, FontsPanelWords, Pending, category_label, family_key, regular, source_name, style_count, style_name};
use crate::panel::app::{
Detail, FontsPanel, FontsPanelWords, NotCopied, Pending, category_label, family_key, regular, source_name, style_count, style_name,
};
use crate::panel::faces::Owner;
use crate::panel::jobs::Kind;
use crate::panel::specimen::{FontSample, SampleFace};
use crate::{Catalog, FaceInfo, Source};
use crate::panel::legal::{Legal, legal_key};
use crate::panel::specimen::{FontSample, HeldFace};
use crate::panel::subsets::SubsetFont;
use crate::store::LegalText;
use crate::{FaceInfo, Source};
/// The sample is at least this many points: the sheet shows styles, not thumbnails.
const MIN_SAMPLE_POINTS: f32 = 24.0;
@@ -36,12 +53,17 @@ const HERO_POINTS: f32 = 96.0;
/// The most languages the sheet lists; the rest are counted.
const LANGUAGES_SHOWN: usize = 60;
/// The most lines of a licence or NOTICE text in view; the rest scrolls.
const LEGAL_LINES: usize = 10;
/// The lines its box has for a shorter text: the least of a multi-line field.
const LEGAL_LEAST_LINES: usize = 2;
/// The sheet's sliders show the face's optical sizes, which its samples are drawn at.
const OPTICAL_SIZE: OpticalSize = OpticalSize::Slider;
/// The facts' labels over their values.
const FACT_COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::fill(1.0)];
/// The installed catalog and the preview catalog, which the faces of the two owners load from.
type Catalogs = (Arc<Catalog>, Arc<Catalog>);
craft_ui::words! {
/// The details sheet's words, English by default.
#[non_exhaustive]
@@ -51,13 +73,39 @@ craft_ui::words! {
installing: "fontDetails.installing" = "Installing";
removing: "fontDetails.removing" = "Removing";
downloading: "fontDetails.downloading" = "Downloading";
updating_system_fonts: "fontDetails.updatingSystemFonts" = "Updating system fonts";
installed: "fontDetails.installed" = "Installed";
installed_on_system: "fontDetails.installedOnSystem" = "Installed on this system";
install_all: "fontDetails.installAll" = "Install all";
install_all_options: "fontDetails.installAllOptions" = "More install all options";
install_all_apps: "fontDetails.installAllApps" = "Install for all apps";
install_craft_apps: "fontDetails.installCraftApps" = "Install for Craft apps only";
/// `{reason}`.
only_craft_apps: template "fontDetails.onlyCraftApps" = "Only in Craft apps: {reason}";
available_to_all: "fontDetails.availableToAll" = "Available to all apps";
kept_in_craft_apps: "fontDetails.keptInCraftApps" = "Kept in Craft apps only";
make_available: "fontDetails.makeAvailable" = "Make available to all apps";
keep_in_craft_apps: "fontDetails.keepInCraftApps" = "Keep in Craft apps only";
/// `{error}`.
copy_failed: template "fontDetails.copyFailed" = "Couldn't copy to your system's fonts folder: {error}";
/// `{file}` and `{name}`.
copy_name_taken: template "fontDetails.copyNameTaken" = "Not copied to your system's fonts folder: {file} already has the font name {name}";
/// `{file}`.
copy_in_the_way: template "fontDetails.copyInTheWay" = "Not copied to your system's fonts folder: {file} is in the way";
remove_all: "fontDetails.removeAll" = "Remove all";
preview: "fontDetails.preview" = "Preview";
install: "fontDetails.install" = "Install";
remove: "fontDetails.remove" = "Remove";
copyright: "fontDetails.copyright" = "Copyright";
/// `{url}`.
upstream: template "fontDetails.upstream" = "Upstream: {url}";
show_licence: "fontDetails.showLicence" = "Show licence text";
show_notice: "fontDetails.showNotice" = "Show notice";
licence_text: "fontDetails.licenceText" = "Licence text";
notice_text: "fontDetails.noticeText" = "Notice";
loading_text: "fontDetails.loadingText" = "Loading…";
/// The style of a variable file that names no instances.
default_style: "fontDetails.defaultStyle" = "Default";
/// `{style}`.
install_style: template "fontDetails.installStyle" = "Install {style}";
/// `{style}`.
@@ -72,6 +120,7 @@ craft_ui::words! {
couldnt_install: "fontDetails.couldntInstall" = "Couldn't install";
couldnt_remove: "fontDetails.couldntRemove" = "Couldn't remove";
couldnt_download: "fontDetails.couldntDownload" = "Couldn't download";
couldnt_update_system_fonts: "fontDetails.couldntUpdateSystemFonts" = "Couldn't update system fonts";
retry: "fontDetails.retry" = "Retry";
system_fonts_note: "fontDetails.systemFontsNote" = "System fonts are removed with your system's own font tools.";
system_fonts_removal: "fontDetails.systemFontsRemoval" = "Removed with your system's font tools";
@@ -151,6 +200,35 @@ fn file_of<'a>(family: &'a Family, face: &FaceInfo) -> Option<&'a FontFile> {
enum Do {
Ask(Pending),
Remove { faces: Vec<FaceInfo>, whole: bool },
AvailableToAll { files: Vec<PathBuf>, on: bool },
ReadLegal(LegalText),
}
/// A licence or NOTICE text as the sheet shows it.
enum LegalShown {
/// Not read yet.
Offer,
Loading,
Text(String),
Failed(String),
}
/// The licence and NOTICE texts `family` has, as far as they are read.
fn legal_texts(panel: &FontsPanel, family: &Family) -> Vec<(LegalText, LegalShown)> {
let files = [(LegalText::Notice, family.notice_file.is_some()), (LegalText::License, family.license_file_name().is_some())];
files
.into_iter()
.filter(|(_, has)| *has)
.filter_map(|(which, _)| {
let shown = match panel.legal.get(&legal_key(family, which)) {
None => LegalShown::Offer,
Some(Legal::Loading(_)) => LegalShown::Loading,
Some(Legal::Ready(text)) => LegalShown::Text(text.clone()?),
Some(Legal::Failed(error)) => LegalShown::Failed(error.clone()),
};
Some((which, shown))
})
.collect()
}
/// The job running for the whole family, as the header shows it.
@@ -176,26 +254,106 @@ struct Failed {
retry: Option<Pending>,
}
/// Whether the family's store fonts are in the OS user font folder for all apps, or why not.
struct SystemFonts {
text: Label,
tone: Option<Tone>,
/// The store files.
files: Vec<PathBuf>,
/// What the line's action sets; none while it can't change.
switch: Option<bool>,
}
impl SystemFonts {
/// The line of the family named `family`; none when `faces` has no store font.
fn read(panel: &FontsPanel, words: &DetailsWords, family: &str, faces: &[FaceInfo]) -> Option<SystemFonts> {
let files: Vec<PathBuf> = faces.iter().filter(|f| f.source == Source::Store).filter_map(|f| f.path.clone()).collect();
if files.is_empty() {
return None;
}
let not_here = panel.installer.available_to_all_unsupported();
let available = not_here.is_none() && panel.installer.is_available_to_all(family, &files);
let (text, tone) = if let Some(reason) = not_here {
(Label::from(words.only_craft_apps.fill(&[("reason", &reason)])), None)
} else if available {
(words.available_to_all.clone(), Some(Tone::Good))
} else if let Some(not_copied) = panel.not_copied.get(&family.to_lowercase()) {
(Label::from(not_copied_text(words, not_copied)), Some(Tone::Warn))
} else {
(words.kept_in_craft_apps.clone(), None)
};
let switch = (panel.installer.available_to_all_supported() && panel.jobs.of("", family).is_none()).then_some(!available);
Some(SystemFonts { text, tone, files, switch })
}
fn show(&self, ui: &mut Ui, words: &DetailsWords, todo: &mut Vec<Do>) {
Row::new().wrap(true).show(ui, |ui, _| {
let text = Text::new(self.text.clone());
match self.tone {
Some(tone) => text.tone(tone),
None => text.shade(Shade::Muted),
}
.show(ui);
if let Some(on) = self.switch {
let action = if on { &words.make_available } else { &words.keep_in_craft_apps };
if clicked(&Link::new(action.clone()).show(ui)) {
todo.push(Do::AvailableToAll { files: self.files.clone(), on });
}
}
});
}
}
/// What the sheet says about a family an install couldn't copy into the OS user font folder.
fn not_copied_text(words: &DetailsWords, not_copied: &NotCopied) -> String {
let conflict = match not_copied {
NotCopied::Failed(error) => return words.copy_failed.fill(&[("error", error)]),
NotCopied::Refused(conflicts) => conflicts.first(),
};
let file = conflict.map(|c| c.path.display().to_string()).unwrap_or_default();
match conflict.and_then(|c| c.postscript.as_deref()) {
Some(name) => words.copy_name_taken.fill(&[("file", &file), ("name", name)]),
None => words.copy_in_the_way.fill(&[("file", &file)]),
}
}
/// A variable file drawn by the preview service, and its axes.
struct FileAxes {
sha256: String,
label: String,
axes: Vec<FontAxis>,
}
/// Everything the sheet shows, read from the panel before the pass draws it.
struct Sheet {
eyebrow: String,
title: String,
byline: Option<String>,
hero: Option<(Owner, FaceInfo)>,
hero: Option<HeldFace>,
run: Option<Run>,
badge: Option<Label>,
install_all: Option<Pending>,
/// The family's position in the index when it can be installed whole.
install_all: Option<usize>,
/// Whether Install all's menu offers installing for all apps or for Craft apps only.
destinations: bool,
removal: Removal,
store: Vec<FaceInfo>,
preview: Option<Pending>,
size_line: Option<String>,
system_fonts: Option<SystemFonts>,
preview_note: Option<String>,
uncurated: Option<String>,
failure: Option<Failed>,
lines: Vec<StyleLine>,
/// The family's files, by position, whose styles the preview service draws.
subset_files: Vec<usize>,
/// The variable files among them, with the sliders of their axes.
axes: Vec<FileAxes>,
facts: Vec<(Label, String)>,
languages: Vec<String>,
scripts: Vec<String>,
/// The web page of the family's own project.
upstream: Option<String>,
legal: Vec<(LegalText, LegalShown)>,
/// The family's position in the index; none for an installed family, whose styles cannot be installed.
index: Option<usize>,
sample: String,
@@ -238,26 +396,33 @@ impl<'a> DetailsSheet<'a> {
let env = Env::of(ui);
let words = env.words::<DetailsWords>();
let host: Option<Arc<Host>> = env.view().host().cloned();
panel.read_notice(host.as_ref());
let Some(sheet) = Sheet::read(panel, &env, &words) else {
panel.detail = None;
return DetailsOutput { response: ui.response(), closed: true };
};
let catalogs: Catalogs = (Arc::clone(&panel.catalog), Arc::clone(&panel.previews));
let points = panel.settings.size.max(MIN_SAMPLE_POINTS);
let mut todo: Vec<Do> = Vec::new();
let mut open = true;
let shown = Dialog::prompt(sheet.title.clone())
// The sheet is for reading: no field of it takes the keyboard when it opens.
let mut shown = Dialog::prompt(sheet.title.clone())
.initial_focus(Initial::Keep)
.overlay(|overlay| {
let dismiss = overlay.dismiss.outside(Outside::Absorb);
overlay.dismiss(dismiss)
})
.opened(Bind::bound(&mut open))
.show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
sheet.header(ui, &env, &words, &catalogs, &mut todo);
sheet.body(ui, &env, &words, &catalogs, points, &mut todo);
Stack::new().fill_width().show(ui, |ui, _| {
sheet.header(ui, &env, &words, &mut todo);
sheet.body(ui, &env, &words, points, &mut panel.detail_axes, &mut todo);
});
});
let index = panel.index();
let family = sheet.index.zip(index.as_deref()).and_then(|(i, index)| Some((index, index.families().get(i)?, sheet.sample.as_str())));
if !craft_ui::runtime::frame::will_rerun(ui.ctx()) {
shown.settle(|_, ()| panel.subsets.request_detail(family, &sheet.subset_files));
}
let closed = shown.output.closed.is_some();
if closed {
panel.detail = None;
@@ -266,6 +431,12 @@ impl<'a> DetailsSheet<'a> {
match action {
Do::Ask(pending) => panel.ask(host.as_ref(), pending),
Do::Remove { faces, whole } => panel.remove(host.as_ref(), &sheet.title, &faces, whole),
Do::ReadLegal(which) => {
if let Some(i) = sheet.index {
panel.load_legal(host.as_ref(), i, which);
}
}
Do::AvailableToAll { files, on } => panel.set_available_to_all(host.as_ref(), &sheet.title, files, on),
}
}
DetailsOutput { response: shown.output.response, closed }
@@ -275,13 +446,10 @@ impl<'a> DetailsSheet<'a> {
impl Sheet {
/// The sheet of the panel's open detail; `None` when there is none or its family is gone.
fn read(panel: &FontsPanel, env: &Env, words: &DetailsWords) -> Option<Sheet> {
let mut sheet = match panel.detail.clone()? {
Detail::Family(i) => Sheet::family(panel, env, words, i)?,
Detail::Installed(name, source) => Sheet::installed(panel, env, words, &name, source)?,
};
// The sample is what the user typed, else the preset for the family's scripts.
sheet.sample = panel.sample_for(sheet.scripts.iter().map(String::as_str));
Some(sheet)
match panel.detail.clone()? {
Detail::Family(i) => Sheet::family(panel, env, words, i),
Detail::Installed(name, source) => Sheet::installed(panel, env, words, &name, source),
}
}
fn family(panel: &FontsPanel, env: &Env, words: &DetailsWords, i: usize) -> Option<Sheet> {
@@ -297,8 +465,8 @@ impl Sheet {
let names = env.words::<FontsPanelWords>();
let eyebrow = [source.to_owned(), category_label(&names, &family)].join(" · ");
let byline = (!family.designer.is_empty()).then(|| words.designed_by.fill(&[("designer", &family.designer)]));
let hero = regular(&installed).cloned().map(|f| (Owner::Installed, f));
let hero = hero.or_else(|| previewed.as_deref().and_then(regular).cloned().map(|f| (Owner::Preview, f)));
let hero = regular(&installed).cloned().map(|f| HeldFace::local(Owner::Installed, f, &panel.catalog));
let hero = hero.or_else(|| previewed.as_deref().and_then(regular).cloned().map(|f| HeldFace::local(Owner::Preview, f, &panel.previews)));
let size = env.units().file_size(family.size());
let all_installed =
!installed.is_empty() && (on_system || family.files.iter().all(|f| store.iter().any(|x| file_name(x).as_deref() == Some(f.file_name()))));
@@ -307,10 +475,25 @@ impl Sheet {
_ => None,
};
let installed_word = if on_system { &words.installed_on_system } else { &words.installed };
let unseen = installed.is_empty() && previewed.is_none();
let sample = panel.family_sample(&index, &family);
let unseen = installed.is_empty() && previewed.is_none() && !panel.subsets.draws_detail(&index, &family, &sample);
let uncurated = (!curated).then(|| index.source_of(&family).and_then(|f| f.user_url.clone()).unwrap_or_default());
let failure = panel.failed.get(&key).map(|f| Failed { what: f.kind, error: f.error.clone(), retry: f.retry.clone() });
let lines = family_lines(&names, &family, &installed, &store, on_system, previewed.as_deref(), &job);
let styles = FamilyStyles {
panel,
names: &names,
words,
index: &index,
family: &family,
sample: &sample,
installed: &installed,
store: &store,
on_system,
previewed: previewed.as_deref(),
job: &job,
};
let (lines, subset_files) = styles.lines();
let axes = styles.axes(&subset_files);
let mut facts = family_facts(env, words, &index, &family, &size);
let not_curated = env.view().resolve(&words.not_curated);
let source_fact = if curated { source.to_owned() } else { format!("{source} · {}", not_curated.as_str()) };
@@ -325,27 +508,32 @@ impl Sheet {
hero,
run,
badge: all_installed.then(|| installed_word.clone()),
install_all: (!all_installed).then_some(Pending::Install(i)),
install_all: (!all_installed).then_some(i),
destinations: panel.installer.available_to_all_supported(),
removal: if store.is_empty() { Removal::None } else { Removal::Allowed },
store,
preview: unseen.then_some(Pending::Preview(i)),
size_line: Some(words.download_size_line.fill(&[("size", &size)])),
system_fonts: SystemFonts::read(panel, words, &family.family, &installed),
preview_note: unseen.then(|| words.preview_note.fill(&[("size", &size)])),
uncurated,
failure,
lines,
subset_files,
axes,
facts,
languages: languages.into_iter().map(|l| l.name.clone()).collect(),
scripts: family.scripts.clone(),
upstream: family.upstream.clone().filter(|url| url.starts_with("https://") || url.starts_with("http://")),
legal: legal_texts(panel, &family),
index: Some(i),
sample: String::new(),
sample,
})
}
fn installed(panel: &FontsPanel, env: &Env, words: &DetailsWords, name: &str, source: Source) -> Option<Sheet> {
let family = panel.installed.iter().find(|f| f.name == name && f.source == source).cloned()?;
let names = env.words::<FontsPanelWords>();
let hero = regular(&family.faces).cloned().map(|f| (Owner::Installed, f));
let hero = regular(&family.faces).cloned().map(|f| HeldFace::local(Owner::Installed, f, &panel.catalog));
let job = panel.jobs.of("", &family.name).map(|j| (j.kind, j.file.clone(), j.fraction()));
let run = match &job {
Some((Kind::Remove, None, _)) => Some(Run { kind: Kind::Remove, fraction: None }),
@@ -354,10 +542,9 @@ impl Sheet {
let lines = family
.faces
.iter()
.map(|face| StyleLine {
label: style_name(&names, face).to_owned(),
face: Some((Owner::Installed, face.clone())),
action: if face.source == Source::Store { Action::Remove(Box::new(face.clone())) } else { Action::None },
.map(|face| {
let action = if face.source == Source::Store { Action::Remove(Box::new(face.clone())) } else { Action::None };
StyleLine::new(style_name(&names, face), Some(HeldFace::local(Owner::Installed, face.clone(), &panel.catalog)), action)
})
.collect();
let mut files: Vec<_> = family.faces.iter().filter_map(|f| f.path.clone()).collect();
@@ -369,7 +556,6 @@ impl Sheet {
(words.styles_fact.clone(), format.integer(family.faces.len() as u64)),
(words.files_fact.clone(), format.integer(files.len() as u64)),
];
let scripts = panel.index().and_then(|index| index.family(&family.name).map(|f| f.scripts.clone())).unwrap_or_default();
Some(Sheet {
eyebrow: source_name(&names, source).as_str().to_owned(),
title: family.name.clone(),
@@ -378,32 +564,32 @@ impl Sheet {
run,
badge: None,
install_all: None,
destinations: false,
removal: if family.removable() { Removal::Allowed } else { Removal::System },
store: family.faces.clone(),
preview: None,
size_line: None,
system_fonts: SystemFonts::read(panel, words, &family.name, &family.faces),
preview_note: None,
uncurated: None,
failure: None,
lines,
subset_files: Vec::new(),
axes: Vec::new(),
facts,
languages: Vec::new(),
scripts,
upstream: None,
legal: Vec::new(),
index: None,
sample: String::new(),
sample: panel.installed_sample(&family.name),
})
}
/// The eyebrow, the "Aa" in the family's face, the byline, and the family's install and remove controls.
fn header(&self, ui: &mut Ui, env: &Env, words: &DetailsWords, catalogs: &Catalogs, todo: &mut Vec<Do>) {
fn header(&self, ui: &mut Ui, env: &Env, words: &DetailsWords, todo: &mut Vec<Do>) {
Text::new(self.eyebrow.clone()).shade(Shade::Faint).show(ui);
if let Some((owner, face)) = &self.hero {
let catalog = match owner {
Owner::Installed => &catalogs.0,
Owner::Preview => &catalogs.1,
};
let face = SampleFace::Face { catalog, owner: *owner, face };
FontSample::new(format!("{}: Aa", self.title), "Aa", face, HERO_POINTS).show(ui);
if let Some(face) = &self.hero {
FontSample::new(format!("{}: Aa", self.title), "Aa", HeldFace::sample(Some(face)), HERO_POINTS).show(ui);
}
if let Some(byline) = &self.byline {
Text::new(byline.clone()).shade(Shade::Muted).show(ui);
@@ -414,6 +600,7 @@ impl Sheet {
Kind::Install => &words.installing,
Kind::Remove => &words.removing,
Kind::Preview => &words.downloading,
Kind::SystemFonts => &words.updating_system_fonts,
};
progress(ui, env, words, what, run.fraction);
return;
@@ -421,10 +608,10 @@ impl Sheet {
if let Some(badge) = &self.badge {
Badge::new(badge.clone()).variant(Variant::look(Emphasis::Soft, Tone::Good)).show(ui);
}
if let Some(pending) = &self.install_all
&& clicked(&Button::new(words.install_all.clone()).variant(Variant::PRIMARY).show(ui))
if let Some(i) = self.install_all
&& let Some(share) = self.install_button(ui, words)
{
todo.push(Do::Ask(pending.clone()));
todo.push(Do::Ask(Pending::Install(i, share)));
}
match self.removal {
Removal::Allowed => {
@@ -447,6 +634,9 @@ impl Sheet {
Text::new(line.clone()).shade(Shade::Faint).show(ui);
}
});
if let Some(system_fonts) = &self.system_fonts {
system_fonts.show(ui, words, todo);
}
if let Some(note) = &self.preview_note {
Text::new(note.clone()).shade(Shade::Muted).show(ui);
}
@@ -458,6 +648,7 @@ impl Sheet {
Kind::Install => &words.couldnt_install,
Kind::Remove => &words.couldnt_remove,
Kind::Preview => &words.couldnt_download,
Kind::SystemFonts => &words.couldnt_update_system_fonts,
};
let mut notice = Notice::new(Tone::Bad, failure.error.clone()).title(what.clone());
if failure.retry.is_some() {
@@ -472,35 +663,40 @@ impl Sheet {
}
}
/// The styles, and beside them (or below, when narrow) the facts and the languages.
fn body(&self, ui: &mut Ui, env: &Env, words: &DetailsWords, catalogs: &Catalogs, points: f32, todo: &mut Vec<Do>) {
Row::new().wrap(true).show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| self.styles(ui, env, words, catalogs, points, todo));
Stack::new().show(ui, |ui, _| self.side(ui, env, words));
});
/// Install all, with a menu that chooses where the fonts go when they can be copied into the OS user font folder.
/// `None` when not pressed; `Some(None)` for the button itself (the family's choice, else the setting), else the
/// choice.
fn install_button(&self, ui: &mut Ui, words: &DetailsWords) -> Option<Option<bool>> {
if !self.destinations {
return clicked(&Button::new(words.install_all.clone()).variant(Variant::PRIMARY).show(ui)).then_some(None);
}
let entries = [Entry::new(true, words.install_all_apps.clone()), Entry::new(false, words.install_craft_apps.clone())];
let out =
SplitButton::new(words.install_all.clone(), &entries).arrow_label(words.install_all_options.clone()).variant(Variant::PRIMARY).show(ui);
out.chosen.map(Some).or_else(|| out.activated.then_some(None))
}
fn styles(&self, ui: &mut Ui, env: &Env, words: &DetailsWords, catalogs: &Catalogs, points: f32, todo: &mut Vec<Do>) {
let total = self.lines.len() as u64;
let installed = self.lines.iter().filter(|l| matches!(l.face, Some((Owner::Installed, _)))).count();
let count = env.format().integer(total);
let heading = if installed == self.lines.len() { words.styles_installed.text(total, &count) } else { words.styles.text(total, &count) };
Text::new(heading).shade(Shade::Faint).show(ui);
/// The styles, the axis sliders of each variable file under its name, the facts, the languages and the licence.
fn body(&self, ui: &mut Ui, env: &Env, words: &DetailsWords, points: f32, axes: &mut HashMap<String, AxisValues>, todo: &mut Vec<Do>) {
self.styles(ui, env, words, points, todo);
for file in &self.axes {
Text::new(file.label.clone()).shade(Shade::Faint).show(ui);
let values = axes.entry(file.sha256.clone()).or_default();
AxisSliders::new(file.label.clone(), &file.axes, Bind::bound(values)).optical_size(OPTICAL_SIZE).show(ui);
}
self.side(ui, env, words);
self.licence(ui, words, todo);
}
fn styles(&self, ui: &mut Ui, env: &Env, words: &DetailsWords, points: f32, todo: &mut Vec<Do>) {
let total = self.lines.iter().filter(|line| !line.sliders).count();
let installed = self.lines.iter().filter(|line| line.face.as_ref().is_some_and(HeldFace::installed)).count();
let count = env.format().integer(total as u64);
let counted = if installed == total { &words.styles_installed } else { &words.styles };
Text::new(counted.text(total as u64, &count)).shade(Shade::Faint).show(ui);
let source = Lines(&self.lines);
let out = StyleList::new(self.title.clone(), words.no_styles.clone()).show_items(ui, &source, &mut |key, _| {
let line = &self.lines[*key];
let face = match &line.face {
Some((owner, face)) => {
let catalog = match owner {
Owner::Installed => &catalogs.0,
Owner::Preview => &catalogs.1,
};
SampleFace::Face { catalog, owner: *owner, face }
}
None => SampleFace::Missing,
};
StyleRow::new(line, &self.title, &self.sample, points, face, words)
});
let out = StyleList::new(self.title.clone(), words.no_styles.clone())
.show_items(ui, &source, &mut |key, _| StyleRow::new(&self.lines[*key], &self.title, &self.sample, points, words));
for event in out.events {
let CollectionEvent::Item(key, _) = event else { continue };
match &self.lines[key].action {
@@ -537,6 +733,48 @@ impl Sheet {
}
}
impl Sheet {
/// The project's page, and the licence and NOTICE texts: each a button that reads it, then the text, or why it
/// couldn't be read.
fn licence(&self, ui: &mut Ui, words: &DetailsWords, todo: &mut Vec<Do>) {
if let Some(url) = &self.upstream {
let shown = url.trim_start_matches("https://").trim_start_matches("http://").trim_end_matches('/');
Link::new(shown.to_owned()).url(url.clone()).wrap(Wrap::Elide).description(words.upstream.fill(&[("url", url)])).show(ui);
}
for (at, (which, shown)) in self.legal.iter().enumerate() {
let (show, title) = match which {
LegalText::License => (&words.show_licence, &words.licence_text),
LegalText::Notice => (&words.show_notice, &words.notice_text),
};
let read = match shown {
LegalShown::Offer => clicked(&Button::new(show.clone()).variant(Variant::SECONDARY).show(ui)),
LegalShown::Loading => {
Text::new(words.loading_text.clone()).shade(Shade::Muted).show(ui);
false
}
LegalShown::Text(text) => {
Text::new(title.clone()).shade(Shade::Faint).show(ui);
TextField::new(title.clone(), Bind::given(text.clone()))
.lines(LEGAL_LEAST_LINES)
.max_lines(LEGAL_LINES)
.sizing(Sizing::FillWidth)
.mono()
.read_only(true)
.show(ui);
false
}
LegalShown::Failed(error) => {
let retry = NoticeAction::new(words.retry.clone());
Notice::new(Tone::Bad, error.clone()).id_salt(("legal", at)).title(title.clone()).action(retry).show(ui).action.is_some()
}
};
if read {
todo.push(Do::ReadLegal(*which));
}
}
}
}
/// A job's progress: the job and the percent done when known, with a bar.
fn progress(ui: &mut Ui, env: &Env, words: &DetailsWords, what: &Label, fraction: Option<f32>) {
let what = env.view().resolve(what);
@@ -551,54 +789,136 @@ fn progress(ui: &mut Ui, env: &Env, words: &DetailsWords, what: &Label, fraction
};
}
/// The rows of the family sheet: the installed faces, then the index files not installed, as the previewed faces when
/// the preview has them.
fn family_lines(
names: &FontsPanelWords,
family: &Family,
installed: &[FaceInfo],
store: &[FaceInfo],
/// The styles of a family of the index, as its sheet lists them.
struct FamilyStyles<'a> {
panel: &'a FontsPanel,
names: &'a FontsPanelWords,
words: &'a DetailsWords,
index: &'a Index,
family: &'a Family,
sample: &'a str,
installed: &'a [FaceInfo],
store: &'a [FaceInfo],
on_system: bool,
previewed: Option<&[FaceInfo]>,
job: &Option<(Kind, Option<String>, Option<f32>)>,
) -> Vec<StyleLine> {
let running = |path: &str| match job {
Some((Kind::Install, Some(p), fraction)) if p == path => Some(*fraction),
_ => None,
};
let mut lines = Vec::new();
for face in installed {
let action = match job {
Some((Kind::Remove, Some(p), _)) if face.path.as_ref().is_some_and(|x| x.display().to_string() == *p) => Action::Running(None),
_ if face.source == Source::Store => Action::Remove(Box::new(face.clone())),
_ => Action::None,
};
lines.push(StyleLine { label: style_name(names, face).to_owned(), face: Some((Owner::Installed, face.clone())), action });
}
if on_system {
return lines;
}
for file in &family.files {
if store.iter().any(|x| file_name(x).as_deref() == Some(file.file_name())) {
continue;
previewed: Option<&'a [FaceInfo]>,
job: &'a Option<(Kind, Option<String>, Option<f32>)>,
}
impl FamilyStyles<'_> {
/// The rows: the installed faces, then the index files not installed, as the previewed faces when the preview has
/// them, else as the preview service draws them; and the files, by position, of the last kind.
fn lines(&self) -> (Vec<StyleLine>, Vec<usize>) {
let mut lines = Vec::new();
let mut subset_files = Vec::new();
for face in self.installed {
let action = match self.job {
Some((Kind::Remove, Some(p), _)) if face.path.as_ref().is_some_and(|x| x.display().to_string() == *p) => Action::Running(None),
_ if face.source == Source::Store => Action::Remove(Box::new(face.clone())),
_ => Action::None,
};
lines.push(self.line(Owner::Installed, face, action));
}
let preview_faces: Vec<&FaceInfo> =
previewed.unwrap_or_default().iter().filter(|f| file_of(family, f).is_some_and(|x| x.path == file.path)).collect();
let action = match running(&file.path) {
Some(fraction) => Action::Running(fraction),
None => Action::Install(file.path.clone()),
};
if preview_faces.is_empty() {
lines.push(StyleLine { label: file_label(file), face: None, action });
} else {
for (n, face) in preview_faces.iter().enumerate() {
if self.on_system {
return (lines, subset_files);
}
for (n, file) in self.family.files.iter().enumerate() {
if self.store.iter().any(|x| file_name(x).as_deref() == Some(file.file_name())) {
continue;
}
let preview_faces: Vec<&FaceInfo> =
self.previewed.unwrap_or_default().iter().filter(|f| file_of(self.family, f).is_some_and(|x| x.path == file.path)).collect();
let action = match self.job {
Some((Kind::Install, Some(p), fraction)) if *p == file.path => Action::Running(*fraction),
_ => Action::Install(file.path.clone()),
};
if !preview_faces.is_empty() {
// A variable file's instances install together: the file's action on its first.
let action = if n == 0 { action.clone() } else { Action::None };
lines.push(StyleLine { label: style_name(names, face).to_owned(), face: Some((Owner::Preview, (*face).clone())), action });
let actions = std::iter::once(action).chain(std::iter::repeat(Action::None));
lines.extend(preview_faces.into_iter().zip(actions).map(|(face, action)| self.line(Owner::Preview, face, action)));
} else if self.panel.subsets.serves(self.family) {
subset_files.push(n);
self.subset_lines(file, action, &mut lines);
} else {
lines.push(StyleLine::new(file_label(file), None, action));
}
}
(lines, subset_files)
}
lines
fn line(&self, owner: Owner, face: &FaceInfo, action: Action) -> StyleLine {
let catalog = match owner {
Owner::Installed => &self.panel.catalog,
Owner::Preview => &self.panel.previews,
};
StyleLine::new(style_name(self.names, face), Some(HeldFace::local(owner, face.clone(), catalog)), action)
}
/// The rows of a file drawn by the preview service: a static file's one, or a variable file's named instances and
/// the row that follows its axis sliders, all at coordinates of one subset that keeps every axis.
fn subset_lines(&self, file: &FontFile, action: Action, lines: &mut Vec<StyleLine>) {
let face = self.subset(file).map(HeldFace::Subset);
if !file.is_variable() {
lines.push(StyleLine::new(file_label(file), face, action));
return;
}
// A variable file installs whole: the file's action on its first row.
if file.instances.is_empty() {
lines.push(StyleLine::new(self.words.default_style.as_str(), face.clone(), action));
} else {
let actions = std::iter::once(action).chain(std::iter::repeat(Action::None));
lines.extend(file.instances.iter().zip(actions).map(|(instance, action)| {
let coords = instance.coordinates.iter().filter_map(|(tag, v)| Some((axis_tag(tag)?, *v))).collect();
StyleLine::new(instance.name.clone(), face.clone(), action).at(coords)
}));
}
let values = self.panel.detail_axes.get(&file.sha256).cloned().unwrap_or_default();
lines.push(StyleLine { sliders: true, ..StyleLine::new(file_label(file), face, Action::None).at(values) });
}
fn subset(&self, file: &FontFile) -> Option<SubsetFont> {
self.panel.subsets.detail_font(self.index, self.family, file, self.sample)
}
/// The axes of the variable files among `files` that have a slider: the subset's own once it is here, else the index's
/// ranges.
fn axes(&self, files: &[usize]) -> Vec<FileAxes> {
files
.iter()
.filter_map(|n| self.family.files.get(*n))
.filter(|file| file.is_variable())
.map(|file| {
let own = self.subset(file).map(|font| read_axes(&font.bytes, 0)).filter(|axes| !axes.is_empty());
FileAxes { sha256: file.sha256.clone(), label: file_label(file), axes: own.unwrap_or_else(|| index_axes(file)) }
})
.filter(|file| shown_axes(&file.axes, OPTICAL_SIZE).next().is_some())
.collect()
}
}
/// `tag` as an OpenType tag: four printable ASCII characters, spaces only at the end.
fn axis_tag(tag: &str) -> Option<[u8; 4]> {
let tag: [u8; 4] = tag.as_bytes().try_into().ok()?;
let printable = tag.iter().all(|b| (0x20..=0x7e).contains(b));
let spaces_last = tag.iter().skip_while(|b| **b != b' ').all(|b| *b == b' ');
(printable && spaces_last && tag[0] != b' ').then_some(tag)
}
/// A variable file's axes as the index gives them: its ranges about the file's default style.
fn index_axes(file: &FontFile) -> Vec<FontAxis> {
file.axes
.iter()
.filter(|axis| axis.min < axis.max)
.filter_map(|axis| {
let tag = axis_tag(&axis.tag)?;
let default = match &tag {
b"wght" => f32::from(file.weight),
b"wdth" => file.width,
b"ital" => f32::from(u8::from(file.is_italic())),
_ => 0.0,
};
Some(FontAxis::new(tag, "", axis.min, default.clamp(axis.min, axis.max), axis.max))
})
.collect()
}
fn family_facts(env: &Env, words: &DetailsWords, index: &Index, family: &Family, size: &str) -> Vec<(Label, String)> {
@@ -609,6 +929,9 @@ fn family_facts(env: &Env, words: &DetailsWords, index: &Index, family: &Family,
facts.push((words.designer.clone(), family.designer.clone()));
}
facts.push((words.licence.clone(), licence_name(&family.license).to_owned()));
if let Some(copyright) = family.copyright.as_deref().map(str::trim).filter(|text| !text.is_empty()) {
facts.push((words.copyright.clone(), copyright.to_owned()));
}
facts.push((words.styles_fact.clone(), format.integer(style_count(family) as u64)));
facts.push((words.files_fact.clone(), format.integer(family.files.len() as u64)));
facts.push((words.download_size.clone(), size.to_owned()));
+28 -12
View File
@@ -18,8 +18,8 @@ use egui::{Pos2, Rect, Response, Vec2};
use super::DetailsWords;
use crate::FaceInfo;
use crate::panel::faces::Owner;
use crate::panel::specimen::{FontSample, SampleFace};
use crate::axes::AxisValues;
use crate::panel::specimen::{FontSample, HeldFace};
/// What a style row offers at its end.
#[derive(Clone, Debug)]
@@ -34,13 +34,30 @@ pub(super) enum Action {
}
/// One style of the sheet.
#[derive(Clone, Debug)]
#[derive(Clone)]
pub(super) struct StyleLine {
pub label: String,
pub face: Option<(Owner, FaceInfo)>,
/// The face the sample is drawn in.
pub face: Option<HeldFace>,
/// The variation coordinates the face is drawn at.
pub coords: AxisValues,
/// The line follows the sheet's axis sliders, so it is no style of its own.
pub sliders: bool,
pub action: Action,
}
impl StyleLine {
/// A style drawn in `face` as it is.
pub(super) fn new(label: impl Into<String>, face: Option<HeldFace>, action: Action) -> Self {
StyleLine { label: label.into(), face, coords: AxisValues::new(), sliders: false, action }
}
/// The style at `coords` of its face.
pub(super) fn at(self, coords: AxisValues) -> Self {
StyleLine { coords, ..self }
}
}
/// The lines as a collection source, keyed by position.
pub(super) struct Lines<'a>(pub &'a [StyleLine]);
@@ -88,11 +105,11 @@ pub(super) struct StyleList {
}
impl StyleList {
/// A list named `label`; it is as tall as its rows, and shows `empty` while it has none.
/// A list named `label`; it fills the width, is as tall as its rows, and shows `empty` while it has none.
pub(super) fn new(label: impl Into<Label>, empty: impl Into<Label>) -> Self {
StyleList {
common: Common::new(),
props: ContainerProps::new().sizing(Sizing::Content),
props: ContainerProps::new().sizing(Sizing::FillWidth),
items: CollectionProps::new().select(SelectMode::Single).natural_height(true).empty(empty),
}
.label(label)
@@ -173,7 +190,6 @@ pub(super) struct StyleRow<'r> {
family: &'r str,
sample: &'r str,
points: f32,
face: SampleFace<'r>,
words: &'r DetailsWords,
pressed: bool,
/// The width of the action, measured in the pass's measure step and read by its paint.
@@ -181,10 +197,9 @@ pub(super) struct StyleRow<'r> {
}
impl<'r> StyleRow<'r> {
/// The row of `line`, a style of `family`, with the sample `sample` at `points` in `face`.
pub(super) fn new(line: &'r StyleLine, family: &'r str, sample: &'r str, points: f32, face: SampleFace<'r>, words: &'r DetailsWords) -> Self {
StyleRow { common: Common::new(), line, family, sample, points, face, words, pressed: false, action: Cell::new(0.0) }
.label(line.label.clone())
/// The row of `line`, a style of `family`, with the sample `sample` at `points`.
pub(super) fn new(line: &'r StyleLine, family: &'r str, sample: &'r str, points: f32, words: &'r DetailsWords) -> Self {
StyleRow { common: Common::new(), line, family, sample, points, words, pressed: false, action: Cell::new(0.0) }.label(line.label.clone())
}
fn style_name(&self) -> [(&'static str, &str); 1] {
@@ -208,7 +223,8 @@ impl<'r> StyleRow<'r> {
}
fn sample_leaf(&self) -> FontSample<'r> {
FontSample::new(format!("{} {}: {}", self.family, self.line.label, self.sample), self.sample, self.face, self.points)
let face = HeldFace::sample(self.line.face.as_ref());
FontSample::new(format!("{} {}: {}", self.family, self.line.label, self.sample), self.sample, face, self.points).coords(&self.line.coords)
}
}
@@ -9,9 +9,10 @@ use super::rows::{Action, Lines, StyleLine, StyleList, StyleRow};
use super::{DetailsSheet, DetailsWords};
use crate::panel::app::Detail;
use crate::panel::faces::Owner;
use crate::panel::fixtures::{SharedPanel, story_catalog, story_panel};
use crate::panel::fixtures::{SharedPanel, VARIABLE, story_catalog, story_panel};
use crate::panel::samples::PANGRAM;
use crate::panel::specimen::SampleFace;
use crate::panel::specimen::HeldFace;
use crate::panel::subsets::SubsetFont;
/// The sample size of the stories, in points.
const POINTS: f32 = 24.0;
@@ -44,28 +45,22 @@ fn lines(count: usize) -> Vec<StyleLine> {
let catalog = story_catalog();
let face = catalog.styles("Hack").into_iter().next();
(0..count)
.map(|n| StyleLine {
label: format!("Style {n}"),
face: face.clone().map(|face| (Owner::Installed, face)),
action: if n % 2 == 0 { Action::Install(format!("ofl/hack/Style{n}.ttf")) } else { Action::None },
.map(|n| {
let action = if n % 2 == 0 { Action::Install(format!("ofl/hack/Style{n}.ttf")) } else { Action::None };
StyleLine::new(format!("Style {n}"), face.clone().map(|face| HeldFace::local(Owner::Installed, face, &catalog)), action)
})
.collect()
}
fn list(ui: &mut Ui, count: usize) -> StoryOutput {
let lines = lines(count);
let catalog = story_catalog();
list_of(ui, &lines(count), PANGRAM)
}
fn list_of(ui: &mut Ui, lines: &[StyleLine], sample: &str) -> StoryOutput {
let words = Env::of(ui).words::<DetailsWords>();
let source = Lines(&lines);
let source = Lines(lines);
StyleList::new("Styles", words.no_styles.clone())
.show_items(ui, &source, &mut |key, _| {
let line = &lines[*key];
let face = match &line.face {
Some((owner, face)) => SampleFace::Face { catalog: &catalog, owner: *owner, face },
None => SampleFace::Missing,
};
StyleRow::new(line, "Hack", PANGRAM, POINTS, face, &words)
})
.show_items(ui, &source, &mut |key, _| StyleRow::new(&lines[*key], "Hack", sample, POINTS, &words))
.into()
}
@@ -84,9 +79,18 @@ fn style_list_many(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
list(ui, 4)
}
/// The styles of one variable subset from the preview service.
#[story(StyleList, covers = [], drive = Drive::Never)]
fn style_list_variable(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let face = HeldFace::Subset(SubsetFont { key: "story/orbitron".to_owned(), bytes: VARIABLE.into() });
let styles = [("Regular", 400.0), ("Bold", 700.0), ("Black", 900.0)];
let lines = styles.map(|(name, weight)| StyleLine::new(name, Some(face.clone()), Action::None).at(vec![(*b"wght", weight)]));
list_of(ui, &lines, "Orbitron")
}
#[story(StyleRow<'static>, covers = [Default], drive = Drive::Never)]
fn style_row_installing(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let line = StyleLine { label: "Bold".to_owned(), face: None, action: Action::Running(Some(0.4)) };
let line = StyleLine::new("Bold", None, Action::Running(Some(0.4)));
let words = Env::of(ui).words::<DetailsWords>();
show_as_only_item(ui, StyleRow::new(&line, "Hack", PANGRAM, POINTS, SampleFace::Missing, &words)).into()
show_as_only_item(ui, StyleRow::new(&line, "Hack", PANGRAM, POINTS, &words)).into()
}
+41 -16
View File
@@ -10,6 +10,7 @@ use craft_ui::primitives::{ContentPainterCx, DocRun, DocText, FacesCx, TextLayou
use craft_ui::style::DataColor;
use egui::{Color32, Pos2, Rect};
use crate::panel::subsets::SubsetFont;
use crate::{Catalog, FaceInfo};
/// Larger files are not drawn: a whole CJK family can be hundreds of megabytes.
@@ -56,6 +57,14 @@ pub(crate) fn shown(at: &impl FacesCx, catalog: &Arc<Catalog>, owner: Owner, fac
})
}
/// The font that draws a subset of the preview service, once the registry has taken it.
pub(crate) fn subset(at: &impl FacesCx, subset: &SubsetFont) -> Shown {
at.document_face(&format!("subset:{}", subset.key), || {
let face = subset.face();
move || Some(face)
})
}
/// The bytes of `face` once [`shown`] has it ready, for reading its tables without loading the file again.
pub(crate) fn bytes(at: &impl FacesCx, owner: Owner, face: &FaceInfo) -> Option<FaceBytes> {
at.document_face_bytes(&key(owner, face))
@@ -82,25 +91,41 @@ pub(crate) struct SampleLine {
pub(crate) baseline: f32,
}
/// `text` in `font` for a band `band` high, laid out by `layout` (a measure's or a painter's) and cut to `room` as
/// A sample's text and the face, size and colour it is drawn in.
#[derive(Clone, Copy)]
pub(crate) struct Sample<'a> {
pub(crate) text: &'a str,
pub(crate) font: &'a FontRef,
/// The variation coordinates (axis tag, value) the face is drawn at; empty for the face as registered.
pub(crate) coords: &'a [([u8; 4], f32)],
pub(crate) points: f32,
pub(crate) color: DataColor,
}
impl<'a> Sample<'a> {
/// `text` in `font` as it is registered, at `points` in `color`.
pub(crate) fn new(text: &'a str, font: &'a FontRef, points: f32, color: DataColor) -> Self {
Sample { text, font, coords: &[], points, color }
}
/// The sample drawn at the coordinates `coords` of its face.
pub(crate) fn at(self, coords: &'a [([u8; 4], f32)]) -> Self {
Sample { coords, ..self }
}
}
/// `sample` for a band `band` high, laid out by `layout` (a measure's or a painter's) and cut to `room` as
/// [`sample_text`] cuts it. Every face sits on one baseline: that of the interface face's line at `points` centred in
/// the band, as a control's line sets its texts. The sample is laid out at `points`, or, where its ink (what the
/// layout draws, as `Galley::mesh_bounds` holds it) would cross the band's top or bottom from that baseline, at the
/// largest size whose ink stays inside the band.
pub(crate) fn sample_line(
layout: impl Fn(&DocText<'_>) -> TextLayout,
font: &FontRef,
text: &str,
points: f32,
band: f32,
room: Option<f32>,
color: DataColor,
) -> SampleLine {
pub(crate) fn sample_line(layout: impl Fn(&DocText<'_>) -> TextLayout, sample: Sample<'_>, band: f32, room: Option<f32>) -> SampleLine {
let Sample { text, font, coords, points, color } = sample;
let probe = [DocRun::new(BASELINE_PROBE, FontRef::proportional(), points, color)];
let line = layout(&DocText::new(&probe));
let baseline = (band - line.size().y) / 2.0 + line.first_baseline;
let at = |size: f32| {
let runs = [DocRun::new(text, font.clone(), size, color)];
let runs = [DocRun::new(text, font.clone(), size, color).coords(coords)];
layout(&sample_text(&runs, room))
};
let mut size = points;
@@ -127,8 +152,6 @@ fn share(room: f32, ink: f32) -> f32 {
if ink > room { room / ink } else { 1.0 }
}
/// `text` on one line in `font` at `points` in the band `rect` ([`sample_line`]), at the reading start of `rect`,
/// clipped to `rect`. The sample keeps its own direction whatever the interface's.
/// The ink of a sample over `rect`: black on a white paper it fills, in every theme, when `on_white`; else `ink`.
pub(crate) fn sample_ink(painter: &ContentPainterCx<'_>, rect: Rect, on_white: bool, ink: Color32) -> DataColor {
if !on_white {
@@ -138,10 +161,12 @@ pub(crate) fn sample_ink(painter: &ContentPainterCx<'_>, rect: Rect, on_white: b
DataColor::new(Color32::from(Srgba::BLACK))
}
pub(crate) fn paint_sample(painter: &ContentPainterCx<'_>, rect: Rect, font: &FontRef, text: &str, points: f32, color: DataColor) {
let line = sample_line(|doc| painter.layout(doc), font, text, points, rect.height(), Some(rect.width()), color);
/// `sample` on one line in the band `rect` ([`sample_line`]), at the reading start of `rect`, clipped to `rect`. The
/// sample keeps its own direction whatever the interface's.
pub(crate) fn paint_sample(painter: &ContentPainterCx<'_>, rect: Rect, sample: Sample<'_>) {
let line = sample_line(|doc| painter.layout(doc), sample, rect.height(), Some(rect.width()));
let size = line.layout.size();
let x = match base_direction(text) {
let x = match base_direction(sample.text) {
Some(Direction::Rtl) => rect.right() - size.x,
_ => rect.left(),
};
@@ -47,6 +47,10 @@ pub(crate) fn story_catalog() -> Arc<Catalog> {
catalog
}
/// A variable font (`wght`), for the samples drawn at variation coordinates.
#[cfg(feature = "suite")]
pub(crate) const VARIABLE: &[u8] = include_bytes!("../../../font-subset/tests/data/orbitron/Orbitron[wght].ttf");
/// The panel over the story catalog and index; its store is a fake that refuses downloads.
pub(crate) fn story_panel() -> FontsPanel {
let store = FakeStore::new(std::env::temp_dir().join("craft-fonts-panel-story"), HashMap::new());
+7 -1
View File
@@ -1,4 +1,10 @@
//! The interface languages the panel offers.
//! The interface languages the panel offers, and its words in them.
use craft_i18n::Embedded;
/// The interface languages offered, in menu order.
pub const LANGUAGES: &[&str] = &["en", "ja", "ar"];
/// The panel's words in Japanese and Arabic: the shared catalogs an app gives the `I18n` of its Host, alone or after its
/// own shared rows. A word without a row shows in English.
pub const CATALOGS: &Embedded = &[("ja", include_str!("catalogs/ja.tsv"), ""), ("ar", include_str!("catalogs/ar.tsv"), "")];
+64 -13
View File
@@ -1,6 +1,8 @@
//! Installs, removals and preview downloads, run through the Host's jobs, one at a time.
//! Installs, removals, preview downloads and copies to the OS user font folder, run through the Host's jobs, one at a
//! time.
use std::collections::{BTreeMap, VecDeque};
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, Mutex, PoisonError};
@@ -8,7 +10,7 @@ use craft_host::{Host, Wake};
use crate::Catalog;
use crate::index::Index;
use crate::store::{Downloaded, Installer, Progress, RemoveRequest, StoreError};
use crate::store::{Conflict, Downloaded, Installer, MadeAvailable, Progress, RemoveRequest, StoreError};
type Task = Box<dyn FnOnce() + Send>;
@@ -37,6 +39,9 @@ pub enum Kind {
Remove,
/// Downloads a family for preview only.
Preview,
/// Copies to or withdraws from the OS user font folder: a family's switch, or the start-up copy, which has no
/// family.
SystemFonts,
}
/// A job that has not ended.
@@ -50,6 +55,8 @@ pub struct Running {
pub kind: Kind,
/// One file's index path or store path, when the job is for one style.
pub file: Option<String>,
/// An install's choice of the OS user font folder (see [`Request::Install`]).
pub share: Option<bool>,
/// The latest report of the installer.
pub progress: Progress,
}
@@ -64,12 +71,17 @@ impl Running {
/// How a job ended well.
#[non_exhaustive]
pub enum Finished {
/// The family or file is installed.
Installed,
/// The family or file is installed, with what copying the family into the OS user font folder did, when it was
/// copied.
Installed(Option<Result<MadeAvailable, StoreError>>),
/// The files are removed.
Removed,
/// The preview faces were downloaded.
Previewed(Vec<Downloaded>),
/// What a family's switch did: copied it, with the outcome, or withdrew it (`None`).
Switched(Option<MadeAvailable>),
/// The families a conflict kept out of the OS user font folder at start.
SharedAtStart(Vec<(String, Vec<Conflict>)>),
}
enum Msg {
@@ -80,14 +92,21 @@ enum Msg {
/// What to start.
#[non_exhaustive]
pub enum Request {
/// A family of the index, by position.
Install(Arc<Index>, usize),
/// A family of the index, by position, and whether to copy it into the OS user font folder (and record that as its
/// choice); `None` keeps its recorded choice, else takes the default.
Install(Arc<Index>, usize, Option<bool>),
/// One file of a family of the index, by its path in the index.
InstallFile(Arc<Index>, usize, String),
/// Installed files to remove.
Remove(RemoveRequest),
/// A family of the index, by position.
Preview(Arc<Index>, usize),
/// Records a store family's choice, by name and store files, then copies it into the OS user font folder (`true`)
/// or withdraws it.
AvailableToAll(String, Vec<PathBuf>, bool),
/// Copies the store families whose choice is the OS user font folder and that aren't all there yet: those
/// installed before installs copied, or whose copy failed.
ShareAtStart,
}
/// The panel's install, removal and preview jobs.
@@ -128,12 +147,14 @@ impl Jobs {
self.running.values().find(|r| r.family.eq_ignore_ascii_case(family) && (source.is_empty() || r.source.is_empty() || r.source == source))
}
/// Runs `request` through `installer`, then rescans `catalog` after an install or removal.
/// Runs `request` through `installer`, then rescans `catalog` after an install or removal. An install also records
/// the family's choice and copies it into the OS user font folder when that is the choice.
pub fn start(&mut self, host: Option<&Arc<Host>>, installer: Arc<dyn Installer>, catalog: Arc<Catalog>, request: Request) {
let id = self.next;
self.next += 1;
let share = if let Request::Install(_, _, share) = &request { *share } else { None };
let (source, family, kind, file, total) = match &request {
Request::Install(index, i) | Request::Preview(index, i) => {
Request::Install(index, i, _) | Request::Preview(index, i) => {
let Some(f) = index.families().get(*i) else { return };
let kind = if matches!(request, Request::Install(..)) { Kind::Install } else { Kind::Preview };
(f.source.clone(), f.family.clone(), kind, None, f.size())
@@ -147,8 +168,10 @@ impl Jobs {
let file = if r.whole { None } else { r.files.first().map(|p| p.display().to_string()) };
(String::new(), r.family.clone(), Kind::Remove, file, 0)
}
Request::AvailableToAll(family, ..) => (String::new(), family.clone(), Kind::SystemFonts, None, 0),
Request::ShareAtStart => (String::new(), String::new(), Kind::SystemFonts, None, 0),
};
self.running.insert(id, Running { source, family, kind, file, progress: Progress { done: 0, total } });
self.running.insert(id, Running { source, family, kind, file, share, progress: Progress { done: 0, total } });
let tx = self.tx.clone();
let wake = self.waker();
let task: Task = Box::new(move || {
@@ -157,17 +180,30 @@ impl Jobs {
wake.wake();
};
let family = |index: &Index, i: usize| index.families().get(i).cloned().ok_or_else(|| StoreError("no such family".into()));
let copy = |name: &str, share: Option<bool>| {
if !installer.available_to_all_supported() {
return Ok(Finished::Installed(None));
}
let share = share.unwrap_or_else(|| installer.shares(name, &[]));
installer.set_available_to_all_choice(name, &[], share)?;
Ok(Finished::Installed(share.then(|| installer.make_available(name, &[]))))
};
let result = match request {
Request::Install(index, i) => {
family(&index, i).and_then(|f| installer.install(&index, &f, &mut progress)).map(|()| Finished::Installed)
Request::Install(index, i, share) => {
family(&index, i).and_then(|f| installer.install(&index, &f, &mut progress).and_then(|()| copy(&f.family, share)))
}
Request::InstallFile(index, i, path) => {
family(&index, i).and_then(|f| installer.install_file(&index, &f, &path, &mut progress)).map(|()| Finished::Installed)
family(&index, i).and_then(|f| installer.install_file(&index, &f, &path, &mut progress).and_then(|()| copy(&f.family, None)))
}
Request::Remove(r) => installer.remove(&r).map(|()| Finished::Removed),
Request::Preview(index, i) => family(&index, i).and_then(|f| installer.download(&index, &f, &mut progress)).map(Finished::Previewed),
Request::AvailableToAll(name, files, on) => installer.set_available_to_all_choice(&name, &files, on).and_then(|()| {
if on { installer.make_available(&name, &files).map(Some) } else { installer.withdraw(&name, &files).map(|_| None) }
.map(Finished::Switched)
}),
Request::ShareAtStart => share_at_start(installer.as_ref()).map(Finished::SharedAtStart),
};
if matches!(result, Ok(Finished::Installed | Finished::Removed)) {
if matches!(result, Ok(Finished::Installed(_) | Finished::Removed)) {
catalog.rescan();
}
let _ = tx.send(Msg::Done(id, result));
@@ -221,3 +257,18 @@ impl Jobs {
done
}
}
/// The work of [`Request::ShareAtStart`]: returns the families a conflict refused.
fn share_at_start(installer: &dyn Installer) -> Result<Vec<(String, Vec<Conflict>)>, StoreError> {
let mut refused = Vec::new();
for (family, files) in installer.store_families() {
let there = installer.is_available_to_all(&family, &files) && installer.not_yet_available(&family, &files).is_empty();
if there || !installer.shares(&family, &files) {
continue;
}
if let MadeAvailable::Refused(conflicts) = installer.make_available(&family, &files)? {
refused.push((family, conflicts));
}
}
Ok(refused)
}
+90
View File
@@ -0,0 +1,90 @@
//! A family's licence and NOTICE texts, read through the store on request.
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, TryRecvError, channel};
use craft_host::Host;
use crate::index::Family;
use crate::panel::app::{Detail, FontsPanel, family_key};
use crate::panel::jobs;
use crate::store::{LegalText, StoreError};
/// A licence or NOTICE text being read, or read.
pub(crate) enum Legal {
Loading(Receiver<Result<Option<String>, StoreError>>),
/// `None` when the family has no such file.
Ready(Option<String>),
Failed(String),
}
/// What a licence or NOTICE text is kept by: the family's key, which text, and the file's sha256 (else its path), so a
/// file an index refresh changed is read again.
pub(crate) type LegalKey = (String, LegalText, String);
pub(crate) type LegalTexts = HashMap<LegalKey, Legal>;
pub(crate) fn legal_key(family: &Family, which: LegalText) -> LegalKey {
let file = match which {
LegalText::License => family.license_file.as_ref(),
LegalText::Notice => family.notice_file.as_ref(),
};
let identity = match (file, which) {
(Some(file), _) => file.sha256.clone(),
(None, LegalText::License) => family.license_path.clone().unwrap_or_default(),
(None, LegalText::Notice) => String::new(),
};
(family_key(&family.source, &family.family), which, identity)
}
impl FontsPanel {
/// Takes in the texts that were read.
pub(crate) fn poll_legal(&mut self) {
for state in self.legal.values_mut() {
if let Legal::Loading(rx) = state {
match rx.try_recv() {
Ok(Ok(text)) => *state = Legal::Ready(text),
Ok(Err(e)) => *state = Legal::Failed(e.0),
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => *state = Legal::Ready(None),
}
}
}
}
/// Reads the NOTICE of the family the details sheet shows once downloads are allowed: an Apache family's NOTICE is
/// shown with its fonts.
pub(crate) fn read_notice(&mut self, host: Option<&Arc<Host>>) {
let Some((index, i)) = self.index().zip(self.detail_family()) else { return };
let unread = index.families().get(i).is_some_and(|f| f.notice_file.is_some() && !self.legal.contains_key(&legal_key(f, LegalText::Notice)));
if unread && self.allowed() {
self.load_legal(host, i, LegalText::Notice);
}
}
fn detail_family(&self) -> Option<usize> {
match &self.detail {
Some(Detail::Family(i)) => Some(*i),
_ => None,
}
}
/// Reads the licence or NOTICE text of the `i`th family through the store, as a job.
pub(crate) fn load_legal(&mut self, host: Option<&Arc<Host>>, i: usize, which: LegalText) {
let Some(index) = self.index() else { return };
let Some(family) = index.families().get(i).cloned() else { return };
let (tx, rx) = channel();
self.legal.insert(legal_key(&family, which), Legal::Loading(rx));
let installer = Arc::clone(&self.installer);
let wake = self.jobs.waker();
jobs::spawn(
host,
"font-licence",
Box::new(move || {
let _ = tx.send(installer.legal_text(&index, &family, which));
wake.wake();
}),
);
}
}
+3
View File
@@ -10,12 +10,15 @@ pub(crate) mod faces;
#[cfg(feature = "screen-testing")]
pub(crate) mod fixtures;
pub(crate) mod jobs;
pub(crate) mod legal;
pub(crate) mod samples;
pub(crate) mod sources;
pub(crate) mod specimen;
pub(crate) mod subsets;
pub use app::{
FontsCommand, FontsPanel, FontsPanelOutput, FontsPanelSettings, FontsPanelView, FontsPanelWords, Options, Preset, Tab, install_interface_fonts,
};
pub use browse::FontsBrowseWords;
pub use i18n::CATALOGS;
pub use sources::{FontSources, FontSourcesOutput};
+12 -2
View File
@@ -1,5 +1,9 @@
//! Sample text: a sentence in the language the catalogue is filtered by, or in a family's own
//! script when it has no Latin, so a sample never comes out as boxes.
//! Sample text: a family's own sentence from the index (its script's, by `sample_script`), the one the preview
//! service's sample subsets hold; a sentence in the language the catalogue is filtered by; and built-in sentences by
//! script for families the index has no sample for, so a sample never comes out as boxes.
use crate::index::{Family, Index};
use crate::panel::app::list_file;
/// The English pangram, the sample for Latin.
pub const PANGRAM: &str = "The quick brown fox jumps over the lazy dog";
@@ -81,6 +85,12 @@ pub fn for_script(script: &str) -> Option<&'static str> {
}
}
/// The sample of the face the list shows for `family`, from the index: the sentence of the face's `sample_script` (else
/// the family's), or the face's own text.
pub(crate) fn of_family<'a>(index: &'a Index, family: &'a Family) -> Option<&'a str> {
list_file(family).and_then(|file| index.sample_text(family, file))
}
/// The sample for a family with `scripts`: the pangram when it has Latin, else a sentence in the
/// first of its scripts there is one for.
pub fn for_scripts<'a>(scripts: impl IntoIterator<Item = &'a str>) -> &'static str {
+51 -8
View File
@@ -12,7 +12,8 @@ use egui::{Color32, Vec2};
use crate::Catalog;
use crate::FaceInfo;
use crate::panel::faces::{self, Owner, Shown};
use crate::panel::faces::{self, Owner, Sample, Shown};
use crate::panel::subsets::SubsetFont;
#[cfg(feature = "suite")]
pub(crate) mod stories;
@@ -35,6 +36,8 @@ pub(crate) struct FontSampleStyle {
pub(crate) enum SampleFace<'a> {
/// A face of `catalog`, which the document-face registry loads when the sample is measured or painted.
Face { catalog: &'a Arc<Catalog>, owner: Owner, face: &'a FaceInfo },
/// A subset of a face from the preview service.
Subset(&'a SubsetFont),
/// A face the host gives, ready as it is (a host row of the picker).
Font(&'a FontRef),
/// No face is here to draw with: the sample keeps its band and shows nothing.
@@ -47,16 +50,51 @@ impl SampleFace<'_> {
/// may lack the sample's characters.
pub(crate) fn ready(&self, at: &impl craft_ui::primitives::FacesCx) -> Option<FontRef> {
match self {
SampleFace::Face { catalog, owner, face } => match faces::shown(at, catalog, *owner, face) {
Shown::Ready(font) => Some(font),
_ => None,
},
SampleFace::Face { catalog, owner, face } => ready(faces::shown(at, catalog, *owner, face)),
SampleFace::Subset(subset) => ready(faces::subset(at, subset)),
SampleFace::Font(font) => Some((*font).clone()),
SampleFace::Missing => None,
}
}
}
fn ready(shown: Shown) -> Option<FontRef> {
match shown {
Shown::Ready(font) => Some(font),
_ => None,
}
}
/// The face a card or a style row draws its sample in, as the panel holds it.
#[derive(Clone)]
pub(crate) enum HeldFace {
/// A face of `catalog`.
Local { owner: Owner, face: Box<FaceInfo>, catalog: Arc<Catalog> },
/// A subset of a face from the preview service.
Subset(SubsetFont),
}
impl HeldFace {
/// `face` of `owner`'s catalog `catalog`.
pub(crate) fn local(owner: Owner, face: FaceInfo, catalog: &Arc<Catalog>) -> HeldFace {
HeldFace::Local { owner, face: Box::new(face), catalog: Arc::clone(catalog) }
}
/// Whether the face is installed here.
pub(crate) fn installed(&self) -> bool {
matches!(self, HeldFace::Local { owner: Owner::Installed, .. })
}
/// The face of a sample: `face`, or none.
pub(crate) fn sample(face: Option<&HeldFace>) -> SampleFace<'_> {
match face {
Some(HeldFace::Local { owner, face, catalog }) => SampleFace::Face { catalog, owner: *owner, face },
Some(HeldFace::Subset(subset)) => SampleFace::Subset(subset),
None => SampleFace::Missing,
}
}
}
/// A sample of `text` in `face`, `points` high. Until the face is ready (while it loads, and for good when it is not
/// available) the sample shows nothing and keeps its band. `points` is the user's sample size (data, as
/// `DocRun::size`), not a UI size. The label names the sample for a screen reader (the family and the sample text).
@@ -81,12 +119,16 @@ pub(crate) struct FontSample<'a> {
/// [`LINE_EM`] of its size.
#[prop(quantity = "band height the caller's layout gives, in points")]
band: Option<f32>,
/// The variation coordinates (axis tag, value) the face is drawn at, over its own: one registered variable face
/// draws every named instance and every axis value.
#[prop]
coords: &'a [([u8; 4], f32)],
}
impl<'a> FontSample<'a> {
/// A sample of `text` in `face` at `points`, named `label`.
pub(crate) fn new(label: impl Into<Label>, text: impl Into<Cow<'a, str>>, face: SampleFace<'a>, points: f32) -> Self {
FontSample { common: Common::new(), text: text.into(), face, points, on_white: false, band: None }.label(label)
FontSample { common: Common::new(), text: text.into(), face, points, on_white: false, band: None, coords: &[] }.label(label)
}
}
@@ -113,7 +155,8 @@ impl Component for FontSample<'_> {
return Vec2::new(cx.room.unwrap_or(0.0), band);
};
let ink = DataColor::new(Color32::PLACEHOLDER);
let line = faces::sample_line(|doc| cx.layout_doc(doc), &font, &self.text, self.points, band, cx.room, ink);
let sample = Sample::new(&self.text, &font, self.points, ink).at(self.coords);
let line = faces::sample_line(|doc| cx.layout_doc(doc), sample, band, cx.room);
Vec2::new(line.layout.size().x, band)
}
@@ -121,7 +164,7 @@ impl Component for FontSample<'_> {
let painter = ui.content_painter(cx);
let ink = faces::sample_ink(&painter, cx.rect, self.on_white, cx.style.ink.egui());
if let Some(font) = self.face.ready(cx) {
faces::paint_sample(&painter, cx.content_rect, &font, &self.text, self.points, ink);
faces::paint_sample(&painter, cx.content_rect, Sample::new(&self.text, &font, self.points, ink).at(self.coords));
}
}
Loaded 100 of 362 files, more files were not shown because too many files have changed in this diff. Show more