Merge main into feat/craft-texture-decode

This commit is contained in:
dotCooCoo committed 2026-11-16 09:53:33 -08:00
commit d87d22463b
341 files changed
+49072 -1370

No files matched your search

+44
View File
@@ -0,0 +1,44 @@
# cargo-nextest (https://nexte.st) runs every test in its own process, in parallel across test
# binaries. The Windows leg of the Workspace gate uses it (.github/workflows/workspace.yml); every
# other leg, and local runs, keep `cargo test`. Nextest does not run doctests, so the Windows leg
# also runs `cargo test --doc`.
#
# cargo nextest run --workspace --profile ci
# cargo test --workspace --doc
#
# Refuse an older nextest: CI installs exactly this version (GHSA-vc25-qg58-w57c is fixed in it).
nextest-version = "0.9.150"
# Some tests share a resource that an in-process mutex keeps to one test at a time. With one
# process per test those mutexes no longer serialize anything, so these groups do it instead, one
# test at a time, as under `cargo test`.
[test-groups]
# craft-ui: `gpu_test_lock()` / `gpu_lock()`. Each renderer creates its own wgpu instance and
# device, and creating or destroying one while another test uses its device can crash.
gpu = { max-threads = 1 }
# craft-video h264_decode: `FIXTURE_GENERATION` keeps a second producer from replacing a fixture
# file another test is reading.
video-fixtures = { max-threads = 1 }
# craft-print: `PRINT_TICKET_PROVIDER` serializes the Windows PrintTicket provider, and the tests
# share the one test print queue the gate installs.
print = { max-threads = 1 }
[[profile.default.overrides]]
filter = 'package(craft-ui) & (binary(visual_regression) | test(/^combo::tests::|selected_tab_erases_a_baseline_centered_on_its_bottom_edge/))'
test-group = 'gpu'
[[profile.default.overrides]]
filter = 'package(craft-video) & binary(h264_decode)'
test-group = 'video-fixtures'
[[profile.default.overrides]]
filter = 'package(craft-print)'
test-group = 'print'
# The gate (`--profile ci`). Run every test and list all failures at the end, as `cargo test`
# reports a whole binary. Slow tests are named every 60 seconds; none is stopped for being slow,
# so a hang is still ended by the gate's own timeout, as before.
[profile.ci]
fail-fast = false
slow-timeout = { period = "60s" }
failure-output = "immediate-final"
+1 -1
View File
@@ -23,5 +23,5 @@ jobs:
# The codec and format code behind features that are off by default. Without these the
# coverage build never compiles it, and new code there reads as untested.
cargo-features: >-
craft-video/dnx,craft-video/vp8,craft-video/prores,craft-video/h264,craft-video/hevc,craft-video/vp9,craft-video/av1,craft-video/threads,craft-audio/decode,craft-audio/encode,craft-audio/peaks,craft-audio/rayon,craft-audio/serde,craft-media/matroska,craft-media/ogg,craft-media/bitstream,craft-media/serde,craft-mesh/stl,craft-mesh/obj,craft-mesh/ply,craft-mesh/gltf,craft-metafile/write,craft-image-codecs/sgi
craft-image-codecs/avif,craft-image-codecs/avif-decode,craft-video/dnx,craft-video/vp8,craft-video/prores,craft-video/h264,craft-video/hevc,craft-video/vp9,craft-video/av1,craft-video/threads,craft-audio/decode,craft-audio/encode,craft-audio/peaks,craft-audio/rayon,craft-audio/serde,craft-media/matroska,craft-media/ogg,craft-media/bitstream,craft-media/serde,craft-mesh/stl,craft-mesh/obj,craft-mesh/ply,craft-mesh/gltf,craft-metafile/write,craft-image-codecs/sgi,craft-image-codecs/sunraster,craft-jsonrpc/async-lines
secrets: inherit
+8 -3
View File
@@ -25,7 +25,8 @@ jobs:
with:
os: '["ubuntu-latest","windows-latest","macos-latest"]'
timeout-minutes: 120
tools: ""
# The Windows leg runs its tests with nextest (.config/nextest.toml).
tools: cargo-nextest@0.9.150
packages: mesa-vulkan-drivers libvulkan1
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
linux-env: WGPU_BACKEND=vulkan
@@ -58,8 +59,12 @@ jobs:
cargo fmt --check
cargo clippy --workspace --all-targets --locked -- -D warnings
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
cargo test --workspace --locked
cargo test --workspace --all-features --locked
# The same tests as `cargo test`, run in parallel across test binaries instead of one
# binary at a time; nextest skips doctests, so `cargo test --doc` runs them.
cargo nextest run --workspace --locked --profile ci
cargo test --workspace --doc --locked
cargo nextest run --workspace --all-features --locked --profile ci
cargo test --workspace --doc --all-features --locked
msrv:
name: Rust 1.95
+1
View File
@@ -101,4 +101,5 @@ and the exact transfer revision are recorded in each vendored crate's SOURCE.jso
`crates/plist` is extracted from `storytold/craft-anything` (`crates/formats/src/plist.rs` and checked byte reads), at source main `88d1d9cac852aec1c7fd97886db451e005e49d2a`. MIT OR Apache-2.0; source license texts are retained in the crate. Primary import Git authors preserve Brandon Thomas, BFlat, RRFZ and Afloat. Regression imports preserve BFlat. XML, JSON projection, calendar formatting and app policy were not imported into the public API.
`crates/tga/src/metadata_tests.rs` and metadata-boundary helpers in `crates/tga/src/lib.rs` are adapted from nuclearspike's FilmCraft #1932 at `e7842f76f887005c460c64a8ab51d59d086e6f27` (MIT OR Apache-2.0). Synthetic fixtures are original contributor test data; primary Git author retained.
The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper are ported from Craft Anything `8f3b775157d331dd31cfa4da911e26d8856b8c77` (same MIT OR Apache-2.0 source licenses). Brandon Thomas is the primary import author; retained hardening credits include Afloat, BFlat, Rahul, RRFZ and NetterSilver. The finite-real fix preserves gmrmad1 as author from Craft Anything #1905 (`d85e104f`); quoted-attribute/line-ending regressions preserve RRFZ. Bounds/adaptation and bounded entity scanning are subsequent Dylan M. Taylor changes. App-specific JSON projections and keyed-archive interpretation remain outside this crate.
Generated
+444 -4
View File
@@ -116,12 +116,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
dependencies = [
"cfg-if",
"getrandom 0.3.4",
"once_cell",
"serde",
"version_check",
"zerocopy",
]
[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
[[package]]
name = "aligned"
version = "0.4.3"
@@ -576,6 +586,15 @@ version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "bit-set"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
dependencies = [
"bit-vec 0.8.0",
]
[[package]]
name = "bit-set"
version = "0.10.0"
@@ -594,6 +613,12 @@ dependencies = [
"bit-vec 0.10.1",
]
[[package]]
name = "bit-vec"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
[[package]]
name = "bit-vec"
version = "0.9.1"
@@ -772,6 +797,12 @@ dependencies = [
"cipher 0.4.4",
]
[[package]]
name = "borrow-or-share"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c"
[[package]]
name = "borsh"
version = "1.8.1"
@@ -883,6 +914,12 @@ version = "3.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
[[package]]
name = "bytecount"
version = "0.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e"
[[package]]
name = "bytemuck"
version = "1.25.2"
@@ -921,6 +958,16 @@ version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "bzip2-rs"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "beeb59e7e4c811ab37cc73680c798c7a5da77fc9989c62b09138e31ee740f735"
dependencies = [
"crc32fast",
"tinyvec",
]
[[package]]
name = "calloop"
version = "0.13.0"
@@ -1451,6 +1498,16 @@ dependencies = [
"encoding_rs",
]
[[package]]
name = "craft-control"
version = "0.1.0"
dependencies = [
"getrandom 0.3.4",
"proptest",
"serde",
"serde_json",
]
[[package]]
name = "craft-control-protocol"
version = "0.1.0"
@@ -1646,6 +1703,15 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-elf"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-eps"
version = "0.1.0"
@@ -1785,9 +1851,12 @@ name = "craft-font-catalog"
version = "0.1.0"
dependencies = [
"fontique",
"harfrust 0.13.3",
"kurbo 0.13.1",
"skrifa 0.47.0",
"thiserror 2.0.21",
"unicode-bidi",
"unicode-segmentation",
"windows-registry",
"write-fonts 0.54.1",
]
@@ -1846,6 +1915,16 @@ dependencies = [
"craft-fonts-build",
]
[[package]]
name = "craft-format"
version = "0.1.0"
dependencies = [
"craft-zip",
"proptest",
"serde_json",
"sha2 0.10.9",
]
[[package]]
name = "craft-gainmap"
version = "0.1.0"
@@ -1868,6 +1947,15 @@ dependencies = [
"image",
]
[[package]]
name = "craft-gridcraft-format"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-gzip"
version = "0.1.0"
@@ -1887,6 +1975,7 @@ name = "craft-heif"
version = "0.1.0"
dependencies = [
"heic-rs",
"proptest",
"rayon",
]
@@ -1989,6 +2078,21 @@ dependencies = [
"indd",
]
[[package]]
name = "craft-ipc"
version = "0.1.0"
dependencies = [
"chrono",
"getrandom 0.2.17",
"interprocess",
"jsonschema",
"libc",
"serde",
"serde_json",
"sha2 0.10.9",
"widestring",
]
[[package]]
name = "craft-jmap"
version = "0.1.0"
@@ -2013,6 +2117,7 @@ name = "craft-jsonrpc"
version = "0.1.0"
dependencies = [
"serde_json",
"tokio",
]
[[package]]
@@ -2076,6 +2181,15 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-macho"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-markdown"
version = "0.1.0"
@@ -2121,6 +2235,14 @@ dependencies = [
"serde_json",
]
[[package]]
name = "craft-mcp-server"
version = "0.1.0"
dependencies = [
"proptest",
"serde_json",
]
[[package]]
name = "craft-media"
version = "0.1.0"
@@ -2155,6 +2277,7 @@ version = "0.1.0"
dependencies = [
"craft-opc",
"craft-xml",
"craft-zip",
"miniz_oxide 0.9.1",
"serde_json",
]
@@ -2366,6 +2489,15 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-pe"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-penpot"
version = "0.1.0"
@@ -2528,6 +2660,7 @@ name = "craft-ps"
version = "0.1.0"
dependencies = [
"craft-eps",
"flate2",
"kurbo 0.13.1",
"miniz_oxide 0.8.9",
"pdf-writer",
@@ -2597,6 +2730,13 @@ dependencies = [
"zune-jpegxl",
]
[[package]]
name = "craft-render-parity"
version = "0.1.0"
dependencies = [
"craft-cms",
]
[[package]]
name = "craft-rtf"
version = "0.1.0"
@@ -2648,6 +2788,10 @@ dependencies = [
name = "craft-sheet"
version = "0.1.0"
[[package]]
name = "craft-shx"
version = "0.1.0"
[[package]]
name = "craft-silhouette-studio"
version = "0.1.0"
@@ -2699,6 +2843,10 @@ dependencies = [
"zeroize",
]
[[package]]
name = "craft-sniff"
version = "0.1.0"
[[package]]
name = "craft-stencilcraft-document"
version = "0.1.0"
@@ -2712,6 +2860,10 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-ssip"
version = "0.1.0"
[[package]]
name = "craft-stencilcraft-format"
version = "0.1.0"
@@ -2759,6 +2911,13 @@ dependencies = [
"kurbo 0.13.1",
]
[[package]]
name = "craft-tar"
version = "0.1.0"
dependencies = [
"serde",
]
[[package]]
name = "craft-tcraft"
version = "0.1.0"
@@ -2775,6 +2934,7 @@ version = "0.1.0"
dependencies = [
"hypher",
"icu_segmenter",
"kurbo 0.13.1",
"miniz_oxide 0.8.9",
"unicode-bidi",
"unicode-bidi-mirroring",
@@ -2930,6 +3090,7 @@ dependencies = [
name = "craft-video"
version = "0.1.0"
dependencies = [
"craft-jpeg",
"craft-media",
"craft-media-testkit",
"rav1e",
@@ -3063,12 +3224,33 @@ dependencies = [
name = "craft-zip"
version = "0.1.0"
dependencies = [
"bzip2-rs",
"craft-zip",
"flate2",
"lzma-rs",
"miniz_oxide 0.8.9",
"ruzstd",
"serde",
"serde_json",
"thiserror 2.0.21",
"zip",
]
[[package]]
name = "crc"
version = "3.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d"
dependencies = [
"crc-catalog",
]
[[package]]
name = "crc-catalog"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"
[[package]]
name = "crc24"
version = "0.1.6"
@@ -3587,6 +3769,12 @@ dependencies = [
"libloading",
]
[[package]]
name = "doctest-file"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2db04e74f0a9a93103b50e90b96024c9b2bdca8bce6a632ec71b88736d3d359"
[[package]]
name = "document-features"
version = "0.2.12"
@@ -3935,6 +4123,15 @@ dependencies = [
"zeroize",
]
[[package]]
name = "email_address"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449"
dependencies = [
"serde",
]
[[package]]
name = "emath"
version = "0.37.0"
@@ -4147,6 +4344,17 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365"
[[package]]
name = "fancy-regex"
version = "0.19.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d301f5bf187b3c295fce6468d3875037a0bccc5f6b151c63cac2f85babf21912"
dependencies = [
"bit-set 0.8.0",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "fastrand"
version = "2.5.0"
@@ -4260,6 +4468,17 @@ dependencies = [
"num-traits",
]
[[package]]
name = "fluent-uri"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc74ac4d8359ae70623506d512209619e5cf8f347124910440dbc221714b328e"
dependencies = [
"borrow-or-share",
"ref-cast",
"serde",
]
[[package]]
name = "fmt-derive"
version = "0.1.2"
@@ -4412,6 +4631,16 @@ dependencies = [
"percent-encoding",
]
[[package]]
name = "fraction"
version = "0.15.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e076045bb43dac435333ed5f04caf35c7463631d0dae2deb2638d94dd0a5b872"
dependencies = [
"lazy_static",
"num",
]
[[package]]
name = "fs-set-times"
version = "0.20.3"
@@ -4843,6 +5072,8 @@ version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash 0.2.0",
]
@@ -5491,6 +5722,19 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "interprocess"
version = "2.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6cb02ffbf25e8ef0f4a95bff054eef75f6d1bf16919474cf2caa63b21997478a"
dependencies = [
"doctest-file",
"libc",
"recvmsg",
"widestring",
"windows-sys 0.61.2",
]
[[package]]
name = "io-extras"
version = "0.19.0"
@@ -5668,6 +5912,58 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "jsonschema"
version = "0.49.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ec8a241beed129f06114aa68007e905ca350e7baeb6e17a7631bb7978d91b2"
dependencies = [
"ahash",
"bytecount",
"data-encoding",
"email_address",
"fancy-regex",
"fraction",
"getrandom 0.3.4",
"idna",
"itoa",
"jsonschema-regex",
"jsonschema-value",
"num-cmp",
"num-traits",
"percent-encoding",
"referencing",
"regex",
"serde",
"serde_json",
"strum",
"unicode-general-category",
"uuid-simd",
]
[[package]]
name = "jsonschema-regex"
version = "0.49.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91994f45017ed5e66aa8e59b8415f4cb033a6380d7200387b7cf117595fbdf85"
dependencies = [
"regex-syntax",
]
[[package]]
name = "jsonschema-value"
version = "0.49.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ec7637f83e510868ae6ed625f7ebfbbde4554ee8ce49854caa5126a8b9b9ecb"
dependencies = [
"ahash",
"bytecount",
"fraction",
"num-cmp",
"num-traits",
"serde_json",
]
[[package]]
name = "jxl-bitstream"
version = "1.1.0"
@@ -6122,6 +6418,16 @@ version = "0.11.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "373f5eceeeab7925e0c1098212f2fbc4d416adec9d35051a6ab251e824c1854a"
[[package]]
name = "lzma-rs"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "297e814c836ae64db86b36cf2a557ba54368d03f6afcd7d947c266692f71115e"
dependencies = [
"byteorder",
"crc",
]
[[package]]
name = "maybe-owned"
version = "0.3.4"
@@ -6135,6 +6441,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519"
dependencies = [
"cfg-if",
"rayon",
]
[[package]]
@@ -6181,6 +6488,12 @@ dependencies = [
"autocfg",
]
[[package]]
name = "micromap"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74"
[[package]]
name = "mime"
version = "0.3.17"
@@ -6425,6 +6738,20 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "num"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
dependencies = [
"num-bigint",
"num-complex",
"num-integer",
"num-iter",
"num-rational",
"num-traits",
]
[[package]]
name = "num-bigint"
version = "0.4.8"
@@ -6452,6 +6779,12 @@ dependencies = [
"zeroize",
]
[[package]]
name = "num-cmp"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63335b2e2c34fae2fb0aa2cecfd9f0832a1e24b3b32ecec612c3426d46dc8aaa"
[[package]]
name = "num-complex"
version = "0.4.6"
@@ -6967,6 +7300,12 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "outref"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e"
[[package]]
name = "p256"
version = "0.13.2"
@@ -7972,6 +8311,7 @@ dependencies = [
"loop9",
"quick-error 2.0.1",
"rav1e",
"rayon",
"rgb",
]
@@ -8091,6 +8431,12 @@ dependencies = [
"yoke",
]
[[package]]
name = "recvmsg"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3edd4d5d42c92f0a659926464d4cce56b562761267ecf0f469d85b7de384175"
[[package]]
name = "redox_syscall"
version = "0.4.1"
@@ -8128,6 +8474,66 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "ref-cast"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3"
dependencies = [
"ref-cast-impl",
]
[[package]]
name = "ref-cast-impl"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "referencing"
version = "0.49.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6efa2154ea6f5ce0fdecdd2a8d18f2fa1a39a8fbba91564f555a592e4dce8278"
dependencies = [
"ahash",
"fluent-uri",
"getrandom 0.3.4",
"hashbrown 0.17.1",
"itoa",
"micromap",
"parking_lot",
"percent-encoding",
"serde_json",
]
[[package]]
name = "regex"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-lite"
version = "0.1.9"
@@ -8523,9 +8929,9 @@ checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"
[[package]]
name = "rustls-webpki"
version = "0.103.15"
version = "0.103.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
dependencies = [
"aws-lc-rs",
"ring",
@@ -9915,9 +10321,21 @@ dependencies = [
"mio",
"pin-project-lite",
"socket2",
"tokio-macros",
"windows-sys 0.61.2",
]
[[package]]
name = "tokio-macros"
version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "tokio-rustls"
version = "0.26.6"
@@ -10385,6 +10803,16 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "uuid-simd"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b082222b4f6619906941c17eb2297fff4c2fb96cb60164170522942a200bd8"
dependencies = [
"outref",
"vsimd",
]
[[package]]
name = "v_frame"
version = "0.3.9"
@@ -10707,6 +11135,12 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "vsimd"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64"
[[package]]
name = "wait-timeout"
version = "0.2.1"
@@ -11176,6 +11610,12 @@ dependencies = [
"web-sys",
]
[[package]]
name = "widestring"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471"
[[package]]
name = "winapi-util"
version = "0.1.11"
@@ -11936,9 +12376,9 @@ dependencies = [
[[package]]
name = "zip"
version = "9.1.0"
version = "9.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2886b00003a72c4ccee3f42cfc34908d33b2508a74d827dc2a4244706475c704"
checksum = "1156b39d142a34b999c2310a50455e0cb3760bf7efad0122f796d813bee26ccb"
dependencies = [
"crc32fast",
"flate2",
+10 -2
View File
@@ -11,11 +11,14 @@ rust-version = "1.95"
repository = "https://github.com/storytold/craft-libs"
[workspace.dependencies]
craft-shx = { path = "crates/shx" }
craft-http-url = { path = "crates/http-url" }
craft-usd = { path = "crates/usd" }
craft-smime = { path = "crates/smime" }
craft-ssip = { path = "crates/ssip" }
craft-ber = { path = "crates/ber" }
craft-proto = { path = "crates/proto" }
craft-render-parity = { path = "crates/render-parity" }
acadrust = "=0.6.6"
log = "0.4"
# internal: add each crate here as `craft-<name> = { path = "crates/<name>" }`
@@ -26,6 +29,7 @@ craft-affinity = { path = "crates/affinity" }
craft-ai-core = { path = "crates/ai-core" }
craft-anicraft-format = { path = "crates/anicraft-format" }
craft-pdf = { path = "crates/pdf", version = "=0.1.0" }
craft-pe = { path = "crates/pe" }
craft-ps = { path = "crates/ps", version = "=0.1.0" }
craft-pdn = { path = "crates/pdn" }
craft-plate-test = { path = "crates/plate-test" }
@@ -41,6 +45,7 @@ bytemuck = "1"
kurbo = "0.13"
thiserror = "2"
craft-gzip = { path = "crates/gzip" }
craft-gridcraft-format = { path = "crates/gridcraft-format" }
craft-aaf = { path = "crates/aaf" }
craft-atomic = { path = "crates/atomic" }
craft-captions = { path = "crates/captions" }
@@ -61,6 +66,7 @@ craft-designcraft-format = { path = "crates/designcraft-format" }
craft-dxf = { path = "crates/dxf" }
craft-drawingml = { path = "crates/drawingml" }
craft-eps = { path = "crates/eps" }
craft-elf = { path = "crates/elf" }
craft-file-formats = { path = "crates/file-formats" }
craft-file-import = { path = "crates/file-import" }
vectorcraft-doc = { git = "https://github.com/storytold/vectorcraft.git", rev = "6b3a6b8788ebcb420d69449199cbdf323888d27e" }
@@ -90,6 +96,7 @@ craft-heif = { path = "crates/heif" }
craft-fig = { path = "crates/fig" }
craft-fonts-build = { path = "crates/fonts-build" }
craft-i18n = { path = "crates/i18n" }
craft-ipc = { path = "crates/ipc" }
craft-idml = { path = "crates/idml" }
craft-indd = { path = "crates/indd" }
craft-jmap = { path = "crates/jmap" }
@@ -106,6 +113,7 @@ craft-kra = { path = "crates/kra" }
craft-audio = { path = "crates/audio" }
craft-latex = { path = "crates/latex" }
craft-markdown = { path = "crates/markdown" }
craft-macho = { path = "crates/macho" }
craft-math = { path = "crates/math" }
# No default features: craft-audio turns on the craft-media modules each of its features needs.
craft-media = { path = "crates/media", default-features = false }
@@ -172,6 +180,8 @@ craft-xcf = { path = "crates/xcf" }
craft-xml = { path = "crates/xml" }
craft-zip = { path = "crates/zip" }
craft-y4m = { path = "crates/y4m" }
craft-sniff = { path = "crates/sniff" }
craft-tar = { path = "crates/tar" }
craft-epub = { path = "crates/epub" }
craft-ews = { path = "crates/ews" }
craft-video = { path = "crates/video" }
@@ -194,13 +204,11 @@ chrono = { version = "0.4.45", default-features = false, features = ["std"] }
[workspace.lints.rust]
unsafe_code = "forbid"
unused_workspace_dependencies = "allow"
unexpected_cfgs = { level = "warn", check-cfg = ["cfg(craft_pdf_unicode_fixtures)"] }
[workspace.lints.clippy]
cognitive_complexity = "deny"
too_many_arguments = "deny"
unused_workspace_dependencies = "allow"
wildcard_imports = "deny"
dbg_macro = "warn"
todo = "warn"
+13 -1
View File
@@ -61,6 +61,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
of compositions, layers, properties, keyframes, effects, masks, shapes, text and footage.
Clean room, from EffectCraft. Mapping onto an app's document stays in the app.
- [`craft-ai-core`](crates/ai-core/README.md): the data model and contract for AI in the Craft Apps (connections, models, tools, requests, jobs, consent, history, route spec). Pure, no I/O, wasm-safe. Contract in [docs/ai-shared-layer.md](docs/ai-shared-layer.md).
- [`craft-pe`](crates/pe/src/lib.rs): PE/COFF headers (`.exe`, `.dll`, `.sys`, `.efi`) from untrusted bytes, from Craft Anything: the COFF header, PE32/PE32+ optional header with its data directories bounded by the header's real size, the section table, RVA-to-file mapping and the decoded Rich header.
- [`craft-pdf`](crates/pdf/README.md): independently optional PDF parsing, interpretation, rasterization and guarded authoring. Apps retain layout, fonts, editing and export policy; writer-only consumers do not enable the shared reader.
- [`craft-pdn`](crates/pdn/README.md): Paint.NET documents (`.pdn`, PDN3), read: the layer list, blend modes and chunked gzip pixel blocks, with a data-only MS-NRBF (.NET binary serialization) reader. From PhotoCraft.
@@ -108,6 +109,7 @@ 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-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)`),
the EPSI preview bitmap, ASCII85 data, and telling EPS, PostScript and Illustrator files
@@ -176,6 +178,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
every frame's position, delay, disposal and transparent colour, the loop count and the first
frame's colour table, without decompressing pixels. Tells an animation from a still and whether
a file can hold the picture it declares before a decoder runs.
- [`craft-gridcraft-format`](crates/gridcraft-format/README.md): GridCraft's native JSON workbook
(`.json`, `.scjson`): the extensions, the reader, the pretty writer, and newer entries kept
unread and written back into a list. The workbook model and what follows a read stay in GridCraft.
- [`craft-hdr`](crates/hdr/src/lib.rs): Radiance HDR (RGBE) picture reader, from FilmCraft: flat,
old and new run-length scan lines and all eight axis orders, to linear float RGB. Scan lines are
validated before the picture is allocated.
@@ -195,6 +200,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
Hasselblad 3FR/FFF, Minolta MRW, Epson ERF, Mamiya MEF, Kodak DCS, Pentax PEF, Samsung SRW, Canon CR2, Nikon NEF/NRW, Panasonic RW2, Fujifilm RAF, Olympus ORF (uncompressed), Sony ARW, Canon CR3 and Canon CRW (through
`craft-crw`) so far; demosaicing and everything after stay with the develop
pipeline.
- [`craft-render-parity`](crates/render-parity/README.md): test support for the shared develop
pipeline (#587): how far two renders of the same photo are apart (per-channel error, CIEDE2000,
the worst pixel) and whether that is within a stated tolerance.
- [`craft-tga`](crates/tga/src/lib.rs): Truevision Targa, from FilmCraft (reader) and PhotoCraft
(writer): true-colour, grayscale and colour-mapped pictures, raw or run-length encoded, any
origin, to RGBA8, and a run-length writer whose packets end with their scan line. Bounded on
@@ -231,6 +239,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
primitives (`.abr`, `.asl`, `.aco`, `.act`, `.ase`, `.grd`, `.pat`, `.atn`, `.csh`, `.shc`) and
the Photoshop blocks of a layered TIFF. Bounded and panic-free on hostile input. Compositing
and the mapping onto a document stay in each app.
- [`craft-ipc`](crates/ipc/README.md): Craft apps talking on one machine: per-user local sockets (Unix socket, Windows named pipe), token auth, instance discovery, launch on demand, focus hand-off, frame transfer and linked-file watching. Native only: it does not build for `wasm32`. Protocol in [PROTOCOL.md](crates/ipc/PROTOCOL.md).
- [`craft-jmap`](crates/jmap/README.md): the JMAP protocol core (RFC 8620), from MailCraft, without
sockets: session, requests of method calls with back-references, responses, ids, address
templates, credentials and the judgement of HTTP answers, over any HTTP implementation. Bounded
@@ -254,6 +263,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
AC-3/E-AC-3, MP1/MP2, MP3 encoding), streaming and seeking, and packet decoding for any demuxer. See its
README for formats and features.
- [`craft-latex`](crates/latex/README.md): LaTeX documents read (the everyday subset) and written (a standalone article), to and from the craft-flow model.
- [`craft-macho`](crates/macho/src/lib.rs): Mach-O header pieces from untrusted bytes, from Craft Anything: universal (fat and fat64) slice tables checked against the file, CPU and load command names, the fixed size each load command needs before its fields are read, and the thread-state program counter.
- [`craft-markdown`](crates/markdown/README.md): Markdown read and written (a CommonMark subset with GitHub tables and strikethrough), to and from the craft-flow model.
- [`craft-math`](crates/math/README.md): equations as one tree (the Office Math object model) with its syntaxes, read and written: OMML, presentation MathML, LaTeX math and the UnicodeMath linear format.
- [`craft-media`](crates/media/README.md): bit-level I/O (`bitstream`), clean-room MP4/MOV
@@ -384,13 +394,15 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
text-format crates read into and write from. WordCraft's model without its editing code.
- [`craft-xlsx`](crates/xlsx/README.md): Excel workbooks (`.xlsx`, `.xlsm`, SpreadsheetML, transitional and strict) and binary workbooks (`.xlsb`) on `craft-opc`: the workbook part, shared strings, the styles tables and worksheet rows streamed one at a time, with limits on the package, the XML and the binary records.
- [`craft-ora`](crates/ora/README.md): OpenRaster documents (`.ora`): the ZIP archive and the `stack.xml` layer tree as written, read with bounded sizes and written. From PhotoCraft.
- [`craft-sniff`](crates/sniff/src/lib.rs): what a file is from its first bytes: one dependency-free, wasm-safe signature table naming the format, its media type, extension and family for images, audio, video, 3D models, archives, compressed streams, executables and databases. Identifies only; parsing stays with each format's reader.
- [`craft-tar`](crates/tar/src/lib.rs): TAR (v7, ustar, GNU long names and base-256 sizes, local and global pax overrides) and cpio (newc, crc, odc) member walkers for hostile input, from Craft Anything: list each member, its kind, mode, link target and where its data lies, without extracting. Bounded by the input and a member cap; an optional `serde` feature serializes listings.
- [`craft-y4m`](crates/y4m/src/lib.rs): YUV4MPEG2 (`.y4m`) reader, from FilmCraft: the stream
header, colour space layouts at 8 to 16 bits, a frame index built from the `FRAME` lines without
loading the file, and plane access. Bounded on hostile input.
- [`craft-kra`](crates/kra/README.md): Krita documents (`.kra`, `.krz`), read: the ZIP archive, the `maindoc.xml` node tree as written, and the tiled pixel files with their LZF compression, a tile at a time. From PhotoCraft.
- [`craft-xcf`](crates/xcf/README.md): GIMP XCF images (`.xcf`, `.xcf.gz`), read: header, properties, parasites, layers with their item paths, channels, and tiled pixels (uncompressed, RLE, zlib) at every precision, under a caller's byte budget. From PhotoCraft.
- [`craft-xml`](crates/xml/README.md): bounded XML for hostile input: an owned element tree with limits on size, depth, nodes and attributes, streaming of repeated elements, namespace handling (as written, by local name, or canonical prefixes by URI), escaping and a writer. No DTDs and no entity expansion.
- [`craft-zip`](crates/zip/README.md): ZIP archives from untrusted files: an entry-count check before the archive is indexed (ZIP64 included), entry reads within per-entry and total budgets that count real bytes, duplicate-name detection, a strict structure preflight, and a deterministic stored/deflate writer. The shared ZIP layer for the package formats.
- [`craft-zip`](crates/zip/README.md): ZIP archives from untrusted files: an entry-count check before the archive is indexed (ZIP64 included), entry reads within per-entry and total budgets that count real bytes, duplicate-name detection, a strict structure preflight, and a deterministic stored/deflate writer. The shared ZIP layer for the package formats. With the `lenient` feature, also a reader of the raw bytes without the `zip` crate, from Craft Anything, for inspectors that must describe damaged archives rather than refuse them: the central-directory listing with ZIP64, prepended-stub and multi-volume checks, CP437 and Info-ZIP Unicode Path names, and entry reads (stored, DEFLATE, and bzip2, LZMA, XZ and Zstandard behind `lenient-*` features) checked against the declared size and CRC-32.
- [Shared UI component audit](docs/ui-components-audit.md): source inventory, extraction priorities
and compatibility boundaries across the Craft suite.
- [Theme infrastructure](docs/theme-infrastructure.md): eight-app comparison and the small shared
+45 -2
View File
@@ -57,13 +57,56 @@ pub struct WriteOptions<'a> {
/// reported.
pub fn write(doc: &Document, opts: &WriteOptions<'_>, report: &mut Report) -> Result<Vec<u8>> {
let version = if opts.small_sectors { craft_cfb::Version::V3 } else { craft_cfb::Version::V4 };
write::write(doc, version, &opts.identity, report)
write::write(doc, version, &opts.identity, &ReferenceOptions::default(), report)
}
/// Optional interpretation choices for applications retaining older interchange behavior.
#[derive(Clone, Copy, Debug)]
pub struct ReadOptions {
/// Interpret a source clip's start using its target slot's edit rate.
pub source_slot_rate: bool,
/// Use the referenced mob name when the clip has no explicit name.
pub infer_clip_name: bool,
/// Decode percent escapes in relative network locators.
pub decode_relative_locator: bool,
/// Report selector and nested-scope flattening.
pub report_flattening: bool,
/// Accept truncated PCM WAVE essence summaries.
pub permissive_pcm: bool,
}
impl Default for ReadOptions {
fn default() -> Self {
Self { source_slot_rate: true, infer_clip_name: true, decode_relative_locator: true, report_flattening: true, permissive_pcm: false }
}
}
/// Read using explicitly selected interpretation choices.
pub fn read_with_options(bytes: &[u8], options: &ReadOptions, report: &mut Report) -> Result<Document> {
read::read(bytes, options, report)
}
/// Optional compatibility choices for writing source references and locators.
#[derive(Clone, Copy, Debug)]
pub struct ReferenceOptions {
/// Write source offsets in target-slot units.
pub source_slot_rate: bool,
/// Percent-encode relative locators.
pub encode_relative_locator: bool,
}
impl Default for ReferenceOptions {
fn default() -> Self {
Self { source_slot_rate: true, encode_relative_locator: true }
}
}
/// Write with explicitly selected reference and locator conventions.
pub fn write_with_references(doc: &Document, opts: &WriteOptions<'_>, references: &ReferenceOptions, report: &mut Report) -> Result<Vec<u8>> {
let version = if opts.small_sectors { craft_cfb::Version::V3 } else { craft_cfb::Version::V4 };
write::write(doc, version, &opts.identity, references, report)
}
/// Read an AAF file: its top-level compositions, the compositions nested in them and their
/// sources. What cannot be represented is skipped and named in `report`.
pub fn read(bytes: &[u8], report: &mut Report) -> Result<Document> {
read::read(bytes, report)
read::read(bytes, &ReadOptions::default(), report)
}
/// Whether `bytes` look like an AAF file (a compound file whose root has the AAF root class or a
+25 -7
View File
@@ -67,6 +67,7 @@ fn indirect_f64(d: &[u8]) -> Option<f64> {
struct R<'a> {
report: &'a mut Report,
options: super::ReadOptions,
mobs: HashMap<MobId, &'a Obj>,
essence: HashMap<MobId, &'a [u8]>,
doc: Document,
@@ -90,7 +91,7 @@ struct NestClip<'a> {
/// Compositions nested deeper than this are read as gaps.
const MAX_NESTING: usize = 16;
pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result<Document> {
pub(crate) fn read(bytes: &[u8], options: &super::ReadOptions, report: &mut Report) -> Result<Document> {
let root = store::read(bytes).map_err(|e| Error::Parse { format: "AAF", message: e })?;
let header = root.strong(pid::ROOT_HEADER).ok_or_else(|| Error::Parse { format: "AAF", message: "no header object".into() })?;
let content = header.strong(pid::CONTENT).ok_or_else(|| Error::Parse { format: "AAF", message: "no content storage".into() })?;
@@ -106,7 +107,8 @@ pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result<Document> {
essence.insert(id, d);
}
}
let mut r = R { report, mobs, essence, doc: Document::default(), sources: HashMap::new(), nests: HashMap::new(), open: Vec::new() };
let mut r =
R { report, options: *options, mobs, essence, doc: Document::default(), sources: HashMap::new(), nests: HashMap::new(), open: Vec::new() };
// Top-level compositions: those no other composition uses, among the ones tagged top-level
// when any are. (Premiere Pro tags a nested sequence's composition top-level too; it is still
// only a nested sequence.) Compositions that only use each other in a circle all count. The
@@ -331,7 +333,9 @@ impl R<'_> {
items
}
x if x == cls::SELECTOR => {
self.report.info("a selector was flattened to its selected input");
if self.options.report_flattening {
self.report.info("a selector was flattened to its selected input");
}
match c.strong(pid::SELECTED) {
Some(s) => {
let mut items = self.segment(s, rate, kind, depth);
@@ -342,7 +346,9 @@ impl R<'_> {
}
}
x if x == cls::NESTED_SCOPE => {
self.report.info("a nested scope was flattened to its final input");
if self.options.report_flattening {
self.report.info("a nested scope was flattened to its final input");
}
match c.objs(pid::NESTED_SLOTS).last() {
Some(s) => {
let mut items = self.segment(s, rate, kind, depth);
@@ -388,7 +394,12 @@ impl R<'_> {
let len = units_to_ticks(len_of(c), rate.0, rate.1);
let tagged_name = tagged_values(c, pid::COMPONENT_USER_COMMENTS).into_iter().find(|(k, _)| k == "Clip Name").map(|(_, v)| v);
let (Some(id), Some(slot)) = (c.mob_id(pid::SOURCE_ID), c.u32(pid::SOURCE_MOB_SLOT_ID)) else { return CItem::Filler(len) };
let name = tagged_name.or_else(|| self.mobs.get(&id).and_then(|mob| mob.string(pid::MOB_NAME))).unwrap_or_default();
let name = if self.options.infer_clip_name {
tagged_name.or_else(|| self.mobs.get(&id).and_then(|mob| mob.string(pid::MOB_NAME)))
} else {
tagged_name
}
.unwrap_or_default();
if id == [0; 32] {
return CItem::Filler(len);
}
@@ -401,6 +412,7 @@ impl R<'_> {
.and_then(|mob| mob.objs(pid::SLOTS).iter().find(|s| s.u32(pid::SLOT_ID) == Some(slot)))
.and_then(|s| rate_of(s, pid::EDIT_RATE))
.unwrap_or(rate);
let source_rate = if self.options.source_slot_rate { source_rate } else { rate };
let start = units_to_ticks(c.i64(pid::START_TIME).unwrap_or(0), source_rate.0, source_rate.1);
match self.resolve(id, slot, start, kind, master_key, 0) {
Some((source, t)) => CItem::Clip(CClip { len, source, start: t, gain: None, name }),
@@ -506,6 +518,7 @@ impl R<'_> {
.and_then(|m| m.objs(pid::SLOTS).iter().find(|s| s.u32(pid::SLOT_ID) == Some(next_slot)))
.and_then(|s| rate_of(s, pid::EDIT_RATE))
.unwrap_or(rate);
let source_rate = if self.options.source_slot_rate { source_rate } else { rate };
let inner = units_to_ticks(clip.i64(pid::START_TIME).unwrap_or(0), source_rate.0, source_rate.1);
if next == [0; 32] {
return None;
@@ -545,7 +558,11 @@ impl R<'_> {
DataKind::Sound => CKind::Sound,
_ => kind,
};
let path = d.objs(pid::LOCATOR).iter().find_map(|l| l.string(pid::URL_STRING)).map(|u| locator_path(&u));
let path = d
.objs(pid::LOCATOR)
.iter()
.find_map(|l| l.string(pid::URL_STRING))
.map(|u| if self.options.decode_relative_locator { locator_path(&u) } else { craft_timeline::path::file_url_to_path(&u) });
let file_rate = rate_of(d, pid::SAMPLE_RATE).unwrap_or(rate);
let length = d
.i64(pid::FILE_LENGTH)
@@ -604,7 +621,8 @@ impl R<'_> {
if let Some(data) = self.essence.get(&id) {
s.embedded = Some(data.to_vec());
// embedded essence may be a whole WAVE / AIFF file
if let Some((pcm, ch, sr, bits)) = crate::pcm::parse_wav(data) {
let pcm = if self.options.permissive_pcm { craft_audio::essence_pcm::parse_wav(data) } else { crate::pcm::parse_wav(data) };
if let Some((pcm, ch, sr, bits)) = pcm {
s.embedded = Some(pcm);
s.file_channels = ch as u32;
s.channels = if s.channel.is_some() { 1 } else { ch as u32 };
+29
View File
@@ -557,3 +557,32 @@ fn relative_media_locator_round_trips_escaped_characters() {
let got = read_clean(&bytes);
assert!(got.sources.iter().any(|s| s.path.as_deref() == Some("Audio Files/100%20 #1.wav")));
}
#[test]
fn compatibility_options_keep_relative_paths_and_parent_rate() {
let mut doc = crate::testdoc::sound_only(None);
doc.compositions[0].sample_rate = 44_100;
doc.sources[0].path = Some("Audio Files/100%20 #1.wav".into());
let mut report = Report::default();
let references = ReferenceOptions { source_slot_rate: false, encode_relative_locator: false };
let bytes = write_with_references(&doc, &WriteOptions { identity: IDENTITY, small_sectors: false }, &references, &mut report).unwrap();
let root = store::read(&bytes).unwrap();
let mut all = Vec::new();
walk(&root, &mut all);
assert!(
all.iter().filter(|o| o.class == cls::NETWORK_LOCATOR).any(|o| o.string(pid::URL_STRING).as_deref() == Some("Audio Files/100%20 #1.wav"))
);
let starts: Vec<i64> = all.iter().filter(|o| o.class == cls::SOURCE_CLIP).filter_map(|o| o.i64(pid::START_TIME)).collect();
assert!(starts.contains(&17_640), "parent rate start: {starts:?}");
let opts = ReadOptions {
source_slot_rate: false,
infer_clip_name: false,
decode_relative_locator: false,
report_flattening: false,
permissive_pcm: true,
};
let back = read_with_options(&bytes, &opts, &mut report).unwrap();
assert!(back.sources.iter().any(|s| s.path.as_deref() == Some("Audio Files/100%20 #1.wav")));
let clip = back.compositions[0].tracks[0].items.iter().find_map(|i| if let CItem::Clip(c) = i { Some(c) } else { None }).unwrap();
assert_eq!(clip.start, FrameRate::FPS_25.tick_of(10));
}
+14 -4
View File
@@ -75,6 +75,7 @@ fn definition(class: Auid, id: Auid, name: &str) -> Obj {
struct W<'a> {
report: &'a mut Report,
inexact: bool,
references: super::ReferenceOptions,
}
struct IdGen {
@@ -350,9 +351,15 @@ fn add_tape_mob(first: &Source, tape_id: [u8; 32], timecode: Option<(i64, FrameR
}
/// Serialise a composition document.
pub(crate) fn write(doc: &Document, version: craft_cfb::Version, identity: &Identity<'_>, report: &mut Report) -> Result<Vec<u8>> {
pub(crate) fn write(
doc: &Document,
version: craft_cfb::Version,
identity: &Identity<'_>,
references: &super::ReferenceOptions,
report: &mut Report,
) -> Result<Vec<u8>> {
let comp = doc.compositions.first().ok_or(Error::Empty)?;
let mut w = W { report, inexact: false };
let mut w = W { report, inexact: false, references: *references };
let mut ids = IdGen::for_document(doc, comp);
let MediaOutput { mut mobs, essence, master_ref } = write_media(doc, &mut w, &mut ids);
let mut used_ops: Vec<Auid> = Vec::new();
@@ -360,7 +367,8 @@ pub(crate) fn write(doc: &Document, version: craft_cfb::Version, identity: &Iden
// ---- nested compositions: a clip refers to one as it does to a master mob, through the
// composition's first track of the clip's kind (a broken-out channel: that channel's track)
let mut refs = Refs { mobs: master_ref, rates: doc.sources.iter().enumerate().map(|(i, s)| (i, source_rate(s))).collect() };
let rates = if references.source_slot_rate { doc.sources.iter().enumerate().map(|(i, s)| (i, source_rate(s))).collect() } else { HashMap::new() };
let mut refs = Refs { mobs: master_ref, rates };
let nested_ids: Vec<[u8; 32]> = doc.nested.iter().map(|_| ids.next()).collect();
for (si, s) in doc.sources.iter().enumerate() {
let Some((comp, id)) = s.nested.and_then(|n| Some((doc.nested.get(n)?, nested_ids.get(n)?))) else { continue };
@@ -795,8 +803,10 @@ fn descriptor(w: &mut W, s: &Source) -> Obj {
if let Some(p) = &s.path {
let url = if craft_timeline::path::is_absolute(p) {
craft_timeline::path::path_to_file_url(p, false)
} else {
} else if w.references.encode_relative_locator {
craft_timeline::path::encode_uri_path(p)
} else {
p.clone()
};
d.set(pid::LOCATOR, Value::StrongVec(vec![Obj::new(cls::NETWORK_LOCATOR).data_prop(pid::URL_STRING, utf16z(&url))]));
}
+4
View File
@@ -29,7 +29,11 @@ mod roundtrip_tests;
#[cfg(test)]
mod testdoc;
/// Diagnostic types used by readers and writers.
pub use craft_timeline::report;
pub use craft_timeline::report::Report;
/// Exact time types used by the composition model.
pub use craft_timeline::time;
/// Error from a reader or writer. Unsupported *features* never error; they go in the [`Report`].
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+340 -10
View File
@@ -12,6 +12,10 @@ type Uid = [u8; 12];
const MAX_REFERENCE_VISITS: usize = 65_536;
/// A source-clip search stopped at its work limit.
#[derive(Clone, Copy)]
struct SearchLimit;
struct R<'a, 'b> {
c: &'b Container<'a>,
report: &'b mut Report,
@@ -21,15 +25,49 @@ struct R<'a, 'b> {
media: HashMap<Uid, Vec<u8>>,
doc: Document,
sources: HashMap<(Uid, u32, String), usize>,
/// Component visits left for [`R::segment`] over the whole document.
budget: usize,
/// Outcome of the source-clip search under each segment: deterministic, so it is made once.
clip_search: HashMap<u32, std::result::Result<Option<u32>, SearchLimit>>,
/// Visits and queued references left for source-clip searches over the whole document:
/// distinct roots over one shared graph would otherwise each search it in full.
search_budget: usize,
}
/// Components one document may expand into timeline items; a small file can reference the same
/// sequence from many places and would otherwise multiply without bound.
const MAX_COMPONENT_VISITS: usize = 1_000_000;
/// Reported when the shared component budget runs out.
const BUDGET_WARNING: &str = "OMF composition is too large to import completely (the remaining components are dropped)";
/// Most visited components, and most queued references, one source-clip search may spend.
const MAX_CLIP_SEARCH_VISITS: usize = 100_000;
const MAX_CLIP_SEARCH_PENDING: usize = 1_000_000;
/// Work all source-clip searches in one document may spend together.
const MAX_DOCUMENT_SEARCH_WORK: usize = 2_000_000;
pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result<Document> {
read_with_budget(bytes, report, MAX_COMPONENT_VISITS)
}
fn read_with_budget(bytes: &[u8], report: &mut Report, budget: usize) -> Result<Document> {
let perr = |m: String| Error::Parse { format: "OMF", message: m };
let c = Container::open(bytes).map_err(perr)?;
let class_of = |o: u32| c.get(o, "OMFI:OOBJ:ObjClass").and_then(|v| v.get(..4).map(|b| [b[0], b[1], b[2], b[3]]));
let head = c.objects.keys().copied().find(|&o| class_of(o) == Some(*b"HEAD")).ok_or_else(|| perr("no OMF header object".into()))?;
let be = c.get(head, "OMFI:HEAD:ByteOrder").is_none_or(|v| v.first() != Some(&0x49));
let mut r = R { c: &c, report, be, mobs: HashMap::new(), media: HashMap::new(), doc: Document::default(), sources: HashMap::new() };
let mut r = R {
c: &c,
report,
be,
mobs: HashMap::new(),
media: HashMap::new(),
doc: Document::default(),
sources: HashMap::new(),
budget,
clip_search: HashMap::new(),
search_budget: MAX_DOCUMENT_SEARCH_WORK,
};
let mob_list = r.refs(head, "OMFI:HEAD:Mobs");
let mob_list = if mob_list.is_empty() {
c.objects.keys().copied().filter(|&o| matches!(class_of(o).as_ref(), Some(b"CMOB" | b"MMOB" | b"SMOB"))).collect()
@@ -66,8 +104,14 @@ pub(crate) fn read(bytes: &[u8], report: &mut Report) -> Result<Document> {
cmobs.iter().copied().filter(|m| r.uid(*m, "OMFI:MOBJ:MobID").is_none_or(|id| !referenced.contains(&id))).collect()
};
for m in top {
// every composition spends from the budget too: a list of up to 65,535 repeated entries must not yield that many
if r.budget == 0 && !r.doc.compositions.is_empty() {
r.report.warn(BUDGET_WARNING);
break;
}
let comp = r.composition(m);
r.doc.compositions.push(comp);
r.budget = r.budget.saturating_sub(1);
}
if r.doc.compositions.is_empty() {
return Err(Error::Empty);
@@ -166,6 +210,13 @@ impl R<'_, '_> {
let slots = self.refs(m, "OMFI:MOBJ:Slots");
let mut na = 0;
for s in slots {
if self.budget == 0 {
self.report.warn(BUDGET_WARNING);
break;
}
// Every slot spends a unit, skipped ones too: a list of up to 65,535 repeated slots
// must not cost that much work in each of 65,535 repeated compositions.
self.budget -= 1;
let Some(seg) = self.r#ref(s, "OMFI:MSLT:Segment") else { continue };
let rate = self.rational(s, "OMFI:MSLT:EditRate").filter(|r| r.0 > 0 && r.1 > 0).unwrap_or((25, 1));
let kind = self.data_kind(seg);
@@ -213,13 +264,32 @@ impl R<'_, '_> {
fn segment(&mut self, seg: u32, rate: (i64, i64), depth: usize) -> Vec<CItem> {
let len = units_to_ticks(self.len(seg), rate.0, rate.1);
// Depth alone does not bound a graph that references the same component many times at
// every level, so each visit also spends from a per-document budget.
// A visit stopped by depth spends from it too.
if self.budget == 0 {
self.report.warn(BUDGET_WARNING);
return vec![CItem::Filler(len)];
}
self.budget -= 1;
if depth > 32 {
return vec![CItem::Filler(len)];
}
match &self.class(seg) {
b"SEQU" => {
let mut out = Vec::new();
let mut expanded = 0i64;
for c in self.refs(seg, "OMFI:SEQU:Components") {
if self.budget == 0 {
// the rest of the sequence keeps its duration as one gap, not a gap per reference
self.report.warn(BUDGET_WARNING);
let rest = self.len(seg).saturating_sub(expanded);
if rest > 0 {
out.push(CItem::Filler(units_to_ticks(rest, rate.0, rate.1)));
}
break;
}
expanded = expanded.saturating_add(self.len(c));
out.extend(self.segment(c, rate, depth + 1));
}
out
@@ -306,12 +376,66 @@ impl R<'_, '_> {
.find(|&s| self.r#ref(s, "OMFI:MSLT:TrackDesc").and_then(|t| self.u32(t, "OMFI:TRKD:TrackID")) == Some(track))
}
fn first_clip(&self, seg: u32) -> Option<u32> {
match &self.class(seg) {
b"SCLP" => Some(seg),
b"SEQU" => self.refs(seg, "OMFI:SEQU:Components").into_iter().find_map(|c| self.first_clip(c)),
_ => None,
/// First source clip under `seg`, depth-first; a sequence referencing itself (directly or
/// through a cycle) ends the search rather than the stack. `Err` when the search spent its
/// budget of visited components or queued references before finishing (the answer is unknown).
fn first_clip(&mut self, seg: u32) -> std::result::Result<Option<u32>, SearchLimit> {
if let Some(found) = self.clip_search.get(&seg) {
return *found;
}
let mut spent = 0;
let found = if self.search_budget == 0 {
Err(SearchLimit)
} else {
let visits = MAX_CLIP_SEARCH_VISITS.min(self.search_budget);
let pending = MAX_CLIP_SEARCH_PENDING.min(self.search_budget);
self.first_clip_within(seg, visits, pending, &mut spent)
};
self.search_budget = self.search_budget.saturating_sub(spent);
self.clip_search.insert(seg, found);
found
}
/// `spent` receives the visits plus queued references the search used.
fn first_clip_within(&self, seg: u32, max_visits: usize, max_pending: usize, spent: &mut usize) -> std::result::Result<Option<u32>, SearchLimit> {
let mut visited = HashSet::new();
let mut todo = vec![seg];
let mut queued = 1usize;
let found = Self::search_from(self, &mut visited, &mut todo, &mut queued, max_visits, max_pending);
*spent = visited.len().saturating_add(queued);
found
}
fn search_from(
&self,
visited: &mut HashSet<u32>,
todo: &mut Vec<u32>,
queued: &mut usize,
max_visits: usize,
max_pending: usize,
) -> std::result::Result<Option<u32>, SearchLimit> {
while let Some(seg) = todo.pop() {
if !visited.insert(seg) {
continue;
}
if visited.len() > max_visits {
return Err(SearchLimit);
}
match &self.class(seg) {
b"SCLP" => return Ok(Some(seg)),
b"SEQU" => {
let comps = self.refs(seg, "OMFI:SEQU:Components");
// sequences may share one component list, so queued references grow with expansions, not visits
*queued = queued.saturating_add(comps.len());
if *queued > max_pending {
return Err(SearchLimit);
}
todo.extend(comps.into_iter().rev());
}
_ => {}
}
}
Ok(None)
}
fn resolve(&mut self, id: Uid, track: u32, start: Tick, master: Option<String>, depth: usize) -> Option<(usize, Tick)> {
@@ -328,7 +452,13 @@ impl R<'_, '_> {
match &self.class(mob) {
b"MMOB" => {
let key = master.unwrap_or_else(|| id.iter().map(|b| format!("{b:02x}")).collect());
let clip = self.first_clip(seg)?;
let clip = match self.first_clip(seg) {
Ok(c) => c?,
Err(SearchLimit) => {
self.report.warn("a master mob is too large to search for its source clip (imported as a gap)");
return None;
}
};
let inner = units_to_ticks(self.i32(clip, "OMFI:SCLP:StartTime").unwrap_or(0), rate.0, rate.1);
let next = self.uid(clip, "OMFI:SCLP:SourceID")?;
let next_track = self.u32(clip, "OMFI:SCLP:SourceTrackID")?;
@@ -353,7 +483,9 @@ impl R<'_, '_> {
let file_rate = sr.filter(|r| r.0 > 0 && r.1 > 0).unwrap_or(rate);
let length = units_to_ticks(self.i32(desc, "OMFI:MDFL:Length").unwrap_or(0), file_rate.0, file_rate.1);
let summary = self.c.get(desc, "OMFI:WAVD:Summary").or_else(|| self.c.get(desc, "OMFI:AIFD:Summary")).unwrap_or_default();
let fmt = crate::pcm::parse_wav(&summary).or_else(|| crate::pcm::parse_aiff(&summary)).map(|(_, ch, sr, bits)| (ch as u32, sr, bits));
let fmt = craft_audio::essence_pcm::parse_wav(&summary)
.or_else(|| craft_audio::essence_pcm::parse_aiff(&summary))
.map(|(_, ch, sr, bits)| (ch as u32, sr, bits));
let mut path = None;
for l in self.refs(desc, "OMFI:MDES:Locator") {
let p = match &self.class(l) {
@@ -373,7 +505,8 @@ impl R<'_, '_> {
let (file_channels, sample_rate, bits) = fmt.unwrap_or((1, file_rate.0 as u32, 16));
let channel = (file_channels > 1 && sound_slots > 1).then(|| track.saturating_sub(1).min(file_channels - 1));
// timecode of the physical source
let tc = self.first_clip(seg).and_then(|clip| {
let first = self.first_clip(seg).ok().flatten();
let tc = first.and_then(|clip| {
let tid = self.uid(clip, "OMFI:SCLP:SourceID")?;
let tape = *self.mobs.get(&tid)?;
let (start_tc, fps, trate) = self.refs(tape, "OMFI:MOBJ:Slots").into_iter().find_map(|s| {
@@ -415,7 +548,7 @@ impl R<'_, '_> {
nested: None,
};
if let Some(d) = self.media.get(&id) {
if let Some((pcm, ch, sr, b)) = crate::pcm::parse_wav(d).or_else(|| crate::pcm::parse_aiff(d)) {
if let Some((pcm, ch, sr, b)) = craft_audio::essence_pcm::parse_wav(d).or_else(|| craft_audio::essence_pcm::parse_aiff(d)) {
s.embedded = Some(pcm);
s.file_channels = ch as u32;
s.channels = if s.channel.is_some() { 1 } else { ch as u32 };
@@ -437,3 +570,200 @@ impl R<'_, '_> {
}
}
}
#[cfg(test)]
mod tests {
use super::super::bento::Writer;
use super::*;
fn obj(w: &mut Writer, class: &[u8; 4]) -> u32 {
let id = w.new_object();
w.set(id, "OMFI:OOBJ:ObjClass", "omfi:ClassID", class);
id
}
fn list(w: &mut Writer, o: u32, p: &str, targets: &[u32]) {
let mut v = (targets.len() as u16).to_be_bytes().to_vec();
for t in targets {
v.extend_from_slice(&t.to_be_bytes());
}
w.set(o, p, "omfi:ObjRefArray", &v);
}
fn search(max_visits: usize, max_pending: usize, build: impl FnOnce(&mut Writer) -> u32) -> std::result::Result<Option<u32>, SearchLimit> {
let mut w = Writer::new();
let root = build(&mut w);
let bytes = w.finish();
let c = Container::open(&bytes).unwrap();
let mut report = Report::default();
let r = R {
c: &c,
report: &mut report,
be: true,
mobs: HashMap::new(),
media: HashMap::new(),
doc: Document::default(),
sources: HashMap::new(),
budget: 0,
clip_search: HashMap::new(),
search_budget: MAX_DOCUMENT_SEARCH_WORK,
};
r.first_clip_within(root, max_visits, max_pending, &mut 0)
}
#[test]
fn clip_search_reports_its_limits() {
// found within the limits
assert!(matches!(
search(10, 10, |w| {
let (s, c) = (obj(w, b"SEQU"), obj(w, b"SCLP"));
list(w, s, "OMFI:SEQU:Components", &[c]);
s
}),
Ok(Some(_))
));
// too many distinct components before any clip
assert!(
search(5, 1000, |w| {
let (s, f) = (obj(w, b"SEQU"), (0..20).map(|_| obj(w, b"FILL")).collect::<Vec<_>>());
list(w, s, "OMFI:SEQU:Components", &f);
s
})
.is_err()
);
// few visits, but sequences that each queue a long list of references
assert!(
search(1000, 500, |w| {
let f = obj(w, b"FILL");
let inner: Vec<u32> = (0..20).map(|_| obj(w, b"SEQU")).collect();
for &i in &inner {
list(w, i, "OMFI:SEQU:Components", &[f; 100]);
}
let s = obj(w, b"SEQU");
list(w, s, "OMFI:SEQU:Components", &inner);
s
})
.is_err()
);
// a search that ends without a clip is not a limit
assert!(matches!(search(10, 10, |w| obj(w, b"FILL")), Ok(None)));
}
#[test]
fn skipped_slots_spend_the_budget() {
let mut w = Writer::new();
let head = obj(&mut w, b"HEAD");
let cm = obj(&mut w, b"CMOB");
let slot = obj(&mut w, b"MSLT");
list(&mut w, cm, "OMFI:MOBJ:Slots", &[slot; 200]);
list(&mut w, head, "OMFI:HEAD:Mobs", &[cm]);
list(&mut w, head, "OMFI:HEAD:PrimaryMobs", &[cm]);
let bytes = w.finish();
let mut report = Report::default();
read_with_budget(&bytes, &mut report, 50).unwrap();
assert!(report.mentions(BUDGET_WARNING), "slots with no segment cost nothing before");
}
#[test]
fn a_source_clip_search_is_made_once_per_segment() {
let mut w = Writer::new();
let (s, c) = (obj(&mut w, b"SEQU"), obj(&mut w, b"SCLP"));
list(&mut w, s, "OMFI:SEQU:Components", &[c]);
let bytes = w.finish();
let c = Container::open(&bytes).unwrap();
let mut report = Report::default();
let mut r = R {
c: &c,
report: &mut report,
be: true,
mobs: HashMap::new(),
media: HashMap::new(),
doc: Document::default(),
sources: HashMap::new(),
budget: 0,
clip_search: HashMap::new(),
search_budget: MAX_DOCUMENT_SEARCH_WORK,
};
let first = r.first_clip(s).ok();
assert!(matches!(first, Some(Some(_))));
assert_eq!(r.clip_search.len(), 1);
assert_eq!(r.first_clip(s).ok(), first);
assert_eq!(r.clip_search.len(), 1);
}
#[test]
fn repeated_slots_and_compositions_spend_the_budget() {
let mut w = Writer::new();
let head = obj(&mut w, b"HEAD");
let cm = obj(&mut w, b"CMOB");
let dd = obj(&mut w, b"DDEF");
w.set(dd, "OMFI:DDEF:DataKindID", "omfi:UniqueName", b"omfi:data:Sound\0");
let fill = obj(&mut w, b"FILL");
w.set(fill, "OMFI:CPNT:DataKind", "omfi:ObjRef", &dd.to_be_bytes());
let slot = obj(&mut w, b"MSLT");
w.set(slot, "OMFI:MSLT:Segment", "omfi:ObjRef", &fill.to_be_bytes());
list(&mut w, cm, "OMFI:MOBJ:Slots", &[slot; 200]);
list(&mut w, head, "OMFI:HEAD:Mobs", &[cm]);
list(&mut w, head, "OMFI:HEAD:PrimaryMobs", &[cm; 200]);
let bytes = w.finish();
let mut report = Report::default();
let doc = read_with_budget(&bytes, &mut report, 50).unwrap();
let tracks: usize = doc.compositions.iter().map(|c| c.tracks.len()).sum();
assert!(tracks <= 50, "{tracks} tracks from a budget of 50");
assert!(doc.compositions.len() <= 2, "{} compositions", doc.compositions.len());
assert!(report.has_warnings());
}
fn with_reader<T>(bytes: &[u8], budget: usize, search_budget: usize, f: impl FnOnce(&mut R) -> T) -> (T, Report) {
let c = Container::open(bytes).unwrap();
let mut report = Report::default();
let mut r = R {
c: &c,
report: &mut report,
be: true,
mobs: HashMap::new(),
media: HashMap::new(),
doc: Document::default(),
sources: HashMap::new(),
budget,
clip_search: HashMap::new(),
search_budget,
};
let out = f(&mut r);
(out, report)
}
#[test]
fn depth_limited_components_spend_the_budget() {
// a chain 33 sequences deep whose last one repeats a depth-limited sequence many times
let mut w = Writer::new();
let deep = obj(&mut w, b"SEQU");
let chain: Vec<u32> = (0..33).map(|_| obj(&mut w, b"SEQU")).collect();
for pair in chain.windows(2) {
list(&mut w, pair[0], "OMFI:SEQU:Components", &[pair[1]]);
}
list(&mut w, chain[32], "OMFI:SEQU:Components", &[deep; 1000]);
let bytes = w.finish();
let (items, report) = with_reader(&bytes, 100, MAX_DOCUMENT_SEARCH_WORK, |r| r.segment(chain[0], (48_000, 1), 0));
assert!(items.len() <= 100, "{} items from a budget of 100", items.len());
assert!(report.mentions(BUDGET_WARNING));
}
#[test]
fn source_clip_searches_share_a_document_budget() {
// distinct roots over one shared clip-free graph
let mut w = Writer::new();
let fills: Vec<u32> = (0..50).map(|_| obj(&mut w, b"FILL")).collect();
let shared = obj(&mut w, b"SEQU");
list(&mut w, shared, "OMFI:SEQU:Components", &fills);
let roots: Vec<u32> = (0..30).map(|_| obj(&mut w, b"SEQU")).collect();
for &root in &roots {
list(&mut w, root, "OMFI:SEQU:Components", &[shared]);
}
let bytes = w.finish();
let (results, _) = with_reader(&bytes, 0, 500, |r| roots.iter().map(|&root| r.first_clip(root)).collect::<Vec<_>>());
assert!(matches!(results[0], Ok(None)), "the first search fits");
assert!(results.iter().any(|r| r.is_err()), "later searches run out of the shared budget");
let (results, _) = with_reader(&bytes, 0, MAX_DOCUMENT_SEARCH_WORK, |r| roots.iter().map(|&root| r.first_clip(root)).collect::<Vec<_>>());
assert!(results.iter().all(|r| matches!(r, Ok(None))));
}
}
-5
View File
@@ -4,8 +4,3 @@
pub(crate) fn parse_wav(b: &[u8]) -> Option<(Vec<u8>, u16, u32, u16)> {
craft_audio::wav_pcm(b).map(|p| (p.data, p.channels, p.sample_rate, p.bits))
}
/// The same for an AIFF / AIFF-C (`NONE`, `twos`, `sowt`) file.
pub(crate) fn parse_aiff(b: &[u8]) -> Option<(Vec<u8>, u16, u32, u16)> {
craft_audio::aiff_pcm(b).map(|p| (p.data, p.channels, p.sample_rate, p.bits))
}
+86 -4
View File
@@ -70,6 +70,9 @@ pub trait AtomicFs {
fn sync_dir(&self, dir: &Path) -> io::Result<()>;
/// Give the open temporary file its final permissions.
fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()>;
/// Put the open temporary file in group `gid` (Unix only).
#[cfg(unix)]
fn set_group(&self, file: &File, gid: u32) -> io::Result<()>;
}
/// The production file system implementation.
@@ -126,6 +129,11 @@ impl AtomicFs for RealFs {
fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()> {
file.set_permissions(perms)
}
#[cfg(unix)]
fn set_group(&self, file: &File, gid: u32) -> io::Result<()> {
std::os::unix::fs::fchown(file, None, Some(gid))
}
}
/// Flush `file` to stable storage (`sync_all`).
@@ -342,10 +350,29 @@ fn split(target: &Path, path: &Path) -> io::Result<(PathBuf, String)> {
Ok((dir, name.to_string_lossy().into_owned()))
}
/// Create a temporary file in `dir`, fill it with `fill`, give it the permissions of the file it
/// replaces (`replaced`, Unix) and flush it. Permission restoration is skipped when the mode
/// already matches after `fill`. A leftover file with the same name is skipped. When any step
/// fails, the temporary file is removed.
/// Give `perms` the replaced file's group, or drop its group bits when the stage cannot join
/// that group. A stage already in the group needs no fchown, which some filesystems reject even
/// as a no-op, and dropping the bits there would narrow a mode the replaced file granted.
#[cfg(unix)]
fn adopt_group(fs: &dyn AtomicFs, file: &File, stage_gid: u32, replaced_gid: u32, perms: std::fs::Permissions) -> io::Result<std::fs::Permissions> {
use std::os::unix::fs::PermissionsExt;
if perms.mode() & 0o070 == 0 || stage_gid == replaced_gid {
return Ok(perms);
}
if fs.set_group(file, replaced_gid).is_ok() {
return Ok(perms);
}
let mut narrowed = perms;
narrowed.set_mode(narrowed.mode() & !0o070);
Ok(narrowed)
}
/// Create a temporary file in `dir`, fill it with `fill`, give it the permissions and group of
/// the file it replaces (`replaced`, Unix) and flush it. Permission restoration is skipped when
/// the mode already matches after `fill`; the group bits are dropped when the file cannot be put
/// in the replaced file's group, so they never open the file to a group that was not granted
/// them. A leftover file with the same name is skipped. When any step fails, the temporary file
/// is removed.
fn stage(
fs: &dyn AtomicFs,
dir: &Path,
@@ -383,6 +410,14 @@ fn stage(
if (file.metadata()?.permissions().mode() & 0o7777) == (p.mode() & 0o7777) {
return Ok(());
}
// The group bits belong to the replaced file's group, which a new
// inode need not be in (setgid directory, another primary group).
if let Some(replaced) = replaced {
let stage_gid = std::os::unix::fs::MetadataExt::gid(&file.metadata()?);
let replaced_gid = std::os::unix::fs::MetadataExt::gid(replaced);
let perms = adopt_group(fs, &file, stage_gid, replaced_gid, p)?;
return fs.set_permissions(&file, perms);
}
}
fs.set_permissions(&file, p)
})
@@ -678,6 +713,9 @@ mod tests {
fixed_mode: Option<u32>,
fail_sync_dir: bool,
fail_normal_create: bool,
/// Simulate a filesystem that refuses the stage's group change.
#[cfg(unix)]
fail_set_group: bool,
normal_collisions: Cell<u32>,
/// Another process creates the target just before the hard link.
created_meanwhile: Option<&'static [u8]>,
@@ -750,6 +788,15 @@ mod tests {
}
/// Record permission restoration and payload length, then inject a configured error
/// or delegate the mode change to the real filesystem.
#[cfg(unix)]
fn set_group(&self, file: &File, gid: u32) -> io::Result<()> {
self.events.borrow_mut().push("set_group");
if self.fail_set_group {
return Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected: set_group failed"));
}
RealFs.set_group(file, gid)
}
fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()> {
self.events.borrow_mut().push("set_permissions");
#[cfg(unix)]
@@ -1090,6 +1137,36 @@ mod tests {
Ok(())
}
#[cfg(unix)]
#[test]
fn group_bits_are_dropped_when_the_stage_cannot_join_the_replaced_group() -> io::Result<()> {
use std::os::unix::fs::{MetadataExt, PermissionsExt};
let d = TempDir::new("group-fallback");
let file = File::create(d.0.join("stage"))?;
let gid = file.metadata()?.gid();
let elsewhere = gid.wrapping_add(1);
let fs = Faulty { fail_set_group: true, ..Default::default() };
let mode = adopt_group(&fs, &file, gid, elsewhere, std::fs::Permissions::from_mode(0o640))?.mode();
assert_eq!(mode & 0o777, 0o600, "group bits are dropped when the group cannot be joined");
assert!(fs.events.borrow().contains(&"set_group"));
// No group bits: the group change is never attempted.
let fs = Faulty { fail_set_group: true, ..Default::default() };
let mode = adopt_group(&fs, &file, gid, elsewhere, std::fs::Permissions::from_mode(0o600))?.mode();
assert_eq!(mode & 0o777, 0o600);
assert!(!fs.events.borrow().contains(&"set_group"));
// A stage already in the replaced file's group keeps its bits untouched.
let fs = Faulty { fail_set_group: true, ..Default::default() };
let mode = adopt_group(&fs, &file, gid, gid, std::fs::Permissions::from_mode(0o640))?.mode();
assert_eq!(mode & 0o777, 0o640);
assert!(!fs.events.borrow().contains(&"set_group"));
assert_no_temp(&d.0);
Ok(())
}
#[cfg(unix)]
#[test]
fn normal_policy_preserves_existing_modes_with_private_staging() -> io::Result<()> {
@@ -1102,6 +1179,11 @@ mod tests {
let fs = Faulty { fail_normal_create: true, ..Default::default() };
replace_with_options(&fs, NO_RETRY, &p, NewFilePermissions::PlatformDefault, |f| f.write_all(b"replacement"))?;
assert_eq!(std::fs::metadata(&p)?.permissions().mode() & 0o777, mode);
assert_eq!(
std::os::unix::fs::MetadataExt::gid(&std::fs::metadata(&p)?),
std::os::unix::fs::MetadataExt::gid(&d.0.metadata()?),
"kept in the directory's group"
);
assert!(!fs.events.borrow().contains(&"create_new_normal"));
assert_eq!(*fs.created_modes.borrow(), [0o600]);
}
+189
View File
@@ -0,0 +1,189 @@
//! Compatibility WAVE and AIFF wrappers for embedded PCM essence in interchange files.
//! PCM inside the model is interleaved little-endian signed integers (8-bit unsigned for WAVE).
pub use crate::{pcm_aiff_header as aiff_header, pcm_wav_file as wav_file, pcm_wav_header as wav_header};
/// PCM, channels, sample rate and bits of a WAVE file (integer PCM only).
pub fn parse_wav(b: &[u8]) -> Option<(Vec<u8>, u16, u32, u16)> {
if b.len() < 12 || &b[..4] != b"RIFF" || &b[8..12] != b"WAVE" {
return None;
}
let mut at = 12;
let mut fmt = None;
while at + 8 <= b.len() {
let id = &b[at..at + 4];
let len = u32::from_le_bytes(b[at + 4..at + 8].try_into().ok()?) as usize;
let body = &b[at + 8..(at + 8).saturating_add(len).min(b.len())];
if id == b"fmt " && body.len() >= 16 {
let tag = u16::from_le_bytes([body[0], body[1]]);
let ch = u16::from_le_bytes([body[2], body[3]]);
let sr = u32::from_le_bytes(body[4..8].try_into().ok()?);
let bits = u16::from_le_bytes([body[14], body[15]]);
if tag != 1 && tag != 0xFFFE {
return None;
}
if tag == 0xFFFE {
// The first two bytes of the sub-format GUID carry the real format code.
let sub = body.get(24..26)?;
if u16::from_le_bytes([sub[0], sub[1]]) != 1 {
return None;
}
}
fmt = Some((ch, sr, bits));
} else if id == b"data" {
let (ch, sr, bits) = fmt?;
return Some((body.to_vec(), ch, sr, bits));
}
at = at.checked_add(8usize.checked_add(len)?.checked_add(len & 1)?)?;
}
None
}
/// A complete AIFF file (big-endian PCM) from little-endian PCM.
pub fn aiff_file(pcm: &[u8], channels: u16, sample_rate: u32, bits: u16) -> Vec<u8> {
let bps = bits.div_ceil(8) as usize;
let frames = pcm.len() / (bps * channels.max(1) as usize).max(1);
let mut v = aiff_header(frames as u32, channels, sample_rate, bits);
for s in pcm.chunks_exact(bps.max(1)) {
if bps == 1 {
v.push(s[0] ^ 0x80); // WAVE 8-bit is unsigned, AIFF signed
} else {
v.extend(s.iter().rev());
}
}
if (v.len() - 8) & 1 == 1 {
v.push(0);
}
v
}
/// PCM (converted to little-endian), channels, sample rate and bits of an AIFF / AIFF-C (`NONE`
/// / `twos` / `sowt`) file.
pub fn parse_aiff(b: &[u8]) -> Option<(Vec<u8>, u16, u32, u16)> {
if b.len() < 12 || &b[..4] != b"FORM" || !(&b[8..12] == b"AIFF" || &b[8..12] == b"AIFC") {
return None;
}
let aifc = &b[8..12] == b"AIFC";
let mut at = 12;
let mut comm = None;
while at + 8 <= b.len() {
let id = &b[at..at + 4];
let len = u32::from_be_bytes(b[at + 4..at + 8].try_into().ok()?) as usize;
let body = &b[at + 8..(at + 8).saturating_add(len).min(b.len())];
if id == b"COMM" && body.len() >= 18 {
let ch = u16::from_be_bytes([body[0], body[1]]);
let bits = u16::from_be_bytes([body[6], body[7]]);
let sr = from_extended(body[8..18].try_into().ok()?).round() as u32;
// AIFF has no compression code (trailing COMM bytes mean nothing); AIFF-C must name one
// of the integer PCM codes, or the samples are not integer PCM at all
let little = if aifc {
match body.get(18..22)? {
b"NONE" | b"twos" => false,
b"sowt" => true,
_ => return None,
}
} else {
false
};
comm = Some((ch, sr, bits, little));
} else if id == b"SSND" && body.len() >= 8 {
let (ch, sr, bits, little) = comm?;
let off = u32::from_be_bytes(body[..4].try_into().ok()?) as usize;
let data = body.get(8usize.checked_add(off)?..)?;
let bps = bits.div_ceil(8) as usize;
let mut pcm = Vec::with_capacity(data.len());
for s in data.chunks_exact(bps.max(1)) {
if bps == 1 {
pcm.push(s[0] ^ 0x80);
} else if little {
pcm.extend_from_slice(s);
} else {
pcm.extend(s.iter().rev());
}
}
return Some((pcm, ch, sr, bits));
}
at = at.checked_add(8usize.checked_add(len)?.checked_add(len & 1)?)?;
}
None
}
fn from_extended(b: [u8; 10]) -> f64 {
let e = (u16::from_be_bytes([b[0], b[1]]) & 0x7FFF) as i32;
let m = u64::from_be_bytes(b[2..10].try_into().unwrap_or([0; 8]));
if e == 0 && m == 0 {
return 0.0;
}
m as f64 / (1u64 << 63) as f64 * 2f64.powi(e - 16383)
}
#[cfg(test)]
mod tests {
/// A mutated EDL whose clip ran for days produced an OMF descriptor for more than 4 GiB of
/// PCM: the RIFF size field overflowed ("attempt to add with overflow").
#[test]
fn huge_wav_header_saturates() {
let h = super::wav_header(u32::MAX, 2, u32::MAX, 24);
assert_eq!(&h[4..8], &u32::MAX.to_le_bytes());
}
use super::*;
#[test]
fn accepts_truncated_essence_summaries() {
let mut wav = wav_file(&[1, 2, 3, 4], 1, 48_000, 16);
wav.truncate(46);
assert_eq!(parse_wav(&wav), Some((vec![1, 2], 1, 48_000, 16)));
let mut aiff = aiff_file(&[1, 2, 3, 4], 1, 48_000, 16);
aiff.truncate(56);
assert_eq!(parse_aiff(&aiff), Some((vec![1, 2], 1, 48_000, 16)));
}
#[test]
fn wav_and_aiff_round_trip() {
let pcm: Vec<u8> = (0..48u8).collect(); // 8 stereo 24-bit frames
let w = wav_file(&pcm, 2, 48_000, 24);
assert_eq!(parse_wav(&w), Some((pcm.clone(), 2, 48_000, 24)));
let a = aiff_file(&pcm, 2, 44_100, 24);
assert_eq!(parse_aiff(&a), Some((pcm.clone(), 2, 44_100, 24)));
let p16: Vec<u8> = (0..32u8).collect();
assert_eq!(parse_aiff(&aiff_file(&p16, 1, 96_000, 16)), Some((p16, 1, 96_000, 16)));
assert!(parse_wav(b"RIFF").is_none());
assert!(parse_aiff(&a[..30]).is_none());
for cut in 0..w.len() {
let _ = parse_wav(&w[..cut]);
let _ = parse_aiff(&a[..cut.min(a.len())]);
}
}
#[test]
fn aifc_needs_an_integer_pcm_compression_code() {
let file = |kind: &[u8; 4], code: &[u8]| {
let mut comm = vec![0, 1, 0, 0, 0, 1, 0, 16];
comm.extend_from_slice(&[0x40, 0x0E, 0xBB, 0x80, 0, 0, 0, 0, 0, 0]);
comm.extend_from_slice(code);
let mut body = kind.to_vec();
body.extend_from_slice(b"COMM");
body.extend_from_slice(&(comm.len() as u32).to_be_bytes());
body.extend_from_slice(&comm);
if comm.len() & 1 == 1 {
body.push(0);
}
body.extend_from_slice(b"SSND");
body.extend_from_slice(&10u32.to_be_bytes());
body.extend_from_slice(&[0; 8]);
body.extend_from_slice(&[0x12, 0x34]);
let mut v = b"FORM".to_vec();
v.extend_from_slice(&(body.len() as u32).to_be_bytes());
v.extend_from_slice(&body);
v
};
assert_eq!(parse_aiff(&file(b"AIFC", b"NONE")).map(|p| p.0), Some(vec![0x34, 0x12]));
assert_eq!(parse_aiff(&file(b"AIFC", b"twos")).map(|p| p.0), Some(vec![0x34, 0x12]));
assert_eq!(parse_aiff(&file(b"AIFC", b"sowt")).map(|p| p.0), Some(vec![0x12, 0x34]));
assert!(parse_aiff(&file(b"AIFC", b"fl32")).is_none(), "float samples are not integer PCM");
assert!(parse_aiff(&file(b"AIFC", b"")).is_none(), "AIFF-C without a compression code");
// plain AIFF ignores trailing COMM bytes
assert_eq!(parse_aiff(&file(b"AIFF", b"sowt")).map(|p| p.0), Some(vec![0x34, 0x12]));
}
}
+8
View File
@@ -76,6 +76,11 @@ pub mod wav_markers;
))]
mod write;
/// PCM WAVE and AIFF wrappers for interchange essence.
#[cfg(feature = "pcm-encode")]
pub mod essence_pcm;
/// Streaming WAVE and AIFF headers and sample packing.
pub mod pcm_export;
/// Interleaved PCM packet decoding.
pub mod pcm_interleaved;
/// Range-backed PCM WAVE access and a 16-bit PCM writer.
@@ -767,3 +772,6 @@ mod tests {
assert!(matches!(e, AudioError::Encode(_)), "{e}");
}
}
/// DVD and Blu-ray LPCM packet decoding.
pub mod lpcm;
+118
View File
@@ -0,0 +1,118 @@
//! DVD-Video and Blu-ray LPCM packet grammar and sample decoding.
/// Blu-ray / AVCHD LPCM packet header (4 bytes before the samples).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BlurayLpcm {
/// Sample rate in hertz.
pub sample_rate: u32,
/// Number of decoded channels.
pub channels: usize,
/// Significant bits per sample.
pub bits: u32,
}
/// Channels of each channel_assignment code (mono, stereo, 3/0, 2/1, 3/1, 2/2, 3/2, 3/2+LFE,
/// 3/4, 3/4+LFE).
const BD_LPCM_CHANNELS: [usize; 12] = [0, 1, 0, 2, 3, 3, 4, 4, 5, 6, 7, 8];
/// Parse and validate the four-byte Blu-ray LPCM header.
pub fn bluray_lpcm_header(p: &[u8]) -> Option<BlurayLpcm> {
if p.len() < 4 {
return None;
}
let channels = *BD_LPCM_CHANNELS.get((p[2] >> 4) as usize).filter(|&&c| c > 0)?;
let sample_rate = match p[2] & 15 {
1 => 48_000,
4 => 96_000,
5 => 192_000,
_ => return None,
};
let bits = match p[3] >> 6 {
1 => 16,
2 => 20,
3 => 24,
_ => return None,
};
Some(BlurayLpcm { sample_rate, channels, bits })
}
/// Decode one Blu-ray LPCM packet (big-endian; channels padded to an even count; 20-bit
/// samples are stored in 24 bits).
pub fn decode_bluray_lpcm(p: &[u8]) -> Option<Vec<Vec<f32>>> {
let h = bluray_lpcm_header(p)?;
let coded = (h.channels + 1) & !1;
let bps = if h.bits == 16 { 2 } else { 3 };
let data = &p[4..];
let n = data.len() / (coded * bps);
let mut out = vec![Vec::with_capacity(n); h.channels];
for k in 0..n {
for (c, o) in out.iter_mut().enumerate() {
let at = (k * coded + c) * bps;
let v = if bps == 2 {
i16::from_be_bytes([data[at], data[at + 1]]) as f32 / 32768.0
} else {
(i32::from_be_bytes([data[at], data[at + 1], data[at + 2], 0]) >> 8) as f32 / 8_388_608.0
};
o.push(v);
}
}
Some(out)
}
/// Bytes per two sample frames of DVD LPCM. The caller must bound `channels` to the DVD channel range.
pub fn dvd_lpcm_group_bytes(channels: usize, bits: u32) -> usize {
match bits {
16 => 4 * channels,
20 => 5 * channels,
_ => 6 * channels,
}
}
/// Decode DVD-Video LPCM (big-endian). 16-bit samples are interleaved; 20- and 24-bit samples
/// come in groups of two frames: the upper 16 bits of all the group's samples, then their low
/// 4 / 8 bits. The caller must bound `channels` to the DVD channel range.
pub fn decode_dvd_lpcm(data: &[u8], channels: usize, bits: u32) -> Vec<Vec<f32>> {
let ch = channels.max(1);
let group = dvd_lpcm_group_bytes(ch, bits);
let groups = data.len() / group;
let mut out = vec![Vec::with_capacity(groups * 2); ch];
for g in 0..groups {
let b = &data[g * group..(g + 1) * group];
for f in 0..2 {
for (c, o) in out.iter_mut().enumerate() {
let k = f * ch + c;
let hi = i16::from_be_bytes([b[2 * k], b[2 * k + 1]]) as i32;
let v = match bits {
16 => hi as f32 / 32768.0,
20 => {
let nib = b[4 * ch + k / 2];
let lo = if k.is_multiple_of(2) { nib >> 4 } else { nib & 15 } as i32;
((hi << 4) | lo) as f32 / 524_288.0
}
_ => ((hi << 8) | b[4 * ch + k] as i32) as f32 / 8_388_608.0,
};
o.push(v);
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bluray_header_and_even_channel_padding() {
let packet = [0, 0, 0x31, 0x40, 0x40, 0, 0xc0, 0];
assert_eq!(bluray_lpcm_header(&packet), Some(BlurayLpcm { sample_rate: 48_000, channels: 2, bits: 16 }));
assert_eq!(decode_bluray_lpcm(&packet), Some(vec![vec![0.5], vec![-0.5]]));
assert_eq!(decode_bluray_lpcm(&packet[..3]), None);
}
#[test]
fn dvd_lpcm_16_20_and_24_bit_groups() {
assert_eq!(decode_dvd_lpcm(&[0x40, 0, 0xc0, 0], 1, 16), vec![vec![0.5, -0.5]]);
assert_eq!(decode_dvd_lpcm(&[0x40, 0, 0xc0, 0, 0], 1, 20), vec![vec![0.5, -0.5]]);
assert_eq!(decode_dvd_lpcm(&[0x40, 0, 0xc0, 0, 0, 0], 1, 24), vec![vec![0.5, -0.5]]);
assert_eq!(decode_dvd_lpcm(&[1, 2, 3], 1, 16), vec![Vec::<f32>::new()]);
}
}
+287
View File
@@ -0,0 +1,287 @@
//! Audio-only files: WAV (RIFF, little-endian PCM; RF64 past 4 GiB) and AIFF (big-endian PCM),
//! 16, 24 or 32-bit integer or 32-bit float ([`SampleFormat`]), for streaming export.
//! Float WAV is `WAVE_FORMAT_IEEE_FLOAT` with a `fact` chunk; float AIFF is AIFF-C (`fl32`).
//!
//! The header is written first from the known length (`header`), then the samples in chunks
//! (`encode`) and the pad byte (`pad`), so an export streams to disk instead of building the
//! file in memory.
/// PCM representation in an exported file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SampleFormat {
/// 16-bit signed integer.
Int16,
/// 24-bit signed integer.
Int24,
/// 32-bit signed integer.
Int32,
/// 32-bit IEEE float.
Float32,
}
impl SampleFormat {
/// Bits per sample.
pub fn bits(self) -> u16 {
match self {
Self::Int16 => 16,
Self::Int24 => 24,
Self::Int32 | Self::Float32 => 32,
}
}
/// Bytes per sample.
pub fn bytes(self) -> usize {
usize::from(self.bits() / 8)
}
/// Whether this is a floating point format.
pub fn is_float(self) -> bool {
self == Self::Float32
}
/// Clip and quantize one sample with symmetric integer full scale; NaN becomes silence.
pub fn quantise(self, s: f32) -> i32 {
let s = s.clamp(-1.0, 1.0);
match self {
Self::Int16 => (s * 32_767.0).round() as i32,
Self::Int24 => (s * 8_388_607.0).round() as i32,
Self::Int32 => (f64::from(s) * 2_147_483_647.0).round() as i32,
Self::Float32 => 0,
}
}
/// Sanitize a floating sample: NaN becomes silence, infinity becomes the largest finite value.
pub fn float(s: f32) -> f32 {
if s.is_nan() { 0.0 } else { s.clamp(f32::MIN, f32::MAX) }
}
}
/// The container of an audio-only export.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PcmContainer {
/// RIFF/WAVE or RF64.
Wav,
/// AIFF or AIFF-C.
Aiff,
}
/// Bytes of sample data for `frames` frames, or None when that does not fit 64 bits.
fn data_len(frames: u64, channels: u16, format: SampleFormat) -> Option<u64> {
frames.checked_mul(u64::from(channels))?.checked_mul(format.bytes() as u64)
}
/// The pad byte after an odd-sized data chunk (RIFF and AIFF chunks are word-aligned).
pub fn pad(frames: u64, channels: u16, format: SampleFormat) -> &'static [u8] {
if data_len(frames, channels, format).is_some_and(|n| n & 1 == 1) { &[0] } else { &[] }
}
/// `KSDATAFORMAT_SUBTYPE_PCM` / `_IEEE_FLOAT` after their first two bytes (the format tag).
const SUBTYPE_TAIL: [u8; 14] = [0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71];
/// AIFF-C format version 1 (`FVER`).
const AIFC_VERSION_1: u32 = 0xA280_5140;
/// The AIFF-C compression name of `fl32`, as a Pascal string of even length.
const FL32_NAME: &[u8] = b"\x1532-bit floating point";
/// Everything before the samples of a file of `frames` frames. A WAV whose RIFF size would not
/// fit 32 bits (4 GiB: 24-bit 5.1 at 96 kHz after about 41 minutes) is written as RF64 (EBU Tech
/// 3306), with the 64-bit sizes in a `ds64` chunk. AIFF has no 64-bit form, so a longer AIFF is
/// an error naming WAV instead.
pub fn header(container: PcmContainer, channels: u16, sample_rate: u32, format: SampleFormat, frames: u64) -> Result<Vec<u8>, String> {
let too_long = || "the audio is too long to write".to_string();
if channels == 0 {
return Err("audio needs at least one channel".into());
}
if sample_rate == 0 {
return Err("audio needs a sample rate".into());
}
let bits = format.bits();
let bps = bits / 8;
let float = format.is_float();
let data = data_len(frames, channels, format).ok_or_else(too_long)?;
let block_align = channels.checked_mul(bps).ok_or("too many audio channels")?;
match container {
PcmContainer::Wav => {
let byte_rate =
u32::try_from(u64::from(sample_rate) * u64::from(block_align)).map_err(|_| "the audio sample rate is too high".to_string())?;
let ext = channels > 2;
// plain PCM has no cbSize; IEEE float has an empty one
let fmt_len: u32 = if ext {
40
} else if float {
18
} else {
16
};
// every format but integer PCM has a `fact` chunk (the frame count; RF64: in `ds64`)
let fact_len: u64 = if float { 12 } else { 0 };
let padded = data.checked_add(data & 1).ok_or_else(too_long)?;
// "WAVE" + fmt chunk + fact chunk + data chunk header + samples
let riff = (4 + 8 + u64::from(fmt_len) + fact_len + 8).checked_add(padded).ok_or_else(too_long)?;
let rf64 = riff > u64::from(u32::MAX);
let mut v = Vec::with_capacity(100);
if rf64 {
const DS64: u64 = 8 + 28;
v.extend_from_slice(b"RF64");
v.extend_from_slice(&u32::MAX.to_le_bytes());
v.extend_from_slice(b"WAVEds64");
v.extend_from_slice(&28u32.to_le_bytes());
v.extend_from_slice(&riff.checked_add(DS64).ok_or_else(too_long)?.to_le_bytes());
v.extend_from_slice(&data.to_le_bytes());
v.extend_from_slice(&frames.to_le_bytes());
v.extend_from_slice(&0u32.to_le_bytes()); // no table entries
} else {
v.extend_from_slice(b"RIFF");
v.extend_from_slice(&(riff as u32).to_le_bytes());
v.extend_from_slice(b"WAVE");
}
let tag: u16 = if float { 3 } else { 1 };
v.extend_from_slice(b"fmt ");
v.extend_from_slice(&fmt_len.to_le_bytes());
v.extend_from_slice(&(if ext { 0xFFFE } else { tag }).to_le_bytes());
v.extend_from_slice(&channels.to_le_bytes());
v.extend_from_slice(&sample_rate.to_le_bytes());
v.extend_from_slice(&byte_rate.to_le_bytes());
v.extend_from_slice(&block_align.to_le_bytes());
v.extend_from_slice(&bits.to_le_bytes());
if ext {
// cbSize, valid bits, channel mask, KSDATAFORMAT_SUBTYPE_PCM / _IEEE_FLOAT
v.extend_from_slice(&22u16.to_le_bytes());
v.extend_from_slice(&bits.to_le_bytes());
let mask: u32 = if channels == 6 { 0x3F } else { 0 };
v.extend_from_slice(&mask.to_le_bytes());
v.extend_from_slice(&tag.to_le_bytes());
v.extend_from_slice(&SUBTYPE_TAIL);
} else if float {
v.extend_from_slice(&0u16.to_le_bytes());
}
if float {
v.extend_from_slice(b"fact");
v.extend_from_slice(&4u32.to_le_bytes());
v.extend_from_slice(&(if rf64 { u32::MAX } else { u32::try_from(frames).unwrap_or(u32::MAX) }).to_le_bytes());
}
v.extend_from_slice(b"data");
v.extend_from_slice(&(if rf64 { u32::MAX } else { data as u32 }).to_le_bytes());
Ok(v)
}
PcmContainer::Aiff => {
let aiff_too_long = || "AIFF holds at most 4 GB of audio: export WAV, which has no such limit".to_string();
let frames32 = u32::try_from(frames).map_err(|_| aiff_too_long())?;
// SSND: offset + block size + samples
let ssnd = u32::try_from(data.checked_add(8).ok_or_else(aiff_too_long)?).map_err(|_| aiff_too_long())?;
// floats need AIFF-C: a version chunk, and the compression type and name in COMM
let comm: u32 = if float { 18 + 4 + FL32_NAME.len() as u32 } else { 18 };
let fver: u32 = if float { 8 + 4 } else { 0 };
let form = (4u32 + fver + (8 + comm))
.checked_add(8)
.and_then(|n| n.checked_add(ssnd))
.and_then(|n| n.checked_add(ssnd & 1))
.ok_or_else(aiff_too_long)?;
let mut v = Vec::with_capacity(90);
v.extend_from_slice(b"FORM");
v.extend_from_slice(&form.to_be_bytes());
if float {
v.extend_from_slice(b"AIFCFVER");
v.extend_from_slice(&4u32.to_be_bytes());
v.extend_from_slice(&AIFC_VERSION_1.to_be_bytes());
} else {
v.extend_from_slice(b"AIFF");
}
v.extend_from_slice(b"COMM");
v.extend_from_slice(&comm.to_be_bytes());
v.extend_from_slice(&channels.to_be_bytes());
v.extend_from_slice(&frames32.to_be_bytes());
v.extend_from_slice(&bits.to_be_bytes());
v.extend_from_slice(&extended(sample_rate));
if float {
v.extend_from_slice(b"fl32");
v.extend_from_slice(FL32_NAME);
}
v.extend_from_slice(b"SSND");
v.extend_from_slice(&ssnd.to_be_bytes());
v.extend_from_slice(&0u32.to_be_bytes()); // offset
v.extend_from_slice(&0u32.to_be_bytes()); // block size
Ok(v)
}
}
}
/// Append interleaved samples in `format` (little-endian for WAV, big-endian for AIFF).
pub fn encode(container: PcmContainer, interleaved: &[f32], format: SampleFormat, out: &mut Vec<u8>) {
let bps = format.bytes();
out.reserve(interleaved.len().saturating_mul(bps));
for &s in interleaved {
let q = if format.is_float() { SampleFormat::float(s).to_bits() as i32 } else { format.quantise(s) };
match container {
PcmContainer::Wav => out.extend_from_slice(q.to_le_bytes().get(..bps).unwrap_or_default()),
PcmContainer::Aiff => out.extend_from_slice(q.to_be_bytes().get(4 - bps..).unwrap_or_default()),
}
}
}
/// A whole file in memory (short audio; exports stream with [`header`] and [`encode`]).
fn write_whole(container: PcmContainer, interleaved: &[f32], channels: u16, sample_rate: u32, format: SampleFormat) -> Result<Vec<u8>, String> {
let per_frame = usize::from(channels.max(1));
if !interleaved.len().is_multiple_of(per_frame) {
return Err("the samples do not make whole frames".into());
}
let frames = (interleaved.len() / per_frame) as u64;
let mut v = header(container, channels, sample_rate, format, frames)?;
encode(container, interleaved, format, &mut v);
v.extend_from_slice(pad(frames, channels, format));
Ok(v)
}
/// A RIFF/WAVE file of interleaved samples. More than two channels are written as
/// `WAVE_FORMAT_EXTENSIBLE` with the speaker mask of the layout (6 channels: L, R, C, LFE, Ls, Rs
/// = `0x3F`).
pub fn write_wav(interleaved: &[f32], channels: u16, sample_rate: u32, format: SampleFormat) -> Result<Vec<u8>, String> {
write_whole(PcmContainer::Wav, interleaved, channels, sample_rate, format)
}
/// IEEE 754 80-bit extended encoding of a sample rate (AIFF `COMM`).
pub fn extended(rate: u32) -> [u8; 10] {
let mut out = [0u8; 10];
if rate == 0 {
return out;
}
let shift = rate.leading_zeros();
let mant = (rate as u64) << (32 + shift);
let exp = 16383 + 31 - shift as u16;
out[..2].copy_from_slice(&exp.to_be_bytes());
out[2..].copy_from_slice(&mant.to_be_bytes());
out
}
/// An AIFF file (`FORM`/`AIFF`, `COMM` + `SSND`; AIFF-C for floats) of interleaved samples.
pub fn write_aiff(interleaved: &[f32], channels: u16, sample_rate: u32, format: SampleFormat) -> Result<Vec<u8>, String> {
write_whole(PcmContainer::Aiff, interleaved, channels, sample_rate, format)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn streaming_formats_preserve_samples_and_bounds() {
let samples = [1.0, -1.0, f32::NAN];
let wav = write_wav(&samples, 1, 48_000, SampleFormat::Int24).unwrap();
assert_eq!(&wav[..4], b"RIFF");
assert_eq!(&wav[44..53], &[255, 255, 127, 1, 0, 128, 0, 0, 0]);
let h = header(PcmContainer::Wav, 6, 96_000, SampleFormat::Int24, 96_000 * 3600).unwrap();
assert_eq!(&h[..4], b"RF64");
assert!(header(PcmContainer::Aiff, 2, 48_000, SampleFormat::Int24, u64::MAX).is_err());
let aiff = write_aiff(&[0.25, -3.0], 1, 44_100, SampleFormat::Float32).unwrap();
assert_eq!(&aiff[8..12], b"AIFC");
assert_eq!(&aiff[aiff.len() - 8..], [0.25f32.to_be_bytes(), (-3.0f32).to_be_bytes()].concat());
}
#[test]
fn zero_channels_rates_and_partial_frames_are_refused() {
for container in [PcmContainer::Wav, PcmContainer::Aiff] {
assert!(header(container, 0, 48_000, SampleFormat::Int16, 1).is_err());
assert!(header(container, 1, 0, SampleFormat::Int16, 1).is_err());
assert!(header(container, 2, 48_000, SampleFormat::Int16, 0).is_ok(), "zero frames stay valid");
}
assert!(write_wav(&[0.5], 0, 48_000, SampleFormat::Int16).is_err());
assert!(write_wav(&[0.1, 0.2, 0.3], 2, 48_000, SampleFormat::Int16).is_err());
assert!(write_aiff(&[0.1, 0.2, 0.3], 2, 48_000, SampleFormat::Int16).is_err());
assert!(write_aiff(&[0.1, 0.2], 2, 48_000, SampleFormat::Int16).is_ok());
}
}
+3
View File
@@ -29,8 +29,10 @@ pub mod lut3d;
pub mod lutfile;
pub mod math;
pub mod named;
mod normalize;
pub mod pipeline;
pub mod profile;
pub mod sony_lut;
pub mod spi1d;
pub mod synth;
pub mod transform;
@@ -44,6 +46,7 @@ pub use gamut::GamutCheck;
pub use gpu_matrix_shaper::GpuMatrixShaper;
pub use lut3d::Lut3d;
pub use named::{NamedColor, NamedColors};
pub use normalize::normalize_for_embedding;
pub use profile::{ColorSpace, Pcs, Profile, ProfileClass};
pub use transform::{SampleKind, Transform, TransformOptions, black_point, cached};
pub use write::profile_id;
+142
View File
@@ -0,0 +1,142 @@
//! Bounded encoded ICC layout normalization, originating in LightCraft.
use std::collections::BTreeMap;
/// Zero the creation date, align tag payloads to four bytes, preserve shared payloads,
/// update the profile length and clear its stale profile ID. No colour tags are interpreted.
///
/// This is a layout operation, not profile validation. Malformed tables or layouts exceeding
/// 4096 tags or 64 MiB output are returned unchanged except for the creation date. The owned
/// input is reused on failure, so rejected input does not require an additional full copy.
/// Consumers needing rejection of invalid profiles must separately use `Profile::parse`.
pub fn normalize_for_embedding(mut bytes: Vec<u8>) -> Vec<u8> {
if let Some(date) = bytes.get_mut(24..36) {
date.fill(0);
}
align(&bytes).unwrap_or(bytes)
}
const MAX_BYTES: usize = 64 * 1024 * 1024;
const MAX_TAGS: usize = 4096;
fn be(bytes: &[u8], at: usize) -> Option<usize> {
let s = bytes.get(at..at.checked_add(4)?)?;
usize::try_from(u32::from_be_bytes([s[0], s[1], s[2], s[3]])).ok()
}
fn align(bytes: &[u8]) -> Option<Vec<u8>> {
if bytes.len() > MAX_BYTES {
return None;
}
let count = be(bytes, 128)?;
if count > MAX_TAGS {
return None;
}
let end = 132usize.checked_add(count.checked_mul(12)?)?;
bytes.get(..end)?;
let mut placements = BTreeMap::new();
let mut offsets = Vec::new();
offsets.try_reserve_exact(count).ok()?;
let mut size = end;
for index in 0..count {
let entry = 132 + index * 12;
let off = be(bytes, entry + 4)?;
let len = be(bytes, entry + 8)?;
if off < end {
return None;
}
bytes.get(off..off.checked_add(len)?)?;
let new_off = if let Some(&placed) = placements.get(&(off, len)) {
placed
} else {
let aligned = size.checked_add(3)? & !3;
size = aligned.checked_add(len)?;
if size > MAX_BYTES {
return None;
}
placements.insert((off, len), aligned);
aligned
};
offsets.push(new_off);
}
size = size.checked_add(3)? & !3;
if size > MAX_BYTES {
return None;
}
let mut out = Vec::new();
out.try_reserve_exact(size).ok()?;
out.resize(size, 0);
out[..end].copy_from_slice(&bytes[..end]);
for ((off, len), target) in placements {
out[target..target + len].copy_from_slice(&bytes[off..off + len]);
}
for (index, off) in offsets.into_iter().enumerate() {
let field = 132 + index * 12 + 4;
out[field..field + 4].copy_from_slice(&u32::try_from(off).ok()?.to_be_bytes());
}
out[..4].copy_from_slice(&u32::try_from(size).ok()?.to_be_bytes());
out[84..100].fill(0);
Some(out)
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#[path = "normalize_legacy_tests.rs"]
mod legacy;
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use super::*;
#[test]
fn matches_frozen_writer_and_preserves_aliases() {
for count in 0..20usize {
let end = 132 + count * 12;
let mut bytes = vec![17; end + 31];
bytes[128..132].copy_from_slice(&(count as u32).to_be_bytes());
for index in 0..count {
let field = 132 + index * 12 + 4;
let off = end + index % 3;
bytes[field..field + 4].copy_from_slice(&(off as u32).to_be_bytes());
bytes[field + 4..field + 8].copy_from_slice(&7u32.to_be_bytes());
}
let expected = legacy::align_tags(&legacy::fixed_date(bytes.clone()));
let result = normalize_for_embedding(bytes);
assert_eq!(result, expected);
assert_eq!(normalize_for_embedding(result.clone()), result);
}
}
#[test]
fn real_profile_preserves_color_tags_and_legacy_bytes() {
let encoded = crate::Builtin::Srgb.profile().clone().with_encoded_bytes();
let input = encoded.to_bytes().to_vec();
let normalized = normalize_for_embedding(input.clone());
assert_eq!(normalized, legacy::align_tags(&legacy::fixed_date(input)));
assert_eq!(&normalized[24..36], &[0; 12]);
assert_eq!(&normalized[84..100], &[0; 16]);
assert!(crate::Profile::parse(&normalized).is_ok());
for index in 0..be(&normalized, 128).unwrap() {
assert_eq!(be(&normalized, 136 + index * 12).unwrap() % 4, 0);
}
}
#[test]
fn hostile_tables_return_owned_input_without_expansion() {
for len in 0..132 {
let bytes = vec![1; len];
assert_eq!(normalize_for_embedding(bytes.clone()), legacy::fixed_date(bytes));
}
for count in [4097u32, u32::MAX] {
let mut bytes = vec![1; 144];
bytes[128..132].copy_from_slice(&count.to_be_bytes());
assert_eq!(normalize_for_embedding(bytes.clone()), legacy::fixed_date(bytes));
}
let mut bytes = vec![1; 144];
bytes[128..132].copy_from_slice(&1u32.to_be_bytes());
bytes[136..140].copy_from_slice(&u32::MAX.to_be_bytes());
bytes[140..144].copy_from_slice(&u32::MAX.to_be_bytes());
assert_eq!(normalize_for_embedding(bytes.clone()), legacy::fixed_date(bytes));
}
}
+43
View File
@@ -0,0 +1,43 @@
//! Encoded ICC normalization extracted from LightCraft.
pub(super) fn align_tags(b: &[u8]) -> Vec<u8> {
let be = |i: usize| b.get(i..i + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize);
let Some(n) = be(128) else { return b.to_vec() };
let table_end = 132 + 12 * n;
let tags: Option<Vec<(usize, usize)>> = (0..n).map(|t| Some((be(132 + 12 * t + 4)?, be(132 + 12 * t + 8)?))).collect();
let Some(tags) = tags.filter(|t| table_end <= b.len() && t.iter().all(|&(o, l)| o >= table_end && o + l <= b.len())) else {
return b.to_vec();
};
let mut out = b[..table_end].to_vec();
let mut placed: Vec<((usize, usize), usize)> = Vec::new();
for (t, &(off, len)) in tags.iter().enumerate() {
let new_off = match placed.iter().find(|(k, _)| *k == (off, len)) {
// tags sharing data keep sharing it
Some(&(_, o)) => o,
None => {
while !out.len().is_multiple_of(4) {
out.push(0);
}
let o = out.len();
out.extend_from_slice(&b[off..off + len]);
placed.push(((off, len), o));
o
}
};
out[132 + 12 * t + 4..132 + 12 * t + 8].copy_from_slice(&(new_off as u32).to_be_bytes());
}
while !out.len().is_multiple_of(4) {
out.push(0);
}
let size = out.len() as u32;
out[0..4].copy_from_slice(&size.to_be_bytes());
// the profile ID (MD5) would no longer match: clear it (= "not computed")
out[84..100].fill(0);
out
}
pub(super) fn fixed_date(mut b: Vec<u8>) -> Vec<u8> {
if let Some(date) = b.get_mut(24..36) {
date.fill(0);
}
b
}
+82
View File
@@ -0,0 +1,82 @@
//! Sony Imageworks SPI3D and SPIMTX text readers, extracted from EffectCraft.
//!
//! These preserve the source reader's format tolerance. SPI3D sample values are not
//! clamped or sanitized; rendering policy belongs to the caller. Duplicate coordinates
//! retain their last value, and the total row count must match the lattice volume.
/// Maximum lattice side accepted by the source reader.
pub const MAX_SIDE: usize = 129;
/// Row-major homogeneous transform with a separate normalized code-value offset.
#[derive(Clone, Debug, PartialEq)]
pub struct Matrix {
pub matrix: [f64; 16],
pub offset: [f64; 4],
}
/// A cubic RGB table, red coordinate varying fastest.
#[derive(Clone, Debug, PartialEq)]
pub struct Lattice {
pub size: usize,
pub values: Vec<[f32; 3]>,
}
/// Read exactly twelve finite SPIMTX numbers, dividing the offset column by 65535.
/// Parsing uses a fixed array, not storage proportional to an oversized input.
pub fn parse_spimtx(text: &str) -> Option<Matrix> {
let mut words = text.split_whitespace();
let mut v = [0.0f64; 12];
for value in &mut v {
*value = words.next()?.parse().ok()?;
if !value.is_finite() {
return None;
}
}
if words.next().is_some() {
return None;
}
let mut matrix = [0.0; 16];
let mut offset = [0.0; 4];
for (r, row) in v.as_chunks::<4>().0.iter().enumerate() {
matrix[r * 4..r * 4 + 3].copy_from_slice(&row[..3]);
offset[r] = row[3] / 65535.0;
}
matrix[15] = 1.0;
Some(Matrix { matrix, offset })
}
/// Read a SPI3D table with a bounded 2..=129 cubic lattice and exactly six fields per row.
/// A `SPILUT` prefix is accepted and the second header line is ignored, as in EffectCraft.
pub fn parse_spi3d(text: &str) -> Option<Lattice> {
let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty());
if !lines.next()?.starts_with("SPILUT") {
return None;
}
lines.next()?;
let mut sizes = lines.next()?.split_whitespace();
let n: usize = sizes.next()?.parse().ok()?;
let g: usize = sizes.next()?.parse().ok()?;
let b: usize = sizes.next()?.parse().ok()?;
if sizes.next().is_some() || g != n || b != n || !(2..=MAX_SIDE).contains(&n) {
return None;
}
let count = n * n * n;
let mut values = vec![[0.0f32; 3]; count];
let mut seen = 0usize;
for line in lines {
if seen == count {
return None;
}
let mut fields = line.split_whitespace();
let r: usize = fields.next()?.parse().ok()?;
let g: usize = fields.next()?.parse().ok()?;
let b: usize = fields.next()?.parse().ok()?;
let color = [fields.next()?.parse().ok()?, fields.next()?.parse().ok()?, fields.next()?.parse().ok()?];
if fields.next().is_some() || r >= n || g >= n || b >= n {
return None;
}
*values.get_mut(r + g * n + b * n * n)? = color;
seen += 1;
}
(seen == count).then_some(Lattice { size: n, values })
}
+46
View File
@@ -0,0 +1,46 @@
use craft_cms::sony_lut::{MAX_SIDE, parse_spi3d, parse_spimtx};
#[test]
fn spimtx_is_finite_exact_and_scales_offsets() {
let m = parse_spimtx("2 0 0 6553.5\n0 3 0 -65535\n0 0 4 0").unwrap();
assert_eq!(m.matrix, [2.0, 0.0, 0.0, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0]);
assert_eq!(m.offset, [0.1, -1.0, 0.0, 0.0]);
for bad in ["", "1 0 0 0", "NaN 0 0 0 0 1 0 0 0 0 1 0", "inf 0 0 0 0 1 0 0 0 0 1 0", "1 0 0 0 0 1 0 0 0 0 1 0 9"] {
assert!(parse_spimtx(bad).is_none());
}
}
fn table() -> String {
let mut text = String::from("SPILUT 1.0\n3 3\n2 2 2\n");
// Reverse row order to prove coordinates, rather than row order, determine storage.
for i in (0..8).rev() {
let (r, g, b) = (i & 1, (i >> 1) & 1, i >> 2);
text.push_str(&format!("{r} {g} {b} {r} {g} {b}\n"));
}
text
}
#[test]
fn spi3d_red_fast_coordinates_and_limits() {
let text = table();
let lut = parse_spi3d(&text).unwrap();
assert_eq!(lut.size, 2);
for (i, row) in lut.values.iter().enumerate() {
assert_eq!(*row, [(i & 1) as f32, ((i >> 1) & 1) as f32, (i >> 2) as f32]);
}
assert!(parse_spi3d(&format!("{text}0 0 0 0 0 0\n")).is_none());
assert!(parse_spi3d("SPILUT 1.0\n3 3\n2 2 2\n0 0 0 0 0 0\n").is_none());
assert!(parse_spi3d(&format!("SPILUT 1.0\n3 3\n{0} {0} {0}\n", MAX_SIDE + 1)).is_none());
assert!(parse_spi3d(&text.replace("2 2 2", "2 2 3")).is_none());
assert!(parse_spi3d(&text.replace("0 0 0 0 0 0", "2 0 0 0 0 0")).is_none());
assert!(parse_spi3d(&text.replace("0 0 0 0 0 0", "0 0 0 0 0 0 extra")).is_none());
}
#[test]
fn inherited_tolerance_is_explicit() {
let text = "SPILUT alternative\nignored\n2 2 2\n".to_owned() + &"0 0 0 -1 2 NaN\n".repeat(8);
let lut = parse_spi3d(&text).unwrap();
assert_eq!(&lut.values[0][..2], &[-1.0, 2.0]);
assert!(lut.values[0][2].is_nan());
assert_eq!(lut.values[1], [0.0; 3]);
}
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "craft-control"
description = "The control channel any app may share: token files, the loopback server, and its requests; no UI toolkit"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
[lints]
workspace = true
[dependencies]
serde = { workspace = true }
serde_json = { workspace = true }
# The loopback server is for desktop apps; the web app is driven through the page instead.
[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"
[dev-dependencies]
proptest = { workspace = true }
+673
View File
@@ -0,0 +1,673 @@
//! The control channel's per-launch token (docs/control-protocol.md). An app listening for
//! control makes a random token, writes it to a file only the user can read
//! ([`App::token_path`]) and refuses every connection whose first request doesn't carry it, so
//! other users on the same machine (loopback is shared, on Windows across remote-desktop sessions
//! too) can't drive the app. Clients find it with [`App::client_token`]. Next to it, `<port>.pid`
//! names the process that wrote it, so a client refused with a leftover token can say the file is
//! stale.
use std::ffi::OsString;
use std::io::{Error, ErrorKind, Read, Result, Write};
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
/// Shortest token accepted from the app's `CONTROL_TOKEN` variable (hex characters).
pub const MIN_TOKEN_LEN: usize = 32;
/// Ports tried from the app's default port upward when it is taken (a second window, another
/// program).
pub const PORT_TRIES: u16 = 16;
/// Which app a control channel belongs to: where its token files live, its environment and its
/// name in messages.
#[derive(Clone, Copy)]
pub struct App {
/// The app's name in messages ("restart SolidCraft").
pub name: &'static str,
/// The per-user data folder; the token files go in its `control` folder.
pub data_dir: fn() -> Option<PathBuf>,
/// The app's environment variable `name` (`CONTROL_DIR`, `CONTROL_TOKEN`), with the app's prefix.
pub env: fn(&str) -> Option<OsString>,
/// A time in seconds since the Unix epoch, as the app writes UTC times in messages.
pub utc: fn(u64) -> String,
/// The port the control channel tries first when the launch gives none. Below the ephemeral
/// ranges of Linux (32768+) and Windows/macOS (49152+), so the system never hands it to an
/// outgoing connection.
pub default_port: u16,
}
/// Where the control channel listens, from the launch's `--control`/environment port and the app's
/// allow-agents setting.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Listen {
/// Exactly this port (`--control PORT`, the app's `CONTROL_PORT`); no fallback.
Exact(u16),
/// The app's [`App::default_port`], or the next free one of [`PORT_TRIES`].
Default,
}
/// What a launch listens on. An explicit port wins over the app's allow-agents setting
/// (`enabled`), so a scripted launch works with the setting off; with the setting off and no port,
/// nothing listens.
pub fn plan(explicit: Option<u16>, enabled: bool) -> Option<Listen> {
match explicit {
Some(port) => Some(Listen::Exact(port)),
None if enabled => Some(Listen::Default),
None => None,
}
}
/// Bind a loopback-only listener on `first`, or on the next free port when it is taken, up to
/// `tries` ports in all.
pub fn bind_with_fallback(first: u16, tries: u16) -> Result<std::net::TcpListener> {
let mut last = Error::new(ErrorKind::AddrInUse, "no port to try");
for port in (first..=u16::MAX).take(usize::from(tries.max(1))) {
match std::net::TcpListener::bind(("127.0.0.1", port)) {
Ok(l) => return Ok(l),
// In use; Windows reports a port another program holds exclusively as denied.
Err(e) if matches!(e.kind(), ErrorKind::AddrInUse | ErrorKind::PermissionDenied) => last = e,
Err(e) => return Err(e),
}
}
Err(last)
}
impl App {
/// The folder of the token files: `<data folder>/control` (the app's `CONTROL_DIR` replaces it).
fn control_dir(&self) -> Option<PathBuf> {
match self.custom_control_dir() {
Some(d) => Some(PathBuf::from(d)),
None => Some((self.data_dir)()?.join("control")),
}
}
/// The folder the app's `CONTROL_DIR` names in place of the default one.
fn custom_control_dir(&self) -> Option<OsString> {
(self.env)("CONTROL_DIR").filter(|d| !d.is_empty())
}
/// The token file of the app listening on `port`: `<data folder>/control/<port>.token`
/// (the app's `CONTROL_DIR` replaces the folder).
pub fn token_path(&self, port: u16) -> Option<PathBuf> {
Some(self.control_dir()?.join(format!("{port}.token")))
}
/// The discovery file: the port of the most recently started app, so a client with no port
/// finds it. It holds only the port; the token stays in its own file.
pub fn current_port_path(&self) -> Option<PathBuf> {
Some(self.control_dir()?.join("current.port"))
}
/// Record `port` as the running app's, readable only by the user like the token files.
pub fn write_current_port(&self, port: u16) -> Result<PathBuf> {
let path = self.current_port_path().ok_or_else(|| Error::new(ErrorKind::NotFound, "no data folder"))?;
self.write_token_file(&path, &port.to_string())?;
Ok(path)
}
/// The port the discovery file names, if there is one.
pub fn read_current_port(&self) -> Option<u16> {
parse_port(&std::fs::read_to_string(self.current_port_path()?).ok().filter(|t| t.len() <= 64)?)
}
/// Remove the discovery file (and its process file) at exit, unless a later app has taken it
/// over: it names another port, or another launch now holds this port's token file. Under
/// Flatpak every instance has its own loopback, so two windows can listen on the same port
/// number and write the same file names; the one closing first must leave the other's (#8794).
/// Run it after [`remove_token_file`], which takes this launch's own token file away first.
pub fn remove_current_port(&self, port: u16, token: &str) {
if let (Some(current), Some(file)) = (self.current_port_path(), self.token_path(port)) {
remove_discovery(&current, &file, port, token);
}
}
/// A token set on purpose with the app's `CONTROL_TOKEN` (test harnesses, sandboxed packages
/// whose data folder the client can't see), if it is long enough.
pub fn env_token(&self) -> Option<String> {
(self.env)("CONTROL_TOKEN").and_then(|v| v.into_string().ok()).map(|t| t.trim().to_string()).filter(|t| t.len() >= MIN_TOKEN_LEN)
}
/// The token a client sends to the app on `port`: `explicit` (`--token`), else the app's
/// `CONTROL_TOKEN`, else the app's token file.
pub fn client_token(&self, port: u16, explicit: Option<&str>) -> Option<ClientToken> {
if let Some(t) = explicit.map(str::trim).filter(|t| !t.is_empty()) {
return Some(ClientToken { token: t.to_string(), file: None, app: *self });
}
if let Some(t) = self.env_token() {
return Some(ClientToken { token: t, file: None, app: *self });
}
// Read directly, not through any agent's file scope: the app's own file.
read_token_file(&self.token_path(port)?, *self)
}
/// Write `token` to `path`, readable and writable only by the user: the folder is made `0700`
/// and the file `0600` on Unix; on Windows the file's inherited permissions are replaced by one
/// entry for the user (`icacls`) before the token goes in; when that fails, the still empty file
/// is removed and no token is written. A file left by an earlier launch is replaced. The process
/// file beside it ([`pid_path`]) records this process, best effort.
pub fn write_token_file(&self, path: &Path, token: &str) -> Result<()> {
#[cfg(windows)]
let restrict = |p: &Path| restrict_to_user(p, self.custom_control_dir().is_some());
#[cfg(not(windows))]
let restrict = |_: &Path| Ok(());
write_token_file_with(path, token, restrict)
}
}
fn parse_port(text: &str) -> Option<u16> {
text.trim().parse::<u16>().ok().filter(|p| *p != 0)
}
/// [`App::remove_current_port`] on given files: `current` is the discovery file, `file` the token
/// file of `port`.
fn remove_discovery(current: &Path, file: &Path, port: u16, token: &str) {
let named = std::fs::read_to_string(current).ok().filter(|t| t.len() <= 64).and_then(|t| parse_port(&t));
if named != Some(port) || held_by_another(file, token) {
return;
}
let _ = std::fs::remove_file(current);
let _ = std::fs::remove_file(pid_path(current));
}
/// A client token and, when it came from a token file, where that file is.
pub struct ClientToken {
pub token: String,
pub file: Option<TokenSource>,
/// The app it is for, named in an explanation.
pub app: App,
}
/// The token file a client read: its path, when it was written and the process that wrote it.
pub struct TokenSource {
pub path: PathBuf,
pub modified: Option<SystemTime>,
/// From `<port>.pid`: the writer's process id and, on Linux, its start time.
pub writer: Option<(u32, Option<u64>)>,
}
impl ClientToken {
/// The app's `error`, and for a refused token read from a file, which file it was, when it
/// was written and whether the instance that wrote it has exited. Never the token itself.
pub fn explain_error(&self, error: &str) -> String {
let Some(src) = &self.file else { return error.to_string() };
if !error.starts_with("unauthorized") {
return error.to_string();
}
let written = src
.modified
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
.map(|t| (self.app.utc)(t.as_secs()))
.unwrap_or_else(|| "at an unknown time".into());
let age = src.modified.and_then(|t| t.elapsed().ok()).map(|d| format!(" ({} s ago)", d.as_secs())).unwrap_or_default();
let path = src.path.display();
let name = self.app.name;
match src.writer.filter(|(pid, start)| writer_exited(*pid, *start)) {
Some((pid, _)) => format!(
"{error}; stale token file from an instance that exited (process {pid}): {path}, written {written}{age}; delete that file or restart {name}"
),
None => format!("{error}; token from {path}, written {written}{age}; if {name} was force-quit, restart it or delete that file"),
}
}
}
/// Files bigger than this are not token files.
const MAX_TOKEN_FILE: u64 = 4096;
fn read_token_file(path: &Path, app: App) -> Option<ClientToken> {
let f = std::fs::File::open(path).ok()?;
let modified = f.metadata().ok().and_then(|m| m.modified().ok());
let mut text = String::new();
f.take(MAX_TOKEN_FILE + 1).read_to_string(&mut text).ok()?;
if text.len() as u64 > MAX_TOKEN_FILE {
return None;
}
let token = text.trim();
if token.is_empty() {
return None;
}
let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
let writer = read_pid_file(&pid_path(&path));
Some(ClientToken { token: token.to_string(), file: Some(TokenSource { path, modified, writer }), app })
}
/// The process file beside the token file `path`: `7878.token` → `7878.pid`.
pub fn pid_path(path: &Path) -> PathBuf {
path.with_extension("pid")
}
/// `<pid> [<start time>]`; anything else (or no file) is no information.
fn read_pid_file(path: &Path) -> Option<(u32, Option<u64>)> {
let mut text = String::new();
std::fs::File::open(path).ok()?.take(256).read_to_string(&mut text).ok()?;
let mut fields = text.split_whitespace();
let pid = fields.next()?.parse::<u32>().ok().filter(|&pid| pid > 0)?;
Some((pid, fields.next().and_then(|s| s.parse().ok())))
}
/// Whether the process that wrote a token file is known to be gone: not running, or its id now
/// belongs to a process that started at another time. Unknown counts as running.
fn writer_exited(pid: u32, start: Option<u64>) -> bool {
process_running(pid) == Some(false) || start.zip(process_start(pid)).is_some_and(|(saved, now)| saved != now)
}
/// Whether process `pid` runs; `None` when that can't be found out.
fn process_running(pid: u32) -> Option<bool> {
#[cfg(target_os = "linux")]
{
if !Path::new("/proc/self").exists() {
return None;
}
match std::fs::metadata(format!("/proc/{pid}")) {
Ok(_) => Some(true),
Err(e) if e.kind() == ErrorKind::NotFound => Some(false),
Err(_) => None,
}
}
#[cfg(all(unix, not(target_os = "linux")))]
{
let output = std::process::Command::new("ps").args(["-p", &pid.to_string(), "-o", "pid="]).output().ok()?;
if output.status.success() {
return Some(true);
}
(output.status.code() == Some(1) && output.stdout.iter().all(u8::is_ascii_whitespace)).then_some(false)
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
let output = std::process::Command::new("tasklist")
.args(["/FI", &format!("PID eq {pid}"), "/FO", "CSV", "/NH"])
.creation_flags(0x0800_0000)
.output()
.ok()?;
if !output.status.success() || output.stdout.is_empty() {
return None;
}
// `"image","pid",…` per process; with no match, a message line without a pid.
let text = String::from_utf8_lossy(&output.stdout);
Some(text.lines().any(|line| line.split("\",\"").nth(1).and_then(|s| s.trim_matches('"').parse::<u32>().ok()) == Some(pid)))
}
#[cfg(not(any(unix, windows)))]
{
let _ = pid;
None
}
}
/// Linux: the process's start time (clock ticks after boot), which tells a reused id apart.
fn process_start(pid: u32) -> Option<u64> {
#[cfg(target_os = "linux")]
{
let mut stat = String::new();
std::fs::File::open(format!("/proc/{pid}/stat")).ok()?.take(4096).read_to_string(&mut stat).ok()?;
stat.rsplit_once(')')?.1.split_whitespace().nth(19)?.parse().ok()
}
#[cfg(not(target_os = "linux"))]
{
let _ = pid;
None
}
}
/// `a == b`, taking the same time wherever they differ.
pub fn tokens_match(a: &str, b: &str) -> bool {
let (a, b) = (a.as_bytes(), b.as_bytes());
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}
/// [`App::write_token_file`], with `restrict` limiting the new file to the user (Windows).
fn write_token_file_with(path: &Path, token: &str, restrict: impl FnOnce(&Path) -> Result<()>) -> Result<()> {
let dir = path.parent().ok_or_else(|| Error::new(ErrorKind::InvalidInput, "no folder"))?;
std::fs::create_dir_all(dir)?;
let _ = std::fs::remove_file(path);
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
opts.mode(0o600);
}
let opened = opts.open(path)?;
// On a refusal the file goes with the closure, so it is closed before it is removed.
let mut f = match restrict(path).map(|()| opened) {
Ok(f) => f,
Err(e) => {
let _ = std::fs::remove_file(path);
return Err(e);
}
};
f.write_all(token.as_bytes())?;
f.write_all(b"\n")?;
f.sync_all()?;
let pid = std::process::id();
let line = process_start(pid).map_or_else(|| format!("{pid}\n"), |start| format!("{pid} {start}\n"));
let _ = std::fs::write(pid_path(path), line);
Ok(())
}
/// Remove a token file this launch wrote, and its process file, while it still holds `token`.
/// Another launch may have written the same file since (a second window on the same port,
/// #8794); its file stays. The process id can't tell the two apart, as every Flatpak instance
/// has the same one, but each launch's token is its own.
pub fn remove_token_file(path: &Path, token: &str) {
if read_token(path).is_some_and(|held| tokens_match(&held, token.trim())) {
let _ = std::fs::remove_file(path);
let _ = std::fs::remove_file(pid_path(path));
}
}
/// The token a token file holds, trimmed; `None` when there is no readable token file.
fn read_token(path: &Path) -> Option<String> {
let mut text = String::new();
std::fs::File::open(path).ok()?.take(MAX_TOKEN_FILE + 1).read_to_string(&mut text).ok()?;
let token = text.trim();
(text.len() as u64 <= MAX_TOKEN_FILE && !token.is_empty()).then(|| token.to_string())
}
/// Whether the token file at `path` holds a token other than `token`: another launch's.
fn held_by_another(path: &Path, token: &str) -> bool {
read_token(path).is_some_and(|held| !tokens_match(&held, token.trim()))
}
/// How long `icacls` may take (#6145). It finishes at once; on some computers the new process
/// is left suspended (security software holding it), and waiting on it without a limit froze
/// the app.
#[cfg(windows)]
const ICACLS_LIMIT: std::time::Duration = std::time::Duration::from_secs(5);
/// How a run of `icacls` ended.
#[cfg(any(windows, test))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum IcaclsEnd {
Succeeded,
Failed,
/// It didn't finish within [`ICACLS_LIMIT`] and was ended.
TimedOut,
}
/// Whether a token may go into a file after `icacls` ended this way. `custom_folder`: the file is
/// in the folder the app's `CONTROL_DIR` names. A timeout is accepted only in the default folder,
/// the user's own local app data, which other users can't read by default; nothing is known about
/// the permissions of any other folder.
#[cfg(any(windows, test))]
fn restriction_result(end: IcaclsEnd, custom_folder: bool, path: &Path) -> Result<()> {
match end {
IcaclsEnd::Succeeded => Ok(()),
IcaclsEnd::TimedOut if !custom_folder => Ok(()),
IcaclsEnd::TimedOut => Err(Error::new(ErrorKind::TimedOut, format!("icacls did not finish in time to restrict {}", path.display()))),
IcaclsEnd::Failed => Err(Error::other(format!("icacls failed to restrict {}", path.display()))),
}
}
/// Windows: drop inherited entries and grant only the current user full access. An `icacls`
/// that doesn't finish in time is ended, and [`restriction_result`] decides what that means.
#[cfg(windows)]
fn restrict_to_user(path: &Path, custom_folder: bool) -> Result<()> {
use std::os::windows::process::CommandExt;
let user = std::env::var("USERNAME").map_err(|_| Error::other("USERNAME is not set"))?;
let domain = std::env::var("USERDOMAIN").ok().filter(|d| !d.is_empty());
let who = domain.map_or(user.clone(), |d| format!("{d}\\{user}"));
let child = std::process::Command::new("icacls")
.arg(path)
.args(["/inheritance:r", "/grant:r", &format!("{who}:F")])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.creation_flags(0x0800_0000)
.spawn()?;
let end = match wait_within(child, ICACLS_LIMIT)? {
Some(status) if status.success() => IcaclsEnd::Succeeded,
Some(_) => IcaclsEnd::Failed,
None => IcaclsEnd::TimedOut,
};
restriction_result(end, custom_folder, path)
}
/// Wait for `child` at most `limit`: its exit status, or `None` (and the child ended) when it
/// hasn't finished by then.
#[cfg(any(windows, test))]
fn wait_within(mut child: std::process::Child, limit: std::time::Duration) -> Result<Option<std::process::ExitStatus>> {
let start = std::time::Instant::now();
loop {
if let Some(status) = child.try_wait()? {
return Ok(Some(status));
}
if start.elapsed() >= limit {
// Not waited for afterwards: a suspended process may not end at once.
let _ = child.kill();
return Ok(None);
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
/// Removes the token file (path, token) when the app ends, while it still holds that token.
pub struct TokenFile(pub PathBuf, pub String);
impl Drop for TokenFile {
fn drop(&mut self) {
remove_token_file(&self.0, &self.1);
}
}
#[cfg(test)]
mod tests {
use super::*;
/// An app with no data folder and no environment, whose times read `t<seconds>`.
const TEST: App = App { name: "TestCraft", data_dir: || None, env: |_| None, utc: |secs| format!("t{secs}"), default_port: 27878 };
/// #6145: a child that doesn't finish in time is given up on, not waited for forever.
#[cfg(unix)]
#[test]
fn a_slow_child_is_waited_for_only_so_long() {
use std::time::{Duration, Instant};
let start = Instant::now();
let slow = std::process::Command::new("sleep").arg("30").spawn().unwrap();
assert!(wait_within(slow, Duration::from_millis(200)).unwrap().is_none());
assert!(start.elapsed() < Duration::from_secs(5), "{:?}", start.elapsed());
let quick = std::process::Command::new("true").spawn().unwrap();
assert!(wait_within(quick, Duration::from_secs(5)).unwrap().is_some_and(|s| s.success()));
let failing = std::process::Command::new("false").spawn().unwrap();
assert!(wait_within(failing, Duration::from_secs(5)).unwrap().is_some_and(|s| !s.success()));
}
/// #6145's freeze fix stays in the default folder, the user's own; a folder picked with
/// the app's `CONTROL_DIR` gets no token unless the file was really restricted.
#[test]
fn only_the_default_folder_accepts_an_icacls_that_timed_out() {
let path = Path::new("control/7878.token");
for custom in [false, true] {
assert!(restriction_result(IcaclsEnd::Succeeded, custom, path).is_ok());
assert!(restriction_result(IcaclsEnd::Failed, custom, path).is_err());
}
assert!(restriction_result(IcaclsEnd::TimedOut, false, path).is_ok());
let e = restriction_result(IcaclsEnd::TimedOut, true, path).unwrap_err();
assert_eq!(e.kind(), ErrorKind::TimedOut);
assert!(e.to_string().contains("7878.token"), "{e}");
}
/// A file that couldn't be restricted is removed, empty and with no process file beside it, and
/// the error goes to the caller. A restricted one gets its token.
#[test]
fn a_token_file_that_could_not_be_restricted_is_removed() {
let dir = std::env::temp_dir().join(format!("craft-control-restrict-{}", std::process::id()));
let path = dir.join("7879.token");
let e = write_token_file_with(&path, "secret-token", |p| {
assert_eq!(std::fs::read(p).unwrap(), b"", "restricted before the token goes in");
restriction_result(IcaclsEnd::TimedOut, true, p)
})
.unwrap_err();
assert_eq!(e.kind(), ErrorKind::TimedOut);
assert!(!path.exists() && !pid_path(&path).exists());
write_token_file_with(&path, "secret-token", |p| restriction_result(IcaclsEnd::TimedOut, false, p)).unwrap();
assert_eq!(read_token(&path).as_deref(), Some("secret-token"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn tokens_compare_whole() {
assert!(tokens_match("abc123", "abc123"));
assert!(!tokens_match("abc123", "abc124"));
assert!(!tokens_match("abc123", "abc12"));
assert!(!tokens_match("", "a"));
}
/// The preference starts the listener by default, off it doesn't, and a port given on the
/// command line or in the environment wins over it either way.
#[test]
fn the_preference_decides_unless_a_port_is_given() {
assert_eq!(plan(None, true), Some(Listen::Default));
assert_eq!(plan(None, false), None);
assert_eq!(plan(Some(7878), false), Some(Listen::Exact(7878)));
assert_eq!(plan(Some(7878), true), Some(Listen::Exact(7878)));
}
/// A taken port falls through to the next free one, on loopback only; a run of taken ports
/// is an error, not a hang.
#[test]
fn a_taken_port_falls_back_to_the_next_free_one() {
let first = bind_with_fallback(TEST.default_port, PORT_TRIES).unwrap();
let a = first.local_addr().unwrap();
assert!(a.ip().is_loopback() && (TEST.default_port..TEST.default_port + PORT_TRIES).contains(&a.port()), "{a}");
let second = bind_with_fallback(a.port(), PORT_TRIES).unwrap();
assert!(second.local_addr().unwrap().port() > a.port());
assert!(bind_with_fallback(a.port(), 1).is_err());
}
#[test]
fn the_discovery_file_holds_a_port() {
assert_eq!(parse_port("27879\n"), Some(27879));
assert_eq!(parse_port("0"), None);
assert_eq!(parse_port("70000"), None);
assert_eq!(parse_port("nope"), None);
let dir = std::env::temp_dir().join(format!("solidcraft-current-port-{}", std::process::id()));
let path = dir.join("current.port");
TEST.write_token_file(&path, "27881").unwrap();
assert_eq!(parse_port(&std::fs::read_to_string(&path).unwrap()), Some(27881));
let _ = std::fs::remove_dir_all(&dir);
}
/// A one-line token file (and one with no process file) still reads.
#[test]
fn a_token_file_reads_with_and_without_its_process_file() {
let dir = std::env::temp_dir().join(format!("craft-control-read-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("7879.token");
std::fs::write(&path, "legacy-token\n").unwrap();
let client = read_token_file(&path, TEST).unwrap();
assert_eq!(client.token, "legacy-token");
let src = client.file.as_ref().unwrap();
assert_eq!(src.path, std::fs::canonicalize(&path).unwrap());
assert!(src.modified.is_some() && src.writer.is_none());
std::fs::write(pid_path(&path), "not a pid\n").unwrap();
assert!(read_token_file(&path, TEST).unwrap().file.unwrap().writer.is_none());
std::fs::write(&path, "x".repeat(4097)).unwrap();
assert!(read_token_file(&path, TEST).is_none());
let _ = std::fs::remove_dir_all(&dir);
}
/// A refused token's explanation names the app and writes the time as the app does.
#[test]
fn an_explanation_names_the_app() {
let file = Some(TokenSource { path: PathBuf::from("7878.token"), modified: Some(UNIX_EPOCH), writer: None });
let client = ClientToken { token: "secret-token".into(), file, app: TEST };
let error = client.explain_error("unauthorized");
assert!(error.contains("written t0 (") && error.contains("if TestCraft was force-quit"), "{error}");
assert!(!error.contains("secret-token"), "{error}");
let explicit = TEST.client_token(0, Some("explicit-token")).unwrap();
assert!(explicit.token == "explicit-token" && explicit.file.is_none());
assert_eq!(explicit.explain_error("unauthorized"), "unauthorized");
}
/// A process file naming a process that has exited marks the token file stale.
/// Where the process inspector cannot run (a sandboxed test runner), the exit
/// is unknown, and the explanation must not claim it.
#[cfg(any(unix, windows))]
#[test]
fn a_token_file_from_an_exited_process_is_stale() {
let mut child = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "auth::tests::tokens_compare_whole"])
.stdout(std::process::Stdio::null())
.spawn()
.unwrap();
let pid = child.id();
assert!(child.wait().unwrap().success());
let source = |writer| Some(TokenSource { path: PathBuf::from("7878.token"), modified: None, writer });
let stale = ClientToken { token: "secret-token".into(), file: source(Some((pid, None))), app: TEST };
let error = stale.explain_error("unauthorized");
match process_running(pid) {
Some(false) => {
assert!(error.contains(&format!("stale token file from an instance that exited (process {pid}): 7878.token")), "{error}");
}
None => assert!(!error.contains("stale") && error.contains("restart it or delete that file"), "{error}"),
Some(true) => panic!("the reaped child {pid} is reported as running"),
}
assert!(!error.contains("secret-token"));
let live = ClientToken { token: "t".into(), file: source(Some((std::process::id(), process_start(std::process::id())))), app: TEST };
assert!(!live.explain_error("unauthorized").contains("stale"));
#[cfg(target_os = "linux")]
{
let reused = process_start(std::process::id()).map(|s| s + 1);
let reused = ClientToken { token: "t".into(), file: source(Some((std::process::id(), reused))), app: TEST };
assert!(reused.explain_error("unauthorized").contains("stale token file"));
}
}
/// The token file is the user's alone, and a client reads it back.
#[cfg(unix)]
#[test]
fn the_token_file_is_private_to_the_user() {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!("craft-control-auth-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let path = dir.join("control/7878.token");
std::fs::create_dir_all(dir.join("control")).unwrap();
std::fs::write(&path, "stale").unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
TEST.write_token_file(&path, "0123456789abcdef0123456789abcdef").unwrap();
let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
assert_eq!(mode(&path), 0o600);
assert_eq!(mode(path.parent().unwrap()), 0o700);
assert_eq!(std::fs::read_to_string(&path).unwrap().trim(), "0123456789abcdef0123456789abcdef");
let writer = read_token_file(&path, TEST).unwrap().file.unwrap().writer;
assert_eq!(writer.map(|(pid, _)| pid), Some(std::process::id()));
drop(TokenFile(path.clone(), "0123456789abcdef0123456789abcdef".into()));
assert!(!path.exists() && !pid_path(&path).exists());
let _ = std::fs::remove_dir_all(&dir);
}
/// #8794: under Flatpak two windows can listen on the same port number (each has its own
/// loopback) and write the same files. The one closing first leaves the other's token, process
/// and discovery files; the last one takes them all away, `current.pid` too.
#[test]
fn a_closing_launch_leaves_another_launchs_files() {
let dir = std::env::temp_dir().join(format!("craft-control-two-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let (file, current) = (dir.join("27878.token"), dir.join("current.port"));
let (first, second) = ("a".repeat(64), "b".repeat(64));
// The first window, then the second on the same port, each writing both files.
for token in [&first, &second] {
TEST.write_token_file(&file, token).unwrap();
TEST.write_token_file(&current, "27878").unwrap();
}
// The first closes: the second's files stay.
remove_token_file(&file, &first);
remove_discovery(&current, &file, 27878, &first);
assert_eq!(read_token(&file).as_deref(), Some(second.as_str()));
assert!(pid_path(&file).exists() && current.exists() && pid_path(&current).exists());
// Another port named in the discovery file is another app's too.
remove_discovery(&current, &file, 27879, &second);
assert!(current.exists());
// The second closes: nothing of either is left.
remove_token_file(&file, &format!(" {second}\n"));
remove_discovery(&current, &file, 27878, &second);
assert!(!file.exists() && !pid_path(&file).exists() && !current.exists() && !pid_path(&current).exists());
// With no token file left (removed by hand, or never written), the discovery file of the
// port still goes; a missing file is no error.
TEST.write_token_file(&current, "27878").unwrap();
remove_token_file(&file, &second);
remove_discovery(&current, &file, 27878, &second);
assert!(!current.exists());
let _ = std::fs::remove_dir_all(&dir);
}
}
+118
View File
@@ -0,0 +1,118 @@
//! Where a control request is, so the connection that sent it can cancel it (`control.cancel`,
//! #1989): shared between the window, which moves it along, and the connection. Whoever changes
//! it first wins.
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::sync::{Mutex, PoisonError};
/// A request's place in the app, and how to stop the work computing it.
#[derive(Default)]
pub struct Ticket {
state: AtomicU8,
/// It is an export computing on a copy, whose worker writes its file.
writes_file: AtomicBool,
/// Tells its worker to stop: set by the window when it hands the request to one.
stopper: Mutex<Option<Box<dyn Fn() + Send + Sync>>>,
}
impl std::fmt::Debug for Ticket {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Ticket").field("state", &self.state).field("writes_file", &self.writes_file).finish_non_exhaustive()
}
}
/// Waiting its turn (sent, or held behind another request).
const WAITING: u8 = 0;
/// Running on the window thread (or handed to something that can't stop it, such as the file
/// loader).
const RUNNING: u8 = 1;
/// Computing off the window thread.
const COMPUTING: u8 = 2;
const CANCELLED: u8 = 3;
/// What [`Ticket::cancel`] did.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cancel {
/// It was waiting its turn: it will not run.
Removed,
/// It was computing off the window thread: it is answered as stopped and nothing of it is
/// applied. An export's worker may still write its file.
Stopped { writes_file: bool },
/// It runs on the window thread: it will finish.
Running,
/// It was cancelled or stopped before.
Already,
}
impl Ticket {
/// Cancel the request, unless it already runs on the window thread.
pub fn cancel(&self) -> Cancel {
let mut state = self.state.load(Ordering::Acquire);
loop {
let done = match state {
WAITING => Cancel::Removed,
COMPUTING => Cancel::Stopped { writes_file: self.writes_file.load(Ordering::Acquire) },
CANCELLED => return Cancel::Already,
_ => return Cancel::Running,
};
match self.state.compare_exchange(state, CANCELLED, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => {
self.stop_worker();
return done;
}
Err(now) => state = now,
}
}
}
pub fn is_cancelled(&self) -> bool {
self.state.load(Ordering::Acquire) == CANCELLED
}
/// The window takes the request to run it: false when it was cancelled.
pub fn take(&self) -> bool {
self.moves(WAITING, RUNNING)
}
/// The work computing it stops on `stop` (a worker's own stop flag). Cancelled already, it is
/// stopped at once.
pub fn on_stop(&self, stop: impl Fn() + Send + Sync + 'static) {
*self.stopper.lock().unwrap_or_else(PoisonError::into_inner) = Some(Box::new(stop));
if self.is_cancelled() {
self.stop_worker();
}
}
/// The window hands it to a worker (`writes_file`: an export on a copy).
pub fn computing(&self, writes_file: bool) {
self.writes_file.store(writes_file, Ordering::Release);
let _ = self.moves(RUNNING, COMPUTING) || self.moves(WAITING, COMPUTING);
}
/// Its worker is done and it runs on the window thread now (or it never left): false when it
/// was cancelled meanwhile. Only the window moves it on from running, so running stays running.
pub fn back(&self) -> bool {
self.moves(COMPUTING, RUNNING) || self.state.load(Ordering::Acquire) == RUNNING
}
/// Computed, but it waits its turn again (a file opening meanwhile): false when cancelled.
pub fn wait_again(&self) -> bool {
self.moves(COMPUTING, WAITING)
}
/// The person at the app stopped it (Stop): its worker stops too.
pub fn stop(&self) {
self.state.store(CANCELLED, Ordering::Release);
self.stop_worker();
}
fn stop_worker(&self) {
if let Some(stop) = self.stopper.lock().unwrap_or_else(PoisonError::into_inner).as_ref() {
stop();
}
}
fn moves(&self, from: u8, to: u8) -> bool {
self.state.compare_exchange(from, to, Ordering::AcqRel, Ordering::Acquire).is_ok()
}
}
+616
View File
@@ -0,0 +1,616 @@
//! The control channel's client (docs/control-protocol.md): a connection to an app's loopback
//! control port, with the app's token ([`App::client_token`]) on every request, one bounded
//! round trip per request, a fresh connection after one is lost, and the wait for a request the
//! app says is still running (#1618), through `control.pending`. Its errors tell an app that is
//! not running from one that went away during a call ([`CallError`]). What a request means, and
//! anything an app adds to its parameters, is the caller's.
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use crate::Effect;
use crate::auth::App;
/// Longest reply line accepted from the app.
pub const MAX_REPLY: u64 = 64 << 20;
/// How long a reply may take: kernel operations (booleans, fillets) on big parts can take a while.
pub const READ_TIMEOUT: Duration = Duration::from_secs(300);
/// How long the app may take to answer a request sent [`Request::once`]: a little longer than its
/// control server waits for a long request (3600 s), so its "still running" reply arrives first.
pub const ONCE_TIMEOUT: Duration = Duration::from_secs(3720);
/// How long connecting to the app may take.
const CONNECT_TIMEOUT: Duration = Duration::from_millis(800);
/// How often a long wait is reported ([`Connection::with_progress`]).
const PROGRESS_EVERY: Duration = Duration::from_secs(30);
/// How an error starts when a request is still running in the app after the wait: the request
/// was not cancelled and its reply waits on the connection; [`Connection::pending`] gets it.
pub use crate::STILL_RUNNING;
/// How long to wait for a request the app says is still running.
#[derive(Clone, Copy, Debug)]
pub struct Waits {
/// How long a call goes on waiting, asking `control.pending`, after the app said its request
/// is still running (the app says so after 60 s), before it says so itself.
pub pending: Duration,
/// How long a later call, or [`Connection::pending`], waits for a request still running from
/// an earlier call.
pub settle: Duration,
/// How often `control.pending` is asked while waiting.
pub poll: Duration,
}
impl Default for Waits {
fn default() -> Self {
Waits { pending: Duration::from_secs(240), settle: Duration::from_secs(60), poll: Duration::from_millis(500) }
}
}
/// Why a call has no result. Each holds the message for the caller (an agent reads it).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CallError {
/// Nothing listens at the address: the app is not running, or it quit before the call was
/// sent. The message says how to start it.
NotRunning(String),
/// The app went away or did not answer during the call, after running it or not.
Lost(String),
/// The request is still running in the app after the wait (it starts with [`STILL_RUNNING`]),
/// or an earlier one is and this one was not sent.
StillRunning(String),
/// The app answered with an error (a refused token says which token file it came from).
Refused(String),
/// The reply was not a control reply.
BadReply(String),
}
impl CallError {
/// The message.
pub fn message(&self) -> &str {
match self {
CallError::NotRunning(m) | CallError::Lost(m) | CallError::StillRunning(m) | CallError::Refused(m) | CallError::BadReply(m) => m,
}
}
}
impl std::fmt::Display for CallError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.message())
}
}
impl std::error::Error for CallError {}
impl From<CallError> for String {
fn from(e: CallError) -> String {
e.message().to_string()
}
}
/// A request: its method and parameters, how messages name it and what it does if it is still
/// running when its call returns.
#[derive(Clone, Debug)]
pub struct Request {
pub method: String,
pub params: Value,
/// The request in messages ("`engine.execute` (solid.fillet)").
pub what: String,
/// What it still does when it finishes after its wait.
pub effect: Effect,
/// Never sent twice: on a fresh connection, waiting up to [`ONCE_TIMEOUT`], and once it is
/// being written any error is final, as the app may have run it. Otherwise a request that
/// finds its connection lost is sent once more on a fresh one (the app may have restarted).
pub once: bool,
}
impl Request {
/// `method` with `params`, named "`method`" in messages, taken to change the document, sent
/// again once on a fresh connection when its connection was lost.
pub fn new(method: &str, params: Value) -> Self {
Request { method: method.to_string(), params, what: format!("`{method}`"), effect: Effect::Changes, once: false }
}
}
/// A control reply as a call's result: its `result`, or its `error`.
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())
}
}
/// A request the app said is still running. Its reply will come on this connection, through
/// `control.pending`, so the connection is kept for it.
struct Outstanding {
what: String,
/// What it does when it finishes; `None`: not known (a request this client did not send).
effect: Option<Effect>,
since: Instant,
}
impl Outstanding {
fn secs(&self) -> u64 {
self.since.elapsed().as_secs()
}
}
/// What became of a request still running when its call returned, once a later call waited it
/// out: kept for [`Connection::pending`].
enum Settled {
Finished { what: String, reply: Value },
Lost { what: String },
}
/// The end of a wait for an outstanding request.
enum Waited {
/// It finished: its own reply.
Done(Value),
/// The app holds nothing (any more) for this connection.
Nothing,
/// Still running when the wait ran out.
Running,
}
/// A connection to the app listening at an address. It connects when a call needs it, so a
/// client started before the app reaches it once it runs.
pub struct Connection {
app: App,
/// What the app calls its document in messages ("design").
document: &'static str,
addr: String,
port: u16,
conn: Option<(BufReader<TcpStream>, TcpStream)>,
/// Counts the connections made, so a caller can tell a fresh one from the one it asked.
serial: u64,
next_id: u64,
/// The token given, when one was. Otherwise each request looks the token up again, since
/// every launch of the app makes a new one.
explicit_token: Option<String>,
/// A request still running in the app; its reply waits on `conn`.
outstanding: Option<Outstanding>,
/// An outstanding request's end, once a later call waited for it (for `pending`).
settled: Option<Settled>,
waits: Waits,
/// Where a long wait is reported.
progress: fn(&str),
}
impl Connection {
/// A connection to `app` at `addr` (`host:port`), with `token` when given, else the app's
/// token found the usual way ([`App::client_token`]); not connected yet.
pub fn new(app: App, addr: &str, token: Option<&str>) -> Self {
let port = addr.rsplit(':').next().and_then(|p| p.parse::<u16>().ok()).unwrap_or(0);
Self {
app,
document: "design",
addr: addr.to_string(),
port,
conn: None,
serial: 0,
next_id: 1,
explicit_token: token.map(str::to_string),
outstanding: None,
settled: None,
waits: Waits::default(),
progress: |_| {},
}
}
/// What the app calls its document in messages ("design", the default).
#[must_use]
pub fn with_document(mut self, document: &'static str) -> Self {
self.document = document;
self
}
/// Report a long wait for a request still running to `progress`, every 30 s.
#[must_use]
pub fn with_progress(mut self, progress: fn(&str)) -> Self {
self.progress = progress;
self
}
/// How long to wait for a request still running.
pub fn set_waits(&mut self, waits: Waits) {
self.waits = waits;
}
/// The address it connects to.
pub fn addr(&self) -> &str {
&self.addr
}
/// The port of the address (0 when it names none).
pub fn port(&self) -> u16 {
self.port
}
/// The token given, if one was.
pub fn explicit_token(&self) -> Option<&str> {
self.explicit_token.as_deref()
}
/// Whether a connection is open now.
pub fn is_connected(&self) -> bool {
self.conn.is_some()
}
/// The number of connections made so far: the same number while the same connection stays
/// open.
pub fn serial(&self) -> u64 {
self.serial
}
/// Whether a request of this connection is still running in the app.
pub fn has_outstanding(&self) -> bool {
self.outstanding.is_some()
}
/// Close the connection. A request still running loses its reply with it.
pub fn disconnect(&mut self) {
self.conn = None;
if let Some(o) = self.outstanding.take() {
self.settled = Some(Settled::Lost { what: o.what });
}
}
/// Connect afresh. Failing to reach the app at all is `NotConnected`, so [`Connection::explain`]
/// can tell it from a connection lost during a call.
///
/// # Errors
/// `NotConnected` when nothing listens at the address (or it does not resolve).
pub fn connect(&mut self) -> std::io::Result<()> {
self.disconnect();
let not_connected = |e: std::io::Error| std::io::Error::new(std::io::ErrorKind::NotConnected, e);
let mut last = std::io::Error::new(std::io::ErrorKind::NotFound, format!("cannot resolve {}", self.addr));
for sa in self.addr.to_socket_addrs().map_err(not_connected)? {
match TcpStream::connect_timeout(&sa, CONNECT_TIMEOUT) {
Ok(s) => {
s.set_nodelay(true).ok();
s.set_read_timeout(Some(READ_TIMEOUT)).ok();
let read = s.try_clone()?;
self.conn = Some((BufReader::new(read), s));
self.serial += 1;
return Ok(());
}
Err(e) => last = e,
}
}
Err(not_connected(last))
}
/// See whether the app is there now; the error says why not. The connection doesn't stay
/// open: the app closes one that shows no token within a few seconds, and the first call may
/// be long away. That call connects again.
///
/// # Errors
/// As [`Connection::connect`].
pub fn try_connect(&mut self) -> std::io::Result<()> {
self.connect()?;
self.disconnect();
Ok(())
}
/// The error for a failed exchange: whether the app is not running (and how to start it) or
/// went away during the call.
pub fn explain(&self, e: &std::io::Error) -> CallError {
let (addr, port, name, document) = (&self.addr, self.port, self.app.name, self.document);
let start = format!("{} --control {port}", name.to_lowercase());
if e.kind() == std::io::ErrorKind::NotConnected {
CallError::NotRunning(format!(
"no {name} app is listening at {addr} ({e}): it is not running, or it quit. Start it with `{start}` (or ask the user to); the \
next call connects to it"
))
} else {
CallError::Lost(format!(
"the {name} app at {addr} did not answer ({e}): it may have quit or crashed during this call, after running it or not. Inspect \
the {document} before sending a change again; if the app quit, start it with `{start}`"
))
}
}
/// The request line for `method`: a fresh id and the app's token (looked up again for every
/// request: an app restarted mid-session has a new one).
pub fn request_line(&mut self, method: &str, params: Value) -> String {
let id = self.next_id;
self.next_id += 1;
let mut msg = json!({"id": id, "method": method, "params": params});
if let Some(t) = self.app.client_token(self.port, self.explicit_token.as_deref()) {
msg["token"] = json!(t.token);
}
msg.to_string()
}
/// One request line out and one reply line back, at most [`MAX_REPLY`] long, connecting
/// first when not connected. Any failure closes the connection (a timed-out read leaves a
/// late reply on the stream).
fn roundtrip(&mut self, line: &str) -> std::io::Result<String> {
if self.conn.is_none() {
self.connect()?;
}
let Some((reader, writer)) = self.conn.as_mut() else { return Err(std::io::Error::other("not connected")) };
// One write: a request that loses its newline still reaches the app as a request.
let sent = writer.write_all(format!("{line}\n").as_bytes()).and_then(|()| writer.flush());
if let Err(e) = sent {
self.disconnect();
return Err(e);
}
let mut reply = String::new();
let n = match reader.by_ref().take(MAX_REPLY).read_line(&mut reply) {
Ok(n) => n,
Err(e) => {
self.disconnect();
return Err(e);
}
};
if n == 0 || !reply.ends_with('\n') {
self.disconnect();
return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "connection closed"));
}
Ok(reply)
}
fn set_read_timeout(&self, t: Duration) {
if let Some((_, writer)) = &self.conn {
writer.set_read_timeout(Some(t)).ok();
}
}
/// A reply line as JSON.
fn parse(reply: &str) -> Result<Value, CallError> {
serde_json::from_str(reply).map_err(|e| CallError::BadReply(format!("bad reply from the app: {e}")))
}
/// A control reply as a call's result; a refused token says which token file it came from
/// (and whether it is stale).
///
/// # Errors
/// [`CallError::Refused`] with the app's error.
pub fn outcome(&self, v: &Value) -> Result<Value, CallError> {
outcome(v).map_err(|error| {
CallError::Refused(
self.app.client_token(self.port, self.explicit_token.as_deref()).map_or_else(|| error.clone(), |t| t.explain_error(&error)),
)
})
}
/// `method` with `params`, at once and once: not behind a request still running on this
/// connection, no second try. The app's whole reply (`ok`, `result` or `error`, and anything
/// it adds), for a request the app answers at once on any connection
/// (`control.capabilities`, `control.running`).
///
/// # Errors
/// As [`Connection::explain`]; [`CallError::BadReply`].
pub fn ask(&mut self, method: &str, params: Value) -> Result<Value, CallError> {
let line = self.request_line(method, params);
let reply = self.roundtrip(&line).map_err(|e| self.explain(&e))?;
Self::parse(&reply)
}
/// `method` with `params`, waiting at most `timeout` for the reply and never behind a request
/// still running: for a request the app answers within a frame, asked again later when the
/// app is busy. One try.
///
/// # Errors
/// [`CallError::StillRunning`] when a request of this connection is still running; as
/// [`Connection::ask`] and [`Connection::outcome`].
pub fn quick(&mut self, method: &str, params: Value, timeout: Duration) -> Result<Value, CallError> {
if self.outstanding.is_some() {
return Err(CallError::StillRunning("a request is still running in the app".into()));
}
if self.conn.is_none() {
self.connect().map_err(|e| self.explain(&e))?;
}
let line = self.request_line(method, params);
self.set_read_timeout(timeout);
let reply = self.roundtrip(&line);
self.set_read_timeout(READ_TIMEOUT);
let reply = reply.map_err(|e| self.explain(&e))?;
let v = Self::parse(&reply)?;
self.outcome(&v)
}
/// Ask the app, on this connection only, about the request it still runs for it.
fn ask_pending(&mut self) -> Result<Value, CallError> {
if self.conn.is_none() {
self.disconnect();
return Err(CallError::Lost("the connection to the app was lost".into()));
}
let v = self.ask("control.pending", json!({}))?;
outcome(&v).map_err(CallError::Refused).inspect_err(|_| self.disconnect())
}
/// `control.cancel` for the request still running on this connection. Sent at once, without
/// waiting for that request first, and never on a fresh connection, which has nothing to
/// cancel. Once the app no longer holds it (removed, stopped or finished), later calls don't
/// wait for it.
///
/// # Errors
/// As [`Connection::ask`]; [`CallError::Refused`].
pub fn cancel(&mut self, params: Value) -> Result<Value, CallError> {
if self.conn.is_none() {
return Ok(json!({"cancelled": null, "note": "nothing to cancel: no request of this client is running in the app"}));
}
let v = self.ask("control.cancel", params)?;
let r = outcome(&v).map_err(CallError::Refused);
if r.is_ok() {
self.outstanding = None;
}
r
}
/// Wait up to `limit` for the outstanding request, asking `control.pending` now and then and
/// reporting how long it takes. An error: the connection, and so the reply, was lost.
fn wait_outstanding(&mut self, limit: Duration) -> Result<Waited, CallError> {
let start = Instant::now();
let mut told = start;
loop {
let Some(o) = &self.outstanding else { return Ok(Waited::Nothing) };
let what = o.what.clone();
let r = self.ask_pending()?;
if r.get("pending").is_none_or(Value::is_null) {
self.outstanding = None;
return Ok(Waited::Nothing);
}
if r.get("done").and_then(Value::as_bool) == Some(true) {
self.outstanding = None;
return Ok(Waited::Done(r.get("reply").cloned().unwrap_or(Value::Null)));
}
let waited = start.elapsed();
if waited >= limit {
return Ok(Waited::Running);
}
if told.elapsed() >= PROGRESS_EVERY {
let secs = self.outstanding.as_ref().map_or(0, Outstanding::secs);
(self.progress)(&format!("{what} is still running in the app ({secs} s); waiting for it"));
told = Instant::now();
}
std::thread::sleep(self.waits.poll.min(limit.saturating_sub(waited)));
}
}
/// The error for the outstanding request still running after its wait.
fn still_running(&self, earlier: bool) -> CallError {
let Some(o) = &self.outstanding else { return CallError::StillRunning(format!("{STILL_RUNNING} a request is still running in the app")) };
let document = self.document;
let effect =
o.effect.map_or_else(|| format!("it was not cancelled and may still change the {document} when it finishes"), |e| e.when_done(document));
let settle = self.waits.settle.as_secs();
CallError::StillRunning(if earlier {
format!(
"{STILL_RUNNING} an earlier request, {}, is still running in the app ({} s; {effect}), so this call was not sent. Call the \
`pending` tool to wait for its result, then send this call again",
o.what,
o.secs()
)
} else {
format!(
"{STILL_RUNNING} {} is still running in the app after {} s ({effect}); don't send it again. Call the `pending` tool to \
wait for its result (up to {settle} s per call); other calls wait for it first",
o.what,
o.secs()
)
})
}
/// Before a new request: wait for one still running from an earlier call, keeping its end for
/// `pending`. Still running after the wait: the new request is not sent.
fn settle_earlier(&mut self) -> Result<(), CallError> {
let Some(what) = self.outstanding.as_ref().map(|o| o.what.clone()) else { return Ok(()) };
match self.wait_outstanding(self.waits.settle) {
Ok(Waited::Done(reply)) => self.settled = Some(Settled::Finished { what, reply }),
Ok(Waited::Nothing) => {}
Ok(Waited::Running) => return Err(self.still_running(true)),
// The connection was lost, and the earlier reply with it (`pending` says so): the new
// request goes on a fresh connection.
Err(_) => {}
}
Ok(())
}
/// `control.pending` for the client: the end of the request still running from an earlier
/// call, waiting for it up to the settle wait: `{pending: what | null, done?, reply?, lost?,
/// running_s?}`. Never sent on a fresh connection, which has nothing pending.
pub fn pending(&mut self) -> Value {
if let Some(s) = self.settled.take() {
return match s {
Settled::Finished { what, reply } => json!({"pending": what, "done": true, "reply": reply}),
Settled::Lost { what } => json!({"pending": what, "lost": true}),
};
}
let Some(what) = self.outstanding.as_ref().map(|o| o.what.clone()) else { return json!({"pending": null}) };
match self.wait_outstanding(self.waits.settle) {
Ok(Waited::Done(reply)) => json!({"pending": what, "done": true, "reply": reply}),
Ok(Waited::Nothing) => json!({"pending": null}),
Ok(Waited::Running) => json!({"pending": what, "done": false, "running_s": self.outstanding.as_ref().map_or(0, Outstanding::secs)}),
Err(_) => {
self.settled = None;
json!({"pending": what, "lost": true})
}
}
}
/// Send `request` and wait for its reply: the app's whole reply (`ok`, `result` or `error`,
/// and anything it adds). First a request still running from an earlier call is waited for
/// (except for `control.running`, which the app answers at once); a request the app says is
/// still running is waited for through `control.pending`; a request refused unrun as busy
/// behind one this client did not know of is sent once more after that one, when
/// `retry_busy`.
///
/// # Errors
/// As [`Connection::explain`]: a request whose connection is lost is sent once more on a fresh
/// one (unless [`Request::once`]), and when nothing listens any more the app went away, maybe
/// while running it ([`CallError::Lost`]); [`CallError::StillRunning`]; [`CallError::BadReply`].
pub fn exchange(&mut self, request: Request, retry_busy: bool) -> Result<Value, CallError> {
let Request { method, params, what, effect, once } = request;
if method != "control.running" {
self.settle_earlier()?;
}
let again = retry_busy.then(|| params.clone());
let sent = Instant::now();
let line = self.request_line(&method, params);
let reply = if once {
// A fresh connection (an idle one may have been closed by an app restart; connecting
// again sends nothing).
self.connect().or_else(|_| self.connect()).and_then(|()| {
self.set_read_timeout(ONCE_TIMEOUT);
let r = self.roundtrip(&line);
self.set_read_timeout(READ_TIMEOUT);
r
})
} else {
self.roundtrip(&line).or_else(|lost| {
self.roundtrip(&line).map_err(|e| if e.kind() == std::io::ErrorKind::NotConnected && lost.kind() != e.kind() { lost } else { e })
})
}
.map_err(|e| self.explain(&e))?;
let v = Self::parse(&reply)?;
// Timed out in the app, still running: wait for its result on this connection.
if v.get("running").and_then(Value::as_bool) == Some(true) {
self.outstanding = Some(Outstanding { what: what.clone(), effect: Some(effect), since: sent });
(self.progress)(&format!(
"{what} is still running in the app after {} s; waiting up to {} s more for it",
sent.elapsed().as_secs(),
self.waits.pending.as_secs()
));
let document = self.document;
return match self.wait_outstanding(self.waits.pending)? {
Waited::Done(reply) => Ok(reply),
Waited::Nothing => Err(CallError::Lost(format!(
"{what} timed out in the app, which kept no result for it: inspect the {document} before sending it again"
))),
Waited::Running => Err(self.still_running(false)),
};
}
// Refused unrun behind a request this client did not know of: wait for that one, then
// send this one once more.
if v.get("busy").and_then(Value::as_bool) == Some(true)
&& let Some(params) = again
{
self.outstanding = Some(Outstanding { what: "an earlier request".into(), effect: None, since: Instant::now() });
self.settle_earlier()?;
return self.exchange(Request { method, params, what, effect, once }, false);
}
Ok(v)
}
/// [`Connection::exchange`] (retrying a busy refusal once) and the reply's result.
///
/// # Errors
/// As [`Connection::exchange`] and [`Connection::outcome`].
pub fn call(&mut self, request: Request) -> Result<Value, CallError> {
let v = self.exchange(request, true)?;
self.outcome(&v)
}
}
#[cfg(test)]
#[path = "client_tests.rs"]
mod tests;
+190
View File
@@ -0,0 +1,190 @@
//! The client against the shared server ([`crate::server::Hub`]) on an ephemeral loopback port.
use super::*;
use crate::ControlRequest;
use crate::server::{Hub, Protocol, Stop, Summary, Waits as ServerWaits};
use std::ffi::OsString;
use std::net::TcpListener;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::mpsc::channel;
const TOKEN: &str = "0123456789abcdef0123456789abcdef";
fn no_dir() -> Option<PathBuf> {
None
}
fn no_env(_: &str) -> Option<OsString> {
None
}
fn utc(secs: u64) -> String {
secs.to_string()
}
/// An app with no token files and no environment: a client sends only the token it is given.
const APP: App = App { name: "Probe", data_dir: no_dir, env: no_env, utc, default_port: 0 };
/// An app whose requests all may change its document.
struct Probe;
impl Protocol for Probe {
fn summary(&self, method: &str, _: &Value) -> Summary {
Summary { what: format!("`{method}`"), effect: Effect::Changes, command: None, steps: None, long: false }
}
fn document(&self) -> &'static str {
"design"
}
fn change_event(&self) -> &'static str {
"design.changed"
}
fn revision_method(&self) -> &'static str {
"document.revision"
}
fn docs(&self) -> &'static str {
"docs/control-protocol.md"
}
fn capabilities(&self) -> Value {
json!({})
}
}
/// The app on `port` (0: an ephemeral one) behind [`TOKEN`]: its window answers each request after
/// `delay` with the request's method and parameters, and the server says a request is still
/// running after `wait`.
fn serve(port: u16, delay: Duration, wait: Duration) -> Stop {
// A port just closed may take a moment to be free again on a loaded machine.
let started = Instant::now();
let mut bound = TcpListener::bind(("127.0.0.1", port));
while bound.is_err() && started.elapsed() < Duration::from_secs(2) {
std::thread::sleep(Duration::from_millis(10));
bound = TcpListener::bind(("127.0.0.1", port));
}
let listener = bound.unwrap();
let (tx, rx) = channel::<ControlRequest>();
std::thread::spawn(move || {
for req in rx {
std::thread::sleep(delay);
let _ = req.reply.send(json!({"ok": true, "result": {"method": req.method, "params": req.params}}));
}
});
let waits = ServerWaits { short: wait, long: wait, token: Duration::from_secs(5) };
let hub = Arc::new(Hub::new(Probe, || {}, 1 << 20).with_waits(waits));
hub.listen_stoppable(listener, TOKEN.into(), tx, false).unwrap()
}
fn addr(port: u16) -> String {
format!("127.0.0.1:{port}")
}
/// A port nothing listens on.
fn free_port() -> u16 {
TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
}
#[test]
fn a_call_is_one_round_trip_with_the_token() {
let app = serve(0, Duration::ZERO, Duration::from_secs(10));
let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN));
assert!(!c.is_connected());
let r = c.call(Request::new("document.inspect", json!({"a": 1}))).unwrap();
assert_eq!(r, json!({"method": "document.inspect", "params": {"a": 1}}));
assert!(c.is_connected());
let serial = c.serial();
// the next call goes on the same connection
c.call(Request::new("document.inspect", json!({}))).unwrap();
assert_eq!(c.serial(), serial);
// `try_connect` sees the app there and leaves no connection open
let mut fresh = Connection::new(APP, &addr(app.port()), Some(TOKEN));
fresh.try_connect().unwrap();
assert!(!fresh.is_connected());
}
#[test]
fn a_wrong_token_or_none_is_refused() {
let app = serve(0, Duration::ZERO, Duration::from_secs(10));
for token in [Some("fedcba9876543210fedcba9876543210"), None] {
let mut c = Connection::new(APP, &addr(app.port()), token);
match c.call(Request::new("document.inspect", json!({}))) {
Err(CallError::Refused(e)) => assert!(e.starts_with("unauthorized"), "{token:?}: {e}"),
other => panic!("{token:?}: {other:?}"),
}
}
}
#[test]
fn an_app_not_running_says_how_to_start_it() {
let port = free_port();
let mut c = Connection::new(APP, &addr(port), Some(TOKEN));
let e = c.call(Request::new("document.inspect", json!({}))).unwrap_err();
let CallError::NotRunning(m) = &e else { panic!("{e:?}") };
assert!(m.starts_with(&format!("no Probe app is listening at 127.0.0.1:{port}")), "{m}");
assert!(m.contains(&format!("`probe --control {port}`")), "{m}");
assert_eq!(c.try_connect().unwrap_err().kind(), std::io::ErrorKind::NotConnected);
}
/// An app that goes away during a call is lost, not "not running"; the next call says it is not
/// running, and once it runs again the next call reaches it.
#[test]
fn an_app_gone_during_a_call_is_lost_and_reached_again_once_back() {
let app = serve(0, Duration::ZERO, Duration::from_secs(10));
let port = app.port();
let mut c = Connection::new(APP, &addr(port), Some(TOKEN));
c.call(Request::new("document.inspect", json!({}))).unwrap();
app.stop();
let e = c.call(Request::new("document.inspect", json!({}))).unwrap_err();
let CallError::Lost(m) = &e else { panic!("{e:?}") };
assert!(m.contains("may have quit") && m.contains("Inspect the design") && m.contains(&format!("`probe --control {port}`")), "{m}");
assert!(matches!(c.call(Request::new("document.inspect", json!({}))), Err(CallError::NotRunning(_))));
let _back = serve(port, Duration::ZERO, Duration::from_secs(10));
assert_eq!(c.call(Request::new("ui.view", json!({}))).unwrap()["method"], json!("ui.view"));
}
/// A server that reads a request and closes the connection without a reply: the call is lost
/// (after one more try on a fresh connection), and the reply is never taken for "not running".
#[test]
fn a_connection_closed_without_a_reply_is_lost() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
for stream in listener.incoming().flatten() {
let mut line = String::new();
let _ = BufReader::new(stream).read_line(&mut line);
}
});
let mut c = Connection::new(APP, &addr(port), Some(TOKEN));
let e = c.call(Request::new("document.inspect", json!({}))).unwrap_err();
assert!(matches!(e, CallError::Lost(_)), "{e:?}");
assert!(!c.is_connected());
}
/// A request the app says is still running is waited for through `control.pending`, on the same
/// connection, and its own reply is the call's result.
#[test]
fn a_request_still_running_is_waited_for_through_pending() {
let app = serve(0, Duration::from_millis(400), Duration::from_millis(50));
let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN));
c.set_waits(Waits { pending: Duration::from_secs(10), settle: Duration::from_secs(10), poll: Duration::from_millis(5) });
let r = c.call(Request::new("solid.slow", json!({"n": 2}))).unwrap();
assert_eq!(r, json!({"method": "solid.slow", "params": {"n": 2}}));
assert!(!c.has_outstanding());
assert_eq!(c.pending(), json!({"pending": null}));
}
/// Past the wait, the call says the request is still running, and `pending` later has its end.
#[test]
fn a_request_still_running_past_the_wait_is_reported_and_its_end_kept() {
let app = serve(0, Duration::from_millis(400), Duration::from_millis(20));
let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN));
c.set_waits(Waits { pending: Duration::from_millis(30), settle: Duration::from_secs(10), poll: Duration::from_millis(5) });
let mut slow = Request::new("solid.slow", json!({}));
slow.what = "`solid.slow` (now)".into();
let e = c.call(slow).unwrap_err();
let CallError::StillRunning(m) = &e else { panic!("{e:?}") };
assert!(m.starts_with(STILL_RUNNING) && m.contains("`solid.slow` (now)") && m.contains("will still apply"), "{m}");
assert!(c.has_outstanding());
let end = c.pending();
assert_eq!(end["done"], json!(true), "{end}");
assert_eq!(end["reply"]["result"]["method"], json!("solid.slow"), "{end}");
}
+27
View File
@@ -0,0 +1,27 @@
//! What a client is told about a control request that outlasts its wait (docs/control-protocol.md,
//! #1618): the app's control server and a bridged client both say what the request still does when
//! it finishes. Which requests do what is the app's to say.
/// What a request still running does when it finishes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Effect {
/// It only reads (the document, the window or the command list): nothing changes.
ReadsOnly,
/// It writes a file (an export, a save, a render to a path); the document stays as it is.
WritesFile,
/// It changes the document (or may: anything not known to read or only write a file).
Changes,
}
impl Effect {
/// What happens when the request finishes, for a message: "it only reads: nothing changes",
/// "it was not cancelled and will still write the file when it finishes; the design does not
/// change", … `document` is what the app calls its document ("design").
pub fn when_done(self, document: &str) -> String {
match self {
Effect::ReadsOnly => "it only reads: nothing changes".into(),
Effect::WritesFile => format!("it was not cancelled and will still write the file when it finishes; the {document} does not change"),
Effect::Changes => "it was not cancelled and will still apply when it finishes".into(),
}
}
}
+26
View File
@@ -0,0 +1,26 @@
//! The control channel any app may share (docs/control-protocol.md): the per-launch token and its
//! files ([`auth`]), the loopback server that admits a connection by the token and hands each
//! request to the window ([`server`]), the client that talks to it ([`client`]), the request the
//! window answers ([`ControlRequest`]), the document watch subscribed connections wait on
//! ([`DocumentWatch`]), and what a request still running does when it finishes ([`Effect`]). It
//! needs no UI toolkit; the window's own requests over egui (`ui.screenshot`, `ui.resize`) are
//! `craft-control-egui`.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
pub mod auth;
mod cancel;
#[cfg(not(target_arch = "wasm32"))]
pub mod client;
mod effect;
mod request;
#[cfg(not(target_arch = "wasm32"))]
pub mod server;
pub use cancel::{Cancel, Ticket};
pub use effect::Effect;
pub use request::{ControlRequest, ControlResponse, DOCUMENT_WATCH, DocumentWatch, Subscriber, cancelled_chat_response, chat_turn_cancelled};
/// How an error from the client (`client`, native only) starts when a request is still running
/// in the app after the wait. Outside the client so callers on every target can test for it.
pub const STILL_RUNNING: &str = "still running:";
+125
View File
@@ -0,0 +1,125 @@
//! A control request as the window gets it, and the design watch subscribed connections wait on.
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::mpsc::Sender;
use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use serde_json::{Value, json};
pub type ControlResponse = Value;
pub struct ControlRequest {
pub method: String,
pub params: Value,
pub reply: Sender<ControlResponse>,
/// Set once the window starts on it; until then it waits its turn (`control.running`, #3654).
pub started: std::sync::Arc<std::sync::atomic::AtomicBool>,
/// Chat requests already admitted by the gate may outlive a tab switch. This turn's
/// validity follows them through queues, computation and cursor animation.
pub chat_turn: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
/// Where the request is, shared with the connection that sent it so it can cancel it
/// (`control.cancel`, #1989).
pub ticket: std::sync::Arc<crate::Ticket>,
/// Told apart from every other request of this run: names its row while it waits.
pub serial: u64,
}
impl ControlRequest {
pub fn new(method: impl Into<String>, params: Value) -> (Self, std::sync::mpsc::Receiver<ControlResponse>) {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
let (tx, rx) = std::sync::mpsc::channel();
let serial = NEXT.fetch_add(1, Ordering::Relaxed);
(Self { method: method.into(), params, reply: tx, started: Default::default(), chat_turn: None, ticket: Default::default(), serial }, rx)
}
/// Answer a request whose agent chat turn has ended, and say so: such a request is not run.
pub fn refuse_cancelled_chat(&self) -> bool {
if chat_turn_cancelled(self.chat_turn.as_deref()) {
let _ = self.reply.send(cancelled_chat_response());
true
} else {
false
}
}
}
/// Whether the agent chat turn a request belongs to has ended (`None`: it belongs to none).
pub fn chat_turn_cancelled(turn: Option<&std::sync::atomic::AtomicBool>) -> bool {
turn.is_some_and(|active| !active.load(std::sync::atomic::Ordering::Relaxed))
}
/// The reply to a request whose agent chat turn has ended.
pub fn cancelled_chat_response() -> Value {
json!({"ok": false, "error": "not run: the agent chat turn ended or its document tab was left"})
}
/// The active design's id and revision for control connections that sent `control.subscribe`
/// (#6985): the window publishes them each frame while one is subscribed, and each such
/// connection waits for them to move, then sends the app's change event (`Protocol::change_event`).
#[derive(Default)]
pub struct DocumentWatch {
subscribers: AtomicUsize,
now: Mutex<Option<(String, u64)>>,
moved: Condvar,
}
/// The app's [`DocumentWatch`].
pub static DOCUMENT_WATCH: DocumentWatch = DocumentWatch::new();
impl DocumentWatch {
pub const fn new() -> Self {
DocumentWatch { subscribers: AtomicUsize::new(0), now: Mutex::new(None), moved: Condvar::new() }
}
fn now(&self) -> MutexGuard<'_, Option<(String, u64)>> {
self.now.lock().unwrap_or_else(PoisonError::into_inner)
}
/// The design as last published (`None` before anything was).
pub fn current(&self) -> Option<(String, u64)> {
self.now().clone()
}
/// The design as it is now; waiters wake only when it moved. Only the latest is kept, so
/// changes made faster than a connection sends them go out as one.
pub fn publish(&self, document_id: &str, revision: u64) {
let mut now = self.now();
if now.as_ref().is_some_and(|(id, r)| id == document_id && *r == revision) {
return;
}
*now = Some((document_id.to_string(), revision));
self.moved.notify_all();
}
/// Whether a connection is subscribed: the window publishes only then.
pub fn subscribed(&self) -> bool {
self.subscribers.load(Ordering::Relaxed) > 0
}
/// Count a subscribed connection until the returned guard is dropped.
pub fn join(&'static self) -> Subscriber {
self.subscribers.fetch_add(1, Ordering::Relaxed);
Subscriber(self)
}
/// Wait up to `wait` for the design to differ from `seen`, or for `stop`; the design then
/// (`None` before anything was published).
pub fn wait(&self, seen: &(String, u64), stop: &AtomicBool, wait: Duration) -> Option<(String, u64)> {
let unmoved = |now: &mut Option<(String, u64)>| now.as_ref() == Some(seen) && !stop.load(Ordering::Relaxed);
let (now, _) = self.moved.wait_timeout_while(self.now(), wait, unmoved).unwrap_or_else(PoisonError::into_inner);
now.clone()
}
}
/// A subscribed connection, counted by its [`DocumentWatch`] while this lives.
pub struct Subscriber(&'static DocumentWatch);
impl Drop for Subscriber {
fn drop(&mut self) {
self.0.subscribers.fetch_sub(1, Ordering::Relaxed);
// Under the lock, so a connection about to wait sees its `stop` set before it does.
let _now = self.0.now();
self.0.moved.notify_all();
}
}
File diff suppressed because it is too large. Load diff
+9 -2
View File
@@ -4,7 +4,7 @@ use std::collections::HashMap;
use craft_wordmodel::para::cap_alt;
use craft_wordmodel::props::{
Align, Border, BorderStyle, Borders, CellProps, CharProps, CombineBrackets, EastAsianLayout, HeightRule, Highlight, LineSpacing, NumRef,
Align, Border, BorderStyle, Borders, CellProps, CharProps, CombineBrackets, EastAsianLayout, HeightRule, Highlight, Kashida, LineSpacing, NumRef,
ParaProps, ParagraphTextDirection, Rgb, RowProps, TabAlign, TabLeader, TabStop, TableFloat, TableLook, TableProps, TextAlignment, TextColor,
TextDirection, Underline, VAlign, VMerge, VertAlign,
};
@@ -465,7 +465,14 @@ impl PropCtx {
_ => {}
}
}
"w:jc" => p.align = k.attr("w:val").map(align),
"w:jc" => {
if let Some(v) = k.attr("w:val") {
p.align = Some(align(v));
if let Some(kashida) = Kashida::from_jc(v) {
p.kashida = Some(kashida);
}
}
}
"w:outlineLvl" => p.outline_level = k.attr("w:val").and_then(u32_of).map(|v| v.min(9) as u8),
"w:rPr" => mark = self.rpr(k),
_ => {}
+1
View File
@@ -47,6 +47,7 @@ pub(crate) fn preset_kind(prst: &str) -> ShapeKind {
"downArrow" => ShapeKind::ArrowDown,
"star4" | "star5" | "star6" | "star7" | "star8" | "star10" | "star12" | "star16" | "star24" | "star32" => ShapeKind::Star,
"heart" => ShapeKind::Heart,
"frame" => ShapeKind::Frame,
_ => ShapeKind::Rectangle,
}
}
+1
View File
@@ -22,6 +22,7 @@ use craft_wordmodel::wordart::TextWarp;
mod blocks;
mod drawing;
mod fields;
mod locked_canvas;
mod runs;
mod vml;
+13 -4
View File
@@ -82,6 +82,10 @@ impl Reader<'_> {
self.read_canvas(sc, c, rels, w, h, float)
} else if let Some(g) = gd.child("wpg:wgp") {
self.read_group(sc, g, rels, w, h, float)?
} else if let Some(lc) = gd.child("lc:lockedCanvas") {
// Word 2007's shapes, pictures and text in a drawing: read as the group they are.
let g = super::locked_canvas::as_group(lc, &self.doc.settings.theme_colors);
self.read_group(sc, &g, rels, w, h, float)?
} else if direct_shape.is_none() && gd.find("a:blip").is_some() {
self.read_pic(gd, rels, w, h, alt.clone(), float)?
} else {
@@ -526,12 +530,17 @@ impl Reader<'_> {
outline_fill: paint.outline_fill,
..ShapeExtra::default()
};
// A rounded rectangle's own corner (`adj`, ECMA-376 §20.1.10.56); other presets drawn as
// rounded rectangles keep the default.
if prst == "roundRect" {
// A rounded rectangle's own corner (`adj`, ECMA-376 §20.1.10.56), a frame's own border
// width (`adj1`); other presets drawn as rounded rectangles keep the default.
let adj = match prst {
"roundRect" => Some("adj"),
"frame" => Some("adj1"),
_ => None,
};
if let Some(adj) = adj {
extra.corner = sppr
.and_then(|s| s.child("a:prstGeom"))
.and_then(|g| preset_adj(g, "adj"))
.and_then(|g| preset_adj(g, adj))
.and_then(|v| u32::try_from(v.clamp(0, i64::from(craft_wordmodel::connector::MAX_CORNER))).ok());
}
// Arrowheads: any end type but `none` (ECMA-376 §20.1.10.33) is drawn as a triangle of its
+265
View File
@@ -0,0 +1,265 @@
//! A DrawingML locked canvas (`lc:lockedCanvas`, ECMA-376 Part 1 §20.3.2.1): the shapes,
//! pictures and text Word 2007 writes in a drawing in compatibility mode (wordcraft#5060). It is a group
//! shape in the DrawingML namespace (`a:sp`, `a:pic`, `a:grpSp`, `a:cxnSp`, text in `a:txSp`), so
//! it is read as the `wpg:wgp` group the reader already knows: each member renamed into its
//! WordprocessingML drawing form, and its DrawingML text into `w:txbxContent` paragraphs.
use super::{El, Node, Rgb};
/// Groups nested deeper than this are left out, as `group_members` does.
const MAX_NEST: usize = 8;
/// DrawingML's text size when neither the run nor the list style gives one (18 pt, in
/// hundredths of a point).
const DEFAULT_SZ: i64 = 1800;
/// The locked canvas `lc` as a `wpg:wgp` group. `theme` resolves its text colours.
pub(super) fn as_group(lc: &El, theme: &[Rgb]) -> El {
el("wpg:wgp", Vec::new(), members(lc, theme, 0))
}
/// The members of DrawingML group `g`, in their WordprocessingML drawing form.
fn members(g: &El, theme: &[Rgb], depth: usize) -> Vec<Node> {
g.els()
.filter_map(|e| match e.name.as_str() {
"a:grpSpPr" => Some(renamed(e, "wpg:grpSpPr")),
"a:grpSp" if depth < MAX_NEST => Some(el("wpg:grpSp", Vec::new(), members(e, theme, depth + 1))),
"a:sp" => Some(shape(e, theme)),
"a:cxnSp" => Some(connector(e)),
"a:pic" => Some(picture(e)),
"a:txSp" => Some(text_shape(e, theme)),
_ => None,
})
.map(Node::El)
.collect()
}
/// `a:sp` as `wps:wsp`: its name, properties and style, and its text as a text box's.
fn shape(sp: &El, theme: &[Rgb]) -> El {
let nv = sp.child("a:nvSpPr");
let mut kids: Vec<Node> = [
nv.and_then(|n| n.child("a:cNvPr")).map(|e| renamed(e, "wps:cNvPr")),
nv.and_then(|n| n.child("a:cNvSpPr")).map(|e| renamed(e, "wps:cNvSpPr")),
sp.child("a:spPr").map(|e| renamed(e, "wps:spPr")),
sp.child("a:style").map(|e| renamed(e, "wps:style")),
]
.into_iter()
.flatten()
.map(Node::El)
.collect();
// The text sits in the shape's own rectangle (`a:useSpRect`); a text rectangle of its own
// (`a:txSp/a:xfrm`) is not kept apart.
if let Some(body) = sp.child("a:txSp").and_then(|t| t.child("a:txBody")) {
kids.extend(text_box(body, theme));
}
el("wps:wsp", Vec::new(), kids)
}
/// A group's text shape (`a:txSp` as a member, text with no shape of its own) as a `wps:wsp` text
/// box without fill or outline at its own rectangle (`a:xfrm`).
fn text_shape(tx: &El, theme: &[Rgb]) -> El {
let none = || Node::El(el("a:noFill", Vec::new(), Vec::new()));
let geometry = el("a:prstGeom", attrs(&[("prst", "rect")]), vec![Node::El(el("a:avLst", Vec::new(), Vec::new()))]);
let mut sp_pr: Vec<Node> = tx.child("a:xfrm").map(|x| Node::El(x.clone())).into_iter().collect();
sp_pr.extend([Node::El(geometry), none(), Node::El(el("a:ln", Vec::new(), vec![none()]))]);
let mut kids = vec![Node::El(el("wps:cNvSpPr", attrs(&[("txBox", "1")]), Vec::new())), Node::El(el("wps:spPr", Vec::new(), sp_pr))];
if let Some(body) = tx.child("a:txBody") {
kids.extend(text_box(body, theme));
}
el("wps:wsp", Vec::new(), kids)
}
/// DrawingML text body `body` as a text box's content and body properties.
fn text_box(body: &El, theme: &[Rgb]) -> Vec<Node> {
let content = el("w:txbxContent", Vec::new(), paragraphs(body, theme));
let mut kids = vec![Node::El(el("wps:txbx", Vec::new(), vec![Node::El(content)]))];
if let Some(bp) = body.child("a:bodyPr") {
kids.push(Node::El(renamed(bp, "wps:bodyPr")));
}
kids
}
/// `a:cxnSp` as a `wps:wsp` line. Its glued ends name shapes by the canvas's own ids, which
/// aren't the document's, so they are left out.
fn connector(cx: &El) -> El {
let kids = [
cx.child("a:nvCxnSpPr").and_then(|n| n.child("a:cNvPr")).map(|e| renamed(e, "wps:cNvPr")),
cx.child("a:spPr").map(|e| renamed(e, "wps:spPr")),
cx.child("a:style").map(|e| renamed(e, "wps:style")),
];
el("wps:wsp", Vec::new(), kids.into_iter().flatten().map(Node::El).collect())
}
/// `a:pic` as `pic:pic`.
fn picture(pic: &El) -> El {
let nv = pic.child("a:nvPicPr").and_then(|n| n.child("a:cNvPr")).map(|e| el("pic:nvPicPr", Vec::new(), vec![Node::El(renamed(e, "pic:cNvPr"))]));
let kids = [nv, pic.child("a:blipFill").map(|e| renamed(e, "pic:blipFill")), pic.child("a:spPr").map(|e| renamed(e, "pic:spPr"))];
el("pic:pic", Vec::new(), kids.into_iter().flatten().map(Node::El).collect())
}
/// The paragraphs of DrawingML text body `body` as `w:p`s. DrawingML text has no space before
/// or after a paragraph and single lines, so each says so rather than taking the document's
/// defaults.
fn paragraphs(body: &El, theme: &[Rgb]) -> Vec<Node> {
body.children("a:p")
.map(|p| {
// A paragraph's properties default to the list style's for its level (`lvl`, 0–8),
// then to the list style's defaults (`a:defPPr`), property by property; a run's to its
// paragraph's own (`a:pPr/a:defRPr`), then to those two's.
let ppr_el = p.child("a:pPr");
let level = ppr_el.and_then(|pp| pp.attr("lvl")).and_then(|v| v.trim().parse::<u8>().ok()).filter(|l| *l <= 8).unwrap_or(0);
let list_style = body.child("a:lstStyle");
let paragraph_styles: Vec<&El> =
[ppr_el, list_style.and_then(|l| l.child(&format!("a:lvl{}pPr", level + 1))), list_style.and_then(|l| l.child("a:defPPr"))]
.into_iter()
.flatten()
.collect();
let defaults: Vec<&El> = paragraph_styles.iter().filter_map(|pp| pp.child("a:defRPr")).collect();
let defaults = defaults.as_slice();
let mut ppr =
vec![Node::El(el("w:spacing", attrs(&[("w:before", "0"), ("w:after", "0"), ("w:line", "240"), ("w:lineRule", "auto")]), Vec::new()))];
let jc = match paragraph_styles.iter().find_map(|pp| pp.attr("algn")) {
Some("ctr") => Some("center"),
Some("r") => Some("right"),
Some("just") => Some("both"),
Some("dist") => Some("distribute"),
Some("l") => Some("left"),
_ => None,
};
if let Some(jc) = jc {
ppr.push(Node::El(el("w:jc", attrs(&[("w:val", jc)]), Vec::new())));
}
// The paragraph mark's own size and font (`a:endParaRPr`), which an empty one's
// height follows.
ppr.push(Node::El(run_props(p.child("a:endParaRPr"), defaults, theme)));
let mut kids = vec![Node::El(el("w:pPr", Vec::new(), ppr))];
for r in p.els() {
let text = match r.name.as_str() {
"a:r" | "a:fld" => Node::El(el(
"w:t",
attrs(&[("xml:space", "preserve")]),
vec![Node::Text(r.child("a:t").map(|t| t.text()).unwrap_or_default())],
)),
"a:br" => Node::El(el("w:br", Vec::new(), Vec::new())),
_ => continue,
};
let rpr = run_props(r.child("a:rPr"), defaults, theme);
kids.push(Node::El(el("w:r", Vec::new(), vec![Node::El(rpr), text])));
}
Node::El(el("w:p", Vec::new(), kids))
})
.collect()
}
/// A DrawingML run's properties (`a:rPr`, each falling back on the first of `defaults`, the
/// `a:defRPr`s in order, that gives it) as `w:rPr`: font, size, bold, italic, underline,
/// strikethrough, caps, baseline and colour.
fn run_props(rpr: Option<&El>, defaults: &[&El], theme: &[Rgb]) -> El {
let get = |n: &str| rpr.and_then(|r| r.attr(n)).or_else(|| defaults.iter().find_map(|d| d.attr(n)));
let child = |n: &str| rpr.and_then(|r| r.child(n)).or_else(|| defaults.iter().find_map(|d| d.child(n)));
// On, off (kept, so the document's style doesn't turn it back on), or not given.
let toggle = |n: &str| match get(n) {
Some("1" | "true") => Some(true),
Some("0" | "false") => Some(false),
_ => None,
};
let mut kids = Vec::new();
let mut push = |name: &str, a: &[(&str, &str)]| kids.push(Node::El(el(name, attrs(a), Vec::new())));
// Theme fonts (`+mn-lt`) are left to the document's.
let face = |n: &str| child(n).and_then(|f| f.attr("typeface")).filter(|t| !t.is_empty() && !t.starts_with('+'));
let mut fonts = Vec::new();
if let Some(f) = face("a:latin") {
fonts.extend([("w:ascii", f), ("w:hAnsi", f)]);
}
if let Some(f) = face("a:ea") {
fonts.push(("w:eastAsia", f));
}
if let Some(f) = face("a:cs") {
fonts.push(("w:cs", f));
}
if !fonts.is_empty() {
push("w:rFonts", &fonts);
}
for (drawingml, word) in [("b", "w:b"), ("i", "w:i")] {
match toggle(drawingml) {
Some(true) => push(word, &[]),
Some(false) => push(word, &[("w:val", "0")]),
None => {}
}
}
match get("cap") {
Some("all") => push("w:caps", &[]),
Some("small") => push("w:smallCaps", &[]),
_ => {}
}
match get("strike") {
Some("sngStrike") => push("w:strike", &[]),
Some("dblStrike") => push("w:dstrike", &[]),
_ => {}
}
match get("u") {
None | Some("none") => {}
Some("dbl") => push("w:u", &[("w:val", "double")]),
Some(_) => push("w:u", &[("w:val", "single")]),
}
match get("baseline").and_then(|v| v.trim().parse::<i64>().ok()) {
Some(b) if b > 0 => push("w:vertAlign", &[("w:val", "superscript")]),
Some(b) if b < 0 => push("w:vertAlign", &[("w:val", "subscript")]),
_ => {}
}
if let Some(rgb) = child("a:solidFill").and_then(|f| crate::read::drawing_color::color(f, theme)) {
push("w:color", &[("w:val", &rgb.hex())]);
}
// Hundredths of a point into half-points, within Word's 1–1638 pt.
let sz = get("sz").and_then(|v| v.trim().parse::<i64>().ok()).unwrap_or(DEFAULT_SZ).clamp(100, 163_800) / 50;
let sz = sz.to_string();
push("w:sz", &[("w:val", &sz)]);
push("w:szCs", &[("w:val", &sz)]);
// WordArt's outline, shadow, glow and reflection, as Word 2010 writes them in `w:rPr`.
kids.extend(text_effects(child("a:ln"), child("a:effectLst"), theme).into_iter().map(Node::El));
el("w:rPr", Vec::new(), kids)
}
/// A DrawingML run's text outline (`a:ln`) and effects (`a:effectLst`: outer shadow, glow,
/// reflection) as the `w14:` run properties ([MS-DOCX] §2.6.1) the run reader takes for WordArt.
/// Colours are resolved here, theme and modifiers included, into a `w14:srgbClr` with its
/// transparency. Lengths (EMUs), angles and percentages carry over as they are.
fn text_effects(ln: Option<&El>, fx: Option<&El>, theme: &[Rgb]) -> Vec<El> {
let color = |e: &El| -> Option<Node> {
let (rgb, transparency) = crate::read::drawing_color::color_alpha(e, theme, None)?;
let alpha = ((transparency.clamp(0.0, 100.0) * 1000.0).round() as i64).to_string();
let kids = if transparency > 0.0 { vec![Node::El(el("w14:alpha", attrs(&[("w14:val", &alpha)]), Vec::new()))] } else { Vec::new() };
Some(Node::El(el("w14:srgbClr", attrs(&[("w14:val", &rgb.hex())]), kids)))
};
// The attributes `names` of `e`, under the `w14:` prefix.
let copied = |e: &El, names: &[&str]| -> Vec<(String, String)> {
names.iter().filter_map(|n| e.attr(n).map(|v| (format!("w14:{n}"), v.to_string()))).collect()
};
let mut out = Vec::new();
if let Some(ln) = ln
&& let Some(c) = ln.child("a:solidFill").and_then(color)
{
out.push(el("w14:textOutline", copied(ln, &["w"]), vec![Node::El(el("w14:solidFill", Vec::new(), vec![c]))]));
}
for e in fx.into_iter().flat_map(|f| f.els()) {
match e.name.as_str() {
"a:outerShdw" => out.push(el("w14:shadow", copied(e, &["blurRad", "dist", "dir"]), color(e).into_iter().collect())),
"a:glow" => out.push(el("w14:glow", copied(e, &["rad"]), color(e).into_iter().collect())),
"a:reflection" => out.push(el("w14:reflection", copied(e, &["blurRad", "stA", "endPos", "dist"]), Vec::new())),
_ => {}
}
}
out
}
fn el(name: &str, attrs: Vec<(String, String)>, kids: Vec<Node>) -> El {
El { name: name.to_string(), attrs, kids }
}
fn attrs(a: &[(&str, &str)]) -> Vec<(String, String)> {
a.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
}
/// `e` under another name, with its attributes and children.
fn renamed(e: &El, name: &str) -> El {
El { name: name.to_string(), ..e.clone() }
}
+5
View File
@@ -151,6 +151,11 @@ pub fn write_as(doc: &Document, flavor: Flavor) -> Result<Vec<u8>, DocxError> {
}
impl Writer<'_> {
/// The document's styles, for writers that need the resolved style chain.
pub(crate) fn styles(&self) -> &craft_wordmodel::styles::StyleSheet {
&self.doc.styles
}
fn assign_media(&mut self) {
let mut used: std::collections::HashSet<String> = std::collections::HashSet::new();
for (key, bytes) in &self.doc.media {
+8 -3
View File
@@ -1,8 +1,8 @@
//! Property writers, in ECMA-376 schema element order.
use craft_wordmodel::props::{
Align, Border, BorderStyle, Borders, CellProps, CharProps, EastAsianLayout, HeightRule, Highlight, LineSpacing, ParaProps, RowProps, TabAlign,
TabLeader, TableFloat, TableLook, TableProps, TextColor, VAlign, VMerge, VertAlign,
Align, Border, BorderStyle, Borders, CellProps, CharProps, EastAsianLayout, HeightRule, Highlight, Kashida, LineSpacing, ParaProps, RowProps,
TabAlign, TabLeader, TableFloat, TableLook, TableProps, TextColor, VAlign, VMerge, VertAlign,
};
use crate::units::{n, twips};
@@ -201,6 +201,11 @@ pub fn align_val(a: Align) -> &'static str {
}
}
/// `w:jc` for a paragraph, including the kashida length of a justified one.
pub fn jc_val(a: Align, kashida: Option<Kashida>) -> &'static str {
if a == Align::Justify { kashida.unwrap_or(Kashida::None).jc() } else { align_val(a) }
}
/// A tab stop's or positional tab's `w:leader` value.
pub fn tab_leader(l: TabLeader) -> &'static str {
match l {
@@ -287,7 +292,7 @@ pub fn ppr_inner(w: &mut W, p: &ParaProps, framed: bool, num_change: Option<&Cha
toggle(w, "w:contextualSpacing", p.contextual_spacing);
toggle(w, "w:mirrorIndents", p.mirror_indents);
if let Some(a) = p.align {
w.val("w:jc", align_val(a));
w.val("w:jc", jc_val(a, p.kashida));
}
if let Some(direction) = p.text_direction {
w.val("w:textDirection", direction.ooxml());
+25 -6
View File
@@ -69,9 +69,18 @@ impl Writer<'_> {
}
/// A shape's or text box's `wps:wsp`, at `off` in its group (or 0, 0). In a group it carries
/// its own `wps:cNvPr` with drawing id `id`.
pub(super) fn wsp(&mut self, w: &mut W, o: &InlineObject, id: Option<&str>, off: (f32, f32), rels: &mut PartRels, depth: usize) {
let InlineObject::Shape { kind, w: sw, h: sh, fill, stroke, stroke_width, story, effects, float, freeform, extra } = o else { return };
/// its own `wps:cNvPr` with drawing id `id`. Returns where in `w` its `w:txbxContent` was
/// written, for a VML fallback to repeat.
pub(super) fn wsp(
&mut self,
w: &mut W,
o: &InlineObject,
id: Option<&str>,
off: (f32, f32),
rels: &mut PartRels,
depth: usize,
) -> Option<std::ops::Range<usize>> {
let InlineObject::Shape { kind, w: sw, h: sh, fill, stroke, stroke_width, story, effects, float, freeform, extra } = o else { return None };
let geom = freeform.as_deref().filter(|_| *kind == ShapeKind::Freeform);
w.open("wps:wsp", &[]);
if let Some(id) = id {
@@ -117,16 +126,22 @@ impl Writer<'_> {
ShapeKind::ArrowDown => "downArrow",
ShapeKind::Star => "star5",
ShapeKind::Heart => "heart",
ShapeKind::Frame => "frame",
};
match geom {
Some(f) => cust_geom(w, f, *sw, *sh),
None => {
w.open("a:prstGeom", &[("prst", prst)]);
match extra.corner.filter(|_| *kind == ShapeKind::RoundedRectangle) {
Some(c) => {
let adj = match kind {
ShapeKind::RoundedRectangle => Some("adj"),
ShapeKind::Frame => Some("adj1"),
_ => None,
};
match adj.zip(extra.corner) {
Some((name, c)) => {
w.open("a:avLst", &[]);
let fmla = format!("val {}", c.min(craft_wordmodel::connector::MAX_CORNER));
w.empty("a:gd", &[("name", "adj"), ("fmla", &fmla)]);
w.empty("a:gd", &[("name", name), ("fmla", &fmla)]);
w.close("a:avLst");
}
None => w.empty("a:avLst", &[]),
@@ -181,6 +196,7 @@ impl Writer<'_> {
// its place in it instead.
let part = (*story).and_then(|id| self.doc.parts.get(&id).filter(|p| p.kind == craft_wordmodel::PartKind::TextBox).map(|p| (id, p)));
let link = part.and_then(|(id, _)| self.txbx_links.get(&id).copied());
let mut content = None;
if let Some((n, seq)) = link.filter(|(_, seq)| *seq > 0) {
w.empty("wps:linkedTxbx", &[("id", &n.to_string()), ("seq", &seq.to_string())]);
} else if let Some((id, part)) = part
@@ -190,6 +206,7 @@ impl Writer<'_> {
Some((n, _)) => w.open("wps:txbx", &[("id", &n.to_string())]),
None => w.open("wps:txbx", &[]),
}
let start = w.s.len();
w.open("w:txbxContent", &[]);
if self.written_boxes.insert(id) {
let blocks = part.blocks.clone();
@@ -198,6 +215,7 @@ impl Writer<'_> {
w.empty("w:p", &[]);
}
w.close("w:txbxContent");
content = Some(start..w.s.len());
w.close("wps:txbx");
self.boxes.leave();
}
@@ -231,6 +249,7 @@ impl Writer<'_> {
w.close("wps:bodyPr");
}
w.close("wps:wsp");
content
}
/// A `w:drawing` holding `graphic` (an `a:graphic`) in a frame of the object's size and place.
+190 -3
View File
@@ -1,7 +1,7 @@
use super::drawing::{DrawingInfo, shape_name, spin_attrs, write_fill, xfrm_spin_only};
use super::field::{FieldData, field_run};
use super::section::comment_reference_style;
use super::{CharProps, Fill, InlineObject, NoteKind, PartRels, TextColor, W, Wrap, Writer, emu, n, rpr};
use super::{Anchor, CharProps, Fill, Float, InlineObject, NoteKind, PartRels, ShapeKind, TextColor, W, Wrap, Writer, emu, n, rpr};
impl Writer<'_> {
/// Write an inline object (`Bookmark`, `Comment`, `Equation`, `Field`, `Shape`, etc.).
@@ -362,10 +362,24 @@ impl Writer<'_> {
}
fn write_shape(&mut self, w: &mut W, o: &InlineObject, props: &CharProps, rels: &mut PartRels, depth: usize) {
let InlineObject::Shape { kind, w: sw, h: sh, float, effects, freeform, extra, .. } = o else { return };
let InlineObject::Shape { kind, w: sw, h: sh, float, effects, freeform, extra, story, .. } = o else { return };
self.rev_open(w, props);
w.open("w:r", &[]);
self.rpr(w, props);
// A Word 2010 shape (`wps`) with a VML form goes in `mc:AlternateContent`, as Word writes
// it: a reader that doesn't know `wps` (Word 2007, the Office Compatibility Pack) takes the
// VML fallback instead of refusing the file. A shape without one stays bare: guarded with
// no fallback, that reader would open the file without the shape and drop it on its next
// save, which is worse than refusing the file.
// VML currently has no chain IDs or mso-next-textbox links. Keep every member of a
// linked story bare, including its head: an unlinked fallback would silently lose
// overflow text in older readers. Unlinked boxes still get the compatibility fallback.
let linked = story.is_some_and(|id| self.txbx_links.contains_key(&id));
let fallback = freeform.is_none() && vml_tag(*kind).is_some() && !linked;
if fallback {
w.open("mc:AlternateContent", &[]);
w.open("mc:Choice", &[("Requires", "wps")]);
}
w.open("w:drawing", &[]);
let docpr = self.shape_docpr(extra.id);
let link = Self::drawing_link(props, rels);
@@ -384,18 +398,164 @@ impl Writer<'_> {
}
let float = &float;
self.drawing_open(w, DrawingInfo { float, size: (*sw, *sh), docpr: &docpr, name: &name, alt: o.alt_text(), link: link.as_deref() });
// This shape's stacking order: floating objects in its text box move `self.z` on.
let z = self.z;
w.empty("wp:cNvGraphicFramePr", &[]);
w.open("a:graphic", &[]);
w.open("a:graphicData", &[("uri", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape")]);
self.wsp(w, o, None, (0.0, 0.0), rels, depth);
let content = self.wsp(w, o, None, (0.0, 0.0), rels, depth);
w.close("a:graphicData");
w.close("a:graphic");
w.close(if float.wrap == Wrap::Inline { "wp:inline" } else { "wp:anchor" });
w.close("w:drawing");
if fallback {
w.close("mc:Choice");
// The same text again: the fallback is a copy of the choice, not more of the story.
let content = content.and_then(|r| w.s.get(r)).map(str::to_owned);
w.open("mc:Fallback", &[]);
self.vml_shape(w, o, float, z, content.as_deref());
w.close("mc:Fallback");
w.close("mc:AlternateContent");
}
w.close("w:r");
self.rev_close(w, props);
}
/// A shape as VML (`w:pict`), for readers older than Word 2010 shapes: its frame, place,
/// wrapping, fill, outline and text box. Only for a kind [`vml_tag`] names.
fn vml_shape(&self, w: &mut W, o: &InlineObject, float: &Float, z: u32, content: Option<&str>) {
let InlineObject::Shape { kind, w: sw, h: sh, fill, stroke, stroke_width, story, extra, .. } = o else { return };
let Some(tag) = vml_tag(*kind) else { return };
let pt = |v: f32| format!("{:.2}pt", craft_wordmodel::geom::finite(v));
let mut style = Vec::new();
if float.wrap != Wrap::Inline {
style.push("position:absolute".to_string());
style.push(format!("margin-left:{}", pt(float.x)));
style.push(format!("margin-top:{}", pt(float.y)));
}
style.push(format!("width:{}", pt(sw.max(0.0))));
style.push(format!("height:{}", pt(sh.max(0.0))));
let spin = float.spin();
if spin.deg != 0.0 {
style.push(format!("rotation:{}", spin.deg));
}
match (spin.flip_h, spin.flip_v) {
(true, true) => style.push("flip:x y".into()),
(true, false) => style.push("flip:x".into()),
(false, true) => style.push("flip:y".into()),
(false, false) => {}
}
if float.wrap != Wrap::Inline {
// The stacking order the choice was given, as a signed 32-bit `z-index`. Behind the text
// is negative, shifted down rather than negated, so a higher `z` still stacks higher.
let z = i64::from(z.min(i32::MAX as u32));
let z = if float.wrap == Wrap::BehindText { z - (i64::from(i32::MAX) + 1) } else { z };
style.push(format!("z-index:{z}"));
// The same clearances from the text as the choice's `distL`/`distR`/`distT`/`distB`.
let d = pt(float.dist.clamp(0.0, 1584.0));
style.push(format!("mso-wrap-distance-left:{d}"));
style.push(format!("mso-wrap-distance-right:{d}"));
style.push(format!("mso-wrap-distance-top:{}", pt(float.dist_top.clamp(0.0, 1584.0))));
style.push(format!("mso-wrap-distance-bottom:{}", pt(float.dist_bottom.clamp(0.0, 1584.0))));
if let Some(a) = float.h_align {
style.push(format!("mso-position-horizontal:{}", a.ooxml(true)));
}
style.push(format!("mso-position-horizontal-relative:{}", vml_rel(float.h_rel, true)));
if let Some(a) = float.v_align {
style.push(format!("mso-position-vertical:{}", a.ooxml(false)));
}
style.push(format!("mso-position-vertical-relative:{}", vml_rel(float.v_rel, false)));
}
let body = (*story).and_then(|id| self.doc.parts.get(&id)).map(|p| p.body).unwrap_or_default();
style.push(
match body.anchor {
craft_wordmodel::props::VAlign::Top => "v-text-anchor:top",
craft_wordmodel::props::VAlign::Center => "v-text-anchor:middle",
craft_wordmodel::props::VAlign::Bottom => "v-text-anchor:bottom",
}
.into(),
);
if float.hidden {
style.push("visibility:hidden".into());
}
let style = style.join(";");
let mut attrs: Vec<(&str, String)> = vec![("style", style)];
if *kind == ShapeKind::RoundedRectangle {
// The same fraction of the shorter side: VML's in 1/65536ths, DrawingML's in 1/100000ths.
let c = match extra.corner {
Some(c) => c.min(craft_wordmodel::connector::MAX_CORNER) as f32 / 100_000.0,
None => craft_wordmodel::connector::DEFAULT_CORNER,
};
attrs.push(("arcsize", format!("{}f", (c * 65_536.0).round() as u32)));
}
if float.wrap != Wrap::Inline {
attrs.push(("o:allowincell", (if float.outside_cell { "f" } else { "t" }).into()));
}
let opacity = match fill.as_ref() {
Some(f) => {
attrs.push(("fillcolor", format!("#{}", f.main_color().hex())));
match f {
Fill::Solid { transparency, .. } if *transparency > 0.0 => Some(format!("{:.4}", (1.0 - transparency / 100.0).clamp(0.0, 1.0))),
_ => None,
}
}
None => {
attrs.push(("filled", "f".into()));
None
}
};
match stroke {
Some(c) => {
attrs.push(("strokecolor", format!("#{}", c.hex())));
attrs.push(("strokeweight", pt(stroke_width.clamp(0.0, 100.0))));
}
None => attrs.push(("stroked", "f".into())),
}
let attrs: Vec<(&str, &str)> = attrs.iter().map(|(k, v)| (*k, v.as_str())).collect();
w.open("w:pict", &[]);
w.open(tag, &attrs);
if let Some(opacity) = &opacity {
w.empty("v:fill", &[("opacity", opacity)]);
}
if let Some(content) = content {
let inset = body.inset.map(|i| i.map(|v| pt(v.min(craft_wordmodel::MAX_TEXT_BOX_INSET) as f32 / 12_700.0)).join(","));
let mut tb: Vec<(&str, &str)> = Vec::new();
if let Some(inset) = &inset {
tb.push(("inset", inset));
}
// Text direction as the VML reader takes it (stacked letters have no VML form).
let mut tb_style = match body.vert {
craft_wordmodel::props::TextVert::Vert => vec!["layout-flow:vertical"],
craft_wordmodel::props::TextVert::Vert270 => vec!["layout-flow:vertical", "mso-layout-flow-alt:bottom-to-top"],
craft_wordmodel::props::TextVert::Horz | craft_wordmodel::props::TextVert::Stacked => Vec::new(),
};
if body.auto_fit {
tb_style.push("mso-fit-shape-to-text:t");
}
let tb_style = tb_style.join(";");
if !tb_style.is_empty() {
tb.push(("style", &tb_style));
}
w.open("v:textbox", &tb);
w.raw(content);
w.close("v:textbox");
}
let wrap = match float.wrap {
Wrap::Square => Some("square"),
Wrap::Tight => Some("tight"),
Wrap::Through => Some("through"),
Wrap::TopAndBottom => Some("topAndBottom"),
Wrap::Inline | Wrap::BehindText | Wrap::InFrontOfText => None,
};
if let Some(wrap) = wrap {
let side = float.wrap_text.ooxml();
let attrs: &[(&str, &str)] = if float.wrap_text.is_both() { &[("type", wrap)] } else { &[("type", wrap), ("side", side)] };
w.empty("w10:wrap", attrs);
}
w.close(tag);
w.close("w:pict");
}
fn write_group(&mut self, w: &mut W, o: &InlineObject, props: &CharProps, rels: &mut PartRels, depth: usize) {
let InlineObject::Group { w: gw, h: gh, float, ch_w, ch_h, children, canvas } = o else { return };
self.rev_open(w, props);
@@ -487,6 +647,33 @@ impl Writer<'_> {
}
}
/// The VML element that draws a shape kind, for the kinds VML has one for.
fn vml_tag(kind: ShapeKind) -> Option<&'static str> {
match kind {
ShapeKind::Rectangle | ShapeKind::TextBox => Some("v:rect"),
ShapeKind::RoundedRectangle => Some("v:roundrect"),
ShapeKind::Ellipse => Some("v:oval"),
_ => None,
}
}
/// A floating object's anchor as VML names it (`mso-position-horizontal-relative`, `-vertical-`).
fn vml_rel(a: Anchor, horiz: bool) -> &'static str {
match (a, horiz) {
(Anchor::Margin, _) => "margin",
(Anchor::Page, _) => "page",
(Anchor::InsideMargin, _) => "inner-margin-area",
(Anchor::OutsideMargin, _) => "outer-margin-area",
(Anchor::LeftMargin, true) => "left-margin-area",
(Anchor::RightMargin, true) => "right-margin-area",
(Anchor::Character, true) => "char",
(Anchor::TopMargin, false) => "top-margin-area",
(Anchor::BottomMargin, false) => "bottom-margin-area",
(Anchor::Line, false) => "line",
_ => "text",
}
}
pub(super) fn ink_name(tool: craft_wordmodel::freeform::InkTool) -> &'static str {
match tool {
craft_wordmodel::freeform::InkTool::Pen => "Pen",
+6
View File
@@ -76,6 +76,12 @@ impl Writer<'_> {
a.push(("w:original", c.original.clone()));
a
});
// `w:jc` encodes alignment and kashida length together. A justified paragraph
// whose kashida is unset (`None`) still inherits a length from its style; writing
// `both` would read back as `Some(Kashida::None)` and cancel that length.
if pp.align == Some(craft_wordmodel::props::Align::Justify) && pp.kashida.is_none() {
pp.kashida = Some(self.styles().resolve_para(&pp).kashida);
}
ppr_inner(w, &pp, framed, num_change.as_ref());
if has_mark {
self.write_mark_rpr(w, &p.mark, &mark_revs);
+7 -1
View File
@@ -184,7 +184,13 @@ fn style_property_xml(wr: &mut Writer<'_>, w: &mut W, st: &Style) {
let para_change = st.para_change.as_deref().filter(|ch| ch.old.formatting() != st.para.formatting());
if (!st.para.is_empty() || para_change.is_some()) && st.kind != StyleKind::Character {
w.open("w:pPr", &[]);
props::ppr_inner(w, &st.para, false, None);
let mut ppr = st.para.clone();
if ppr.align == Some(craft_wordmodel::props::Align::Justify) && ppr.kashida.is_none() {
let mut probe = ppr.clone();
probe.style = Some(st.id.clone());
ppr.kashida = Some(wr.styles().resolve_para(&probe).kashida);
}
props::ppr_inner(w, &ppr, false, None);
if let Some(ch) = para_change {
let a = wr.change_attrs(ch.rev);
open_change(w, "w:pPrChange", &a);
+3 -1
View File
@@ -52,8 +52,10 @@ pub const NAMESPACES: &[(&str, &str)] = &[
pub const DECORATIVE_EXT: &str = "{C183D7F6-B498-43B3-948B-1728B52AA6E4}";
pub const DECORATIVE_NS: &str = "http://schemas.microsoft.com/office/drawing/2017/decorative";
/// Namespaces that only appear in non-body parts.
/// Namespaces that only appear in non-body parts, or that the reader reads but never writes.
const OTHER_NAMESPACES: &[(&str, &str)] = &[
// A locked canvas, read into a drawing group (wordcraft#5060).
("lc", "http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas"),
("b", "http://schemas.openxmlformats.org/officeDocument/2006/bibliography"),
("rel", "http://schemas.openxmlformats.org/package/2006/relationships"),
("ct", "http://schemas.openxmlformats.org/package/2006/content-types"),
+33
View File
@@ -2729,6 +2729,39 @@ fn rounded_rectangle_corners_are_read_and_saved() {
assert_eq!(corners(&craft_docx::read(&bytes).unwrap()), expected);
}
/// A `frame` preset (a letterhead's page border) is a frame, not a filled rectangle: its border
/// width is its `adj1`, read, capped and written back as the same preset.
#[test]
fn frame_presets_keep_their_hole_and_border_width() {
let geom =
|av: &str| format!(r#"<a:prstGeom prst="frame"><a:avLst>{av}</a:avLst></a:prstGeom><a:solidFill><a:srgbClr val="E3AB48"/></a:solidFill>"#);
let gd = |fmla: &str| format!(r#"<a:gd name="adj1" fmla="{fmla}"/>"#);
let body = [geom(&gd("val 2604")), geom(""), geom(&gd("val 90000")), geom(r#"<a:gd name="adj" fmla="val 100"/>"#)]
.iter()
.map(|sppr| anchored_wsp("Frame", 2540000, 1270000, sppr, "", "<wps:cNvSpPr/>"))
.collect::<String>();
let frames = |d: &Document| -> Vec<(ShapeKind, Option<u32>)> {
paras(d)[0]
.objects
.iter()
.filter_map(|o| match o {
InlineObject::Shape { kind, extra, .. } => Some((*kind, extra.corner)),
_ => None,
})
.collect()
};
let f = ShapeKind::Frame;
let expected = vec![(f, Some(2604)), (f, None), (f, Some(50_000)), (f, None)];
let d = read_body(&format!("<w:p>{body}</w:p>"));
assert_eq!(frames(&d), expected);
let bytes = craft_docx::write(&d).unwrap();
let mut xml = String::new();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
assert!(xml.contains(r#"<a:prstGeom prst="frame"><a:avLst><a:gd name="adj1" fmla="val 2604"/></a:avLst></a:prstGeom>"#), "{xml}");
assert_eq!(frames(&craft_docx::read(&bytes).unwrap()), expected);
}
/// #611: legacy VML lines and rectangles (documents without DrawingML).
#[test]
fn vml_lines_and_rectangles() {
+136
View File
@@ -0,0 +1,136 @@
//! Justified paragraphs keep their kashida length (`ST_Jc` `lowKashida`, `mediumKashida`,
//! `highKashida`, and ordinary `both` / `justify`) through read and write.
use std::io::{Read, Write};
use std::sync::Arc;
use craft_wordmodel::props::{Align, Kashida, ParaProps};
use craft_wordmodel::styles::{Style, StyleKind, StyleSheet};
use craft_wordmodel::{Document, Paragraph, para_block};
fn zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
for (name, bytes) in entries {
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
}
zw.finish().unwrap().into_inner()
}
fn docx(body: &str) -> Vec<u8> {
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let doc = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
);
zip(&[("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())])
}
fn paras(d: &Document) -> Vec<&Paragraph> {
d.body.iter().filter_map(|b| b.as_para()).collect()
}
fn document_xml(bytes: &[u8]) -> String {
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut s = String::new();
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
s
}
fn jc_para(body: &str, val: &str) -> String {
format!(r#"<w:p><w:pPr><w:jc w:val="{val}"/></w:pPr><w:r><w:t>{body}</w:t></w:r></w:p>"#)
}
#[test]
fn kashida_jc_values_are_read() {
let body = [
jc_para("both", "both"),
jc_para("justify", "justify"),
jc_para("low", "lowKashida"),
jc_para("medium", "mediumKashida"),
jc_para("high", "highKashida"),
jc_para("left", "left"),
]
.join("");
let d = craft_docx::read(&docx(&body)).unwrap();
let ps = paras(&d);
let got: Vec<_> = ps.iter().map(|p| (p.props.align, p.props.kashida)).collect();
assert_eq!(
got,
vec![
(Some(Align::Justify), Some(Kashida::None)),
(Some(Align::Justify), Some(Kashida::None)),
(Some(Align::Justify), Some(Kashida::Short)),
(Some(Align::Justify), Some(Kashida::Medium)),
(Some(Align::Justify), Some(Kashida::Long)),
(Some(Align::Left), None),
]
);
}
#[test]
fn kashida_length_round_trips() {
let cases = [
(Some(Kashida::None), "w:val=\"both\""),
(Some(Kashida::Short), "w:val=\"lowKashida\""),
(Some(Kashida::Medium), "w:val=\"mediumKashida\""),
(Some(Kashida::Long), "w:val=\"highKashida\""),
];
for (kashida, token) in cases {
let mut p = Paragraph::with_text("مثال", Default::default());
p.props = ParaProps { align: Some(Align::Justify), kashida, ..Default::default() };
let mut d = Document::new();
d.body = vec![para_block(p.clone())];
let bytes = craft_docx::write(&d).unwrap();
let xml = document_xml(&bytes);
assert!(xml.contains(token), "expected {token} in {xml}");
let r = craft_docx::read(&bytes).unwrap();
let q = paras(&r)[0];
assert_eq!(q.props.align, Some(Align::Justify));
assert_eq!(q.props.kashida, kashida, "round-trip of {token}");
}
}
fn body_style(kashida: Kashida) -> StyleSheet {
let mut sheet = StyleSheet::empty();
sheet.styles.push(Style {
id: "Body".into(),
name: "Body".into(),
kind: StyleKind::Paragraph,
para: ParaProps { align: Some(Align::Justify), kashida: Some(kashida), ..ParaProps::default() },
..Style::default()
});
sheet
}
#[test]
fn style_kashida_length_survives_a_write_when_the_paragraph_has_no_direct_jc() {
let mut p = Paragraph::with_text("مثال", Default::default());
p.props = ParaProps { style: Some("Body".into()), ..ParaProps::default() };
let mut d = Document::new();
d.styles = Arc::new(body_style(Kashida::Short));
d.body = vec![para_block(p)];
assert_eq!(d.styles.resolve_para(&d.body[0].as_para().unwrap().props).kashida, Kashida::Short);
let bytes = craft_docx::write(&d).unwrap();
let r = craft_docx::read(&bytes).unwrap();
let q = paras(&r)[0];
assert_eq!(q.props.kashida, None, "no direct w:jc on the paragraph");
assert_eq!(r.styles.resolve_para(&q.props).kashida, Kashida::Short);
}
#[test]
fn writing_justify_without_a_local_kashida_keeps_the_style_length() {
let mut p = Paragraph::with_text("مثال", Default::default());
p.props = ParaProps { style: Some("Body".into()), align: Some(Align::Justify), kashida: None, ..ParaProps::default() };
let mut d = Document::new();
d.styles = Arc::new(body_style(Kashida::Medium));
d.body = vec![para_block(p)];
let bytes = craft_docx::write(&d).unwrap();
let xml = document_xml(&bytes);
assert!(xml.contains("w:val=\"mediumKashida\""), "expected mediumKashida in {xml}");
let r = craft_docx::read(&bytes).unwrap();
let q = paras(&r)[0];
assert_eq!(q.props.align, Some(Align::Justify));
assert_eq!(q.props.kashida, Some(Kashida::Medium));
assert_eq!(r.styles.resolve_para(&q.props).kashida, Kashida::Medium);
}
+163
View File
@@ -0,0 +1,163 @@
//! A DrawingML locked canvas (`lc:lockedCanvas`, ECMA-376 Part 1 §20.3.2.1), as Word 2007 writes
//! shapes, pictures and WordArt in a drawing in compatibility mode (wordcraft#5060). Fixtures are
//! hand-written from ECMA-376 Part 1 §20.1 (DrawingML main) and §20.3 (locked canvas).
use std::io::Write;
use craft_wordmodel::para::ShapeKind;
use craft_wordmodel::props::{Rgb, TextColor};
use craft_wordmodel::{Document, InlineObject, StoryRef};
const NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main""#;
fn docx(body: &str) -> Vec<u8> {
let doc = format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document {NS}><w:body>{body}</w:body></w:document>"#);
let types =
r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="png" ContentType="image/png"/></Types>"#;
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId8" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image1.png"/></Relationships>"#;
let entries: [(&str, &[u8]); 5] = [
("[Content_Types].xml", types.as_bytes()),
("_rels/.rels", root.as_bytes()),
("word/document.xml", doc.as_bytes()),
("word/_rels/document.xml.rels", rels.as_bytes()),
("word/media/image1.png", "\u{89}PNG stand-in".as_bytes()),
];
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
for (name, bytes) in entries {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
}
zw.finish().unwrap().into_inner()
}
/// A floating drawing, 200 × 100 pt, holding `canvas` (the locked canvas's members) in a canvas
/// whose members' space starts at 10 pt, 10 pt.
fn drawing(canvas: &str) -> String {
format!(
r#"<w:p><w:r><w:drawing><wp:anchor behindDoc="0" distT="0" distB="0" distL="0" distR="0" simplePos="0" relativeHeight="1" locked="0" layoutInCell="1" allowOverlap="1"><wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="2540000" cy="1270000"/><wp:wrapNone/><wp:docPr id="1" name="Object 1"/><a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas"><lc:lockedCanvas xmlns:lc="http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas"><a:nvGrpSpPr><a:cNvPr id="0" name=""/><a:cNvGrpSpPr/></a:nvGrpSpPr><a:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="2540000" cy="1270000"/><a:chOff x="127000" y="127000"/><a:chExt cx="2540000" cy="1270000"/></a:xfrm></a:grpSpPr>{canvas}</lc:lockedCanvas></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r></w:p>"#
)
}
const OVAL: &str = r#"<a:sp><a:nvSpPr><a:cNvPr id="2" name="Oval 2"/><a:cNvSpPr/></a:nvSpPr><a:spPr><a:xfrm><a:off x="127000" y="127000"/><a:ext cx="1270000" cy="635000"/></a:xfrm><a:prstGeom prst="ellipse"><a:avLst/></a:prstGeom><a:solidFill><a:srgbClr val="FFFF66"/></a:solidFill><a:ln w="12700"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln></a:spPr></a:sp>"#;
/// WordArt in a nested group: bold, all-caps red text with a green outline and a reflection,
/// 32 pt, centred, bent by a chevron warp; a second paragraph takes the list style's size, and an
/// empty third one its mark's.
const WORD_ART: &str = r#"<a:grpSp><a:nvGrpSpPr><a:cNvPr id="3" name="Group 3"/><a:cNvGrpSpPr/></a:nvGrpSpPr><a:grpSpPr><a:xfrm><a:off x="1397000" y="762000"/><a:ext cx="1270000" cy="635000"/><a:chOff x="0" y="0"/><a:chExt cx="2540000" cy="1270000"/></a:xfrm></a:grpSpPr><a:sp><a:nvSpPr><a:cNvPr id="4" name="Rectangle 4"/><a:cNvSpPr/></a:nvSpPr><a:spPr><a:xfrm><a:off x="254000" y="254000"/><a:ext cx="508000" cy="254000"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></a:spPr><a:txSp><a:txBody><a:bodyPr wrap="square"><a:prstTxWarp prst="textChevron"><a:avLst/></a:prstTxWarp><a:spAutoFit/></a:bodyPr><a:lstStyle><a:lvl1pPr><a:defRPr sz="1400"/></a:lvl1pPr></a:lstStyle><a:p><a:pPr algn="ctr"/><a:r><a:rPr lang="en-US" sz="3200" b="1" cap="all"><a:ln w="9525"><a:solidFill><a:srgbClr val="00FF00"/></a:solidFill></a:ln><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill><a:effectLst><a:reflection blurRad="12700" stA="28000" endPos="45000" dist="1000" dir="5400000"/></a:effectLst><a:latin typeface="Corsiva Stand-in"/></a:rPr><a:t>Young</a:t></a:r></a:p><a:p><a:r><a:rPr lang="en-US"/><a:t>keepers</a:t></a:r></a:p><a:p><a:endParaRPr lang="en-US" sz="1000"/></a:p></a:txBody><a:useSpRect/></a:txSp></a:sp></a:grpSp>"#;
const PICTURE: &str = r#"<a:pic><a:nvPicPr><a:cNvPr id="5" name="Picture 5" descr="A logo"/><a:cNvPicPr/></a:nvPicPr><a:blipFill><a:blip r:embed="rId8"/><a:stretch><a:fillRect/></a:stretch></a:blipFill><a:spPr><a:xfrm><a:off x="127000" y="762000"/><a:ext cx="635000" cy="635000"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></a:spPr></a:pic>"#;
/// A line glued to the oval by the canvas's own id, which isn't a document shape's.
const LINE: &str = r#"<a:cxnSp><a:nvCxnSpPr><a:cNvPr id="6" name="Line 6"/><a:cNvCxnSpPr><a:stCxn id="2" idx="0"/></a:cNvCxnSpPr></a:nvCxnSpPr><a:spPr><a:xfrm><a:off x="127000" y="1143000"/><a:ext cx="2540000" cy="0"/></a:xfrm><a:prstGeom prst="line"><a:avLst/></a:prstGeom><a:ln w="12700"><a:solidFill><a:srgbClr val="0000FF"/></a:solidFill></a:ln></a:spPr></a:cxnSp>"#;
fn group(d: &Document) -> (f32, f32, Vec<craft_wordmodel::para::GroupChild>) {
let p = d.body.iter().find_map(|b| b.as_para()).unwrap();
match p.objects.first() {
Some(InlineObject::Group { w, h, children, canvas: None, .. }) => (*w, *h, children.clone()),
o => panic!("{o:?}"),
}
}
/// wordcraft#5060: the locked canvas is a group of its shapes, text, picture and line, each where the
/// canvas (and the group inside it) puts it, and nothing is lost on save.
#[test]
fn a_locked_canvas_reads_as_a_group_of_its_members() {
let d = craft_docx::read(&docx(&drawing(&[OVAL, WORD_ART, PICTURE, LINE].concat()))).unwrap();
for d in [&d, &craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap()] {
let (w, h, children) = group(d);
assert_eq!((w, h), (200.0, 100.0));
let at: Vec<(f32, f32)> = children.iter().map(|c| (c.x, c.y)).collect();
assert_eq!(at, [(0.0, 0.0), (110.0, 60.0), (0.0, 50.0), (0.0, 80.0)]);
let [oval, art, picture, line] = &children[..] else { panic!("{children:?}") };
let InlineObject::Shape { kind: ShapeKind::Ellipse, w: 100.0, h: 50.0, fill: Some(fill), stroke: Some(stroke), .. } = &oval.obj else {
panic!("{:?}", oval.obj)
};
assert_eq!((fill.main_color(), *stroke), (Rgb(0xFF, 0xFF, 0x66), Rgb(0, 0, 0)));
let InlineObject::Shape { kind: ShapeKind::TextBox, w: 20.0, h: 10.0, story: Some(id), extra, .. } = &art.obj else {
panic!("{:?}", art.obj)
};
assert_eq!(extra.warp.as_ref().map(|w| w.preset.as_str()), Some("textChevron"));
assert_eq!(d.plain_text(StoryRef::Part(*id)).trim_end(), "Young\nkeepers");
let blocks = &d.parts.get(id).unwrap().blocks;
let first = blocks[0].as_para().unwrap();
assert_eq!(first.props.align, Some(craft_wordmodel::props::Align::Center));
assert_eq!((first.props.space_before, first.props.space_after), (Some(0.0), Some(0.0)), "DrawingML text has no paragraph spacing");
let run = &first.runs[0].props;
assert_eq!((run.size, run.bold, run.caps, run.color), (Some(32.0), Some(true), Some(true), Some(TextColor::Rgb(Rgb(0xFF, 0, 0)))));
assert_eq!(run.font.as_deref(), Some("Corsiva Stand-in"));
let fx = run.text_effects.as_deref().unwrap();
let outline = fx.outline.unwrap();
assert_eq!((outline.color, outline.width), (Some(Rgb(0, 0xFF, 0)), 0.75));
assert!(fx.reflection.is_some(), "{fx:?}");
assert_eq!(blocks[1].as_para().unwrap().runs[0].props.size, Some(14.0), "the list style's size");
assert_eq!(blocks[2].as_para().unwrap().mark.size, Some(10.0), "an empty paragraph's mark");
let InlineObject::Image { w: 50.0, h: 50.0, alt, .. } = &picture.obj else { panic!("{:?}", picture.obj) };
assert_eq!(alt, "A logo");
let InlineObject::Shape { kind: ShapeKind::Line, stroke: Some(blue), extra, .. } = &line.obj else { panic!("{:?}", line.obj) };
assert_eq!((*blue, extra.start), (Rgb(0, 0, 0xFF), None), "no glue to a canvas id");
}
}
/// A text shape as a member of the canvas (`a:txSp`, text with no shape of its own) is a text box
/// at its own rectangle. Runs take their paragraph's own defaults (`a:pPr/a:defRPr`) before the
/// list style's for the paragraph's level.
#[test]
fn a_locked_canvas_text_shape_and_paragraph_defaults() {
let text = r#"<a:txSp><a:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="1400" i="1"/></a:lvl1pPr><a:lvl2pPr><a:defRPr sz="2000"/></a:lvl2pPr></a:lstStyle><a:p><a:pPr><a:defRPr sz="3200"/></a:pPr><a:r><a:rPr lang="en-US"/><a:t>Own</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US"/><a:t>Level</a:t></a:r></a:p><a:p><a:r><a:rPr lang="en-US"/><a:t>First</a:t></a:r></a:p></a:txBody><a:useSpRect/><a:xfrm><a:off x="635000" y="381000"/><a:ext cx="1270000" cy="508000"/></a:xfrm></a:txSp>"#;
let d = craft_docx::read(&docx(&drawing(text))).unwrap();
for d in [&d, &craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap()] {
let (_, _, children) = group(d);
let [shape] = &children[..] else { panic!("{children:?}") };
assert_eq!((shape.x, shape.y), (40.0, 20.0));
let InlineObject::Shape { kind: ShapeKind::TextBox, w: 100.0, h: 40.0, fill: None, stroke: None, story: Some(id), .. } = &shape.obj else {
panic!("{:?}", shape.obj)
};
assert_eq!(d.plain_text(StoryRef::Part(*id)).trim_end(), "Own\nLevel\nFirst");
let blocks = &d.parts.get(id).unwrap().blocks;
let run = |i: usize| blocks[i].as_para().unwrap().runs[0].props.clone();
assert_eq!((run(0).size, run(0).italic), (Some(32.0), Some(true)), "the paragraph's own size, the level's italic");
assert_eq!((run(1).size, run(1).italic), (Some(20.0), None), "level 2's");
assert_eq!((run(2).size, run(2).italic), (Some(14.0), Some(true)), "level 1's");
}
}
/// A paragraph's alignment and its runs' properties fall back on its level's style, then on the
/// list style's defaults (`a:defPPr`); a run's bold set off stays off.
#[test]
fn a_locked_canvas_paragraph_takes_its_level_and_the_list_defaults() {
use craft_wordmodel::props::Align;
let text = r#"<a:txSp><a:txBody><a:bodyPr/><a:lstStyle><a:defPPr algn="r"><a:defRPr sz="1600" b="1"/></a:defPPr><a:lvl2pPr algn="ctr"/></a:lstStyle><a:p><a:r><a:rPr lang="en-US" b="0"/><a:t>Plain</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US"/><a:t>Centred</a:t></a:r></a:p><a:p><a:pPr lvl="1" algn="l"/><a:r><a:rPr lang="en-US"/><a:t>Own</a:t></a:r></a:p></a:txBody><a:useSpRect/><a:xfrm><a:off x="635000" y="381000"/><a:ext cx="1270000" cy="508000"/></a:xfrm></a:txSp>"#;
let d = craft_docx::read(&docx(&drawing(text))).unwrap();
for d in [&d, &craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap()] {
let (_, _, children) = group(d);
let [shape] = &children[..] else { panic!("{children:?}") };
let InlineObject::Shape { story: Some(id), .. } = &shape.obj else { panic!("{:?}", shape.obj) };
let blocks = &d.parts.get(id).unwrap().blocks;
let para = |i: usize| blocks[i].as_para().unwrap();
let aligns: Vec<Option<Align>> = (0..3).map(|i| para(i).props.align).collect();
assert_eq!(aligns, [Some(Align::Right), Some(Align::Center), Some(Align::Left)], "the list defaults', the level's, its own");
let runs: Vec<(Option<f32>, Option<bool>)> = (0..3).map(|i| (para(i).runs[0].props.size, para(i).runs[0].props.bold)).collect();
assert_eq!(runs, [(Some(16.0), Some(false)), (Some(16.0), Some(true)), (Some(16.0), Some(true))]);
}
}
/// Before wordcraft#5060 only the canvas's first picture showed: the shapes and their text were dropped.
#[test]
fn a_locked_canvas_is_not_read_as_its_picture_alone() {
let d = craft_docx::read(&docx(&drawing(&[OVAL, PICTURE].concat()))).unwrap();
let (_, _, children) = group(&d);
assert_eq!(children.len(), 2);
}
/// Hostile canvases never panic: no members, groups nested past the limit, text with no runs,
/// huge and broken sizes.
#[test]
fn hostile_locked_canvases_never_panic() {
let deep = format!("{}{}{}", r#"<a:grpSp><a:grpSpPr/>"#.repeat(40), OVAL, "</a:grpSp>".repeat(40));
let odd = r#"<a:sp><a:spPr/><a:txSp><a:txBody><a:p/><a:p><a:r><a:rPr sz="99999999999" baseline="x"/></a:r><a:br/><a:fld><a:t>f</a:t></a:fld></a:p></a:txBody></a:txSp></a:sp><a:pic/><a:cxnSp/><a:graphicFrame/>"#;
for canvas in ["", deep.as_str(), odd] {
let d = craft_docx::read(&docx(&drawing(canvas))).unwrap();
let _ = craft_docx::write(&d).unwrap();
}
}
+3
View File
@@ -20,9 +20,11 @@ mod emphasis_marks;
mod fixtures;
mod glossary;
mod heading_levels;
mod kashida;
mod legacy_forms;
mod ligatures;
mod line_numbering;
mod locked_canvas;
mod malformed;
mod missing_pictures;
mod nested_block_controls;
@@ -49,3 +51,4 @@ mod undefined_style;
mod vml_shapes;
mod word_xml;
mod wordml2003_write;
mod wps_fallback;
+6 -4
View File
@@ -6,8 +6,8 @@ use std::sync::Arc;
use craft_wordmodel::numbering::ListKind;
use craft_wordmodel::para::{Anchor, Float, FloatAlign, NoteKind, ShapeKind, Wrap};
use craft_wordmodel::props::{
Align, Border, BorderStyle, Borders, CharProps, HeightRule, Highlight, LineSpacing, NumRef, ParaProps, ParagraphTextDirection, Rgb, RowProps,
TabAlign, TabLeader, TabStop, TableLook, TextAlignment, TextColor, TextDirection, Underline, VAlign, VMerge, VertAlign,
Align, Border, BorderStyle, Borders, CharProps, HeightRule, Highlight, Kashida, LineSpacing, NumRef, ParaProps, ParagraphTextDirection, Rgb,
RowProps, TabAlign, TabLeader, TabStop, TableLook, TextAlignment, TextColor, TextDirection, Underline, VAlign, VMerge, VertAlign,
};
use craft_wordmodel::section::{Columns, DocGrid, DocGridType, LineNumberRestart, LineNumbering, NumFormat, PageVAlign, SectionProps, SectionStart};
use craft_wordmodel::styles::{Style, StyleKind};
@@ -163,6 +163,7 @@ fn every_para_prop_round_trips() {
let pp = ParaProps {
style: Some("Heading1".into()),
align: Some(Align::Justify),
kashida: Some(Kashida::Medium),
indent_left: Some(36.0),
indent_right: Some(18.0),
indent_first: Some(-18.0),
@@ -956,7 +957,8 @@ fn toc_field_skips_nested_stories() {
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let boxes: Vec<(usize, usize)> = xml.match_indices("<w:txbxContent>").map(|(a, _)| (a, a + xml[a..].find("</w:txbxContent>").unwrap())).collect();
assert_eq!(boxes.len(), 2, "{xml}");
// Each box twice: its shape and its VML fallback.
assert_eq!(boxes.len(), 4, "{xml}");
let in_box = |i: usize| boxes.iter().any(|(a, b)| (*a..*b).contains(&i));
for kind in ["begin", "separate", "end"] {
let at: Vec<usize> = xml.match_indices(&format!(r#"fldCharType="{kind}""#)).map(|(i, _)| i).collect();
@@ -964,7 +966,7 @@ fn toc_field_skips_nested_stories() {
assert!(!in_box(at[0]), "field {kind} written inside a text box: {xml}");
}
let (begin, end) = (xml.find(r#"fldCharType="begin""#).unwrap(), xml.find(r#"fldCharType="end""#).unwrap());
assert!(begin > boxes[0].1 && end > boxes[1].1 && end < xml.find("</w:sdt>").unwrap(), "{xml}");
assert!(begin > boxes[1].1 && end > boxes[3].1 && end < xml.find("</w:sdt>").unwrap(), "{xml}");
}
#[test]
+2 -1
View File
@@ -257,5 +257,6 @@ fn story_shared_by_many_shapes_is_written_once() {
}
let xml = document_xml(&craft_docx::write(&d).unwrap());
assert!(xml.len() < 2_000_000, "document.xml is {} bytes", xml.len());
assert_eq!(xml.matches(text.as_str()).count(), 1);
// Once in the first shape and once in its VML fallback; the other shapes don't repeat it.
assert_eq!(xml.matches(text.as_str()).count(), 2);
}
+188
View File
@@ -0,0 +1,188 @@
//! Word 2010 shapes (`wps:wsp`) are written inside `mc:AlternateContent` with a VML fallback
//! (ECMA-376 Part 3, Markup Compatibility; Part 4 §14.1, VML), so a reader that doesn't know
//! `wps` — Word 2007, or Word 2000-2003 with the Office Compatibility Pack — takes the fallback
//! instead of refusing the whole file. A shape with no VML form is left bare.
use std::io::Read;
use craft_wordmodel::para::{Anchor, FloatAlign, ShapeKind, Wrap};
use craft_wordmodel::props::TextVert;
use craft_wordmodel::{Document, InlineObject, PartKind, TextBody, para_block};
fn document_xml(bytes: &[u8]) -> String {
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut s = String::new();
z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap();
s
}
fn shape(kind: ShapeKind, story: Option<u32>) -> InlineObject {
let float = craft_wordmodel::para::Float {
wrap: Wrap::Square,
h_rel: Anchor::Margin,
h_align: Some(FloatAlign::End),
v_rel: Anchor::Paragraph,
y: 0.05,
..Default::default()
};
InlineObject::Shape {
kind,
w: 10.7,
h: 12.2,
fill: None,
stroke: None,
stroke_width: 0.75,
float,
story,
effects: Default::default(),
freeform: None,
extra: Default::default(),
}
}
/// A page number in a floating text box, as in a footer: the shape that made the
/// Compatibility Pack refuse the file.
#[test]
fn a_text_box_gets_a_vml_fallback_with_its_text() {
let mut d = Document::from_text("a");
let id = d.add_part(PartKind::TextBox, vec![para_block(craft_wordmodel::Paragraph::with_text("29", Default::default()))]);
d.parts.get_mut(&id).unwrap().body = TextBody { auto_fit: true, inset: Some([0; 4]), ..Default::default() };
let mut o = shape(ShapeKind::TextBox, Some(id));
if let InlineObject::Shape { float, .. } = &mut o {
(float.dist, float.dist_top, float.dist_bottom) = (18.0, 12.0, 6.0);
}
d.insert_object(&craft_wordmodel::Pos::body(0, 1), o, &Default::default()).unwrap();
let bytes = craft_docx::write(&d).unwrap();
let xml = document_xml(&bytes);
assert!(xml.contains(r#"<mc:AlternateContent><mc:Choice Requires="wps"><w:drawing>"#), "{xml}");
assert!(!xml.contains("<w:r><w:drawing>"), "no bare Word 2010 shape: {xml}");
let fallback = &xml[xml.find("<mc:Fallback>").expect("a fallback")..];
assert!(fallback.starts_with("<mc:Fallback><w:pict><v:rect "), "{fallback}");
for want in [
"position:absolute",
"mso-position-horizontal:right",
"mso-position-horizontal-relative:margin",
"mso-position-vertical-relative:text",
"mso-wrap-distance-left:18.00pt;mso-wrap-distance-right:18.00pt;mso-wrap-distance-top:12.00pt;mso-wrap-distance-bottom:6.00pt",
r#"filled="f""#,
r#"stroked="f""#,
r#"<v:textbox inset="0.00pt,0.00pt,0.00pt,0.00pt" style="mso-fit-shape-to-text:t"><w:txbxContent>"#,
r#"<w10:wrap type="square"/></v:rect></w:pict></mc:Fallback></mc:AlternateContent>"#,
] {
assert!(fallback.contains(want), "{want} in {fallback}");
}
assert_eq!(xml.matches(">29</w:t>").count(), 2, "the text in the choice and again in the fallback");
// Read back: the choice, once.
let r = craft_docx::read(&bytes).unwrap();
let mut boxes = Vec::new();
r.objects_in_reading_order(&mut |o| boxes.extend(o.text_boxes()));
boxes.retain(|id| r.parts.get(id).is_some_and(|p| p.kind == PartKind::TextBox));
assert_eq!(boxes.len(), 1, "one text box, not the fallback as well");
assert_eq!(r.plain_text(craft_wordmodel::StoryRef::Part(boxes[0])), "29");
}
/// The fallback keeps the box's own stacking order (not that of a floating object inside it),
/// its hidden flag and its text direction.
#[test]
fn the_fallback_keeps_order_visibility_and_direction() {
let mut d = Document::from_text("a");
let inner = d.add_part(PartKind::TextBox, vec![para_block(craft_wordmodel::Paragraph::with_text("inner", Default::default()))]);
let mut nested = shape(ShapeKind::TextBox, Some(inner));
if let InlineObject::Shape { float, .. } = &mut nested {
float.z = 100;
}
let mut p = craft_wordmodel::Paragraph::with_text("outer", Default::default());
p.insert_object(0, nested, &Default::default()).unwrap();
let outer = d.add_part(PartKind::TextBox, vec![para_block(p)]);
d.parts.get_mut(&outer).unwrap().body = TextBody { vert: TextVert::Vert270, ..Default::default() };
let mut o = shape(ShapeKind::TextBox, Some(outer));
if let InlineObject::Shape { float, .. } = &mut o {
float.z = 10;
float.hidden = true;
}
d.insert_object(&craft_wordmodel::Pos::body(0, 1), o, &Default::default()).unwrap();
let xml = document_xml(&craft_docx::write(&d).unwrap());
// The outer box's VML: the `v:rect` holding the vertical text box (the inner box's fallback
// is copied into the outer one's text, so it comes after it).
let tb = xml.find(r#"<v:textbox style="layout-flow:vertical;mso-layout-flow-alt:bottom-to-top">"#).expect("the outer box's text, turned");
let rect = &xml[xml[..tb].rfind("<v:rect ").expect("its v:rect")..tb];
assert!(rect.contains("z-index:10;"), "{rect}");
assert!(rect.contains("visibility:hidden"), "{rect}");
}
/// Shapes behind the text keep their order in the fallback: a higher `z` stacks higher, below
/// the text (a negative `z-index` in signed 32-bit range).
#[test]
fn behind_text_shapes_keep_their_order() {
let mut d = Document::from_text("a");
for z in [10, 20, u32::MAX] {
let mut o = shape(ShapeKind::Rectangle, None);
if let InlineObject::Shape { float, .. } = &mut o {
float.wrap = Wrap::BehindText;
float.z = z;
}
d.insert_object(&craft_wordmodel::Pos::body(0, 1), o, &Default::default()).unwrap();
}
let xml = document_xml(&craft_docx::write(&d).unwrap());
let mut got: Vec<i64> = xml
.match_indices("z-index:")
.map(|(i, m)| {
let v = &xml[i + m.len()..];
v[..v.find([';', '"']).unwrap()].parse().unwrap()
})
.collect();
got.sort_unstable();
let low = -(1i64 << 31);
assert_eq!(got, vec![low + 10, low + 20, -1], "{xml}");
}
/// A shape VML has no simple form for stays a bare `wps:wsp`: guarded without a fallback, an old
/// reader would open the file without it and drop it on its next save.
#[test]
fn a_shape_without_a_vml_form_is_not_guarded() {
let mut d = Document::from_text("a");
d.insert_object(&craft_wordmodel::Pos::body(0, 1), shape(ShapeKind::Star, None), &Default::default()).unwrap();
let bytes = craft_docx::write(&d).unwrap();
let xml = document_xml(&bytes);
assert!(xml.contains("<w:r><w:drawing>") && xml.contains(r#"<a:prstGeom prst="star5">"#), "{xml}");
assert!(!xml.contains("<mc:AlternateContent>"), "{xml}");
let r = craft_docx::read(&bytes).unwrap();
let mut kinds = Vec::new();
r.objects_in_reading_order(&mut |o| {
if let InlineObject::Shape { kind, .. } = o {
kinds.push(*kind);
}
});
assert_eq!(kinds, vec![ShapeKind::Star]);
}
/// A partial fallback must not turn a linked story into independent boxes in older readers.
#[test]
fn linked_boxes_stay_bare_while_unlinked_boxes_keep_their_fallback() {
let mut d = Document::from_text("a\nb\nc\nd");
let mut ids = Vec::new();
for (i, text) in ["Flows on", "", "", "Independent"].into_iter().enumerate() {
let id = d.add_part(PartKind::TextBox, vec![para_block(craft_wordmodel::Paragraph::with_text(text, Default::default()))]);
ids.push(id);
d.insert_object(&craft_wordmodel::Pos::body(i, 1), shape(ShapeKind::TextBox, Some(id)), &Default::default()).unwrap();
}
d.parts.get_mut(&ids[0]).unwrap().body.next = Some(ids[1]);
d.parts.get_mut(&ids[1]).unwrap().body.next = Some(ids[2]);
let bytes = craft_docx::write(&d).unwrap();
let xml = document_xml(&bytes);
assert_eq!(xml.matches("<mc:AlternateContent>").count(), 1, "{xml}");
assert_eq!(xml.matches("<mc:Fallback>").count(), 1, "{xml}");
let fallback = xml.split("<mc:Fallback>").nth(1).unwrap().split("</mc:Fallback>").next().unwrap();
assert!(fallback.contains(">Independent</w:t>"), "{fallback}");
assert!(!fallback.contains("Flows on"), "the chain head must not get an unlinked fallback");
assert_eq!(xml.matches(">Flows on</w:t>").count(), 1);
assert!(xml.contains(r#"<wps:txbx id="1">"#), "{xml}");
assert!(xml.contains(r#"<wps:linkedTxbx id="1" seq="1"/>"#), "{xml}");
assert!(xml.contains(r#"<wps:linkedTxbx id="1" seq="2"/>"#), "{xml}");
let read = craft_docx::read(&bytes).unwrap();
let chains = read.text_box_chains();
assert_eq!(chains.len(), 1);
assert_eq!(chains[0].len(), 3);
assert_eq!(read.plain_text(craft_wordmodel::StoryRef::Part(chains[0][0])), "Flows on");
}
+3
View File
@@ -34,6 +34,9 @@
//! Input is treated as hostile: every header read is bounds-checked, the picture size is capped
//! by [`Limits`] and the image data must be present in full before anything is allocated.
/// RGBA8-to-10-bit DPX encoding.
pub mod rgba8_dpx10;
#[cfg(test)]
mod tests;
+122
View File
@@ -0,0 +1,122 @@
//! Uncompressed RGB(A) output from top-down RGBA8 pixels.
/// Why the supplied frame cannot be encoded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Rgba8EncodeError {
/// Empty, overflowing, or mismatched dimensions.
FrameSize,
/// A dimension cannot fit the output format.
TooLarge,
/// The output buffer could not be allocated.
OutOfMemory,
}
/// Reserves the DPX output up front; a failed reservation becomes [`Rgba8EncodeError::OutOfMemory`].
fn output_buffer(size: usize) -> std::result::Result<Vec<u8>, Rgba8EncodeError> {
let mut buf = Vec::new();
match buf.try_reserve_exact(size) {
Ok(()) => Ok(buf),
Err(_) => Err(Rgba8EncodeError::OutOfMemory),
}
}
fn checked_len(rgba: &[u8], w: u32, h: u32) -> std::result::Result<usize, Rgba8EncodeError> {
let n = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(4)).ok_or(Rgba8EncodeError::FrameSize)?;
if w == 0 || h == 0 || rgba.len() != n {
return Err(Rgba8EncodeError::FrameSize);
}
Ok(n)
}
/// Header size of the DPX files we write (file + image + orientation + film + TV headers).
const DPX_HEADER: usize = 2048;
/// A DPX file: 10-bit RGB (8-bit values widened by bit replication, so 0 → 0 and 255 → 1023).
pub fn encode_rgba8_dpx10(rgba: &[u8], w: u32, h: u32, creator: &str) -> std::result::Result<Vec<u8>, Rgba8EncodeError> {
let n = checked_len(rgba, w, h)?;
// one 32-bit word per pixel; `n` is already `w * h * 4`
let size = n.checked_add(DPX_HEADER).ok_or(Rgba8EncodeError::FrameSize)?;
let file_size = u32::try_from(size).map_err(|_| Rgba8EncodeError::TooLarge)?;
// SMPTE ST 268: undefined numeric fields are all ones, undefined text fields are NUL
let mut hd = vec![0xFF_u8; DPX_HEADER];
for (a, b) in [
(36, 660), // file name, creation time, creator, project, copyright
(664, 768), // reserved
(1356, 1408), // reserved
(1432, 1620), // source file name, time, input device, serial number
(1644, 1664), // reserved
(1664, 1712), // film manufacturer, type, offset, prefix, count, format
(1732, 1920), // frame id, slate, reserved
(1972, 2048), // reserved
] {
hd[a..b].fill(0);
}
for e in 0..8 {
let d = 780 + e * 72 + 40;
hd[d..d + 32].fill(0); // element descriptions
}
let put32 = |hd: &mut Vec<u8>, at: usize, v: u32| hd[at..at + 4].copy_from_slice(&v.to_be_bytes());
let put16 = |hd: &mut Vec<u8>, at: usize, v: u16| hd[at..at + 2].copy_from_slice(&v.to_be_bytes());
// file information header
hd[0..4].copy_from_slice(b"SDPX");
put32(&mut hd, 4, DPX_HEADER as u32); // offset to the image data
hd[8..16].copy_from_slice(b"V2.0\0\0\0\0");
put32(&mut hd, 16, file_size);
put32(&mut hd, 20, 1); // ditto key: new frame
put32(&mut hd, 24, 1664); // generic header length
put32(&mut hd, 28, 384); // industry header length
put32(&mut hd, 32, 0); // user data length
let creator = creator.as_bytes();
let n = creator.len().min(100);
hd[160..160 + n].copy_from_slice(&creator[..n]);
// image information header
put16(&mut hd, 768, 0); // orientation: left to right, top to bottom
put16(&mut hd, 770, 1); // one image element
put32(&mut hd, 772, w);
put32(&mut hd, 776, h);
let el = 780;
put32(&mut hd, el, 0); // unsigned
put32(&mut hd, el + 4, 0); // reference low data code
put32(&mut hd, el + 12, 1023); // reference high data code
hd[el + 20] = 50; // descriptor: RGB
hd[el + 21] = 6; // transfer: ITU-R BT.709
hd[el + 22] = 6; // colorimetric: ITU-R BT.709
hd[el + 23] = 10; // bit depth
put16(&mut hd, el + 24, 1); // packing: filled to 32-bit words, method A
put16(&mut hd, el + 26, 0); // no encoding (uncompressed)
put32(&mut hd, el + 28, DPX_HEADER as u32); // offset to the element's data
put32(&mut hd, el + 32, 0); // end-of-line padding
put32(&mut hd, el + 36, 0); // end-of-image padding
// image orientation header: no offset, square pixels
put32(&mut hd, 1408, 0);
put32(&mut hd, 1412, 0);
put32(&mut hd, 1424, w);
put32(&mut hd, 1428, h);
put32(&mut hd, 1628, 1);
put32(&mut hd, 1632, 1);
// television header: progressive
hd[1928] = 0;
// The caller already holds the frame; reserve the output fallibly so a large export reports
// an error instead of aborting the process.
let mut out = output_buffer(size)?;
out.extend_from_slice(&hd);
let ten = |v: u8| (u32::from(v) << 2) | (u32::from(v) >> 6);
for &[r, g, b, _] in rgba.as_chunks::<4>().0 {
out.extend_from_slice(&((ten(r) << 22) | (ten(g) << 12) | (ten(b) << 2)).to_be_bytes());
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn packed_rgb_and_creator() {
let bytes = encode_rgba8_dpx10(&[255, 0, 128, 255], 1, 1, "FilmCraft").unwrap();
assert_eq!(&bytes[..4], b"SDPX");
assert_eq!(&bytes[160..169], b"FilmCraft");
assert_eq!(&bytes[2048..], &((1023u32 << 22) | (514u32 << 2)).to_be_bytes());
assert_eq!(encode_rgba8_dpx10(&[], 0, 1, ""), Err(Rgba8EncodeError::FrameSize));
}
#[test]
fn output_reservation_failure_maps_to_out_of_memory() {
assert!(matches!(output_buffer(usize::MAX), Err(Rgba8EncodeError::OutOfMemory)));
assert_eq!(output_buffer(DPX_HEADER).map(|b| b.capacity() >= DPX_HEADER), Ok(true));
}
}
+20
View File
@@ -354,6 +354,10 @@ pub struct Chart {
pub legend: Option<String>,
/// `c:legend/c:overlay`: the legend is drawn over the plot instead of shrinking it.
pub legend_overlay: bool,
/// `c:legend/c:legendEntry`: entries whose text has its own size, weight or colour, over
/// the legend's.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub legend_entries: Vec<LegendEntry>,
/// Text size in points of the axis labels and legend (from their `c:txPr`, else the chart's);
/// `None`: the file gives none.
#[serde(skip_serializing_if = "Option::is_none")]
@@ -431,6 +435,21 @@ pub struct Chart {
pub kept: ChartKept,
}
/// One legend entry's own text (`c:legendEntry/c:txPr`): what it sets wins over the legend's.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct LegendEntry {
/// The entry's place in the legend, from 0 (`c:idx`).
pub idx: u32,
/// Text size in points.
#[serde(skip_serializing_if = "Option::is_none")]
pub size: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bold: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub color: Option<ColorRef>,
}
/// One relationship of a chart part, with the target string as it was written.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -483,6 +502,7 @@ impl Default for Chart {
series: vec![],
legend: Some("b".into()),
legend_overlay: false,
legend_entries: vec![],
text_size: None,
title_size: None,
data_labels: false,
+47
View File
@@ -143,6 +143,7 @@ fn chart_within(root: &El, mut budget: usize) -> Option<Chart> {
c.legend = ch.child(Local("legend")).map(|l| l.child(Local("legendPos")).and_then(|c| c.attr_local("val")).unwrap_or("r").to_string());
c.legend_overlay =
ch.child(Local("legend")).and_then(|l| l.child(Local("overlay"))).and_then(|o| o.attr_local("val").and_then(value::to_bool)).unwrap_or(false);
c.legend_entries = legend_entries(ch.child(Local("legend")));
c.chart_fill = simple_fill(root.child(Local("spPr")));
c.plot_fill = simple_fill(pa.child(Local("spPr")));
@@ -552,6 +553,52 @@ fn text_color(e: Option<&El>) -> Option<crate::style::ColorRef> {
rec(e?, 0)
}
/// Legend entries read from one chart; a legend lists at most one per series or category.
const MAX_LEGEND_ENTRIES: usize = 1024;
/// The legend's entries with text of their own (`c:legendEntry/c:txPr`), over the legend's.
fn legend_entries(legend: Option<&El>) -> Vec<crate::chart::LegendEntry> {
legend
.into_iter()
.flat_map(|l| l.children(Local("legendEntry")))
.take(MAX_LEGEND_ENTRIES)
.filter_map(|e| {
// The paragraph's own run properties first, then the list style's defaults
// (`a:lstStyle` comes before `a:p`, and is the less specific of the two).
let tx = e.child(Local("txPr"));
let para = tx.and_then(|t| t.child(Local("p")));
let entry = crate::chart::LegendEntry {
idx: e.child(Local("idx")).and_then(|i| i.attr_local("val")).and_then(|v| v.parse().ok())?,
size: text_size(para).or_else(|| text_size(tx)),
bold: text_bold(para).or_else(|| text_bold(tx)),
color: text_color(para).or_else(|| text_color(tx)),
};
(entry.size.is_some() || entry.bold.is_some() || entry.color.is_some()).then_some(entry)
})
.collect()
}
/// The weight (`b`) of the first `a:defRPr` or `a:rPr` that sets one under `e`.
fn text_bold(e: Option<&El>) -> Option<bool> {
fn rec(e: &El, depth: usize) -> Option<bool> {
if depth > 8 {
return None;
}
for c in e.elements() {
if (c.is(Local("defRPr")) || c.is(Local("rPr")))
&& let Some(b) = c.attr_local("b").and_then(value::to_bool)
{
return Some(b);
}
if let Some(v) = rec(c, depth + 1) {
return Some(v);
}
}
None
}
rec(e?, 0)
}
/// The size in points of the first `a:defRPr` or `a:rPr` with one under `e` (`sz` in hundredths).
fn text_size(e: Option<&El>) -> Option<f64> {
fn rec(e: &El, depth: usize) -> Option<f64> {
+101
View File
@@ -101,6 +101,38 @@ fn tx_pr(w: &mut Writer, c: &Chart) {
w.close();
}
/// `c:legendEntry` with the entry's own text size, weight and colour.
fn legend_entry(w: &mut Writer, e: &crate::chart::LegendEntry) {
w.open("c:legendEntry", &[]);
w.tag("c:idx").attr("val", e.idx).empty();
w.open("c:txPr", &[]);
w.empty("a:bodyPr", &[]);
w.empty("a:lstStyle", &[]);
w.open("a:p", &[]);
w.open("a:pPr", &[]);
let mut run = w.tag("a:defRPr");
if let Some(sz) = e.size.filter(|v| v.is_finite() && *v > 0.0) {
// 1 to 400 pt, as the reader takes it, so a size reads back as written.
run = run.attr("sz", (sz * 100.0).round().clamp(100.0, 40_000.0) as u32);
}
if let Some(b) = e.bold {
run = run.attr("b", u8::from(b));
}
match &e.color {
Some(c) => {
run.open();
dml::solid(w, c);
w.close();
}
None => run.empty(),
}
w.close();
w.tag("a:endParaRPr").attr("lang", "en-US").empty();
w.close();
w.close();
w.close();
}
fn rich(w: &mut Writer, text: &str, color: Option<&crate::style::ColorRef>) {
w.open("c:tx", &[]);
w.open("c:rich", &[]);
@@ -781,6 +813,9 @@ pub fn chart_xml(c: &Chart) -> (Vec<u8>, bool) {
};
w.open("c:legend", &[]);
w.tag("c:legendPos").attr("val", p).empty();
for e in &c.legend_entries {
legend_entry(&mut w, e);
}
w.tag("c:overlay").attr("val", u8::from(c.legend_overlay)).empty();
tx_pr(&mut w, c);
w.close();
@@ -1058,6 +1093,72 @@ mod tests {
use crate::color::{ColorTransform, Rgba};
use crate::style::ColorRef;
/// A legend entry's own text (`c:legendEntry/c:txPr`: size, bold, colour) is read, and a
/// rebuilt part writes it back, in schema order before `c:overlay` (DeckCraft #2067).
#[test]
fn legend_entry_text_is_read_and_survives_an_edit() {
let read = |xml: &[u8]| crate::chart::read::read_chart_xml(xml).unwrap();
let entry = |idx: u32, rgb: &str| {
format!(
r#"<c:legendEntry><c:idx val="{idx}"/><c:txPr><a:bodyPr/><a:lstStyle/><a:p><a:pPr><a:defRPr sz="2000" b="1"><a:solidFill><a:srgbClr val="{rgb}"/></a:solidFill></a:defRPr></a:pPr><a:endParaRPr lang="en-US"/></a:p></c:txPr></c:legendEntry>"#
)
};
let xml = format!(
r#"<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><c:chart><c:plotArea><c:lineChart><c:grouping val="standard"/><c:ser><c:idx val="0"/><c:val><c:numRef><c:numCache><c:ptCount val="1"/><c:pt idx="0"><c:v>1</c:v></c:pt></c:numCache></c:numRef></c:val></c:ser><c:axId val="1"/><c:axId val="2"/></c:lineChart><c:catAx><c:axId val="1"/><c:crossAx val="2"/></c:catAx><c:valAx><c:axId val="2"/><c:crossAx val="1"/></c:valAx></c:plotArea><c:legend><c:legendPos val="r"/>{}{}<c:legendEntry><c:idx val="2"/><c:txPr><a:bodyPr/><a:p><a:pPr><a:defRPr/></a:pPr></a:p></c:txPr></c:legendEntry><c:overlay val="0"/><c:txPr><a:bodyPr/><a:p><a:pPr><a:defRPr sz="1200"><a:solidFill><a:srgbClr val="7F7F7F"/></a:solidFill></a:defRPr></a:pPr></a:p></c:txPr></c:legend></c:chart></c:chartSpace>"#,
entry(0, "C00000"),
entry(1, "00B050")
);
let c = read(xml.as_bytes());
let want = |idx: u32, rgb: (u8, u8, u8)| crate::chart::LegendEntry {
idx,
size: Some(20.0),
bold: Some(true),
color: Some(ColorRef::rgb(Rgba::rgb(rgb.0, rgb.1, rgb.2))),
};
// The third entry sets nothing of its own and is not kept.
assert_eq!(c.legend_entries, vec![want(0, (0xC0, 0, 0)), want(1, (0, 0xB0, 0x50))]);
assert_eq!(c.text_size, Some(12.0), "the legend's own size stays the legend's");
let mut e = c.clone();
e.title = Some("Units".into());
e.raw = None;
let (out, kept) = super::chart_xml(&e);
assert!(!kept);
let s = String::from_utf8(out.clone()).unwrap();
let legend = &s[s.find("<c:legend>").unwrap()..];
let (pos, entry0, overlay) =
(legend.find("<c:legendPos").unwrap(), legend.find("<c:legendEntry>").unwrap(), legend.find("<c:overlay").unwrap());
assert!(pos < entry0 && entry0 < overlay, "{s}");
assert_eq!(read(&out).legend_entries, c.legend_entries);
// None: nothing written.
e.legend_entries.clear();
assert!(!String::from_utf8(super::chart_xml(&e).0).unwrap().contains("legendEntry"));
// The paragraph's own properties win over the list style's, which come first in the XML.
let listed = xml.replacen(
r#"<c:legendEntry><c:idx val="0"/><c:txPr><a:bodyPr/><a:lstStyle/>"#,
r#"<c:legendEntry><c:idx val="0"/><c:txPr><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="1200" b="0"><a:solidFill><a:srgbClr val="0000FF"/></a:solidFill></a:defRPr></a:lvl1pPr></a:lstStyle>"#,
1,
);
assert_ne!(listed, xml, "the list style was put in");
let c = read(listed.as_bytes());
assert_eq!(c.legend_entries[0], want(0, (0xC0, 0, 0)), "the paragraph's 20 pt, bold, C00000");
// The list style alone still counts.
let only_list =
listed.replacen(r#"<a:defRPr sz="2000" b="1"><a:solidFill><a:srgbClr val="C00000"/></a:solidFill></a:defRPr>"#, "<a:defRPr/>", 1);
let entry = &read(only_list.as_bytes()).legend_entries[0];
assert_eq!((entry.size, entry.bold), (Some(12.0), Some(false)));
// A size reads back as it was written, within the reader's 1-400 pt.
for (size, back) in [(20.5, 20.5), (400.0, 400.0), (500.0, 400.0)] {
let mut e = c.clone();
e.raw = None;
e.legend_entries = vec![crate::chart::LegendEntry { idx: 0, size: Some(size), bold: Some(false), color: None }];
let written = super::chart_xml(&e).0;
let sz = format!(r#"sz="{}""#, (back * 100.0) as u32);
assert!(String::from_utf8_lossy(&written).contains(&sz), "{size} pt is written as {sz}");
let back_entry = &read(&written).legend_entries[0];
assert_eq!((back_entry.size, back_entry.bold), (Some(back), Some(false)), "{size} pt");
}
}
#[test]
fn export_cost_counts_the_caches_each_group_writes() {
let s = Series { values: vec![Some(1.0); 600], ..Default::default() };
+22 -5
View File
@@ -234,16 +234,18 @@ fn sci(toks: &[Tok], v: f64, sep: char, dec: char) -> Option<String> {
m *= 10.0;
exp -= 1;
}
// Rounding the mantissa to its digits can reach 10 (9.999 as `0.00`).
if format!("{m:.mant_frac$}").starts_with("10") {
m /= 10.0;
exp += 1;
}
}
let step = mant.iter().take_while(|t| **t != Tok::Dot).filter(|t| matches!(t, Tok::Digit(_))).count().max(1) as i32;
let shift = exp.rem_euclid(step);
exp -= shift;
m *= 10f64.powi(shift);
// Round after forming the engineering mantissa: 999.94 as `##0.0` stays 999.9.
// Carry only when rounding exceeds all of the format's integer placeholders.
let carry = 10f64.powi(step);
if format!("{m:.mant_frac$}").parse::<f64>().is_ok_and(|rounded| rounded >= carry) {
m /= carry;
exp += step;
}
let mantissa = fixed(mant, mfirst, mlast, m, sep, dec);
let sign = if exp < 0 {
"-"
@@ -404,6 +406,21 @@ mod tests {
assert_eq!(format("##0.0E+0", 999.96, None), "1.0E+3");
}
#[test]
fn engineering_formats_round_the_full_mantissa() {
for (code, value, expected) in [
("##0.0E+00", 999.94, "999.9E+00"),
("##0.0E+00", 0.99994, "999.9E-03"),
("##0.0E+00", -999.94, "-999.9E+00"),
("#0.0E+00", 99.94, "99.9E+00"),
("##0.0E+00", 999.96, "1.0E+03"),
("#0.0E+00", 99.96, "1.0E+02"),
] {
assert_eq!(format(code, value, None), expected, "{code}, {value}");
}
assert_eq!(format("##0.0E+00", 999.94, Some("de-DE")), "999,9E+00");
}
#[test]
fn never_panics() {
for code in ["", ";", ";;;", "\"", "[", "\\", "0.", ".", "#,", "%", "_", "*", "@", "0E+00", "[$", "\"unterminated"] {
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "craft-elf"
description = "ELF program headers and dynamic section entries from hostile bytes, from Craft Anything: 32/64-bit, either byte order, with bounded counts and overflow-checked offsets, plus segment, permission and dynamic tag names. Pure Rust, no I/O."
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
[lints]
workspace = true
[dependencies]
thiserror = { workspace = true }
# `serde`: `Serialize` on `ProgramHeader` (addresses as `0x…` strings), for apps that report
# segments as JSON.
serde = { workspace = true, optional = true }
[features]
serde = ["dep:serde"]
[dev-dependencies]
serde_json = { workspace = true }
+37
View File
@@ -0,0 +1,37 @@
//! Bounds-checked reads of fixed-width integers in both byte orders: out of range is `None`.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Reader<'a> {
buf: &'a [u8],
}
macro_rules! int {
($le:ident, $be:ident, $ty:ty) => {
pub(crate) fn $le(&self, at: usize) -> Option<$ty> {
self.take(at).map(<$ty>::from_le_bytes)
}
pub(crate) fn $be(&self, at: usize) -> Option<$ty> {
self.take(at).map(<$ty>::from_be_bytes)
}
};
}
impl<'a> Reader<'a> {
pub(crate) fn new(buf: &'a [u8]) -> Self {
Self { buf }
}
pub(crate) fn u8(&self, at: usize) -> Option<u8> {
self.buf.get(at).copied()
}
fn take<const N: usize>(&self, at: usize) -> Option<[u8; N]> {
let end = at.checked_add(N)?;
self.buf.get(at..end)?.try_into().ok()
}
int!(u16_le, u16_be, u16);
int!(u32_le, u32_be, u32);
int!(u64_le, u64_be, u64);
}
+5
View File
@@ -0,0 +1,5 @@
//! Addresses serialised as `0x…` strings, as Craft Anything reports them.
pub(crate) fn serialize<S: serde::Serializer>(value: &u64, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&format!("{value:#x}"))
}
+244
View File
@@ -0,0 +1,244 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
//! ELF program headers and dynamic section entries from untrusted bytes, 32- or 64-bit in either
//! byte order: [`program_headers`], [`dynamic_entries`], [`va_to_off`], and the segment type,
//! permission and dynamic tag names.
//!
//! From Craft Anything (`crates/formats/src/elf.rs`), where the mitigations, dynamic symbols,
//! symbol versions and core-file notes built on these stay. With the `serde` feature,
//! [`ProgramHeader`] is `Serialize` with `vaddr` as a `0x…` string.
mod bytes;
#[cfg(feature = "serde")]
mod hex;
use crate::bytes::Reader;
/// Program headers read from one table.
pub const MAX_PHDRS: usize = 4096;
/// Dynamic entries read from one segment.
pub const MAX_DYN: usize = 65_536;
/// Why a read gave up.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ElfError {
/// The ELF header ends before the file does.
#[error("the file ends early ({0})")]
Truncated(&'static str),
/// No ELF magic, or an invalid class, encoding or field.
#[error("the file is malformed ({0})")]
Malformed(String),
}
/// Endian/class-aware reads over an ELF image.
#[derive(Clone, Copy)]
struct E<'a> {
r: Reader<'a>,
is64: bool,
le: bool,
}
impl<'a> E<'a> {
fn new(data: &'a [u8]) -> Result<Self, ElfError> {
if !data.starts_with(b"\x7fELF") {
return Err(ElfError::Malformed("no ELF magic".into()));
}
let r = Reader::new(data);
let class = r.u8(4).ok_or(ElfError::Truncated("ELF ident"))?;
let enc = r.u8(5).ok_or(ElfError::Truncated("ELF ident"))?;
if !matches!(class, 1 | 2) || !matches!(enc, 1 | 2) {
return Err(ElfError::Malformed("bad ELF class or data encoding".into()));
}
Ok(E { r, is64: class == 2, le: enc == 1 })
}
fn u16(&self, off: usize) -> Option<u16> {
if self.le { self.r.u16_le(off) } else { self.r.u16_be(off) }
}
fn u32(&self, off: usize) -> Option<u32> {
if self.le { self.r.u32_le(off) } else { self.r.u32_be(off) }
}
fn u64(&self, off: usize) -> Option<u64> {
if self.le { self.r.u64_le(off) } else { self.r.u64_be(off) }
}
fn word(&self, off: usize) -> Option<u64> {
if self.is64 { self.u64(off) } else { self.u32(off).map(u64::from) }
}
fn word_size(&self) -> usize {
if self.is64 { 8 } else { 4 }
}
}
/// One program header.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ProgramHeader {
/// [`segment_type_name`] of `p_type`.
pub kind: String,
/// [`permissions`] of `p_flags`.
pub flags: String,
pub offset: u64,
#[cfg_attr(feature = "serde", serde(serialize_with = "hex::serialize"))]
pub vaddr: u64,
pub file_size: u64,
pub mem_size: u64,
pub align: u64,
/// The raw segment type.
#[cfg_attr(feature = "serde", serde(skip))]
pub p_type: u32,
/// The raw `PF_R`/`PF_W`/`PF_X` flags.
#[cfg_attr(feature = "serde", serde(skip))]
pub p_flags: u32,
}
/// A segment type's `PT_` name without the prefix (`LOAD`, `GNU_RELRO`…), or its number in hex.
pub fn segment_type_name(t: u32) -> String {
match t {
0 => "NULL".into(),
1 => "LOAD".into(),
2 => "DYNAMIC".into(),
3 => "INTERP".into(),
4 => "NOTE".into(),
5 => "SHLIB".into(),
6 => "PHDR".into(),
7 => "TLS".into(),
0x6474_e550 => "GNU_EH_FRAME".into(),
0x6474_e551 => "GNU_STACK".into(),
0x6474_e552 => "GNU_RELRO".into(),
0x6474_e553 => "GNU_PROPERTY".into(),
0x7000_0001 => "ARM_EXIDX".into(),
other => format!("{other:#x}"),
}
}
/// `p_flags` as `rwx`, with `-` for each permission missing.
pub fn permissions(f: u32) -> String {
format!("{}{}{}", if f & 4 != 0 { 'r' } else { '-' }, if f & 2 != 0 { 'w' } else { '-' }, if f & 1 != 0 { 'x' } else { '-' })
}
/// The program headers of an ELF file, at most [`MAX_PHDRS`]. A table that runs past the file
/// ends at the last complete entry.
pub fn program_headers(data: &[u8]) -> Result<Vec<ProgramHeader>, ElfError> {
let e = E::new(data)?;
let (phoff, phentsize, phnum) = if e.is64 { (e.u64(32), e.u16(54), e.u16(56)) } else { (e.u32(28).map(u64::from), e.u16(42), e.u16(44)) };
let phoff = usize::try_from(phoff.ok_or(ElfError::Truncated("ELF header"))?).map_err(|_| ElfError::Malformed("phoff".into()))?;
let phentsize = usize::from(phentsize.unwrap_or(0));
let phnum = usize::from(phnum.unwrap_or(0)).min(MAX_PHDRS);
let min = if e.is64 { 56 } else { 32 };
if phnum > 0 && phentsize < min {
return Err(ElfError::Malformed("program header entry too small".into()));
}
let mut out = Vec::new();
for i in 0..phnum {
// The fields below sit within `phentsize` bytes of `o`, so their offsets can't overflow either.
let Some(o) = i.checked_mul(phentsize).and_then(|x| x.checked_add(phoff)).filter(|&o| o.checked_add(phentsize).is_some()) else { break };
let ph = if e.is64 {
(e.u32(o), e.u32(o + 4), e.u64(o + 8), e.u64(o + 16), e.u64(o + 32), e.u64(o + 40), e.u64(o + 48))
} else {
(
e.u32(o),
e.u32(o + 24),
e.u32(o + 4).map(u64::from),
e.u32(o + 8).map(u64::from),
e.u32(o + 16).map(u64::from),
e.u32(o + 20).map(u64::from),
e.u32(o + 28).map(u64::from),
)
};
let (Some(t), Some(f), Some(off), Some(va), Some(fs), Some(ms), Some(al)) = ph else { break };
out.push(ProgramHeader {
kind: segment_type_name(t),
flags: permissions(f),
offset: off,
vaddr: va,
file_size: fs,
mem_size: ms,
align: al,
p_type: t,
p_flags: f,
});
}
Ok(out)
}
/// A dynamic tag's `DT_` name without the prefix (`NEEDED`, `GNU_HASH`…), or its number in hex.
pub fn dynamic_tag_name(tag: u64) -> String {
match tag {
0 => "NULL",
1 => "NEEDED",
2 => "PLTRELSZ",
3 => "PLTGOT",
4 => "HASH",
5 => "STRTAB",
6 => "SYMTAB",
7 => "RELA",
8 => "RELASZ",
9 => "RELAENT",
10 => "STRSZ",
11 => "SYMENT",
12 => "INIT",
13 => "FINI",
14 => "SONAME",
15 => "RPATH",
16 => "SYMBOLIC",
17 => "REL",
18 => "RELSZ",
19 => "RELENT",
20 => "PLTREL",
21 => "DEBUG",
22 => "TEXTREL",
23 => "JMPREL",
24 => "BIND_NOW",
25 => "INIT_ARRAY",
26 => "FINI_ARRAY",
27 => "INIT_ARRAYSZ",
28 => "FINI_ARRAYSZ",
29 => "RUNPATH",
30 => "FLAGS",
0x6fff_fef5 => "GNU_HASH",
0x6fff_fffb => "FLAGS_1",
0x6fff_fff0 => "VERSYM",
0x6fff_fffe => "VERNEED",
0x6fff_ffff => "VERNEEDNUM",
_ => return format!("{tag:#x}"),
}
.into()
}
/// Map a virtual address to a file offset using `PT_LOAD` headers. Addresses in a segment's
/// zero-filled tail, or whose offset would overflow, map to nothing.
pub fn va_to_off(phdrs: &[ProgramHeader], va: u64) -> Option<u64> {
phdrs.iter().filter(|p| p.p_type == 1).find(|p| va >= p.vaddr && va - p.vaddr < p.file_size).and_then(|p| p.offset.checked_add(va - p.vaddr))
}
/// The (tag, value) pairs of the `PT_DYNAMIC` segment in `phdrs`, up to its `DT_NULL`, at most
/// [`MAX_DYN`]. Empty without a dynamic segment.
pub fn dynamic_entries(data: &[u8], phdrs: &[ProgramHeader]) -> Result<Vec<(u64, u64)>, ElfError> {
Ok(entries(&E::new(data)?, phdrs))
}
fn entries(e: &E<'_>, phdrs: &[ProgramHeader]) -> Vec<(u64, u64)> {
let mut out = Vec::new();
let Some(d) = phdrs.iter().find(|p| p.p_type == 2) else { return out };
let ent = 2 * e.word_size();
let n = usize::try_from(d.file_size).unwrap_or(0) / ent;
let start = usize::try_from(d.offset).unwrap_or(usize::MAX);
for i in 0..n.min(MAX_DYN) {
let Some(o) = i.checked_mul(ent).and_then(|x| start.checked_add(x)) else { break };
let (Some(tag), Some(val)) = (e.word(o), o.checked_add(e.word_size()).and_then(|v| e.word(v))) else { break };
if tag == 0 {
break;
}
out.push((tag, val));
}
out
}
#[cfg(test)]
mod tests;
+201
View File
@@ -0,0 +1,201 @@
//! Program header and dynamic section tests. `an_address_past_the_last_file_offset_maps_to_nothing`
//! is from Craft Anything's `elf.rs`; the image builder is a small stand-in for its testkit's.
use super::*;
/// Field writer in the image's class and byte order.
struct Image {
d: Vec<u8>,
is64: bool,
le: bool,
}
impl Image {
fn put(&mut self, at: usize, value: u64, width: usize) {
let bytes = value.to_le_bytes();
let mut field = bytes[..width].to_vec();
if !self.le {
field.reverse();
}
self.d[at..at + width].copy_from_slice(&field);
}
fn word(&mut self, at: usize, value: u64) {
self.put(at, value, if self.is64 { 8 } else { 4 });
}
}
/// An executable with PT_PHDR, PT_LOAD (r-x, whole file at 0x40_0000), PT_DYNAMIC at file 0x200
/// and PT_GNU_STACK (rw-). The dynamic section holds NEEDED, STRTAB and a DT_NULL, then junk.
fn elf(is64: bool, le: bool) -> Vec<u8> {
let mut img = Image { d: vec![0u8; 0x300], is64, le };
img.d[..4].copy_from_slice(b"\x7fELF");
img.d[4] = if is64 { 2 } else { 1 };
img.d[5] = if le { 1 } else { 2 };
img.d[6] = 1;
let (phoff_at, entsize_at, num_at, phoff, entsize) = if is64 { (32, 54, 56, 64, 56) } else { (28, 42, 44, 52, 32) };
img.word(phoff_at, phoff as u64);
img.put(entsize_at, entsize as u64, 2);
img.put(num_at, 4, 2);
let headers = [
(6u32, 4u32, phoff as u64, 0x40_0040, 4 * entsize as u64),
(1, 5, 0, 0x40_0000, 0x300),
(2, 6, 0x200, 0x40_0200, 0x60),
(0x6474_e551, 6, 0, 0, 0),
];
for (i, (t, f, off, va, size)) in headers.into_iter().enumerate() {
let o = phoff + i * entsize;
img.put(o, u64::from(t), 4);
if is64 {
img.put(o + 4, u64::from(f), 4);
img.word(o + 8, off);
img.word(o + 16, va);
img.word(o + 32, size);
img.word(o + 40, size);
img.word(o + 48, 0x1000);
} else {
img.word(o + 4, off);
img.word(o + 8, va);
img.word(o + 16, size);
img.word(o + 20, size);
img.put(o + 24, u64::from(f), 4);
img.word(o + 28, 0x1000);
}
}
let w = if is64 { 8 } else { 4 };
for (i, (tag, value)) in [(1u64, 1u64), (5, 0x40_0280), (0, 0), (1, 9)].into_iter().enumerate() {
img.word(0x200 + i * 2 * w, tag);
img.word(0x200 + i * 2 * w + w, value);
}
img.d
}
#[test]
fn program_headers_in_every_class_and_byte_order() {
for is64 in [false, true] {
for le in [false, true] {
let ph = program_headers(&elf(is64, le)).unwrap();
let kinds: Vec<(&str, &str)> = ph.iter().map(|p| (p.kind.as_str(), p.flags.as_str())).collect();
assert_eq!(kinds, [("PHDR", "r--"), ("LOAD", "r-x"), ("DYNAMIC", "rw-"), ("GNU_STACK", "rw-")], "is64={is64} le={le}");
assert_eq!((ph[1].offset, ph[1].vaddr, ph[1].file_size, ph[1].mem_size, ph[1].align), (0, 0x40_0000, 0x300, 0x300, 0x1000));
assert_eq!((ph[2].p_type, ph[2].p_flags), (2, 6));
let dynamic = dynamic_entries(&elf(is64, le), &ph).unwrap();
assert_eq!(dynamic, [(1, 1), (5, 0x40_0280)], "stops at DT_NULL");
assert_eq!(va_to_off(&ph, 0x40_0280), Some(0x280));
}
}
}
#[test]
fn bad_idents_and_headers_are_errors() {
assert_eq!(program_headers(b"\x7fELX\x02\x01"), Err(ElfError::Malformed("no ELF magic".into())));
assert_eq!(program_headers(b"\x7fELF"), Err(ElfError::Truncated("ELF ident")));
assert_eq!(program_headers(b"\x7fELF\x02"), Err(ElfError::Truncated("ELF ident")));
assert_eq!(program_headers(b"\x7fELF\x03\x01"), Err(ElfError::Malformed("bad ELF class or data encoding".into())));
assert_eq!(program_headers(b"\x7fELF\x01\x00"), Err(ElfError::Malformed("bad ELF class or data encoding".into())));
assert_eq!(program_headers(&elf(true, true)[..20]), Err(ElfError::Truncated("ELF header")));
assert_eq!(ElfError::Truncated("ELF header").to_string(), "the file ends early (ELF header)");
let mut small = elf(true, true);
small[54] = 40;
assert_eq!(program_headers(&small).unwrap_err().to_string(), "the file is malformed (program header entry too small)");
assert!(dynamic_entries(b"nope", &[]).is_err());
}
#[test]
fn a_table_cut_short_keeps_its_complete_entries() {
let d = elf(true, true);
assert_eq!(program_headers(&d[..64 + 56 * 2 + 10]).unwrap().len(), 2);
let mut none = d.clone();
none[56] = 0;
none[54] = 0;
assert!(program_headers(&none).unwrap().is_empty(), "no headers need no entry size");
let mut far = d.clone();
far[32..40].copy_from_slice(&u64::MAX.to_le_bytes());
assert!(program_headers(&far).unwrap().is_empty(), "offsets that overflow stop the walk");
}
#[test]
fn dynamic_entries_need_a_dynamic_segment_inside_the_file() {
let d = elf(false, true);
let mut ph = program_headers(&d).unwrap();
assert!(dynamic_entries(&d, &ph[..2]).unwrap().is_empty());
ph[2].offset = 0x2f8;
assert!(dynamic_entries(&d, &ph).unwrap().is_empty(), "an entry cut off by the end of the file");
ph[2].offset = u64::MAX;
assert!(dynamic_entries(&d, &ph).unwrap().is_empty());
}
fn load(offset: u64, vaddr: u64, file_size: u64) -> ProgramHeader {
ProgramHeader { kind: "LOAD".into(), flags: String::new(), offset, vaddr, file_size, mem_size: file_size, align: 0, p_type: 1, p_flags: 0 }
}
#[test]
fn an_address_past_the_last_file_offset_maps_to_nothing() {
assert_eq!(va_to_off(&[load(0x200, 0x1000, 0x100)], 0x1010), Some(0x210));
assert_eq!(va_to_off(&[load(u64::MAX, 0x1000, 0x100)], 0x1000), Some(u64::MAX));
assert_eq!(va_to_off(&[load(u64::MAX, 0x1000, 0x100)], 0x1001), None, "the offset would pass u64::MAX");
assert_eq!(va_to_off(&[load(0x200, 0x1000, 0x100)], 0x1100), None, "the zero-filled tail has no file bytes");
let mut dynamic = load(0, 0x1000, 0x100);
dynamic.p_type = 2;
assert_eq!(va_to_off(&[dynamic], 0x1010), None, "only PT_LOAD maps");
}
#[test]
fn names() {
let segments: Vec<String> =
[0, 1, 2, 3, 4, 5, 6, 7, 0x6474_e550, 0x6474_e551, 0x6474_e552, 0x6474_e553, 0x7000_0001, 0x99].into_iter().map(segment_type_name).collect();
assert_eq!(
segments,
[
"NULL",
"LOAD",
"DYNAMIC",
"INTERP",
"NOTE",
"SHLIB",
"PHDR",
"TLS",
"GNU_EH_FRAME",
"GNU_STACK",
"GNU_RELRO",
"GNU_PROPERTY",
"ARM_EXIDX",
"0x99"
]
);
assert_eq!([0, 1, 2, 4, 7].map(permissions), ["---", "--x", "-w-", "r--", "rwx"]);
let tags: Vec<String> =
(0..=30).chain([0x6fff_fef5, 0x6fff_fffb, 0x6fff_fff0, 0x6fff_fffe, 0x6fff_ffff, 0x7000_0000]).map(dynamic_tag_name).collect();
assert_eq!(tags[..3], ["NULL", "NEEDED", "PLTRELSZ"]);
assert_eq!(tags[29..], ["RUNPATH", "FLAGS", "GNU_HASH", "FLAGS_1", "VERSYM", "VERNEED", "VERNEEDNUM", "0x70000000"]);
assert!(tags.iter().all(|t| !t.is_empty()));
}
#[cfg(feature = "serde")]
#[test]
fn program_headers_serialize_with_hex_addresses() {
let ph = program_headers(&elf(true, true)).unwrap();
let value = serde_json::to_value(&ph[1]).unwrap();
assert_eq!(value["kind"], "LOAD");
assert_eq!(value["vaddr"], "0x400000");
assert!(value.get("p_type").is_none());
}
#[test]
fn damaged_input_never_panics() {
for sample in [elf(true, true), elf(false, false)] {
for i in 0..sample.len() {
if let Ok(ph) = program_headers(&sample[..i]) {
let _ = dynamic_entries(&sample[..i], &ph);
}
for v in [0x00, 0x7f, 0xff] {
let mut m = sample.clone();
m[i] = v;
if let Ok(ph) = program_headers(&m) {
let _ = dynamic_entries(&m, &ph);
let _ = va_to_off(&ph, 0x40_0280);
}
}
}
}
}
+263 -44
View File
@@ -7,7 +7,7 @@
//! - [`decode_part`] decodes the channels of one flat part that a filter keeps, in their stored
//! sample type, over the part's data window. Every compression the `exr` crate reads is read,
//! scan lines and tiles alike (the largest resolution level). Other parts' chunks are skipped
//! unread, and channels the filter drops are never allocated.
//! unread, and channels the filter drops are never allocated. Other parts may be deep.
//! - [`write`] writes one scan-line part.
//!
//! The `exr` crate sizes buffers from headers before it reads pixels, so everything that reaches
@@ -18,7 +18,7 @@
use std::io::Cursor;
use exr::block::UncompressedBlock;
use exr::block::chunk::TileCoordinates;
use exr::block::chunk::{Chunk, CompressedBlock, CompressedScanLineBlock, CompressedTileBlock, TileCoordinates};
use exr::image::read::image::ReadImage;
use exr::image::read::layers::{ChannelsReader, ReadAllLayers, ReadChannels};
use exr::meta::MetaData;
@@ -245,11 +245,21 @@ fn window_size(size: exr::math::Vec2<usize>) -> (u32, u32) {
/// Reads the headers and checks every part's declared size, alone and together, before any pixel
/// allocation. Headers are read without the crate's validation, which refuses deep parts.
fn read_meta(bytes: &[u8], limits: &Limits) -> Result<MetaData> {
pub(super) fn read_meta(bytes: &[u8], limits: &Limits) -> Result<MetaData> {
check_previews(bytes)?;
let meta = MetaData::read_from_buffered(Cursor::new(bytes), false).map_err(map_exr)?;
let (mut total, mut dwa) = (0u64, 0u64);
for header in meta.headers.iter() {
let (mut total, mut flat, mut dwa) = (0u64, 0u64, 0u64);
for (index, header) in meta.headers.iter().enumerate() {
// The crate sizes a flat chunk's bound as a block's pixels times the bytes a pixel takes,
// without checking the product, before it reads the chunk.
let block_pixels = match header.blocks {
exr::meta::BlockDescription::Tiles(tiles) => (tiles.tile_size.0 as u64).checked_mul(tiles.tile_size.1 as u64),
exr::meta::BlockDescription::ScanLines => (header.compression.scan_lines_per_block() as u64).checked_mul(header.layer_size.0 as u64),
};
let block_bytes = block_pixels.and_then(|n| n.checked_mul(header.channels.bytes_per_pixel as u64)).and_then(|n| usize::try_from(n).ok());
if !header.deep && block_bytes.is_none() {
return Err(Error::LimitExceeded(format!("a block of part {index} holds more bytes than this platform can address")));
}
let (w, h) = window_size(header.layer_size);
if w > limits.max_width || h > limits.max_height {
return Err(Error::LimitExceeded(format!("a {w}x{h} part exceeds {}x{}", limits.max_width, limits.max_height)));
@@ -260,23 +270,24 @@ fn read_meta(bytes: &[u8], limits: &Limits) -> Result<MetaData> {
}
let bytes = pixels.saturating_mul(header.channels.list.len().max(1) as u64 * 4);
total = total.saturating_add(bytes);
if matches!(header.compression, ExrCompression::DWAA(_) | ExrCompression::DWAB(_)) {
dwa = dwa.saturating_add(bytes);
if !header.deep {
flat = flat.saturating_add(bytes);
if matches!(header.compression, ExrCompression::DWAA(_) | ExrCompression::DWAB(_)) {
dwa = dwa.saturating_add(bytes);
}
}
}
if total > limits.max_bytes {
return Err(Error::LimitExceeded(format!("{total} bytes across {} parts exceed {}", meta.headers.len(), limits.max_bytes)));
}
// The crate allocates a flat part's samples before reading its chunks, so the file must be
// able to hold them. DWA's run-length channels are zlib-packed on top and reach about
// 132000:1, so DWA parts are counted at a quarter. Deep parts size their samples from the
// file's own counts.
if !meta.requirements.has_deep_data {
let declared = total.saturating_sub(dwa).saturating_add(dwa / 4);
let capacity = (bytes.len() as u64).saturating_mul(limits.max_ratio).saturating_add(1 << 20);
if declared > capacity {
return Err(Error::LimitExceeded(format!("a {} byte file cannot hold {declared} bytes of samples", bytes.len())));
}
// A flat part's samples are allocated before its chunks are read, so the file must be able
// to hold the flat parts' samples. DWA's run-length channels are zlib-packed on top and reach
// about 132000:1, so DWA parts are counted at a quarter. Deep parts size their samples from
// the file's own counts and are not counted here.
let declared = flat.saturating_sub(dwa).saturating_add(dwa / 4);
let capacity = (bytes.len() as u64).saturating_mul(limits.max_ratio).saturating_add(1 << 20);
if declared > capacity {
return Err(Error::LimitExceeded(format!("a {} byte file cannot hold {declared} bytes of samples", bytes.len())));
}
Ok(meta)
}
@@ -459,19 +470,24 @@ pub fn decode_display_part(
}
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 image = ReadImage::new(ReadAllLayers { read_channels: select }, |_| {})
.from_buffered(Cursor::new(bytes))
.map_err(|error| block_limit.take().map(Error::LimitExceeded).unwrap_or_else(|| map_exr(error)))?;
let channels = image
.layer_data
.into_iter()
.nth(index)
.ok_or_else(|| malformed("the part was not read"))?
.channel_data
.into_iter()
.flatten()
.map(|(name, samples)| DisplayChannel { name, samples })
.collect();
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 {
ReadImage::new(ReadAllLayers { read_channels: select }, |_| {})
.from_buffered(Cursor::new(bytes))
.map_err(exr_error)?
.layer_data
.into_iter()
.nth(index)
.ok_or_else(|| malformed("the part was not read"))?
.channel_data
};
let channels = planes.into_iter().flatten().map(|(name, samples)| DisplayChannel { name, samples }).collect();
Ok(DisplayPart { info, channels })
}
@@ -515,18 +531,23 @@ impl<'s> ReadChannels<'s> for DisplaySelect<'_> {
u32s: vec![],
});
}
// The EXR crate decompresses each accepted block before `read_block` can discard ignored
// channels. Bound that all-channel input separately from the selected output planes.
let Some(block_bytes) = layer_w
.checked_mul(layer_h)
.and_then(|pixels| pixels.checked_mul(header.channels.list.len().max(1)))
.and_then(|samples| samples.checked_mul(std::mem::size_of::<f32>()))
else {
// The EXR crate decompresses each accepted block, with every channel, before `read_block`
// can discard the ignored ones, so bound that all-channel block separately from the
// selected output planes. Blocks are decompressed one at a time, so the bound is the
// largest block (a tile within the data window, or a scan-line group across it), not the
// whole part: a part whose full channel set is larger than `max_bytes` still decodes when
// the kept planes and each block fit.
let block_pixels = match header.blocks {
exr::meta::BlockDescription::Tiles(tiles) => tiles.tile_size.0.min(layer_w).checked_mul(tiles.tile_size.1.min(layer_h)),
// a part shorter than its compression's scan-line group has only its own rows
exr::meta::BlockDescription::ScanLines => header.compression.scan_lines_per_block().min(layer_h).checked_mul(layer_w),
};
let Some(block_bytes) = block_pixels.and_then(|pixels| pixels.checked_mul(header.channels.bytes_per_pixel.max(1))) else {
self.block_limit.set(Some(format!("data-window block size exceeds {}", self.limits.max_bytes)));
return Err(exr::error::Error::Invalid("data-window block size overflow".into()));
};
if u64::try_from(block_bytes).map_or(true, |bytes| bytes > self.limits.max_bytes) || block_bytes > isize::MAX as usize {
self.block_limit.set(Some(format!("{block_bytes} data-window bytes exceed {}", self.limits.max_bytes)));
self.block_limit.set(Some(format!("{block_bytes} bytes in one data-window block exceed {}", self.limits.max_bytes)));
return Err(exr::error::Error::Invalid("data-window blocks exceed limit".into()));
}
let pixels = display_w.checked_mul(display_h).filter(|n| *n > 0).ok_or(exr::error::Error::Invalid("display window".into()))?;
@@ -727,22 +748,220 @@ impl ChannelsReader for SelectReader {
}
}
/// Where the headers end and the offset tables begin: [`MetaData::read_from_buffered`] consumes
/// exactly the version field and the headers.
fn tables_start(bytes: &[u8]) -> Result<u64> {
let mut cursor = Cursor::new(bytes);
MetaData::read_from_buffered(&mut cursor, false).map_err(map_exr)?;
Ok(cursor.position())
}
/// Stable dense ordinal without materializing every tile. The library's block iterator
/// internally allocates a Vec of all coordinates, which is unsuitable for cropped reads.
pub(super) fn flat_block_ordinal(header: &Header, tile: TileCoordinates) -> Result<usize> {
use exr::math::Vec2;
use exr::meta::attribute::LevelMode;
let mut start = 0usize;
let tile_size = header.max_block_pixel_size();
if tile_size.0 == 0 || tile_size.1 == 0 {
return Err(malformed("flat block has a zero dimension"));
}
let mut visit = |level: Vec2<usize>, size: Vec2<usize>| -> Result<Option<usize>> {
let nx = size.0.div_ceil(tile_size.0);
let ny = size.1.div_ceil(tile_size.1);
if tile.level_index == level {
if tile.tile_index.0 >= nx || tile.tile_index.1 >= ny {
return Err(malformed("flat tile lies outside its level"));
}
return tile
.tile_index
.1
.checked_mul(nx)
.and_then(|n| n.checked_add(tile.tile_index.0))
.and_then(|n| start.checked_add(n))
.map(Some)
.ok_or_else(|| malformed("block ordinal overflow"));
}
start = nx.checked_mul(ny).and_then(|n| start.checked_add(n)).ok_or_else(|| malformed("block count overflow"))?;
Ok(None)
};
match header.blocks {
exr::meta::BlockDescription::Tiles(tiles) => match tiles.level_mode {
LevelMode::Singular => {
if let Some(i) = visit(Vec2(0, 0), header.layer_size)? {
return Ok(i);
}
}
LevelMode::MipMap => {
for (level, size) in exr::meta::mip_map_levels(tiles.rounding_mode, header.layer_size) {
if let Some(i) = visit(Vec2(level, level), size)? {
return Ok(i);
}
}
}
LevelMode::RipMap => {
for (level, size) in exr::meta::rip_map_levels(tiles.rounding_mode, header.layer_size) {
if let Some(i) = visit(level, size)? {
return Ok(i);
}
}
}
},
exr::meta::BlockDescription::ScanLines => {
if let Some(i) = visit(Vec2(0, 0), header.layer_size)? {
return Ok(i);
}
}
}
Err(malformed("flat tile names a missing level"))
}
/// 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
/// deep headers, so here only the flat headers are validated, the offset tables (one `u64` per
/// chunk, a table per part in header order) are walked from the end of the headers, and only the
/// selected part's chunks are read. Each chunk must start past the last offset table and inside
/// the file, carry the selected part's number, and hold one of the part's blocks that no other
/// chunk of the part holds, so the part's chunks hold every one of its blocks. A scan-line
/// chunk's y must be the first line of its block, and no chunk may declare more bytes than the
/// file has left after it.
fn read_flat_part_chunks(bytes: &[u8], meta: &MetaData, index: usize, reader: &mut impl ChannelsReader, limits: &Limits) -> Result<()> {
let header = meta.headers.get(index).ok_or_else(|| malformed(format!("part {index}")))?;
let multipart = meta.requirements.is_multilayer();
let mut long_names = false;
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)?;
// 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);
if tracking_bytes as u64 > limits.max_bytes || tracking_bytes > isize::MAX as usize {
return Err(Error::LimitExceeded("block tracking exceeds the byte budget".into()));
}
let mut seen = Vec::new();
seen.try_reserve_exact(tracking_bytes).map_err(|_| Error::LimitExceeded("cannot allocate block tracking".into()))?;
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"))?;
// 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 };
let shape = if matches!(header.blocks, exr::meta::BlockDescription::Tiles(_)) {
let coordinates = TileCoordinates::read(&mut Cursor::new(&chunk[coordinate_at..])).map_err(map_exr)?;
CompressedBlock::Tile(CompressedTileBlock { coordinates, compressed_pixels_le: Vec::new() })
} else {
let y = chunk
.get(coordinate_at..coordinate_at + 4)
.and_then(|b| <[u8; 4]>::try_from(b).ok())
.ok_or_else(|| malformed("truncated scan-line coordinate"))?;
CompressedBlock::ScanLine(CompressedScanLineBlock { y_coordinate: i32::from_le_bytes(y), compressed_pixels_le: Vec::new() })
};
let tile = header.get_block_data_indices(&shape).map_err(map_exr)?;
if let CompressedBlock::ScanLine(block) = &shape {
// The block index is rounded toward zero, so a y that is not the first line of a
// block, or lies just above the data window, would still name a block.
let lines = header.compression.scan_lines_per_block() as i64;
let first = i64::from(header.own_attributes.layer_position.y()) + tile.tile_index.y() as i64 * lines;
if i64::from(block.y_coordinate) != first {
return Err(malformed(format!(
"the scan-line chunk at offset {offset} starts at y {}, which is not the first line of a block",
block.y_coordinate
)));
}
}
let ordinal = flat_block_ordinal(header, tile)?;
let flag = 1u8 << (ordinal % 8);
let byte = seen.get_mut(ordinal / 8).ok_or_else(|| malformed("block is outside its chunk table"))?;
if *byte & flag != 0 {
return Err(malformed("duplicate flat block"));
}
*byte |= flag;
if reader.filter_block(tile) {
let area = header.get_absolute_block_pixel_coordinates(tile).map_err(map_exr)?.size;
let raw_size = area
.0
.checked_mul(area.1)
.and_then(|n| n.checked_mul(header.channels.bytes_per_pixel))
.ok_or_else(|| Error::LimitExceeded("flat block byte size overflows".into()))?;
if raw_size as u64 > limits.max_bytes || raw_size > isize::MAX as usize {
return Err(Error::LimitExceeded("flat block exceeds the byte budget".into()));
}
// Packed size need not be less than raw size for every accepted compression.
// Bound its allocation independently, rather than rejecting valid compressed data
// solely because a clipped edge block has fewer raw bytes.
if size as u64 > limits.max_bytes || size > isize::MAX as usize {
return Err(Error::LimitExceeded("packed flat block exceeds the byte budget".into()));
}
let chunk = Chunk::read(&mut Cursor::new(chunk), meta).map_err(map_exr)?;
let block = UncompressedBlock::decompress_chunk(chunk, meta, false).map_err(map_exr)?;
reader.read_block(header, block).map_err(map_exr)?;
}
}
Ok(())
}
/// Decodes the channels of flat part `index` that `keep` accepts (by the name as stored), in
/// their stored type. A file with deep parts, or a kept channel that is subsampled, is
/// [`Error::Unsupported`].
/// their stored type. A deep part, or a kept channel that is subsampled, is
/// [`Error::Unsupported`]; the file's other parts may be deep.
pub fn decode_part(bytes: &[u8], index: usize, keep: &dyn Fn(&str) -> bool, limits: &Limits) -> Result<Part> {
let meta = read_meta(bytes, limits)?;
if meta.requirements.has_deep_data {
let header = meta.headers.get(index).ok_or_else(|| malformed(format!("part {index} of {}", meta.headers.len())))?;
if header.deep {
return Err(Error::Unsupported("deep data (use the deep reader)".into()));
}
let header = meta.headers.get(index).ok_or_else(|| malformed(format!("part {index} of {}", meta.headers.len())))?;
if matches!(header.compression, ExrCompression::HTJ2K32 | ExrCompression::HTJ2K256) {
return Err(Error::Unsupported("HTJ2K compression".into()));
}
let info = part_info(index, header);
let select = Select { index, keep, seen: std::cell::Cell::new(0) };
let image = ReadImage::new(ReadAllLayers { read_channels: select }, |_| {}).from_buffered(Cursor::new(bytes)).map_err(map_exr)?;
let planes = image.layer_data.into_iter().nth(index).map(|l| l.channel_data).ok_or_else(|| malformed("the part was not read"))?;
let planes = if meta.headers.iter().any(|header| header.deep) {
select.seen.set(index);
let mut reader = select.create_channels_reader(header).map_err(map_exr)?;
read_flat_part_chunks(bytes, &meta, index, &mut reader, limits)?;
reader.into_channels()
} else {
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"))?
};
let channels = info.channels.iter().zip(planes).filter_map(|(c, p)| Some(Channel { name: c.name.clone(), samples: p? })).collect();
Ok(Part { info, channels })
}
+473 -4
View File
@@ -1,4 +1,5 @@
//! The preview check is PhotoCraft's test; the rest builds files with the `exr` crate.
//! The preview check is PhotoCraft's test; the rest builds files with the `exr` crate, except the
//! files that mix flat and deep parts, which are built by hand.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use exr::meta::attribute::{Preview, Text};
@@ -129,10 +130,30 @@ fn decoded_display_part_places_selected_channels_and_checks_total_budget() {
let limits = Limits { max_bytes: 6 * 4 - 1, ..Limits::default() };
assert!(matches!(decode_display_part(&bytes, 0, &all, &|_| 0.0, &limits), Err(Error::LimitExceeded(_))));
// One selected display plane fits exactly, but the EXR decoder must decompress both data
// channels in its input block before discarding the ignored one.
// One selected display plane fits exactly. Both data channels together (2x2x2 f32, 32 bytes)
// don't, but they are decompressed one scan-line block (2 pixels x 2 channels) at a time.
let block_limits = Limits { max_bytes: 6 * 4, ..Limits::default() };
assert!(matches!(decode_display_part(&bytes, 0, &|name| name == "R", &|_| 0.0, &block_limits), Err(Error::LimitExceeded(_))));
let part = decode_display_part(&bytes, 0, &|name| name == "R", &|_| 9.0, &block_limits).unwrap();
assert_eq!(part.channels[0].samples, [0.0, 1.0, 9.0, 2.0, 3.0, 9.0]);
}
#[test]
fn decoded_display_part_bounds_each_all_channel_block() {
// The kept R plane is 4 pixels of f32 (16 bytes), but each scan-line block carries all four
// channels (64 bytes) before the ignored ones are discarded.
let bytes = file(vec![layer(None, 4, 1, &["R", "G", "B", "A"], false, exr::prelude::Compression::ZIP1)], (4, 1));
let r = |name: &str| name == "R";
assert!(matches!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &Limits { max_bytes: 16, ..Limits::default() }), Err(Error::LimitExceeded(_))));
assert_eq!(decode_display_part(&bytes, 0, &r, &|_| 0.0, &Limits { max_bytes: 64, ..Limits::default() }).unwrap().channels.len(), 1);
// ZIP groups 16 scan lines, but a one-row part's block is that row: still 64 bytes, not 1024
let zip16 = file(vec![layer(None, 4, 1, &["R", "G", "B", "A"], false, exr::prelude::Compression::ZIP16)], (4, 1));
assert!(matches!(decode_display_part(&zip16, 0, &r, &|_| 0.0, &Limits { max_bytes: 63, ..Limits::default() }), Err(Error::LimitExceeded(_))));
assert_eq!(decode_display_part(&zip16, 0, &r, &|_| 0.0, &Limits { max_bytes: 64, ..Limits::default() }).unwrap().channels.len(), 1);
// A tile is the block of a tiled part: a 4x4 tile of four f32 channels is 256 bytes, while
// the whole 8x8 part is 1024 and the kept R plane of the 2x2 display window only 16.
let tiled = file(vec![layer(None, 8, 8, &["R", "G", "B", "A"], true, exr::prelude::Compression::ZIP1)], (2, 2));
assert!(matches!(decode_display_part(&tiled, 0, &r, &|_| 0.0, &Limits { max_bytes: 255, ..Limits::default() }), Err(Error::LimitExceeded(_))));
assert_eq!(decode_display_part(&tiled, 0, &r, &|_| 0.0, &Limits { max_bytes: 256, ..Limits::default() }).unwrap().channels[0].samples.len(), 4);
}
#[test]
@@ -238,3 +259,451 @@ fn hostile_files_never_panic() {
}
assert!(parts(b"not exr", &limits).is_err());
}
// A multi-part file with a flat part and a deep scan-line part, built by hand per the OpenEXR file
// layout (the `exr` crate's writer refuses deep headers): version 2 with the deep and multi-part
// flags, the headers and an empty header, one offset table per part, then chunks that each start
// with their part number. Both parts are uncompressed, two chunks a part: the deep part and a
// scan-line flat part hold one scan line a chunk, and a tiled flat part one 2 × 2 tile a chunk.
fn mixed_attr(out: &mut Vec<u8>, name: &str, ty: &str, payload: &[u8]) {
out.extend_from_slice(name.as_bytes());
out.push(0);
out.extend_from_slice(ty.as_bytes());
out.push(0);
out.extend_from_slice(&(payload.len() as i32).to_le_bytes());
out.extend_from_slice(payload);
}
/// The version field and the headers of a mixed file whose flat part is `w × h` with float
/// `B`, `G`, `R` channels, in scan lines or (with `tiled`) in one level of 2 × 2 tiles, and whose
/// deep part is 3 × 2 with one float `A` channel. Both parts are uncompressed.
fn mixed_headers(deep_first: bool, tiled: bool, (w, h): (usize, usize)) -> Vec<u8> {
mixed_headers_with(deep_first, tiled, (w, h), 0, &["B", "G", "R"], 2)
}
/// [`mixed_headers`] with the flat part's compression code (0 for none, or 3 for ZIP, which
/// holds 16 scan lines a block), its float channels, and the width and height of its tiles.
fn mixed_headers_with(deep_first: bool, tiled: bool, (w, h): (usize, usize), compression: u8, flat_channels: &[&str], tile: u32) -> Vec<u8> {
mixed_headers_with_deep_size(deep_first, tiled, (w, h), compression, flat_channels, tile, (3, 2))
}
fn mixed_headers_with_deep_size(
deep_first: bool,
tiled: bool,
(w, h): (usize, usize),
compression: u8,
flat_channels: &[&str],
tile: u32,
deep_size: (usize, usize),
) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(&0x0131_2f76u32.to_le_bytes());
out.extend_from_slice(&(2u32 | 0x800 | 0x1000).to_le_bytes());
for deep in if deep_first { [true, false] } else { [false, true] } {
let (w, h, channels): (usize, usize, &[&str]) = if deep { (deep_size.0, deep_size.1, &["A"]) } else { (w, h, flat_channels) };
let mut chlist = Vec::new();
for name in channels {
chlist.extend_from_slice(name.as_bytes());
chlist.push(0);
chlist.extend_from_slice(&2i32.to_le_bytes()); // float
chlist.extend_from_slice(&[0u8; 4]); // pLinear and reserved
chlist.extend_from_slice(&1i32.to_le_bytes());
chlist.extend_from_slice(&1i32.to_le_bytes());
}
chlist.push(0);
let window: Vec<u8> = [0i32, 0, w as i32 - 1, h as i32 - 1].iter().flat_map(|v| v.to_le_bytes()).collect();
let tiled = tiled && !deep;
let compression = if deep { 0 } else { compression };
let lines = if compression == 3 { 16 } else { 1 };
let chunks = if tiled { w.div_ceil(tile as usize) * h.div_ceil(tile as usize) } else { h.div_ceil(lines) };
mixed_attr(&mut out, "channels", "chlist", &chlist);
mixed_attr(&mut out, "chunkCount", "int", &(chunks as i32).to_le_bytes());
mixed_attr(&mut out, "compression", "compression", &[compression]);
mixed_attr(&mut out, "dataWindow", "box2i", &window);
mixed_attr(&mut out, "displayWindow", "box2i", &window);
mixed_attr(&mut out, "lineOrder", "lineOrder", &[0]);
if deep {
mixed_attr(&mut out, "maxSamplesPerPixel", "int", &1i32.to_le_bytes());
}
mixed_attr(&mut out, "name", "string", if deep { b"deep" } else { b"flat" });
mixed_attr(&mut out, "pixelAspectRatio", "float", &1f32.to_le_bytes());
mixed_attr(&mut out, "screenWindowCenter", "v2f", &[0u8; 8]);
mixed_attr(&mut out, "screenWindowWidth", "float", &1f32.to_le_bytes());
if tiled {
// `tile` × `tile` tiles, one level, rounded down.
let mut desc: Vec<u8> = [tile, tile].iter().flat_map(|v| v.to_le_bytes()).collect();
desc.push(0);
mixed_attr(&mut out, "tiles", "tiledesc", &desc);
}
let ty: &[u8] = if deep {
b"deepscanline"
} else if tiled {
b"tiledimage"
} else {
b"scanlineimage"
};
mixed_attr(&mut out, "type", "string", ty);
if deep {
mixed_attr(&mut out, "version", "int", &1i32.to_le_bytes());
}
out.push(0); // end of this header
}
out.push(0); // end of the header list
out
}
/// Sample `i` of a flat channel: `R` is 1, 2, 3, …, `G` 10 more and `B` 100 more, top row first.
fn mixed_flat(channel: f32, i: usize) -> f32 {
channel + 1.0 + i as f32
}
/// A mixed file with a 3 × 2 flat part, and its chunk offsets as `offsets[part][chunk]`. The
/// tiled flat part's chunks hold the tiles at (0, 0) and (1, 0).
fn mixed_file(deep_first: bool, tiled: bool) -> (Vec<u8>, [[usize; 2]; 2]) {
let (w, h) = (3usize, 2usize);
let mut out = mixed_headers(deep_first, tiled, (w, h));
let chunks: Vec<Vec<Vec<u8>>> = (0..2i32)
.map(|part| {
let deep = (part == 0) == deep_first;
(0..h)
.map(|y| {
let mut c = Vec::new();
c.extend_from_slice(&part.to_le_bytes());
if tiled && !deep {
// Tile (y, 0) at level (0, 0): columns 2y and 2y + 1 that lie inside.
[y as i32, 0, 0, 0].iter().for_each(|v| c.extend_from_slice(&v.to_le_bytes()));
let xs = 2 * y..(2 * y + 2).min(w);
c.extend_from_slice(&((xs.len() * h * 3 * 4) as i32).to_le_bytes());
for row in 0..h {
for channel in [100.0, 10.0, 0.0] {
xs.clone().for_each(|x| c.extend_from_slice(&mixed_flat(channel, row * w + x).to_le_bytes()));
}
}
return c;
}
c.extend_from_slice(&(y as i32).to_le_bytes());
if deep {
// Packed count table, packed and unpacked sample data: one sample a pixel.
for size in [w * 4, w * 4, w * 4] {
c.extend_from_slice(&(size as u64).to_le_bytes());
}
(1..=w as u32).for_each(|n| c.extend_from_slice(&n.to_le_bytes()));
(0..w).for_each(|_| c.extend_from_slice(&0.5f32.to_le_bytes()));
} else {
c.extend_from_slice(&((w * 3 * 4) as i32).to_le_bytes());
for channel in [100.0, 10.0, 0.0] {
(0..w).for_each(|x| c.extend_from_slice(&mixed_flat(channel, y * w + x).to_le_bytes()));
}
}
c
})
.collect()
})
.collect();
let mut offsets = [[0usize; 2]; 2];
let mut at = out.len() + 2 * h * 8;
for (part, lines) in chunks.iter().enumerate() {
for (y, c) in lines.iter().enumerate() {
offsets[part][y] = at;
out.extend_from_slice(&(at as u64).to_le_bytes());
at += c.len();
}
}
chunks.into_iter().flatten().for_each(|c| out.extend_from_slice(&c));
(out, offsets)
}
#[test]
fn a_flat_part_beside_a_deep_part_decodes() {
let limits = Limits::default();
for (deep_first, tiled) in [(false, false), (true, false), (false, true), (true, true)] {
let (bytes, _) = mixed_file(deep_first, tiled);
let (flat, deep) = if deep_first { (1, 0) } else { (0, 1) };
let parts = parts(&bytes, &limits).unwrap();
assert_eq!((parts[flat].deep, parts[deep].deep, parts[flat].name.as_deref()), (false, true, Some("flat")));
let part = decode_part(&bytes, flat, &all, &limits).unwrap();
for (name, channel) in [("R", 0.0), ("G", 10.0), ("B", 100.0)] {
let expected: Vec<f32> = (0..6).map(|i| mixed_flat(channel, i)).collect();
assert_eq!(part.channel(name).unwrap().samples, Samples::F32(expected), "deep first {deep_first} tiled {tiled} {name}");
}
let only_g = decode_part(&bytes, flat, &|n| n == "G", &limits).unwrap();
assert_eq!(only_g.channels.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["G"]);
let display = decode_display_part(&bytes, flat, &|n| n == "flat.R", &|_| 9.0, &limits).unwrap();
assert_eq!(display.channels.len(), 1);
assert_eq!((display.channels[0].name.as_str(), display.channels[0].samples.as_slice()), ("flat.R", &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0][..]));
assert!(matches!(decode_part(&bytes, deep, &all, &limits), Err(Error::Unsupported(_))));
assert!(matches!(decode_display_part(&bytes, deep, &all, &|_| 0.0, &limits), Err(Error::Unsupported(_))));
assert!(matches!(decode_part(&bytes, 2, &all, &limits), Err(Error::Malformed(_))));
let deep_image = crate::deep::decode_deep(&bytes, &limits).unwrap();
assert_eq!((deep_image.width, deep_image.height), (3, 2));
}
}
#[test]
fn a_flat_part_s_chunks_beside_a_deep_part_are_checked_before_they_are_read() {
let limits = Limits::default();
for deep_first in [false, true] {
let (good, offsets) = mixed_file(deep_first, false);
let (flat, deep) = if deep_first { (1, 0) } else { (0, 1) };
let tables = mixed_headers(deep_first, false, (3, 2)).len();
let entry = tables + flat * 2 * 8;
let with_offset = |slot: usize, value: u64| {
let mut b = good.clone();
b[entry + slot * 8..entry + slot * 8 + 8].copy_from_slice(&value.to_le_bytes());
b
};
let refused = |b: &[u8]| {
for r in [decode_part(b, flat, &all, &limits).map(|_| ()), decode_display_part(b, flat, &all, &|_| 0.0, &limits).map(|_| ())] {
assert!(matches!(&r, Err(Error::Malformed(_))), "deep first {deep_first}: {r:?}");
}
};
// The deep part's chunk, the end of the file and past it, the offset tables, the same
// chunk twice.
refused(&with_offset(0, offsets[deep][0] as u64));
refused(&with_offset(0, good.len() as u64));
refused(&with_offset(0, u64::MAX));
refused(&with_offset(0, (tables + 8) as u64));
refused(&with_offset(1, offsets[flat][0] as u64));
// A chunk naming another part, and one declaring more bytes than a block holds.
let mut b = good.clone();
b[offsets[flat][1]..offsets[flat][1] + 4].copy_from_slice(&(deep as i32).to_le_bytes());
refused(&b);
let mut b = good.clone();
b[offsets[flat][0] + 8..offsets[flat][0] + 12].copy_from_slice(&i32::MAX.to_le_bytes());
refused(&b);
// Offset tables longer than the file.
refused(&good[..tables + 20]);
for n in 0..good.len() {
let _ = decode_part(&good[..n], flat, &all, &limits);
let _ = decode_display_part(&good[..n], flat, &all, &|_| 0.0, &limits);
}
for i in 0..good.len() {
for v in [0u8, 1, 0x7F, 0xFF] {
let mut b = good.clone();
b[i] = v;
if let Ok(p) = decode_part(&b, flat, &all, &limits) {
let n = p.info.data_window.width as usize * p.info.data_window.height as usize;
assert!(p.channels.iter().all(|c| c.samples.len() == n));
}
let _ = decode_display_part(&b, flat, &all, &|_| 0.0, &limits);
}
}
}
}
#[test]
fn a_tiled_flat_part_beside_a_deep_part_must_hold_each_of_its_tiles() {
let limits = Limits::default();
for deep_first in [false, true] {
let (good, offsets) = mixed_file(deep_first, true);
let flat = usize::from(deep_first);
// The second chunk names tile (0, 0) at level (1, 1), which a one-level part does not
// have, or tile (0, 0) again, so tile (1, 0) has no chunk.
for coordinates in [[0i32, 0, 1, 1], [0, 0, 0, 0]] {
let mut b = good.clone();
let at = offsets[flat][1] + 4;
coordinates.iter().enumerate().for_each(|(i, v)| b[at + i * 4..at + i * 4 + 4].copy_from_slice(&v.to_le_bytes()));
for r in [decode_part(&b, flat, &all, &limits).map(|_| ()), decode_display_part(&b, flat, &all, &|_| 0.0, &limits).map(|_| ())] {
assert!(matches!(&r, Err(Error::Malformed(_))), "deep first {deep_first} {coordinates:?}: {r:?}");
}
}
}
}
#[test]
fn a_scan_line_chunk_beside_a_deep_part_must_start_at_its_block_s_first_line() {
// A ZIP flat part (16 lines a block) holds its 3 × 2 pixels in one chunk, stored raw, as a
// block is when compressing it does not make it smaller; the deep part follows.
let limits = Limits::default();
let (w, h) = (3usize, 2usize);
let (plain, offsets) = mixed_file(false, false);
let deep = &plain[offsets[1][0]..];
let with_y = |y: i32| {
let mut out = mixed_headers_with(false, false, (w, h), 3, &["B", "G", "R"], 2);
let mut chunk = Vec::new();
chunk.extend_from_slice(&0i32.to_le_bytes());
chunk.extend_from_slice(&y.to_le_bytes());
chunk.extend_from_slice(&((w * h * 3 * 4) as i32).to_le_bytes());
for row in 0..h {
for channel in [100.0, 10.0, 0.0] {
(0..w).for_each(|x| chunk.extend_from_slice(&mixed_flat(channel, row * w + x).to_le_bytes()));
}
}
let flat_at = out.len() + 3 * 8;
let deep_at = flat_at + chunk.len();
for at in [flat_at, deep_at, deep_at + offsets[1][1] - offsets[1][0]] {
out.extend_from_slice(&(at as u64).to_le_bytes());
}
out.extend_from_slice(&chunk);
out.extend_from_slice(deep);
out
};
let part = decode_part(&with_y(0), 0, &all, &limits).unwrap();
assert_eq!(part.channel("R").unwrap().samples, Samples::F32((0..6).map(|i| mixed_flat(0.0, i)).collect()));
// Each of these y values rounds to block 0, but none is that block's first line.
for y in [-15, -1, 1, 15] {
let b = with_y(y);
for r in [decode_part(&b, 0, &all, &limits).map(|_| ()), decode_display_part(&b, 0, &all, &|_| 0.0, &limits).map(|_| ())] {
assert!(matches!(&r, Err(Error::Malformed(_))), "y {y}: {r:?}");
}
}
}
/// A mixed file whose flat part, first, is one pixel of these float channels (each 1.0) in one
/// `tile` × `tile` tile, held by a chunk that declares `size` payload bytes.
fn mixed_one_tile(channels: &[&str], tile: u32, size: i32) -> Vec<u8> {
let (plain, offsets) = mixed_file(false, false);
let mut out = mixed_headers_with(false, true, (1, 1), 0, channels, tile);
let mut chunk = Vec::new();
[0i32, 0, 0, 0, 0, size].iter().for_each(|v| chunk.extend_from_slice(&v.to_le_bytes()));
channels.iter().for_each(|_| chunk.extend_from_slice(&1f32.to_le_bytes()));
let flat_at = out.len() + 3 * 8;
let deep_at = flat_at + chunk.len();
for at in [flat_at, deep_at, deep_at + offsets[1][1] - offsets[1][0]] {
out.extend_from_slice(&(at as u64).to_le_bytes());
}
out.extend_from_slice(&chunk);
out.extend_from_slice(&plain[offsets[1][0]..]);
out
}
#[test]
fn a_chunk_beside_a_deep_part_must_fit_the_rest_of_the_file() {
// 2^14 × 2^14 tiles of three floats let a chunk hold up to 3 GiB (also on 32-bit), so the crate would
// allocate the 2 GiB this chunk declares before it found the file too short.
let limits = Limits::default();
let channels = ["B", "G", "R"];
let good = mixed_one_tile(&channels, 1 << 14, 12);
assert_eq!(decode_part(&good, 0, &all, &limits).unwrap().channel("R").unwrap().samples, Samples::F32(vec![1.0]));
let b = mixed_one_tile(&channels, 1 << 14, i32::MAX);
for r in [decode_part(&b, 0, &all, &limits).map(|_| ()), decode_display_part(&b, 0, &all, &|_| 0.0, &limits).map(|_| ())] {
assert!(matches!(&r, Err(Error::Malformed(m)) if m.contains("remain in the file")), "{r:?}");
}
}
#[test]
fn a_tile_too_large_to_address_is_refused_before_a_chunk_is_read() {
// Five float channels in 10^9 × 10^9 tiles: 20 bytes a pixel times 10^18 pixels does not fit
// in a 64-bit size, though the 1 × 1 part passes every size limit.
let limits = Limits::default();
let channels = ["A", "B", "C", "D", "E"];
let tile = 1_000_000_000u32;
let mixed = mixed_one_tile(&channels, tile, 20);
// A file of flat parts only, read by the crate's own reader, with its 4 × 4 tiles widened.
let mut flat_only = file(vec![layer(None, 1, 1, &channels, true, exr::prelude::Compression::Uncompressed)], (1, 1));
let at = flat_only.windows(9).position(|w| w == b"tiledesc\0").unwrap() + 9 + 4;
[tile, tile].iter().enumerate().for_each(|(i, v)| flat_only[at + i * 4..at + i * 4 + 4].copy_from_slice(&v.to_le_bytes()));
for (name, b) in [("mixed", &mixed), ("flat only", &flat_only)] {
let results = [
parts(b, &limits).map(|_| ()),
decode_part(b, 0, &all, &limits).map(|_| ()),
decode_display_part(b, 0, &all, &|_| 0.0, &limits).map(|_| ()),
];
for r in results {
assert!(matches!(&r, Err(Error::LimitExceeded(_))), "{name}: {r:?}");
}
}
}
#[test]
fn the_flat_parts_of_a_mixed_file_must_fit_the_file() {
// 1024 × 1024 × 3 float samples (12 MiB) declared in a file of a few hundred bytes: over a
// ratio of 1 plus the 1 MiB slack, though another part is deep.
let headers = mixed_headers(false, false, (1024, 1024));
assert!(parts(&headers, &Limits::default()).is_ok());
let tight = Limits { max_ratio: 1, ..Limits::default() };
for r in [parts(&headers, &tight).map(|_| ()), decode_part(&headers, 0, &all, &tight).map(|_| ())] {
assert!(matches!(&r, Err(Error::LimitExceeded(_))), "{r:?}");
}
// The deep part's samples are not counted, and a small flat part passes the same ratio.
assert!(parts(&mixed_file(false, false).0, &tight).is_ok());
}
#[test]
fn deep_samples_do_not_count_against_the_flat_expansion_ratio() {
// The 4 MiB deep plane would exceed max_ratio=1 plus the 1 MiB slack if counted.
// Header inspection does not allocate those samples; deep decoding bounds its own counts.
let headers = mixed_headers_with_deep_size(false, false, (1, 1), 0, &["R"], 2, (1024, 1024));
let limits = Limits { max_ratio: 1, max_bytes: 8 * 1024 * 1024, ..Limits::default() };
assert!(parts(&headers, &limits).is_ok());
}
#[test]
fn mixed_display_decode_bounds_each_block_not_the_whole_flat_part() {
for (tiled, block_bytes) in [(false, 36), (true, 48)] {
for deep_first in [false, true] {
let (bytes, _) = mixed_file(deep_first, tiled);
let flat = usize::from(deep_first);
let keep = |name: &str| name == "flat.R";
// The full flat part is 72 bytes; the selected plane is 24 bytes.
let limits = Limits { max_bytes: block_bytes, ..Limits::default() };
let part = decode_display_part(&bytes, flat, &keep, &|_| 0.0, &limits).unwrap();
assert_eq!(part.channels[0].samples, [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
let tight = Limits { max_bytes: block_bytes - 1, ..limits };
assert!(matches!(decode_display_part(&bytes, flat, &keep, &|_| 0.0, &tight), Err(Error::LimitExceeded(_))));
}
}
}
#[test]
fn present_packed_payload_is_bounded_before_allocation() {
let packed = 1024 * 1024;
let mut bytes = mixed_one_tile(&["R"], 1 << 15, packed);
// Make the declared payload present, not merely a truncated-file error. The nominal
// huge tile allows this size in exr::Chunk::read, but the actual flat image is 1x1.
bytes.resize(bytes.len() + packed as usize, 0);
let limits = Limits { max_bytes: 4, ..Limits::default() };
assert!(matches!(
decode_display_part(&bytes, 0, &|_| true, &|_| 0.0, &limits),
Err(Error::LimitExceeded(message)) if message.contains("packed flat block")
));
// decode_part also includes the deep header's 24 bytes in its aggregate header budget.
let limits = Limits { max_bytes: 32, ..limits };
assert!(matches!(decode_part(&bytes, 0, &all, &limits), Err(Error::LimitExceeded(message)) if message.contains("packed flat block")));
}
#[test]
fn cropped_mixed_display_bounds_block_tracking() {
let mut bytes = mixed_headers_with(false, true, (100, 100), 0, &["R"], 1);
// Both display windows are 1x1; the flat data window still has 10,000 one-pixel tiles.
let needle = b"displayWindow\0box2i\0";
let positions: Vec<usize> = bytes.windows(needle.len()).enumerate().filter_map(|(i, w)| (w == needle).then_some(i + needle.len() + 4)).collect();
for at in positions {
bytes[at..at + 16].fill(0);
}
// Supply all offset-table bytes so validation reaches bookkeeping, not truncation.
bytes.resize(bytes.len() + (10_000 + 2) * 8, 0);
let limits = Limits { max_bytes: 4, ..Limits::default() };
assert!(matches!(
decode_display_part(&bytes, 0, &|_| true, &|_| 0.0, &limits),
Err(Error::LimitExceeded(message)) if message.contains("block tracking")
));
}
#[test]
fn dense_block_ordinals_cover_scan_lines_and_all_tile_levels() {
use exr::block::chunk::TileCoordinates;
use exr::meta::attribute::LevelMode;
for tiled in [false, true] {
let bytes = file(vec![layer(None, 9, 7, &["R"], tiled, exr::prelude::Compression::ZIP1)], (9, 7));
let mut meta = read_meta(&bytes, &Limits::default()).unwrap();
let header = &mut meta.headers[0];
for mode in [LevelMode::Singular, LevelMode::MipMap, LevelMode::RipMap] {
if let exr::meta::BlockDescription::Tiles(tiles) = &mut header.blocks {
tiles.level_mode = mode;
}
for (i, block) in header.blocks_increasing_y_order().enumerate() {
assert_eq!(flat_block_ordinal(header, block.location).unwrap(), i);
}
let absent = TileCoordinates { tile_index: exr::math::Vec2(0, 0), level_index: exr::math::Vec2(100, 100) };
assert!(flat_block_ordinal(header, absent).is_err());
}
}
}
+22 -7
View File
@@ -391,19 +391,14 @@ fn decode_deep_meta(meta: &MetaData, bytes: &[u8], limits: &Limits) -> Result<De
let bytes_per_sample: usize = exr_types.iter().map(|t| sample_bytes(*t)).sum();
let multipart = meta.requirements.has_multiple_layers;
// The offset tables follow the headers: `chunk_count` u64 per header, in header order.
// Our part's table starts after the tables of all earlier parts.
let mut table_pos = header_end(bytes)?;
for h_ in meta.headers.iter().take(header_index) {
table_pos = table_pos.saturating_add((h_.chunk_count.min(1 << 24) as u64).saturating_mul(8));
}
// A chunk offset before the end of the last offset table points into table data.
let (table_pos, tables_end) = offset_tables(meta, bytes, header_index)?;
let mut cur = Cursor::new(bytes);
seek_to(&mut cur, table_pos)?;
let mut offsets = Vec::with_capacity(header.chunk_count.min(1 << 20));
for _ in 0..header.chunk_count {
offsets.push(u64(&mut cur)?);
}
let tables_end = cur.position();
// Block geometry.
let (tiles_x, tile_w, tile_h, slots) = match &header.blocks {
@@ -631,6 +626,26 @@ fn header_end(bytes: &[u8]) -> Result<u64> {
Ok(cur.position())
}
/// Where part `header_index`'s offset table starts and where the last part's table ends. The
/// tables follow the headers, `chunk_count` u64 per header in header order, and the chunks
/// follow the last table. Sizes that overflow, or tables that run past the end of the file,
/// are errors.
fn offset_tables(meta: &MetaData, bytes: &[u8], header_index: usize) -> Result<(u64, u64)> {
let mut table_pos = header_end(bytes)?;
let mut tables_end = table_pos;
for (i, h) in meta.headers.iter().enumerate() {
let len = u64::try_from(h.chunk_count).ok().and_then(|n| n.checked_mul(8));
tables_end = len.and_then(|len| tables_end.checked_add(len)).ok_or_else(|| err("the offset tables are too large"))?;
if i < header_index {
table_pos = tables_end;
}
}
if tables_end > bytes.len() as u64 {
return Err(err(format!("the offset tables end at byte {tables_end}, past the end of the file")));
}
Ok((table_pos, tables_end))
}
/// Composite the deep samples into a flat image: per pixel, samples sorted by Z (stable; the
/// file is assumed messy), front-to-back `over` with premultiplied colour, un-premultiplied
/// into straight alpha at the end. Without any alpha channel the front-most sample wins,
+100
View File
@@ -886,6 +886,106 @@ fn inconsistent_count_table_errors() {
assert!(matches!(decode_deep_exr(&bytes, &Limits::none()), Err(CodecError::Malformed(_))));
}
/// A two-part file made from the single-part deep file `deep` and a 1×1 flat scan-line part,
/// the deep part first when `deep_first`: each header gains `name` and `chunkCount`, the
/// version field the multipart bit, and each chunk its part number. The offset tables follow
/// the headers in header order, then the chunks. Returns the file, where the first table
/// starts, where the second table starts and where the last table ends.
fn two_part(deep: &[u8], deep_first: bool) -> (Vec<u8>, usize, usize, usize) {
let end = header_end_of(deep);
let first = u64::from_le_bytes(deep[end..end + 8].try_into().expect("8")) as usize;
let offsets: Vec<usize> =
(0..(first - end) / 8).map(|i| u64::from_le_bytes(deep[end + 8 * i..end + 8 * i + 8].try_into().expect("8")) as usize).collect();
let deep_chunks: Vec<&[u8]> = offsets.iter().enumerate().map(|(i, &o)| &deep[o..offsets.get(i + 1).copied().unwrap_or(deep.len())]).collect();
let mut deep_header = deep[8..end - 1].to_vec();
attr(&mut deep_header, "name", "string", b"deep");
attr(&mut deep_header, "chunkCount", "int", &(deep_chunks.len() as i32).to_le_bytes());
let mut flat_header = Vec::new();
let mut chlist = b"R\0".to_vec();
chlist.extend_from_slice(&1i32.to_le_bytes()); // half
chlist.extend_from_slice(&[0u8; 4]); // pLinear, reserved
chlist.extend_from_slice(&1i32.to_le_bytes());
chlist.extend_from_slice(&1i32.to_le_bytes());
chlist.push(0);
attr(&mut flat_header, "channels", "chlist", &chlist);
attr(&mut flat_header, "compression", "compression", &[0]);
let dw: Vec<u8> = [0i32; 4].iter().flat_map(|v| v.to_le_bytes()).collect();
attr(&mut flat_header, "dataWindow", "box2i", &dw);
attr(&mut flat_header, "displayWindow", "box2i", &dw);
attr(&mut flat_header, "lineOrder", "lineOrder", &[0]);
attr(&mut flat_header, "pixelAspectRatio", "float", &1f32.to_le_bytes());
attr(&mut flat_header, "screenWindowCenter", "v2f", &[0f32.to_le_bytes(), 0f32.to_le_bytes()].concat());
attr(&mut flat_header, "screenWindowWidth", "float", &1f32.to_le_bytes());
attr(&mut flat_header, "name", "string", b"flat");
attr(&mut flat_header, "type", "string", b"scanlineimage");
attr(&mut flat_header, "chunkCount", "int", &1i32.to_le_bytes());
// The flat part's one chunk: y, the data size, one half sample.
let mut flat_chunk = 0i32.to_le_bytes().to_vec();
flat_chunk.extend_from_slice(&2i32.to_le_bytes());
flat_chunk.extend_from_slice(&f16::from_f32(0.5).to_le_bytes());
let flat_chunks: Vec<&[u8]> = vec![&flat_chunk];
let parts: [(&[u8], &[&[u8]]); 2] = if deep_first {
[(&deep_header, &deep_chunks), (&flat_header, &flat_chunks)]
} else {
[(&flat_header, &flat_chunks), (&deep_header, &deep_chunks)]
};
let mut out = deep[..4].to_vec();
out.extend_from_slice(&(2u32 | 0x800 | 0x1000).to_le_bytes());
for (header, _) in &parts {
out.extend_from_slice(header);
out.push(0); // end of this header
}
out.push(0); // end of the headers
let first_table = out.len();
let second_table = first_table + parts[0].1.len() * 8;
let tables_end = second_table + parts[1].1.len() * 8;
let mut pos = tables_end;
for (_, chunks) in &parts {
for c in chunks.iter() {
out.extend_from_slice(&(pos as u64).to_le_bytes());
pos += 4 + c.len();
}
}
for (part, (_, chunks)) in parts.iter().enumerate() {
for c in chunks.iter() {
out.extend_from_slice(&(part as i32).to_le_bytes());
out.extend_from_slice(c);
}
}
(out, first_table, second_table, tables_end)
}
/// The deep part of a two-part file decodes as the single-part file does, first or second.
/// Its chunks start after every part's offset table: a chunk offset into the other part's
/// table, or one byte before the end of the last table, is refused as table data, and a file
/// that ends inside the last table is refused even when the deep part's own table is whole.
#[test]
fn multipart_deep_chunks_start_after_every_offset_table() {
let single = gen_deep(4, 4, &RGBAZ, 0, None, COUNTS_ONE, &sample_rgba);
let want = decode_deep_exr(&single, &Limits::none()).expect("single part");
for deep_first in [true, false] {
let (bytes, ..) = two_part(&single, deep_first);
let deep = decode_deep_exr(&bytes, &Limits::none()).expect("two parts");
assert_eq!(deep.counts, want.counts);
assert_eq!(deep.channel("Z").expect("Z").samples, want.channel("Z").expect("Z").samples);
}
let refused = |bytes: &[u8], what: &str| match decode_deep_exr(bytes, &Limits::none()) {
Err(e @ CodecError::Malformed(_)) => assert!(e.to_string().contains(what), "{e}"),
Err(e) => panic!("{e}, want an error about {what}"),
Ok(_) => panic!("decoded, want an error about {what}"),
};
let (bytes, first_table, second_table, tables_end) = two_part(&single, true);
for off in [second_table, tables_end - 1] {
let mut into_table = bytes.clone();
into_table[first_table..first_table + 8].copy_from_slice(&(off as u64).to_le_bytes());
refused(&into_table, "outside the chunk area");
}
refused(&bytes[..tables_end - 4], "past the end of the file");
}
/// `gen_deep` for a cropped render: the data window sits at `(dwx, dwy)` inside a larger
/// display window of `sw × sh` (the stage the renderer composed onto). Scanline chunk Y
/// coordinates are absolute display rows, so they carry the data-window offset.
+19 -1
View File
@@ -342,6 +342,20 @@ fn rich_inlines(doc: &Document, o: &InlineObject, f: &Fmt, opts: FlowOpts) -> Op
})
}
/// The freeform a `w` × `h` frame shape with border `corner` (see
/// [`craft_wordmodel::connector::frame_width`]) draws: its outline clockwise and its hole the
/// other way, so the hole stays empty under either fill rule.
fn frame_freeform(corner: Option<u32>, w: f32, h: f32) -> craft_wordmodel::freeform::Freeform {
use craft_wordmodel::freeform::{FreePath, Freeform};
let (w, h) = (craft_wordmodel::geom::finite(w).max(0.0), craft_wordmodel::geom::finite(h).max(0.0));
let t = craft_wordmodel::connector::frame_width(corner, w, h);
let mut paths = vec![FreePath { pts: vec![[0.0, 0.0], [w, 0.0], [w, h], [0.0, h]], closed: true }];
if w - 2.0 * t > 0.0 && h - 2.0 * t > 0.0 {
paths.push(FreePath { pts: vec![[t, t], [t, h - t], [w - t, h - t], [w - t, t]], closed: true });
}
Freeform { w, h, paths, ..Default::default() }
}
/// Comment `c` (a reply to `parent`) of `doc` as a flow comment: its text holds no comments or
/// notes of its own.
/// The flow inline for picture, shape or group `o` of `doc` (a member of groups `depth` deep),
@@ -358,8 +372,12 @@ fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize
{
// A connector stays one in formats that glue them (ODT, with boxes); elsewhere it is a
// straight line.
// A frame (a border with a hole), which the other formats have no shape for, is the
// freeform it draws: its outline and, wound the other way, its hole.
let frame = (*kind == ShapeKind::Frame).then(|| std::sync::Arc::new(frame_freeform(extra.corner, *w, *h)));
let kind = match kind {
ShapeKind::StraightConnector | ShapeKind::ElbowConnector | ShapeKind::CurvedConnector if !opts.boxes => ShapeKind::Line,
ShapeKind::Frame => ShapeKind::Freeform,
k => *k,
};
let inner = FlowOpts { notes: false, comments: false, boxes: false, ..opts };
@@ -383,7 +401,7 @@ fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize
Box::new(crate::Chain { name: format!("Frame{id}"), next })
}),
};
let path = freeform.clone().filter(|_| kind == ShapeKind::Freeform);
let path = frame.or_else(|| freeform.clone()).filter(|_| kind == ShapeKind::Freeform);
Some(Inline::Shape { kind, w: w * sx, h: h * sy, float: kept_float(float), blocks, look, path })
}
InlineObject::Image { media, w, h, alt, float, ole, crop, .. } => {
+2 -1
View File
@@ -841,7 +841,8 @@ impl<'a> Builder<'a> {
tb.props.style = None;
}
if t.widths.len() == cols && t.widths.iter().all(|w| w.is_finite() && *w > 1.0) {
tb.grid = t.widths.iter().map(|w| w.clamp(6.0, 1584.0)).collect();
// Narrow columns stay as they are: raising them would widen the table past its source.
tb.grid = t.widths.iter().map(|w| w.min(1584.0)).collect();
}
tb.rows.clear();
if let Some(x) = &t.extra {
+3
View File
@@ -15,9 +15,12 @@ default = ["system"]
system = ["dep:fontique"]
[dependencies]
harfrust = "0.13"
kurbo = { workspace = true }
skrifa = { version = "0.47", default-features = false, features = ["std"] }
thiserror = { workspace = true }
unicode-bidi = "0.3.18"
unicode-segmentation = "1.13"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
fontique = { version = "0.11.1", default-features = false, features = ["system", "fontconfig-dlopen"], optional = true }
+89
View File
@@ -0,0 +1,89 @@
//! Shared ownership of a font file and a face within it.
use std::sync::Arc;
/// Font file bytes and the index of a face in that file.
///
/// Clones share owned bytes, so collection faces and variable instances do not copy the file.
/// Static bytes let applications use embedded fonts without allocating a copy.
#[derive(Clone, Debug)]
pub struct FaceData {
bytes: Bytes,
index: u32,
}
#[derive(Clone, Debug)]
enum Bytes {
Static(&'static [u8]),
Owned(Arc<Vec<u8>>),
Shared(Arc<[u8]>),
}
impl FaceData {
/// A face in statically embedded font bytes.
pub fn from_static(bytes: &'static [u8], index: u32) -> Self {
Self { bytes: Bytes::Static(bytes), index }
}
/// A face in a shared vector, without copying its allocation.
pub fn from_owned(bytes: Arc<Vec<u8>>, index: u32) -> Self {
Self { bytes: Bytes::Owned(bytes), index }
}
/// A face in bytes shared by a catalog.
pub fn from_shared(bytes: Arc<[u8]>, index: u32) -> Self {
Self { bytes: Bytes::Shared(bytes), index }
}
/// The entire font file.
pub fn bytes(&self) -> &[u8] {
match &self.bytes {
Bytes::Static(bytes) => bytes,
Bytes::Owned(bytes) => bytes.as_slice(),
Bytes::Shared(bytes) => bytes,
}
}
/// The index of this face in the file.
pub fn index(&self) -> u32 {
self.index
}
/// Parse this face for font metadata and outlines.
pub fn skrifa(&self) -> Option<skrifa::FontRef<'_>> {
skrifa::FontRef::from_index(self.bytes(), self.index).ok()
}
/// Parse this face for shaping.
pub fn harfrust(&self) -> Option<harfrust::FontRef<'_>> {
harfrust::FontRef::from_index(self.bytes(), self.index).ok()
}
}
impl From<crate::FontData> for FaceData {
fn from(data: crate::FontData) -> Self {
Self::from_shared(data.bytes, data.index)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sources_keep_bytes_and_face_index_without_copying() {
static DATA: &[u8] = b"not a font";
let owned = Arc::new(DATA.to_vec());
let shared: Arc<[u8]> = Arc::from(DATA);
for data in [FaceData::from_static(DATA, 2), FaceData::from_owned(owned.clone(), 2), FaceData::from_shared(shared.clone(), 2)] {
let clone = data.clone();
assert_eq!(clone.bytes(), DATA);
assert_eq!(clone.bytes().as_ptr(), data.bytes().as_ptr());
assert_eq!(clone.index(), 2);
assert!(clone.skrifa().is_none());
assert!(clone.harfrust().is_none());
}
assert_eq!(Arc::strong_count(&owned), 1);
assert_eq!(Arc::strong_count(&shared), 1);
}
}
+62
View File
@@ -0,0 +1,62 @@
//! Face choice for a grapheme cluster.
/// Characters requiring their own glyph, after numeral or other caller-supplied mapping.
/// Controls, joiners and variation selectors affect shaping but do not need a separate glyph.
pub fn drawable_characters<'a>(cluster: &'a str, map: impl Fn(char) -> char + Copy + 'a) -> impl Iterator<Item = char> + 'a {
cluster
.chars()
.map(map)
.filter(|&c| !(c.is_control() || matches!(c, '\u{200C}' | '\u{200D}' | '\u{2028}' | '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}')))
}
/// Select one face for a cluster: prefer the primary if it covers every drawable character;
/// otherwise try each character's fallback until a face covers the whole cluster. If none does,
/// use the first character's fallback when the primary lacks it, or keep the primary.
/// The caller controls the font catalog, ordering and style matching.
pub fn cluster_face<F: Clone>(
cluster: &str,
primary: &F,
map: impl Fn(char) -> char + Copy,
primary_covers: impl Fn(char) -> bool,
mut fallback: impl FnMut(char) -> Option<F>,
covers: impl Fn(&F, char) -> bool,
) -> F {
let characters = || drawable_characters(cluster, map);
if characters().all(&primary_covers) {
return primary.clone();
}
for c in characters() {
if let Some(face) = fallback(c)
&& characters().all(|ch| covers(&face, ch))
{
return face;
}
}
if let Some(c) = characters().next()
&& !primary_covers(c)
&& let Some(face) = fallback(c)
{
return face;
}
primary.clone()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn chooses_one_face_for_a_base_and_mark() {
let fallback = |c| match c {
'a' => Some(1),
'\u{301}' => Some(2),
_ => None,
};
let covers = |face: &u8, c| *face == 2 || (*face == 1 && c == 'a');
assert_eq!(cluster_face("a\u{301}\u{200d}", &0, |c| c, |_| false, fallback, covers), 2);
assert_eq!(drawable_characters("a\u{200d}\u{fe0f}", |c| c).collect::<String>(), "a");
}
#[test]
fn uses_first_character_fallback_when_no_face_covers_cluster() {
assert_eq!(cluster_face("ab", &0, |c| c, |_| false, |c| if c == 'a' { Some(1) } else { Some(2) }, |face, c| (*face, c) == (1, 'a')), 1);
}
}
+16
View File
@@ -23,21 +23,37 @@
mod catalog;
mod embedding;
mod env;
mod face_data;
mod fallback;
mod fontconfig;
mod ligature;
mod line_break;
mod outline;
mod plan_cache;
mod registry;
mod scan;
mod segments;
/// Bounded SFNT face metadata discovery over caller-provided random-access readers.
pub mod sfnt;
mod shape;
mod suitcase;
pub mod system;
mod visual_order;
pub use catalog::{Catalog, FontData, FontFileError, Limits, Lister, LoadedFace, Match, Watch};
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 ligature::ligature_caret_stops;
pub use line_break::settle_line_break;
pub use outline::{FontOutline, GlyphPen, OutlineError};
pub use plan_cache::ShapePlanCache;
pub use scan::{FaceInfo, LocalizedName, Source, is_font_file, style_italic, style_weight, style_width};
pub use segments::SegmentBoundary;
pub use shape::{RunGlyph, RunInput, ShapeRunError, shape_run};
pub use visual_order::{VisualGlyph, visual_order};
#[cfg(test)]
mod tests;
+33
View File
@@ -0,0 +1,33 @@
//! Map ligature caret fractions to grapheme boundaries.
use unicode_segmentation::UnicodeSegmentation;
/// Return logical source-byte caret stops inside a shaped cluster. `font_carets` receives the
/// number of stops and may return their normalized positions along the glyph's logical width.
/// Missing or incorrectly sized font data falls back to equal divisions of the width.
pub fn ligature_caret_stops(text: &str, byte: usize, len: usize, font_carets: impl FnOnce(usize) -> Option<Vec<f64>>) -> Vec<(usize, f64)> {
let Some(s) = byte.checked_add(len).and_then(|end| text.get(byte..end)).filter(|_| len > 1) else { return Vec::new() };
let starts: Vec<usize> = s.grapheme_indices(true).skip(1).map(|(i, _)| byte + i).collect();
if starts.is_empty() {
return Vec::new();
}
let parts = starts.len() + 1;
let mut at =
font_carets(starts.len()).filter(|c| c.len() == starts.len()).unwrap_or_else(|| (1..parts).map(|j| j as f64 / parts as f64).collect());
at.sort_by(f64::total_cmp);
starts.into_iter().zip(at).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn maps_graphemes_and_sorts_font_positions() {
assert_eq!(ligature_caret_stops("ábc", 0, 5, |_| Some(vec![0.8, 0.3])), vec![(3, 0.3), (4, 0.8)]);
}
#[test]
fn falls_back_and_rejects_invalid_ranges() {
assert_eq!(ligature_caret_stops("abc", 0, 3, |_| Some(vec![0.5])), vec![(1, 1.0 / 3.0), (2, 2.0 / 3.0)]);
assert!(ligature_caret_stops("abc", usize::MAX, 2, |_| None).is_empty());
assert!(ligature_caret_stops("é", 1, 1, |_| None).is_empty());
}
}
+49
View File
@@ -0,0 +1,49 @@
//! Choose a line break after measuring candidate lines as drawn.
/// Choose the latest candidate that fits when a tab changes the line's drawn width.
///
/// `breaks` must be sorted by glyph index and the boolean marks hyphenated breaks.
/// `checks` limits the candidates measured individually from the end; older non-hyphenated
/// candidates are bisected, assuming their drawn widths are nondecreasing. If none fits,
/// the earliest eligible break is returned. Without a tab or a measurement callback the
/// original `chosen` break is returned.
pub fn settle_line_break(
tabbed: bool,
checks: usize,
start: usize,
chosen: (usize, bool),
breaks: &[(usize, bool)],
fits: Option<&dyn Fn(usize, bool) -> bool>,
) -> (usize, bool) {
let Some(fits) = fits.filter(|_| tabbed) else { return chosen };
if fits(chosen.0, chosen.1) {
return chosen;
}
let earlier = breaks.get(breaks.partition_point(|b| b.0 <= start)..breaks.partition_point(|b| b.0 < chosen.0)).unwrap_or_default();
if let Some(&b) = earlier.iter().rev().take(checks).find(|b| fits(b.0, b.1)) {
return b;
}
let rest = earlier.get(..earlier.len().saturating_sub(checks)).unwrap_or_default();
let plain: Vec<&(usize, bool)> = rest.iter().filter(|b| !b.1).collect();
let fitting = plain.partition_point(|b| fits(b.0, b.1));
fitting.checked_sub(1).and_then(|k| plain.get(k).copied()).or(earlier.first()).copied().unwrap_or(chosen)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn measures_latest_candidates_and_preserves_hyphenation() {
let breaks = [(1, false), (2, false), (3, true), (4, false)];
let fits = |i, hyphen| i <= 2 || (i == 3 && hyphen);
assert_eq!(settle_line_break(true, 2, 0, (4, false), &breaks, Some(&fits)), (3, true));
assert_eq!(settle_line_break(false, 2, 0, (4, false), &breaks, Some(&fits)), (4, false));
}
#[test]
fn bisects_older_plain_breaks_and_falls_back_to_first_eligible() {
let breaks = [(1, false), (2, true), (3, false), (4, false), (5, false)];
assert_eq!(settle_line_break(true, 1, 0, (5, false), &breaks, Some(&|i, _| i <= 3)), (3, false));
assert_eq!(settle_line_break(true, 1, 1, (5, false), &breaks, Some(&|_, _| false)), (2, true));
assert_eq!(settle_line_break(true, 1, 5, (5, false), &breaks, Some(&|_, _| false)), (5, false));
}
}
+52
View File
@@ -0,0 +1,52 @@
//! Per-face bounded shaping plan reuse.
use std::sync::{Arc, Mutex};
/// A cache for one font face and variation instance. Do not share it across faces or instances.
/// Plans are created outside the lock, then checked again to avoid retaining duplicates.
#[derive(Default)]
pub struct ShapePlanCache {
plans: Mutex<Vec<Arc<harfrust::ShapePlan>>>,
}
impl ShapePlanCache {
/// Maximum number of plans retained; the oldest is evicted when this is reached.
pub const CAPACITY: usize = 32;
/// Returns a matching plan or builds and retains one for this face.
pub fn get_or_create(
&self,
shaper: &harfrust::Shaper<'_>,
instance: Option<&harfrust::ShaperInstance>,
direction: harfrust::Direction,
script: Option<harfrust::Script>,
language: Option<&harfrust::Language>,
features: &[harfrust::Feature],
) -> Arc<harfrust::ShapePlan> {
let key = harfrust::ShapePlanKey::new(script, direction).language(language).instance(instance).features(features);
let kept = |plans: &[Arc<harfrust::ShapePlan>]| plans.iter().rev().find(|p| key.matches(p)).cloned();
if let Some(plan) = kept(&self.plans.lock().unwrap_or_else(|e| e.into_inner())) {
return plan;
}
let plan = Arc::new(harfrust::ShapePlan::new(shaper, direction, script, language, features));
let mut plans = self.plans.lock().unwrap_or_else(|e| e.into_inner());
if let Some(made) = kept(&plans) {
return made;
}
if plans.len() >= Self::CAPACITY {
plans.remove(0);
}
plans.push(plan.clone());
plan
}
/// Number of retained plans.
pub fn len(&self) -> usize {
self.plans.lock().unwrap_or_else(|e| e.into_inner()).len()
}
/// Whether this cache contains no plans.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
+55
View File
@@ -0,0 +1,55 @@
//! Boundaries between runs that need separate shaping.
/// Tracks the properties of the current shaping segment while walking grapheme clusters.
/// The caller resolves font faces, bidi levels and script classification; marks stay with the
/// preceding segment even when their face, level or case differs.
pub struct SegmentBoundary<F, L, S> {
face: F,
level: L,
small_caps: bool,
strong_script: Option<S>,
}
impl<F: Copy + Eq, L: Copy + Eq, S: Copy + Eq> SegmentBoundary<F, L, S> {
/// Begin at the first segment's face and bidi level.
pub fn new(face: F, level: L) -> Self {
Self { face, level, small_caps: false, strong_script: None }
}
/// Observe a cluster and return whether it begins a new shaping segment. Pass `None` for
/// common or inherited script and `true` for marks, joiners and variation selectors.
pub fn advance(&mut self, face: F, level: L, small_caps: bool, strong_script: Option<S>, mark: bool) -> bool {
let script_change = matches!((self.strong_script, strong_script), (Some(a), Some(b)) if a != b);
let split = (self.face != face || self.level != level || self.small_caps != small_caps || script_change) && !mark;
if split {
self.face = face;
self.level = level;
self.small_caps = small_caps;
}
if let Some(script) = strong_script {
self.strong_script = Some(script);
}
split
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn preserves_marks_and_splits_on_face_direction_case_and_script() {
let mut state = SegmentBoundary::<u8, u8, u8>::new(1, 0);
assert!(!state.advance(1, 0, false, Some(1), false));
assert!(!state.advance(2, 1, true, None, true));
assert!(state.advance(2, 1, true, Some(2), false));
assert!(!state.advance(2, 1, true, None, false));
assert!(state.advance(2, 1, true, Some(1), false));
}
#[test]
fn strong_script_on_a_mark_updates_the_following_boundary() {
let mut state = SegmentBoundary::<u8, u8, u8>::new(1, 0);
assert!(!state.advance(1, 0, false, Some(1), false));
assert!(!state.advance(1, 0, false, Some(2), true));
assert!(!state.advance(1, 0, false, Some(2), false));
}
}
+181
View File
@@ -0,0 +1,181 @@
//! Shape a run with its source clusters and surrounding text context.
use std::sync::Arc;
use harfrust::{BufferClusterLevel, Direction, Feature, Language, Script, ShapeOptions, ShapePlan, Shaper, UnicodeBuffer};
/// Parameters for a single directional run. Text is in logical order and `source_start` is its
/// byte offset in the complete source. Context influences joining but emits no glyphs.
pub struct RunInput<'a> {
/// Text in this run.
pub text: &'a str,
/// Its byte offset in the complete source.
pub source_start: usize,
/// Text before the run, within the same shaping context.
pub pre_context: &'a str,
/// Text after the run, within the same shaping context.
pub post_context: &'a str,
/// Direction of shaping.
pub direction: Direction,
/// Language used for language-specific forms.
pub language: Option<&'a Language>,
/// OpenType features with ranges in source byte coordinates.
pub features: &'a [Feature],
/// Use character-level instead of monotone grapheme clusters.
pub character_clusters: bool,
/// Uppercase each mapped character without losing its source cluster.
pub uppercase: bool,
}
/// A glyph in design units, with its source-byte cluster and directional advances and offsets.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RunGlyph {
pub glyph_id: u32,
pub cluster: u32,
pub x_advance: i32,
pub y_advance: i32,
pub x_offset: i32,
pub y_offset: i32,
}
/// A run's source offsets cannot fit HarfRust's 32-bit clusters.
#[derive(Debug, thiserror::Error)]
#[error("shaping cluster exceeds the 32-bit source offset range")]
pub struct ShapeRunError;
/// Shape a run using a caller's face-specific plan cache. `map_character` applies digit or other
/// character mapping before case conversion; expansions retain the original byte cluster.
/// The plan callback receives the guessed script, direction, language and feature set so it can
/// reuse plans for the particular shaper and its variable-font instance.
pub fn shape_run(
shaper: &Shaper<'_>,
input: &RunInput<'_>,
mut map_character: impl FnMut(char) -> char,
plan: impl FnOnce(&Shaper<'_>, Direction, Option<Script>, Option<&Language>, &[Feature]) -> Arc<ShapePlan>,
) -> Result<Vec<RunGlyph>, ShapeRunError> {
let mut buffer = UnicodeBuffer::new();
for (offset, character) in input.text.char_indices() {
let cluster = input.source_start.checked_add(offset).and_then(|n| u32::try_from(n).ok()).ok_or(ShapeRunError)?;
let character = map_character(character);
if input.uppercase {
for upper in character.to_uppercase() {
buffer.add(upper, cluster);
}
} else {
buffer.add(character, cluster);
}
}
buffer.set_direction(input.direction);
buffer.guess_segment_properties();
if input.character_clusters {
buffer.set_cluster_level(BufferClusterLevel::Characters);
}
if let Some(language) = input.language {
buffer.set_language(language.clone());
}
buffer.set_pre_context(input.pre_context);
buffer.set_post_context(input.post_context);
let script = Some(buffer.script()).filter(|s| *s != harfrust::script::UNKNOWN);
let plan = plan(shaper, buffer.direction(), script, input.language, input.features);
let glyphs = shaper.shape(buffer, ShapeOptions::new().features(input.features).plan(Some(&plan)));
Ok(glyphs
.glyph_infos()
.iter()
.zip(glyphs.glyph_positions())
.map(|(info, pos)| RunGlyph {
glyph_id: info.glyph_id,
cluster: info.cluster,
x_advance: pos.x_advance,
y_advance: pos.y_advance,
x_offset: pos.x_offset,
y_offset: pos.y_offset,
})
.collect())
}
#[cfg(test)]
mod tests {
use super::*;
use harfrust::{FontRef, ShaperData};
#[test]
fn synthetic_face_runs_without_installed_fonts() {
// A tiny face with a single .notdef glyph. The shaper still processes source
// clusters, direction, mapping, features and context without external font files.
let mut builder = write_fonts::FontBuilder::new();
let mut head = vec![0; 54];
head[18..20].copy_from_slice(&1000u16.to_be_bytes());
let mut hhea = vec![0; 36];
hhea[34..36].copy_from_slice(&1u16.to_be_bytes());
for (tag, bytes) in [(b"head", head), (b"hhea", hhea), (b"hmtx", vec![0, 100, 0, 0]), (b"maxp", vec![0, 0, 0x50, 0, 0, 1])] {
builder.add_raw(write_fonts::types::Tag::new(tag), bytes);
}
check_run(&builder.build());
}
#[test]
fn run_matches_direct_shaping_with_source_clusters_and_context() {
let Ok(dir) = std::env::var("CRAFT_FONTS_DIR") else { return };
let bytes = std::fs::read(std::path::Path::new(&dir).join("fonts/noto-sans-arabic/NotoSansArabic.ttf")).unwrap();
check_run(&bytes);
}
fn check_run(bytes: &[u8]) {
let font = FontRef::from_index(bytes, 0).unwrap();
let data = ShaperData::new(&font);
let shaper = data.shaper(&font).build();
let overflow = RunInput {
text: "ab",
source_start: usize::MAX,
pre_context: "",
post_context: "",
direction: Direction::LeftToRight,
language: None,
features: &[],
character_clusters: false,
uppercase: false,
};
assert!(shape_run(&shaper, &overflow, |c| c, |s, d, script, lang, f| Arc::new(ShapePlan::new(s, d, script, lang, f))).is_err());
let language: Language = "ar".parse().unwrap();
let features = [Feature::new(harfrust::Tag::new(b"kern"), 0, 19..25)];
for direction in [Direction::LeftToRight, Direction::RightToLeft, Direction::TopToBottom] {
let input = RunInput {
text: "بaß1",
source_start: 19,
pre_context: "س",
post_context: "م",
direction,
language: Some(&language),
features: &features,
character_clusters: true,
uppercase: true,
};
let map = |c| if c == '1' { '٢' } else { c };
let actual =
shape_run(&shaper, &input, map, |s, d, script, lang, features| Arc::new(ShapePlan::new(s, d, script, lang, features))).unwrap();
let mut buffer = UnicodeBuffer::new();
for (i, c) in input.text.char_indices() {
for upper in map(c).to_uppercase() {
buffer.add(upper, 19 + i as u32);
}
}
buffer.set_direction(direction);
buffer.guess_segment_properties();
buffer.set_cluster_level(BufferClusterLevel::Characters);
buffer.set_language(language.clone());
buffer.set_pre_context(input.pre_context);
buffer.set_post_context(input.post_context);
let script = Some(buffer.script()).filter(|s| *s != harfrust::script::UNKNOWN);
let plan = ShapePlan::new(&shaper, direction, script, Some(&language), &features);
let expected = shaper.shape(buffer, ShapeOptions::new().features(&features).plan(Some(&plan)));
let tuples: Vec<_> = expected
.glyph_infos()
.iter()
.zip(expected.glyph_positions())
.map(|(i, p)| (i.glyph_id, i.cluster, p.x_advance, p.y_advance, p.x_offset, p.y_offset))
.collect();
assert_eq!(actual.iter().map(|g| (g.glyph_id, g.cluster, g.x_advance, g.y_advance, g.x_offset, g.y_offset)).collect::<Vec<_>>(), tuples);
assert!(!actual.is_empty());
}
}
}
+19
View File
@@ -569,6 +569,25 @@ fn a_read_is_capped_where_the_file_has_grown() {
let _ = std::fs::remove_file(&path);
}
#[test]
fn shape_plan_cache_reuses_and_evicts_plans() {
let data = font(&spec("Test", "Regular", 400));
let face = harfrust::FontRef::from_index(&data, 0).unwrap();
let shaper_data = harfrust::ShaperData::new(&face);
let shaper = shaper_data.shaper(&face).build();
let cache = ShapePlanCache::default();
let make = |language: &harfrust::Language| cache.get_or_create(&shaper, None, harfrust::Direction::LeftToRight, None, Some(language), &[]);
let languages: Vec<harfrust::Language> = ('a'..='z').flat_map(|a| ['a', 'b'].map(move |b| format!("{a}{b}").parse().unwrap())).collect();
let first = make(&languages[0]);
assert!(Arc::ptr_eq(&first, &make(&languages[0])));
for language in languages.iter().skip(1) {
make(language);
}
assert_eq!(cache.len(), ShapePlanCache::CAPACITY);
assert!(!Arc::ptr_eq(&first, &make(&languages[0])));
assert_eq!(cache.len(), ShapePlanCache::CAPACITY);
}
#[test]
fn bounded_sfnt_reader_preserves_face_names_and_collection_indices() {
let mut bold = spec("Example", "Bold Italic", 700);
+69
View File
@@ -0,0 +1,69 @@
//! Visual ordering of shaped clusters after line bidi levels are resolved.
use std::ops::Range;
use unicode_bidi::{BidiInfo, Level};
/// A glyph's source byte, source length and original resolved level.
/// Zero-length glyphs represent list markers.
#[derive(Clone, Copy)]
pub struct VisualGlyph {
/// Byte offset in the original text.
pub byte: usize,
/// Source length in bytes, or zero for a list marker.
pub len: usize,
/// Original level, also used when the line levels lack this byte.
pub level: Level,
}
/// Order glyph indices by cluster using caller-resolved line levels (UAX #9 L1–L2).
/// `levels` is indexed relative to `paragraph_start`. Adjacent marker glyphs at the
/// same byte form their own cluster and reverse internally at a right-to-left level.
pub fn visual_order(glyphs: impl IntoIterator<Item = VisualGlyph>, paragraph_start: usize, levels: &[Level]) -> Vec<usize> {
let mut clusters: Vec<(Range<usize>, VisualGlyph)> = Vec::new();
for (i, glyph) in glyphs.into_iter().enumerate() {
if let Some((range, _)) = clusters.last_mut().filter(|(_, prev)| prev.byte == glyph.byte && (prev.len == 0) == (glyph.len == 0)) {
range.end = i + 1;
} else {
clusters.push((i..i + 1, glyph));
}
}
let cluster_levels: Vec<_> = clusters
.iter()
.map(|(_, g)| if g.len == 0 { g.level } else { levels.get(g.byte.saturating_sub(paragraph_start)).copied().unwrap_or(g.level) })
.collect();
BidiInfo::reorder_visual(&cluster_levels)
.into_iter()
.filter_map(|i| clusters.get(i))
.flat_map(|(range, glyph)| {
let mut indices: Vec<_> = range.clone().collect();
if glyph.len == 0 && glyph.level.is_rtl() {
indices.reverse();
}
indices
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clusters_and_markers_keep_their_distinct_order() {
let l = Level::ltr();
let r = Level::rtl();
let glyphs = [
VisualGlyph { byte: 5, len: 0, level: r },
VisualGlyph { byte: 5, len: 0, level: r },
VisualGlyph { byte: 5, len: 2, level: r },
VisualGlyph { byte: 5, len: 2, level: r },
VisualGlyph { byte: 7, len: 1, level: l },
];
assert_eq!(visual_order(glyphs, 5, &[r, r, l]), vec![2, 3, 1, 0, 4]);
assert!(visual_order([], 0, &[]).is_empty());
}
#[test]
fn missing_levels_fall_back_to_glyph_level() {
let r = Level::rtl();
let glyphs = [VisualGlyph { byte: 2, len: 1, level: r }, VisualGlyph { byte: 3, len: 1, level: r }];
assert_eq!(visual_order(glyphs, 0, &[]), vec![1, 0]);
}
}
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "craft-format"
description = "Versioned JSON file formats: the format tag, the registry of versions (hand-written steps, then one folder of changes per version, then the pending changes), the upgrade of an older file and the telling of a newer one"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
[lints]
workspace = true
[dependencies]
serde_json = { workspace = true }
# The container: content-addressed blobs (SHA-256) in a ZIP package.
sha2 = { version = "0.10", default-features = false, features = ["std"] }
craft-zip = { workspace = true }
[dev-dependencies]
proptest = { workspace = true }
+237
View File
@@ -0,0 +1,237 @@
//! For a build script: the generated lists of a family's changes. Each change is one `.rs` file in
//! the family's folder, in `v<N>/` once a release fixed its number, else in `pending/`; the lists
//! are generated so that a change adds a file and never edits a line another change also edits.
//!
//! The generated code, for the app to `include!`, is per family a `FOLDED` list (each folded
//! format and its parts) and a `PENDING` list, both prefixed by the family's `list_prefix`, then a
//! module per change file. It names the app's `Part` type, which the including module has in scope
//! (`type Part = craft_format::Part<AppError>;`), and a change file's step as `step` (a
//! `pub fn step(v: &mut Value) -> Result<(), AppError>`, when the file has one).
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
/// A family's change files: their folder (relative to the crate's manifest), the last format
/// before them, and the prefix of the family's lists.
pub struct Family {
pub folder: &'static str,
pub base: u32,
pub list_prefix: &'static str,
}
/// What [`lists`] made: the code to write, and the folders the build script reruns on.
pub struct Lists {
pub code: String,
pub watch: Vec<PathBuf>,
}
/// The `FOLDED` and `PENDING` lists of every family, and a module for each change file. Refuses
/// versions that are not contiguous from a family's base, a change file not named with lowercase
/// letters, digits and dashes, and one that doesn't start with a `//!` note.
pub fn lists(manifest: &Path, families: &[Family]) -> Result<Lists, String> {
let mut code = String::new();
let mut mods = String::new();
let mut watch = Vec::new();
for family in families {
let root = manifest.join(family.folder);
family_lists(family, &root, &mut code, &mut mods)?;
watch.push(root);
}
code.push_str(&mods);
Ok(Lists { code, watch })
}
/// A family's `FOLDED` and `PENDING` lists; its folded formats follow on from its base.
fn family_lists(family: &Family, root: &Path, out: &mut String, mods: &mut String) -> Result<(), String> {
let Family { folder, base, list_prefix } = family;
let mut folded: Vec<(u32, PathBuf)> = Vec::new();
for entry in std::fs::read_dir(root).map_err(|e| format!("{}: {e}", root.display()))? {
// an entry that can't be read could be a version folder: fail rather than drop it
let path = entry.map_err(|e| format!("{}: {e}", root.display()))?.path();
let version = path.file_name().and_then(|n| n.to_str()).and_then(|n| n.strip_prefix('v')).and_then(|n| n.parse().ok());
if let Some(version) = version
&& path.is_dir()
{
folded.push((version, path));
}
}
folded.sort();
for (i, (version, _)) in folded.iter().enumerate() {
let expected = base + 1 + i as u32;
if *version != expected {
return Err(format!("{folder}/: expected v{expected}/ next, found v{version}/ (versions are contiguous)"));
}
}
// Module names start with the family's (`drawing_pending_…`), so two families' changes of one
// name never clash.
let module = list_prefix.to_ascii_lowercase();
let _ = writeln!(
out,
"/// The changes of each format after the base, oldest first (`{folder}/v<N>/`).\nconst {list_prefix}FOLDED: &[(u32, &[Part])] = &["
);
for (version, dir) in &folded {
let _ = writeln!(out, " ({version}, &[");
parts(dir, &format!("{module}v{version}"), false, out, mods)?;
out.push_str(" ]),\n");
}
let _ = writeln!(out, "];\n\n/// The changes no release has a number for yet (`{folder}/pending/`).\nconst {list_prefix}PENDING: &[Part] = &[");
parts(&root.join("pending"), &format!("{module}pending"), true, out, mods)?;
out.push_str("];\n\n");
Ok(())
}
/// Whether a change file declares its `step` function (`fn step(`, `pub fn step (` …) on a line of
/// code: a mention in a comment or a note is not a declaration.
fn declares_step(text: &str) -> bool {
let code = without_comments(text);
let ident = |c: char| c.is_alphanumeric() || c == '_';
// `fn`, whitespace, `step`, then `(` (or generics), across lines
code.match_indices("fn").any(|(at, _)| {
let before_ok = code[..at].chars().next_back().is_none_or(|c| !ident(c));
let rest = &code[at + 2..];
before_ok
&& rest.starts_with(char::is_whitespace)
&& rest
.trim_start()
.strip_prefix("step")
.is_some_and(|rest| matches!(rest.trim_start().chars().next(), Some('(' | '<')) && !rest.starts_with(ident))
})
}
/// `text` as code only: its `//` and (nested) `/* */` comments become a space, and the contents
/// of its string literals (plain, byte and raw) are dropped, line breaks kept throughout. A comment
/// marker inside a string is not a comment, and `fn/* note */step` still reads as `fn step`.
fn without_comments(text: &str) -> String {
let chars: Vec<char> = text.chars().collect();
let at = |i: usize| chars.get(i).copied();
let mut out = String::with_capacity(text.len());
let (mut i, mut depth) = (0usize, 0usize);
while let Some(c) = at(i) {
let next = at(i + 1);
if depth > 0 {
match (c, next) {
('/', Some('*')) => (depth, i) = (depth + 1, i + 2),
('*', Some('/')) => (depth, i) = (depth - 1, i + 2),
_ => {
if c == '\n' {
out.push('\n');
}
i += 1;
}
}
if depth == 0 {
out.push(' ');
}
continue;
}
let ident_before = i > 0 && at(i - 1).is_some_and(|p| p.is_alphanumeric() || p == '_');
match (c, next) {
('/', Some('/')) => {
while at(i).is_some_and(|c| c != '\n') {
i += 1;
}
out.push(' ');
}
('/', Some('*')) => (depth, i) = (1, i + 2),
('"', _) => {
out.push('"');
i += 1;
while let Some(c) = at(i) {
i += 1;
match c {
'\\' => i += 1,
'"' => break,
'\n' => out.push('\n'),
_ => {}
}
}
out.push('"');
}
// a raw string, `r"…"` or `r#"…"#`, after a byte prefix or on its own
('r', Some('"' | '#'))
if !ident_before || (i > 0 && at(i - 1) == Some('b') && !(i > 1 && at(i - 2).is_some_and(|p| p.is_alphanumeric() || p == '_'))) =>
{
let mut j = i + 1;
let mut hashes = 0;
while at(j) == Some('#') {
hashes += 1;
j += 1;
}
if at(j) != Some('"') {
out.push(c);
i += 1;
continue;
}
out.push('"');
i = j + 1;
while let Some(c) = at(i) {
if c == '"' && (1..=hashes).all(|k| at(i + k) == Some('#')) {
i += 1 + hashes;
break;
}
if c == '\n' {
out.push('\n');
}
i += 1;
}
out.push('"');
}
// a character literal (`'"'`, `'\''`), not a lifetime
('\'', Some('\\')) => {
i += 2;
while at(i).is_some_and(|c| c != '\'') {
i += 1;
}
i += 1;
out.push_str("' '");
}
('\'', Some(_)) if at(i + 2) == Some('\'') => {
i += 3;
out.push_str("' '");
}
_ => {
out.push(c);
i += 1;
}
}
}
out
}
/// The `Part`s of the change files in `dir`, in file-name order, and a module for each. A missing
/// folder is an empty list only where it may be absent (`optional`: `pending/`); any other error
/// reading it fails the build rather than leave a change out of the lists.
fn parts(dir: &Path, prefix: &str, optional: bool, out: &mut String, mods: &mut String) -> Result<(), String> {
let entries = match std::fs::read_dir(dir) {
Ok(entries) => entries,
Err(e) if optional && e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(e) => return Err(format!("{}: {e}", dir.display())),
};
let mut files: Vec<PathBuf> = Vec::new();
for entry in entries {
let path = entry.map_err(|e| format!("{}: {e}", dir.display()))?.path();
if path.extension().is_some_and(|x| x == "rs") {
files.push(path);
}
}
files.sort();
for path in files {
let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or_default().to_string();
if name.is_empty() || !name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') {
return Err(format!("{}: name a format change file with lowercase letters, digits and dashes", path.display()));
}
let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
if !text.trim_start().starts_with("//!") {
return Err(format!("{}: start a format change with a `//!` note", path.display()));
}
let module = format!("{prefix}_{}", name.replace('-', "_"));
let step = if declares_step(&text) { format!("Some({module}::step)") } else { "None".into() };
let _ = writeln!(out, " Part {{ name: {name:?}, step: {step} }},");
let _ = writeln!(mods, "#[path = {:?}]\nmod {module};", path.display().to_string());
}
Ok(())
}
#[cfg(test)]
#[path = "build_tests.rs"]
mod tests;
+115
View File
@@ -0,0 +1,115 @@
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
/// A fresh, empty folder for one test.
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("craft-format-build-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn write(path: &Path, text: &str) {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
/// The error of a run that must fail.
fn refused(dir: &Path) -> String {
match lists(dir, &[DRAWING]) {
Ok(_) => panic!("expected an error"),
Err(e) => e,
}
}
const DRAWING: Family = Family { folder: "drawing", base: 3, list_prefix: "DRAWING_" };
#[test]
fn lists_folded_and_pending_changes_with_their_modules() {
let dir = scratch("ok");
write(&dir.join("drawing/v4/add-layers.rs"), "//! Layers.\npub fn step(v: &mut Value) -> Result<(), E> { Ok(()) }\n");
write(&dir.join("drawing/v4/notes.txt"), "not a change");
write(&dir.join("drawing/v5/rename.rs"), "\n//! A rename with no step.\n");
write(&dir.join("drawing/pending/next-1.rs"), "//! Pending.\nfn step(v: &mut Value) {}\n");
std::fs::create_dir_all(dir.join("drawing/v6x")).unwrap();
write(&dir.join("drawing/v7"), "a file, not a version folder");
let lists = lists(&dir, &[DRAWING]).unwrap();
assert_eq!(lists.watch, vec![dir.join("drawing")]);
let code = &lists.code;
assert!(code.contains("const DRAWING_FOLDED: &[(u32, &[Part])] = &["), "{code}");
assert!(code.contains(" (4, &[\n Part { name: \"add-layers\", step: Some(drawing_v4_add_layers::step) },\n ]),"), "{code}");
assert!(code.contains("Part { name: \"rename\", step: None }"), "{code}");
assert!(
code.contains("const DRAWING_PENDING: &[Part] = &[\n Part { name: \"next-1\", step: Some(drawing_pending_next_1::step) },"),
"{code}"
);
assert!(code.contains("mod drawing_v5_rename;"), "{code}");
assert!(!code.contains("notes"), "{code}");
assert!(code.find("const DRAWING_PENDING").unwrap() < code.find("#[path").unwrap(), "modules follow the lists");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_empty_family_has_empty_lists() {
let dir = scratch("empty");
std::fs::create_dir_all(dir.join("drawing")).unwrap();
let code = lists(&dir, &[DRAWING]).unwrap().code;
assert!(code.contains("const DRAWING_FOLDED: &[(u32, &[Part])] = &[\n];"), "{code}");
assert!(code.contains("const DRAWING_PENDING: &[Part] = &[\n];"), "{code}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn refuses_gaps_bad_names_missing_notes_and_missing_folders() {
let dir = scratch("bad");
assert!(refused(&dir).contains("drawing"));
write(&dir.join("drawing/v5/a.rs"), "//! a");
assert!(refused(&dir).contains("expected v4/ next, found v5/"));
std::fs::rename(dir.join("drawing/v5"), dir.join("drawing/v4")).unwrap();
write(&dir.join("drawing/v4/Bad_Name.rs"), "//! b");
assert!(refused(&dir).contains("lowercase letters"));
std::fs::remove_file(dir.join("drawing/v4/Bad_Name.rs")).unwrap();
write(&dir.join("drawing/pending/no-note.rs"), "pub fn step() {}");
assert!(refused(&dir).contains("`//!` note"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_step_is_a_declaration_not_a_mention() {
assert!(!declares_step("//! No fn step() is needed.\n"));
assert!(!declares_step("//! a note\n// fn step(v) was removed\nconst X: u8 = 1;\n"));
assert!(declares_step("//! a note\npub fn step (v: &mut Value) -> Result<(), E> { Ok(()) }\n"));
// a declaration inside a block comment, nested or not, is not one
assert!(!declares_step("//! Documentation only.\n/*\nfn step() {}\n*/\n"));
assert!(!declares_step("/* outer /* inner */\nfn step() {}\n*/\nconst X: u8 = 1;\n"));
assert!(declares_step("/* a note */\nfn step(v: &mut Value) {}\n"));
// comment markers inside strings and character literals are not comments
assert!(declares_step("//! A change with a step.\nconst MARKER: &str = \"/*\";\npub fn step(_v: &mut Value) -> Result { Ok(()) }\n"));
assert!(declares_step("const A: &str = r#\"/* \"quoted\" \"#;\nconst B: &[u8] = br\"/*\";\nfn step(v: &mut Value) {}\n"));
assert!(declares_step("const Q: char = '\"';\nconst E: char = '\\'';\nfn step(v: &mut Value) { let _: &'static str = \"\"; }\n"));
assert!(declares_step("const S: &str = \"a \\\" /* b\";\nfn step(v: &mut Value) {}\n"));
assert!(!declares_step("const S: &str = \"\nfn step(v) \";\n"), "inside a string");
// a comment between the words is whitespace
assert!(declares_step("pub fn/* migration */step(v: &mut Value) {}\n"));
// across lines
assert!(declares_step("//! A change with a step.\npub fn step\n (_v: &mut Value) -> Result {\n Ok(())\n}\n"));
assert!(declares_step("pub fn\nstep(v: &mut Value) {}\n"));
assert!(!declares_step("fn stepper(v: &mut Value) {}\nfn prefn step() {}\n"), "other names");
assert!(declares_step("const X: u8 = 1; // fn step() is below\nfn step(v: &mut Value) {}\n"));
assert!(declares_step("//! a note\npub(crate) fn step(v: &mut Value) -> Result<(), E> { Ok(()) }\n"));
assert!(declares_step("//! a note\n fn step(v: &mut Value) {}\n"));
assert!(!declares_step("//! a note\nfn stepper(v: &mut Value) {}\nfn fnstep() {}\n"));
}
#[test]
fn a_documentation_only_change_has_no_step_and_a_missing_version_folder_fails() {
let dir = scratch("doc-only");
write(&dir.join("drawing/v4/doc.rs"), "//! No fn step() is needed.\n");
let code = lists(&dir, &[DRAWING]).unwrap().code;
assert!(code.contains("Part { name: \"doc\", step: None }"), "{code}");
// a version folder that can't be listed is an error, not an empty format
let missing = parts(&dir.join("drawing/v9"), "x", false, &mut String::new(), &mut String::new());
assert!(missing.is_err());
assert!(parts(&dir.join("drawing/pending"), "x", true, &mut String::new(), &mut String::new()).is_ok());
let _ = std::fs::remove_dir_all(&dir);
}
+440
View File
@@ -0,0 +1,440 @@
//! The file container: a ZIP package of named parts (the file's JSON, binary payloads, optional
//! caches), never extracted to filesystem paths. Payloads are content-addressed blobs,
//! `blobs/<sha256>.<extension>`, stored once however often they are referred to. Every size is
//! bounded by the app's [`Limits`]: the file, each part, all parts expanded, the payloads resolved,
//! and the number of entries; a part is read no further than its declared size (a decompression
//! bomb stops there). What a part holds, and how a payload is encoded, is the app's.
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Seek, SeekFrom};
use std::sync::Arc;
use serde_json::Value;
use sha2::{Digest, Sha256};
use crate::FormatError;
/// How hard the payloads are compressed: Fast favours interactive file operations; Compact trades
/// CPU time for space.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Compression {
#[default]
Fast,
Compact,
}
/// An app's budgets for its containers. The functions are read each time they are needed, so a
/// limit the app lets the user raise takes effect at once.
#[derive(Clone, Copy)]
pub struct Limits {
/// The most entries a container holds.
pub max_entries: usize,
/// The most bytes all parts may expand to, and all payloads may resolve to.
pub max_expanded: fn() -> usize,
/// The most bytes a part of this name may expand to.
pub part_limit: fn(&str) -> usize,
/// The Deflate level of a compressed part of this name and size.
pub level: fn(&str, usize) -> i64,
/// Whether a container of this many bytes may be read, or why not.
pub check_size: fn(u64) -> Result<(), String>,
/// Whether the work is cancelled (a save the person stopped): checked before each part, and
/// a long part is written a piece at a time and stops before the next piece when this says
/// so ([`FormatError::Cancelled`]). `None`: it cannot be cancelled here.
pub cancelled: Option<fn() -> bool>,
}
/// The most bytes of a part written between two cancellation checks.
const PIECE: usize = 1 << 20;
fn invalid(message: impl std::fmt::Display) -> FormatError {
FormatError::Invalid(message.to_string())
}
/// Whether the bytes start as a container does, whatever the file is called.
pub fn is_container(bytes: &[u8]) -> bool {
bytes.starts_with(b"PK\x03\x04")
}
/// The SHA-256 of the bytes.
pub fn sha256(bytes: &[u8]) -> [u8; 32] {
Sha256::digest(bytes).into()
}
fn hex(digest: &[u8; 32]) -> String {
use std::fmt::Write as _;
let mut out = String::with_capacity(64);
for byte in digest {
// Writing to a `String` cannot fail.
let _ = write!(&mut out, "{byte:02x}");
}
out
}
/// The SHA-256 of the bytes, in lowercase hexadecimal: a blob's name, and how a cache is keyed to
/// the file it was written for.
pub fn digest(bytes: &[u8]) -> String {
hex(&sha256(bytes))
}
/// One part a [`Writer`] wrote, with the SHA-256 of its uncompressed content. A caller that signs
/// a container uses these to bind the parts without reading the file back.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PartDigest {
pub name: String,
pub len: u64,
pub digest: [u8; 32],
}
/// A container being written.
pub struct Writer {
zip: craft_zip::Writer,
names: BTreeSet<String>,
expanded: usize,
resolved: usize,
limits: Limits,
/// Which written parts to record for a signature, and the records so far.
tracked: Option<TrackedParts>,
}
/// A tracking closure and the part digests collected so far.
type TrackedParts = (fn(&str) -> bool, Vec<PartDigest>);
impl Writer {
pub fn new(limits: Limits) -> Writer {
Writer { zip: craft_zip::Writer::new(), names: BTreeSet::new(), expanded: 0, resolved: 0, limits, tracked: None }
}
/// Record the parts written from now on whose name `include` accepts, with their SHA-256, for
/// [`Writer::take_parts`]. Used by a caller that signs the container.
pub fn track_parts(&mut self, include: fn(&str) -> bool) {
self.tracked = Some((include, Vec::new()));
}
/// The tracked parts written so far, oldest first, and stop tracking.
pub fn take_parts(&mut self) -> Option<Vec<PartDigest>> {
self.tracked.take().map(|(_, parts)| parts)
}
/// The container's bytes.
pub fn finish(self) -> Result<Vec<u8>, FormatError> {
self.zip.finish().map_err(invalid)
}
/// Add a part, compressed or stored. A name already written is written once.
pub fn part(&mut self, name: &str, bytes: &[u8], compressed: bool) -> Result<(), FormatError> {
self.part_with_digest(name, bytes, compressed, None)
}
/// [`Writer::part`] with a digest the caller already worked out (a blob's name is its digest),
/// so a signed save does not hash the same bytes twice.
fn part_with_digest(&mut self, name: &str, bytes: &[u8], compressed: bool, digest: Option<[u8; 32]>) -> Result<(), FormatError> {
if bytes.len() > (self.limits.part_limit)(name) {
return Err(invalid("part too large"));
}
if self.names.contains(name) {
return Ok(());
}
// Check the counters this part would leave, and commit them only once it is written: a
// refused part is not remembered as written.
let expanded = self.expanded.checked_add(bytes.len()).ok_or_else(|| invalid("expanded size overflow"))?;
if expanded > (self.limits.max_expanded)() || self.names.len().saturating_add(1) > self.limits.max_entries {
return Err(invalid("package too large"));
}
let cancelled = self.limits.cancelled;
if cancelled.is_some_and(|c| c()) {
return Err(FormatError::Cancelled);
}
// the configured level, clamped to the Deflate levels craft-zip writes (1 to 9)
let compression = if compressed {
craft_zip::Compression::Level((self.limits.level)(name, bytes.len()).clamp(1, 9) as u8)
} else {
craft_zip::Compression::Stored
};
match cancelled {
Some(cancelled) if bytes.len() > PIECE => {
let mut stopped = false;
let written = self.zip.add_with(name, compression, |out| {
for piece in bytes.chunks(PIECE) {
if cancelled() {
stopped = true;
return Err(std::io::Error::other("cancelled"));
}
out.write_all(piece)?;
}
Ok(())
});
if stopped {
return Err(FormatError::Cancelled);
}
written.map_err(invalid)?;
}
_ => self.zip.add(name, bytes, compression).map_err(invalid)?,
}
self.names.insert(name.to_owned());
self.expanded = expanded;
if let Some((include, parts)) = &mut self.tracked
&& include(name)
{
let digest = digest.unwrap_or_else(|| sha256(bytes));
parts.push(PartDigest { name: name.to_owned(), len: bytes.len() as u64, digest });
}
Ok(())
}
/// Would `entries` more optional parts of `extra` bytes, stored uncompressed, still keep the
/// file within `budget` and its expanded size within the reader's budget? The parts already
/// written count at their expanded size (an upper bound on what they take in the file).
pub fn room(&self, entries: usize, extra: usize, budget: usize) -> bool {
self.remaining(entries, budget).is_some_and(|left| extra <= left)
}
/// The bytes `entries` more optional parts may hold together ([`Writer::room`]).
pub fn space(&self, entries: usize, budget: usize) -> usize {
self.remaining(entries, budget).unwrap_or(0)
}
/// The bytes left for `entries` more parts, or `None` when the entries don't fit or what is
/// written already is past `budget` or the reader's budget.
fn remaining(&self, entries: usize, budget: usize) -> Option<usize> {
let count = self.names.len().checked_add(entries).filter(|&n| n <= self.limits.max_entries)?;
let overhead = count.saturating_mul(256).saturating_add(65_536);
let in_file = budget.checked_sub(overhead.saturating_add(self.expanded))?;
let expanded = (self.limits.max_expanded)().checked_sub(self.expanded)?;
Some(in_file.min(expanded))
}
/// Add a payload as a blob, `blobs/<sha256>.<extension>`, and say its name, for the JSON that
/// refers to it.
pub fn blob(&mut self, bytes: &[u8], extension: &str, compressed: bool) -> Result<Value, FormatError> {
let resolved = self
.resolved
.checked_add(bytes.len())
.filter(|&n| n <= (self.limits.max_expanded)())
.ok_or_else(|| invalid("resolved payloads too large"))?;
let digest = sha256(bytes);
let name = format!("blobs/{}.{extension}", hex(&digest));
self.part_with_digest(&name, bytes, compressed, Some(digest))?;
self.resolved = resolved;
Ok(Value::String(name))
}
}
/// A container being read. Opening reads all bytes into memory and checks the directory
/// (the entry count, unique and plain names, every part's
/// declared size), not the parts.
pub struct Reader {
archive: craft_zip::Archive<'static>,
blobs: BTreeMap<String, Vec<u8>>,
/// The bytes of payloads resolved so far, repeats counted: bounded by the expanded budget.
pub hydrated: usize,
document: Option<Arc<[u8]>>,
limits: Limits,
/// Every byte part reads have expanded to, whatever the budget was at the time.
read_total: u64,
}
impl Reader {
pub fn new(mut source: impl Read + Seek, limits: Limits) -> Result<Self, FormatError> {
let length = source.seek(SeekFrom::End(0)).map_err(invalid)?;
(limits.check_size)(length).map_err(invalid)?;
// Read all bytes into memory for the archive, no more than the length just approved: a file
// that grew since is refused rather than read past its budget.
source.seek(SeekFrom::Start(0)).map_err(invalid)?;
let capacity = usize::try_from(length).map_err(|_| invalid("file too large"))?;
let mut bytes = Vec::new();
bytes.try_reserve_exact(capacity).map_err(|_| invalid("file too large"))?;
source.take(length.saturating_add(1)).read_to_end(&mut bytes).map_err(invalid)?;
if bytes.len() as u64 != length {
return Err(invalid("the file changed while it was read"));
}
let mut archive = craft_zip::Archive::open_owned(
bytes,
craft_zip::Limits { max_entries: limits.max_entries as u64, max_total_bytes: (limits.max_expanded)() as u64 },
)
.map_err(invalid)?;
// the directory lists distinct names, so a repeated name is caught here
if archive.has_duplicate_names() {
return Err(invalid("duplicate or invalid archive entry"));
}
// Validate entry names match format rules: no empty, no backslashes,
// no path components that are "." or "..", and no duplicates; and every part's declared
// size within its configured limit.
let mut name_set = BTreeSet::new();
for entry_idx in 0..archive.len() {
// an entry whose name can't be read would be left out of the package unnoticed
let Ok(Some(name)) = archive.entry_name(entry_idx) else {
return Err(invalid("duplicate or invalid archive entry"));
};
{
if name.is_empty()
|| name.contains('\\')
|| name.split('/').any(|c| c.is_empty() || c == "." || c == "..")
|| !name_set.insert(name.clone())
{
return Err(invalid("duplicate or invalid archive entry"));
}
if archive.declared_size(&name).is_some_and(|size| size > (limits.part_limit)(&name) as u64) {
return Err(invalid("part too large"));
}
}
}
Ok(Self { archive, blobs: BTreeMap::new(), hydrated: 0, document: None, limits, read_total: 0 })
}
/// The file's own part, `document.json`, read once and kept: provisional caches and the
/// authoritative reading are bound to the same bytes, even if another process overwrites the
/// open file in place. Blobs remain hash-checked.
pub fn document(&mut self, limit: usize) -> Result<Arc<[u8]>, FormatError> {
if self.document.is_none() {
let bytes = self.limited_part("document.json", limit)?;
self.document = Some(bytes.into());
}
// a cached document still keeps the current part limit
let limit = limit.min((self.limits.part_limit)("document.json"));
self.document.as_ref().filter(|d| d.len() <= limit).cloned().ok_or_else(|| invalid("metadata budget"))
}
/// Whether the container has a part of this name.
pub fn has_part(&self, name: &str) -> bool {
self.archive.contains(name)
}
/// The names of every part, in the container's order.
pub fn part_names(&self) -> Vec<String> {
self.archive.names().map(|n| n.into_owned()).collect()
}
/// The part of this name, at most `limit` bytes and never more than its configured limit.
pub fn limited_part(&mut self, name: &str, limit: usize) -> Result<Vec<u8>, FormatError> {
let limit = limit.min((self.limits.part_limit)(name));
let expected = self.archive.declared_size(name).ok_or_else(|| invalid("part not found"))?;
if expected > limit as u64 {
return Err(invalid("part too large"));
}
// the expanded budget is read each time: a raised (or lowered) one applies at once, the
// bytes already read still counting against it
let budget = self.archive.budget_mut();
*budget = craft_zip::Budget::new(budget.what(), (self.limits.max_expanded)() as u64);
if budget.charge(self.read_total).is_err() {
return Err(invalid("package too large"));
}
// Read within budget. craft-zip's read() handles decompression bombs via the limit.
let bytes = self.archive.read(name, limit as u64).map_err(invalid)?.ok_or_else(|| invalid("part not found"))?;
if bytes.len() as u64 != expected {
return Err(invalid("part length mismatch"));
}
self.read_total = self.read_total.saturating_add(expected);
Ok(bytes)
}
/// The blob `value`'s `field` names, of this extension, within its part limit.
pub fn blob(&mut self, value: &Value, field: &str, extension: &str) -> Result<&[u8], FormatError> {
let limit = (self.limits.part_limit)(&format!("blob.{extension}"));
self.limited_blob(value, field, extension, limit)
}
/// [`Reader::blob`] within `limit` bytes. Its hash is checked when it is first read, and every
/// reference counts against the resolved budget.
pub fn limited_blob(&mut self, value: &Value, field: &str, extension: &str, limit: usize) -> Result<&[u8], FormatError> {
let name = value.get(field).and_then(Value::as_str).ok_or_else(|| invalid(format!("missing `{field}` reference")))?;
// a cached blob still keeps the part's current limit
let limit = limit.min((self.limits.part_limit)(name));
let hash = name
.strip_prefix("blobs/")
.and_then(|n| n.strip_suffix(&format!(".{extension}")))
.filter(|h| h.len() == 64 && h.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
.ok_or_else(|| invalid("invalid blob reference"))?;
if !self.blobs.contains_key(name) {
let bytes = self.limited_part(name, limit)?;
if digest(&bytes) != hash {
return Err(invalid(format!("blob hash mismatch: {name}")));
}
self.blobs.insert(name.to_owned(), bytes);
}
let bytes = self.blobs.get(name).ok_or_else(|| invalid("missing blob"))?;
if bytes.len() > limit {
return Err(invalid("blob exceeds its resource budget"));
}
// Count repeated references too: a tiny archive must not expand into unbounded owned
// strings or arrays when the same blob is referenced repeatedly.
self.hydrated = self
.hydrated
.checked_add(bytes.len())
.filter(|&n| n <= (self.limits.max_expanded)())
.ok_or_else(|| invalid("resolved payloads too large"))?;
Ok(bytes)
}
}
/// A small PNG picture of the file, kept in the container as a disposable cache keyed to the
/// exact file it shows: `cache/thumbnail.json` (its key) and `cache/thumbnail.png`. Reading it
/// never resolves a payload; a picture that isn't one, or is stale, is a miss.
#[derive(Clone, Copy, Debug)]
pub struct Thumbnail {
/// The key's format tag.
pub format: &'static str,
/// The build that wrote it: only the same build reads it back.
pub app: &'static str,
/// Its width and height in pixels.
pub size: [usize; 2],
/// The most bytes it may have.
pub max_bytes: usize,
}
impl Thumbnail {
/// Whether the bytes start as a PNG of this size within the byte budget (not a decode: a
/// consumer decodes with its own dimension and allocation limits).
pub fn valid(&self, bytes: &[u8]) -> bool {
bytes.len() <= self.max_bytes
&& bytes.get(..8) == Some(b"\x89PNG\r\n\x1a\n")
&& bytes.get(8..16) == Some(b"\0\0\0\rIHDR")
&& bytes.get(16..20) == Some((self.size[0] as u32).to_be_bytes().as_slice())
&& bytes.get(20..24) == Some((self.size[1] as u32).to_be_bytes().as_slice())
}
/// Add the picture, keyed to `document` (the file's own part), when it is one and there is
/// room for it within `budget`; otherwise leave it out, never failing the save.
pub fn write(&self, writer: &mut Writer, png: &[u8], document: &[u8], budget: usize) -> Result<(), FormatError> {
if !self.valid(png) {
return Ok(());
}
let key =
serde_json::to_vec(&serde_json::json!({"format": self.format, "app": self.app, "document": digest(document), "payload": digest(png)}))
.map_err(invalid)?;
let fits = |name: &str, len: usize| len <= (writer.limits.part_limit)(name);
if !fits("cache/thumbnail.json", key.len())
|| !fits("cache/thumbnail.png", png.len())
|| !writer.room(2, key.len().saturating_add(png.len()), budget)
{
return Ok(());
}
writer.part("cache/thumbnail.json", &key, false)?;
writer.part("cache/thumbnail.png", png, false)
}
/// The picture, when this build wrote it for exactly the file's own part (`document.json`,
/// read within `document_limit`).
pub fn read(&self, reader: &mut Reader, document_limit: usize) -> Result<Vec<u8>, FormatError> {
let key: Value = serde_json::from_slice(&reader.limited_part("cache/thumbnail.json", 4096)?).map_err(invalid)?;
let document = reader.document(document_limit)?;
if key.get("format").and_then(Value::as_str) != Some(self.format)
|| key.get("app").and_then(Value::as_str) != Some(self.app)
|| key.get("document").and_then(Value::as_str) != Some(digest(&document).as_str())
{
return Err(invalid("thumbnail key"));
}
let png = reader.limited_part("cache/thumbnail.png", self.max_bytes)?;
if !self.valid(&png) || key.get("payload").and_then(Value::as_str) != Some(digest(&png).as_str()) {
return Err(invalid("thumbnail payload"));
}
Ok(png)
}
}
#[cfg(test)]
#[path = "container_tests.rs"]
mod tests;
+260
View File
@@ -0,0 +1,260 @@
use super::*;
use std::io::Cursor;
const LIMITS: Limits = Limits {
max_entries: 8,
max_expanded: || 1 << 20,
part_limit: |name| if name.ends_with(".big") { 1 << 20 } else { 1024 },
level: |_, _| 1,
check_size: |length| if length <= 1 << 20 { Ok(()) } else { Err("too large".into()) },
cancelled: None,
};
/// Parts and blobs written are read back as they were; a blob is stored once, named by its hash,
/// and checked against it.
#[test]
fn parts_and_blobs_read_back() {
let mut writer = Writer::new(LIMITS);
writer.part("document.json", br#"{"a":1}"#, true).unwrap();
let first = writer.blob(b"payload", "bin", false).unwrap();
let again = writer.blob(b"payload", "bin", true).unwrap();
assert_eq!(first, again, "the same payload is one blob");
assert_eq!(first, Value::String(format!("blobs/{}.bin", digest(b"payload"))));
let bytes = writer.finish().unwrap();
assert!(is_container(&bytes));
let mut reader = Reader::new(Cursor::new(bytes), LIMITS).unwrap();
assert_eq!(reader.part_names().len(), 2);
assert!(reader.has_part("document.json") && !reader.has_part("other.json"));
assert_eq!(&*reader.document(64).unwrap(), br#"{"a":1}"#);
let reference = serde_json::json!({"blob": first});
assert_eq!(reader.blob(&reference, "blob", "bin").unwrap(), b"payload");
assert!(reader.blob(&reference, "blob", "png").is_err(), "another extension");
assert_eq!(reader.hydrated, 7);
reader.hydrated = (LIMITS.max_expanded)();
assert!(reader.blob(&reference, "blob", "bin").unwrap_err().to_string().contains("resolved payloads too large"));
}
/// A part past its limit, or more entries than the limit, are refused as they are written.
#[test]
fn budgets_are_kept_when_writing() {
let mut writer = Writer::new(LIMITS);
assert_eq!(writer.part("small.json", &[0; 1025], false), Err(FormatError::Invalid("part too large".into())));
assert!(writer.part("large.big", &[0; 1025], true).is_ok());
for i in 0..7 {
writer.part(&format!("{i}.json"), b"x", false).unwrap();
}
assert_eq!(writer.part("one-more.json", b"x", false), Err(FormatError::Invalid("package too large".into())));
assert!(!writer.room(1, 0, 1 << 20), "no room for an entry past the limit");
}
/// A thumbnail is kept only for the file it shows.
#[test]
fn a_thumbnail_is_keyed_to_its_file() {
let picture = Thumbnail { format: "app-thumbnail/1", app: "1.0", size: [2, 1], max_bytes: 1024 };
let mut png = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
png.extend_from_slice(&2u32.to_be_bytes());
png.extend_from_slice(&1u32.to_be_bytes());
assert!(picture.valid(&png));
let mut writer = Writer::new(LIMITS);
writer.part("document.json", b"{}", false).unwrap();
picture.write(&mut writer, &png, b"{}", 8 << 20).unwrap();
let mut reader = Reader::new(Cursor::new(writer.finish().unwrap()), LIMITS).unwrap();
assert_eq!(picture.read(&mut reader, 64).unwrap(), png);
let mut writer = Writer::new(LIMITS);
writer.part("document.json", b"{\"changed\":1}", false).unwrap();
picture.write(&mut writer, &png, b"{}", 8 << 20).unwrap();
let mut reader = Reader::new(Cursor::new(writer.finish().unwrap()), LIMITS).unwrap();
assert!(picture.read(&mut reader, 64).is_err(), "stale");
}
/// A refused part is not remembered as written: once the budget is raised it is written.
#[test]
fn a_refused_part_can_be_written_later() {
static BUDGET: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(4);
let limits = Limits { max_expanded: || BUDGET.load(std::sync::atomic::Ordering::SeqCst), ..LIMITS };
let mut writer = Writer::new(limits);
assert_eq!(writer.part("a.json", b"12345678", false), Err(FormatError::Invalid("package too large".into())));
assert!(writer.blob(b"12345678", "bin", false).is_err());
BUDGET.store(1 << 20, std::sync::atomic::Ordering::SeqCst);
writer.part("a.json", b"12345678", false).unwrap();
writer.blob(b"12345678", "bin", false).unwrap();
let reader = Reader::new(Cursor::new(writer.finish().unwrap()), limits).unwrap();
assert_eq!(reader.part_names().len(), 2, "both parts were written on the retry");
}
/// A cancelled save writes no more parts, whether the part is small or written in pieces.
#[test]
fn cancellation_stops_the_save() {
let cancelled = Limits { cancelled: Some(|| true), ..LIMITS };
let mut writer = Writer::new(cancelled);
assert_eq!(writer.part("a.json", b"a", false), Err(FormatError::Cancelled));
// cancelled after the first piece of a long part: checks before the part, then per piece
static CHECKS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let midway = Limits {
cancelled: Some(|| CHECKS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) >= 2),
max_expanded: || 1 << 22,
part_limit: |_| 1 << 22,
..LIMITS
};
let mut writer = Writer::new(midway);
assert_eq!(writer.part("big.big", &vec![0; PIECE + 1], true), Err(FormatError::Cancelled));
assert_eq!(CHECKS.load(std::sync::atomic::Ordering::SeqCst), 3);
let going = Limits { cancelled: Some(|| false), max_expanded: || 1 << 22, part_limit: |_| 1 << 22, ..LIMITS };
let mut writer = Writer::new(going);
writer.part("big.big", &vec![7; PIECE + 1], true).unwrap();
let mut reader = Reader::new(Cursor::new(writer.finish().unwrap()), going).unwrap();
assert_eq!(reader.limited_part("big.big", 1 << 22).unwrap().len(), PIECE + 1);
}
/// Room counts what is already written, and the reader keeps every part's configured limit.
#[test]
fn room_counts_written_parts_and_reads_keep_part_limits() {
let mut writer = Writer::new(LIMITS);
writer.part("large.big", &[0; 500 * 1024], false).unwrap();
assert!(!writer.room(1, 200 * 1024, 600 * 1024));
assert!(writer.room(1, 1024, 1 << 20));
// what is written already is past the budget: not even an empty part fits
assert!(!writer.room(1, 0, 400 * 1024));
assert_eq!(writer.space(1, 400 * 1024), 0);
let wide = Limits { part_limit: |_| 1 << 20, ..LIMITS };
let mut writer = Writer::new(wide);
writer.part("document.json", &[b' '; 2048], false).unwrap();
let bytes = writer.finish().unwrap();
assert!(Reader::new(Cursor::new(bytes.clone()), LIMITS).is_err(), "declared past its configured limit");
let mut reader = Reader::new(Cursor::new(bytes), wide).unwrap();
assert!(reader.limited_part("document.json", 4096).is_ok());
}
/// A thumbnail past a cache part's own limit is left out, never failing the save.
#[test]
fn a_thumbnail_past_its_part_limit_is_left_out() {
let picture = Thumbnail { format: "app-thumbnail/1", app: "1.0", size: [2, 1], max_bytes: 2048 };
let mut png = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
png.extend_from_slice(&2u32.to_be_bytes());
png.extend_from_slice(&1u32.to_be_bytes());
png.resize(1500, 0);
let mut writer = Writer::new(LIMITS);
picture.write(&mut writer, &png, b"{}", 8 << 20).unwrap();
let reader = Reader::new(Cursor::new(writer.finish().unwrap()), LIMITS).unwrap();
assert!(!reader.has_part("cache/thumbnail.json") && !reader.has_part("cache/thumbnail.png"));
}
/// A source that grows after its length was approved is refused.
#[test]
fn a_source_that_grows_while_read_is_refused() {
struct Growing(Cursor<Vec<u8>>, bool);
impl Read for Growing {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if !self.1 {
self.1 = true;
let end = self.0.get_ref().len();
self.0.get_mut().extend_from_slice(&[0; 16]);
self.0.set_position(self.0.position().min(end as u64));
}
self.0.read(buf)
}
}
impl Seek for Growing {
fn seek(&mut self, to: SeekFrom) -> std::io::Result<u64> {
self.0.seek(to)
}
}
let mut writer = Writer::new(LIMITS);
writer.part("document.json", b"{}", false).unwrap();
let bytes = writer.finish().unwrap();
assert!(Reader::new(Growing(Cursor::new(bytes), false), LIMITS).err().is_some_and(|e| e.to_string().contains("changed")));
}
/// Compressed parts use the configured Deflate level.
#[test]
fn compressed_parts_use_the_configured_level() {
// words in a varied order, so the levels compress them differently
let words = ["alpha ", "beta ", "gamma ", "delta ", "epsilon ", "zeta ", "eta ", "theta "];
let mut seed = 7u32;
let text: Vec<u8> = (0..150)
.flat_map(|_| {
seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
words[(seed >> 16) as usize % words.len()].bytes()
})
.take(1000)
.collect();
let size = |level: fn(&str, usize) -> i64| {
let mut writer = Writer::new(Limits { level, ..LIMITS });
writer.part("document.json", &text, true).unwrap();
writer.finish().unwrap().len()
};
assert_ne!(size(|_, _| 1), size(|_, _| 9), "the level is used");
assert_eq!(size(|_, _| 42), size(|_, _| 9), "past 9 is clamped");
assert_eq!(size(|_, _| -3), size(|_, _| 1), "below 1 is clamped");
}
/// An archive naming one part twice is refused.
#[test]
fn a_repeated_part_name_is_refused() {
let mut writer = Writer::new(LIMITS);
writer.part("document.json", b"{}", false).unwrap();
writer.part("documenX.json", b"[]", false).unwrap();
let mut bytes = writer.finish().unwrap();
let (from, to) = (b"documenX.json", b"document.json");
let mut at = 0;
while let Some(i) = bytes[at..].windows(from.len()).position(|w| w == from) {
bytes[at + i..at + i + to.len()].copy_from_slice(to);
at += i + to.len();
}
assert!(Reader::new(Cursor::new(bytes), LIMITS).is_err());
}
/// Cached documents and blobs keep the current part limits.
#[test]
fn cached_parts_keep_the_current_part_limits() {
let wide = Limits { part_limit: |_| 1 << 20, ..LIMITS };
let mut writer = Writer::new(wide);
writer.part("document.json", &[b' '; 512], false).unwrap();
let blob = writer.blob(&[7; 512], "bin", false).unwrap();
let bytes = writer.finish().unwrap();
let mut reader = Reader::new(Cursor::new(bytes), wide).unwrap();
let reference = serde_json::json!({"blob": blob});
assert!(reader.document(4096).is_ok());
assert!(reader.blob(&reference, "blob", "bin").is_ok());
reader.limits = Limits { part_limit: |_| 128, ..wide };
assert!(reader.document(4096).is_err());
assert!(reader.limited_blob(&reference, "blob", "bin", 4096).is_err());
}
/// A raised expanded budget applies to the open reader, and what was read still counts.
#[test]
fn a_raised_expanded_budget_applies_at_once() {
static BUDGET: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(600);
let limits = Limits { max_expanded: || BUDGET.load(std::sync::atomic::Ordering::Relaxed), part_limit: |_| 1 << 20, ..LIMITS };
let wide = Limits { max_expanded: || 1 << 20, ..limits };
let mut writer = Writer::new(wide);
writer.part("document.json", &[b' '; 256], false).unwrap();
writer.part("other.big", &[1; 512], false).unwrap();
let bytes = writer.finish().unwrap();
BUDGET.store(1 << 20, std::sync::atomic::Ordering::Relaxed);
let mut reader = Reader::new(Cursor::new(bytes), limits).unwrap();
BUDGET.store(600, std::sync::atomic::Ordering::Relaxed);
assert!(reader.limited_part("document.json", 4096).is_ok());
assert!(reader.limited_part("other.big", 4096).is_err(), "256 read + 512 is past 600");
BUDGET.store(1024, std::sync::atomic::Ordering::Relaxed);
assert!(reader.limited_part("other.big", 4096).is_ok(), "768 fits the raised 1024");
// a lowered budget does not forget what was read: 768 + 256 is past 1000 after a dip to 100
BUDGET.store(100, std::sync::atomic::Ordering::Relaxed);
assert!(reader.limited_part("document.json", 4096).is_err());
BUDGET.store(1000, std::sync::atomic::Ordering::Relaxed);
assert!(reader.limited_part("document.json", 4096).is_err(), "1024 is past 1000");
BUDGET.store(1024, std::sync::atomic::Ordering::Relaxed);
assert!(reader.limited_part("document.json", 4096).is_ok());
}
/// An entry whose local header can't be read is refused at open, not skipped.
#[test]
fn an_unreadable_entry_is_refused() {
let mut writer = Writer::new(LIMITS);
writer.part("document.json", b"{}", false).unwrap();
writer.part("other.json", b"[]", false).unwrap();
let mut bytes = writer.finish().unwrap();
let second = bytes.windows(4).enumerate().filter(|(_, w)| *w == b"PK\x03\x04").map(|(i, _)| i).nth(1).unwrap();
bytes[second + 2] = 0;
assert!(Reader::new(Cursor::new(bytes), LIMITS).is_err());
}
+257
View File
@@ -0,0 +1,257 @@
//! Versioned file formats: what an app needs to read every file it ever wrote, and to open a file
//! a newer build of it wrote.
//!
//! A file starts with `"format": "<prefix>N"`. A [`Family`] is one kind of file (an app's designs,
//! its drawings): its tag, its own numbers, and how a file of an older number is brought up to
//! this build's, step by step (N → N+1 → … → current). The app's code only knows the current
//! format; all translation lives in the steps:
//! - the steps written out by hand for the first formats, one per format ([`Formats::hand`]);
//! - then one folder per format, `v<N>/`, one file per change in it ([`Part`]), each with a step
//! when files from before the change are rewritten as they open ([`Formats::folded`]);
//! - then the changes no release has a number for yet, in `pending/` ([`Formats::pending`]):
//! while there are any, the build writes the next number, with their names in the file's
//! `format_pending`, so a later build runs just the steps a file is missing. A release moves
//! them into the next `v<N>/`. [`build`] lists the folders for a build script.
//!
//! A file a newer build wrote says so by a number past this build's or a change name this build
//! doesn't have ([`Family::newer`]); the app then reads what it can and keeps the rest
//! ([`newer`]). A file is saved as JSON, or in a [`container`] with its binary payloads.
//!
//! Steps are JSON-level (the file's shape) and return the app's own error type; every error this
//! crate makes is a [`FormatError`], which the app's error type takes `From`.
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
use serde_json::Value;
pub mod build;
pub mod container;
pub mod newer;
/// Why a file is refused: its text says what is wrong, as the user reads it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FormatError {
/// The file isn't one of the family's, or it is damaged.
Invalid(String),
/// The work was cancelled (a save the person stopped): nothing more was written.
Cancelled,
}
impl std::fmt::Display for FormatError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FormatError::Invalid(why) => f.write_str(why),
FormatError::Cancelled => f.write_str("cancelled"),
}
}
}
impl std::error::Error for FormatError {}
/// One JSON-level upgrade step: rewrites a file in place, or says why it can't.
pub type Step<E> = fn(&mut Value) -> Result<(), E>;
/// One change to a family's file format: a file in its `v<N>/` or `pending/` folder.
pub struct Part<E> {
/// The file's name, which a file written while the change was pending lists.
pub name: &'static str,
/// How a file from before the change is rewritten as it opens, if it is.
pub step: Option<Step<E>>,
}
/// Another spelling of a change name that a file of one format may carry (a build that named the
/// change otherwise): read as the change it stands for, never written.
#[derive(Clone, Copy, Debug)]
pub struct Alias {
/// The format whose files may say it.
pub format: u32,
/// The spelling in the file.
pub name: &'static str,
/// The change it stands for.
pub known_as: &'static str,
}
/// A family's upgrade path: the steps written out by hand, the folded formats after them (each a
/// list of changes) and the pending changes, which make the next format.
pub struct Formats<'a, E> {
/// Entry `i` turns format `i + 1` into `i + 2`.
pub hand: &'a [Step<E>],
/// Each format after the hand-written ones, oldest first, and its changes.
pub folded: &'a [(u32, &'a [Part<E>])],
/// The changes no release has a number for yet.
pub pending: &'a [Part<E>],
}
/// A kind of file whose format is versioned: its own format tag, its own numbers and its own
/// changes. Reading a file's format, telling a file a newer build saved and the upgrade are the
/// same for every family.
pub struct Family<'a, E> {
/// The app, as messages name it.
pub app: &'static str,
/// What a file of the family is called in messages.
pub noun: &'static str,
/// The tag before the number in a file's `format`.
pub prefix: &'static str,
/// The tag files saved under an older name carry: read, never written.
pub legacy_prefix: Option<&'static str>,
/// The format of a file that names none, if such files exist.
pub untagged: Option<u32>,
/// Other spellings of change names that files may carry.
pub aliases: &'a [Alias],
/// The upgrade path.
pub formats: Formats<'a, E>,
}
/// How a file shows a newer build saved it ([`Family::newer`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Newer {
/// The number the file says.
pub format: u32,
/// The number this build reads up to.
pub reads_up_to: u32,
/// The changes the file names that this build doesn't have.
pub unknown_changes: Vec<String>,
}
impl<E> Formats<'_, E> {
/// The format this build writes: the last folded one, or the next while changes are pending.
pub const fn current(&self) -> u32 {
self.hand.len() as u32 + 1 + self.folded.len() as u32 + if self.pending.is_empty() { 0 } else { 1 }
}
/// The changes format `version` is made of, if it is made of changes.
fn parts(&self, version: u32) -> Option<&[Part<E>]> {
let after = version.checked_sub(self.hand.len() as u32 + 2)? as usize;
match self.folded.get(after) {
Some((_, parts)) => Some(parts),
None if after == self.folded.len() && !self.pending.is_empty() => Some(self.pending),
None => None,
}
}
/// Whether a change of this name is anywhere in this build's history.
fn knows_part_name(&self, name: &str) -> bool {
self.folded.iter().flat_map(|(_, parts)| *parts).chain(self.pending).any(|part| part.name == name)
}
}
impl<E> Family<'_, E> {
/// The format this build writes: the last folded one, or the next while changes are pending.
pub const fn current(&self) -> u32 {
self.formats.current()
}
/// What a file of the family is called in messages.
pub const fn noun(&self) -> &'static str {
self.noun
}
/// The names of the pending changes this build writes into a file (`format_pending`).
pub fn pending_names(&self) -> Vec<String> {
self.formats.pending.iter().map(|p| p.name.to_string()).collect()
}
/// The format tag of format `n`.
pub fn format_string(&self, n: u32) -> String {
format!("{}{n}", self.prefix)
}
/// The version in one of this family's format tags; `None` for any other tag, another
/// family's included.
pub fn version_of(&self, s: &str) -> Option<u32> {
// each tag form parses on its own: a legacy prefix may start with the primary one
// (`app/` and `app/design/`)
let parse = |prefix: &str| s.strip_prefix(prefix).and_then(|n| n.parse().ok());
parse(self.prefix).or_else(|| self.legacy_prefix.and_then(parse))
}
/// The change a name a file of format `version` lists stands for: its alias's, or itself.
/// An alias counts only while this build has the change it stands for, so recognising it
/// never grants support to another reader.
fn canonical_applied_name<'name>(&self, version: u32, name: &'name str) -> &'name str {
match self.aliases.iter().find(|a| a.format == version && a.name == name) {
Some(alias) if self.formats.knows_part_name(alias.known_as) => alias.known_as,
_ => name,
}
}
/// What says a file of format `version` with the changes `applied` came from a newer build:
/// a number past this build's, or a change this build doesn't have anywhere in its history
/// (a branch's pending change may have landed at a later number). A list beside a format that
/// isn't made of changes means nothing (a tool or a test set an older number on a newer file).
/// `None` for a file this build fully knows.
pub fn newer(&self, version: u32, applied: Option<&[String]>) -> Option<Newer> {
let current = self.current();
let listed = applied.filter(|_| version > current || self.formats.parts(version).is_some()).unwrap_or_default();
let unknown_changes: Vec<String> =
listed.iter().filter(|name| !self.formats.knows_part_name(self.canonical_applied_name(version, name))).cloned().collect();
(version > current || !unknown_changes.is_empty()).then_some(Newer { format: version, reads_up_to: current, unknown_changes })
}
}
impl<E: From<FormatError>> Family<'_, E> {
/// Read a file's format and take its `format_pending` out of its JSON, before anything else
/// in it is read: a file that isn't this family's is refused here. One a newer build saved is
/// not: [`Family::newer`] says so.
pub fn take_version(&self, v: &mut Value) -> Result<(u32, Option<Vec<String>>), E> {
let (app, noun) = (self.app, self.noun);
let not_ours = |what: String| E::from(FormatError::Invalid(format!("not a {app} {noun} ({what})")));
let Some(obj) = v.as_object() else { return Err(not_ours("expected a JSON object".into())) };
let version = match obj.get("format") {
None => self.untagged.ok_or_else(|| not_ours("no format".into()))?,
Some(Value::String(f)) => self.version_of(f).ok_or_else(|| not_ours(format!("format `{f}`")))?,
Some(_) => return Err(not_ours("format is not a string".into())),
};
let applied = take_names(v, "format_pending", noun).map_err(E::from)?;
if version == 0 {
return Err(not_ours("format 0".into()));
}
Ok((version, applied))
}
/// Bring a file of format `version` up to this build's; `applied` is its `format_pending`
/// (both from [`Family::take_version`]): the changes of its format it already has, when it
/// was written while they were pending. The others' steps run first, and already-applied
/// changes never run again at their later number. A file past this build's number has no
/// steps to run.
pub fn upgrade(&self, v: &mut Value, version: u32, applied: Option<&[String]>) -> Result<(), E> {
let formats = &self.formats;
if version == 0 {
return Err(E::from(FormatError::Invalid(format!("not a {} {} (format 0)", self.app, self.noun))));
}
// A list beside a format that isn't made of changes is ignored, like any field an upgrade
// drops.
let applied = applied.filter(|_| formats.parts(version).is_some());
let already_applied =
|part: &Part<E>| applied.is_some_and(|names| names.iter().any(|name| self.canonical_applied_name(version, name) == part.name));
if applied.is_some() {
for part in formats.parts(version).unwrap_or_default().iter().filter(|part| !already_applied(part)) {
part.step.map_or(Ok(()), |step| step(v))?;
}
}
for from in version..self.current() {
match formats.hand.get(from as usize - 1) {
Some(step) => step(v)?,
None => {
for part in formats.parts(from + 1).unwrap_or_default().iter().filter(|part| !already_applied(part)) {
part.step.map_or(Ok(()), |step| step(v))?;
}
}
}
}
Ok(())
}
}
/// Take a short list of names out of a file's JSON: its `format_pending` (the pending changes it
/// has).
fn take_names(v: &mut Value, key: &str, noun: &str) -> Result<Option<Vec<String>>, FormatError> {
let Some(list) = v.as_object_mut().and_then(|o| o.remove(key)) else { return Ok(None) };
let invalid = || FormatError::Invalid(format!("damaged {noun}: `{key}` is not a short list of names"));
let list = list.as_array().filter(|l| l.len() <= 1000).ok_or_else(invalid)?;
list.iter().map(|n| n.as_str().filter(|n| n.len() <= 128).map(str::to_string).ok_or_else(invalid)).collect::<Result<_, _>>().map(Some)
}
#[cfg(test)]
#[path = "lib_tests.rs"]
mod tests;
+142
View File
@@ -0,0 +1,142 @@
use super::*;
use serde_json::json;
/// The app's error, as an app has one.
#[derive(Debug, PartialEq)]
struct AppError(String);
impl From<FormatError> for AppError {
fn from(e: FormatError) -> Self {
AppError(e.to_string())
}
}
/// Each step appends its name to the file's `log`, so the order steps ran in can be read back.
fn log(v: &mut Value, step: &str) {
if let Some(list) = v.get_mut("log").and_then(Value::as_array_mut) {
list.push(json!(step));
}
}
const HAND: [Step<AppError>; 2] = [
|v| {
log(v, "1to2");
Ok(())
},
|v| {
log(v, "2to3");
Ok(())
},
];
const V4: [Part<AppError>; 2] = [
Part {
name: "a",
step: Some(|v| {
log(v, "a");
Ok(())
}),
},
Part { name: "b", step: None },
];
const V5: [Part<AppError>; 1] = [Part {
name: "c",
step: Some(|v| {
log(v, "c");
Ok(())
}),
}];
const FOLDED: [(u32, &[Part<AppError>]); 2] = [(4, &V4), (5, &V5)];
const PENDING: [Part<AppError>; 2] = [
Part {
name: "d",
step: Some(|v| {
log(v, "d");
Ok(())
}),
},
Part {
name: "e",
step: Some(|v| {
log(v, "e");
Ok(())
}),
},
];
const ALIASES: [Alias; 1] = [Alias { format: 5, name: "old-c", known_as: "c" }];
/// Format 1 untagged; hand steps to 3; folded 4 and 5; pending changes make 6.
const FAMILY: Family<'static, AppError> = Family {
app: "App",
noun: "design",
prefix: "app/",
legacy_prefix: Some("old/"),
untagged: Some(1),
aliases: &ALIASES,
formats: Formats { hand: &HAND, folded: &FOLDED, pending: &PENDING },
};
fn steps_run(version: u32, applied: Option<&[String]>) -> Vec<String> {
let mut v = json!({"log": []});
FAMILY.upgrade(&mut v, version, applied).unwrap();
v["log"].as_array().unwrap().iter().map(|s| s.as_str().unwrap().to_string()).collect()
}
#[test]
fn tags_and_numbers() {
assert_eq!(FAMILY.current(), 6);
assert_eq!(FAMILY.format_string(6), "app/6");
assert_eq!(FAMILY.version_of("app/4"), Some(4));
assert_eq!(FAMILY.version_of("old/3"), Some(3), "the legacy tag is read");
assert_eq!(FAMILY.version_of("other/3"), None);
assert_eq!(FAMILY.pending_names(), vec!["d".to_string(), "e".to_string()]);
}
#[test]
fn a_file_is_taken_apart_or_refused_with_the_apps_words() {
let mut v = json!({"format": "app/6", "format_pending": ["d"], "x": 1});
assert_eq!(FAMILY.take_version(&mut v), Ok((6, Some(vec!["d".to_string()]))));
assert!(v.get("format_pending").is_none(), "taken out");
assert_eq!(FAMILY.take_version(&mut json!({})), Ok((1, None)), "untagged");
let refused = |mut v: Value| FAMILY.take_version(&mut v).unwrap_err().0;
assert_eq!(refused(json!([])), "not a App design (expected a JSON object)");
assert_eq!(refused(json!({"format": "other/2"})), "not a App design (format `other/2`)");
assert_eq!(refused(json!({"format": 2})), "not a App design (format is not a string)");
assert_eq!(refused(json!({"format": "app/0"})), "not a App design (format 0)");
assert_eq!(refused(json!({"format": "app/2", "format_pending": [1]})), "damaged design: `format_pending` is not a short list of names");
}
#[test]
fn every_step_runs_once_in_order() {
assert_eq!(steps_run(1, None), ["1to2", "2to3", "a", "c", "d", "e"]);
assert_eq!(steps_run(4, None), ["c", "d", "e"]);
assert_eq!(steps_run(6, None), Vec::<String>::new());
// A file written while `d` was pending has it: only `e` runs.
assert_eq!(steps_run(6, Some(&["d".to_string()])), ["e"]);
// A file of format 5 written while `c` was still pending, without it: `c` runs first.
assert_eq!(steps_run(5, Some(&[])), ["c", "d", "e"]);
// Under its other spelling `c` counts as had.
assert_eq!(steps_run(5, Some(&["old-c".to_string()])), ["d", "e"]);
// A list beside a hand-written format means nothing.
assert_eq!(steps_run(2, Some(&["d".to_string()])), ["2to3", "a", "c", "d", "e"]);
let mut v = json!({});
assert_eq!(FAMILY.upgrade(&mut v, 0, None), Err(AppError("not a App design (format 0)".into())));
}
#[test]
fn a_newer_file_is_told_by_its_number_or_an_unknown_change() {
assert_eq!(FAMILY.newer(6, None), None);
assert_eq!(FAMILY.newer(6, Some(&["d".to_string()])), None);
assert_eq!(FAMILY.newer(7, None), Some(Newer { format: 7, reads_up_to: 6, unknown_changes: Vec::new() }));
assert_eq!(FAMILY.newer(6, Some(&["z".to_string()])), Some(Newer { format: 6, reads_up_to: 6, unknown_changes: vec!["z".to_string()] }));
assert_eq!(FAMILY.newer(5, Some(&["old-c".to_string()])), None, "an alias of a known change");
assert_eq!(FAMILY.newer(4, Some(&["old-c".to_string()])), Some(Newer { format: 4, reads_up_to: 6, unknown_changes: vec!["old-c".to_string()] }));
assert_eq!(FAMILY.newer(2, Some(&["z".to_string()])), None, "a list beside a hand-written format means nothing");
}
#[test]
fn a_legacy_prefix_that_extends_the_primary_one_is_read() {
let nested = Family { prefix: "app/", legacy_prefix: Some("app/design/"), ..FAMILY };
assert_eq!(nested.version_of("app/design/3"), Some(3));
assert_eq!(nested.version_of("app/4"), Some(4));
assert_eq!(nested.version_of("app/design/x"), None);
}
+470
View File
@@ -0,0 +1,470 @@
//! A file a newer build saved: it opens, with a warning, and saving it loses nothing.
//!
//! A newer format number, or a change the file names that this build doesn't have, says a newer
//! build saved the file ([`crate::Family::newer`]). It may use nothing this build lacks, so the app
//! reads it as usual. When part of it can't be read, that part stays out of the way and the rest
//! opens: the app reads the elements of its lists it can ([`NewerFile::keep_element`]), then any
//! other top-level section it can't read is left out whole ([`leave_out_unreadable`],
//! [`read_around`]), and a field it doesn't know, which typed reading would drop, is noticed by
//! comparing the file with what was read ([`NewerFile::compare`]).
//!
//! All of these are named in [`NewerFile::not_understood`] and go back into the file when it is
//! saved ([`NewerFile::restore_into`]), as they came. What can't be put back because the file was
//! changed around it is what `restore_into` returns.
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use serde_json::{Map, Value, json};
use crate::Newer;
/// The most sections left out one at a time to find the one a file can't be read with.
const MAX_SECTION_TRIES: usize = 64;
/// What the file says and holds that this build doesn't read.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct NewerFile {
/// The app, as the notice names it.
pub app: &'static str,
/// The number the file says.
pub format: u32,
/// The number this build reads up to.
pub reads_up_to: u32,
/// The changes the file names that this build doesn't have.
pub unknown_changes: Vec<String>,
/// What this build couldn't read, by name.
pub not_understood: Vec<String>,
/// Fields known records lost in typed reading.
kept: Option<Kept>,
/// Top-level sections left out whole.
sections: Vec<Section>,
/// Elements left out of a top-level list: its key and the element.
elements: Vec<(String, Value)>,
/// The parts of a container this build has no use for: name and bytes. A blob only one of the
/// kept pieces refers to is one of them.
pub parts: Vec<(String, Arc<[u8]>)>,
/// The file's `container.json`, when this build doesn't know what it says.
pub container: Option<Value>,
}
#[derive(Clone, Debug, PartialEq)]
struct Section {
key: String,
value: Value,
/// This build's record of the section, without the file's: while it is unchanged, the file's
/// goes back.
empty: Option<Value>,
}
/// The fields of a record that typed reading dropped.
#[derive(Clone, Debug, PartialEq)]
enum Kept {
Field(Value),
Fields(BTreeMap<String, Kept>),
Items(Vec<(Anchor, Kept)>),
}
/// Which element of a list some kept fields belong to.
#[derive(Clone, Debug, PartialEq)]
enum Anchor {
Id(u64),
Name(String),
/// Its place, good only while the list keeps its length.
Index {
at: usize,
of: usize,
},
}
impl NewerFile {
/// A file of `app` that `newer` says a newer build saved, nothing left out of it yet.
pub fn new(app: &'static str, newer: &Newer) -> NewerFile {
NewerFile {
app,
format: newer.format,
reads_up_to: newer.reads_up_to,
unknown_changes: newer.unknown_changes.clone(),
..NewerFile::default()
}
}
/// What to tell the user, whatever else is said.
pub fn notice(&self) -> String {
let (app, reads, format) = (self.app, self.reads_up_to, self.format);
match self.unknown_changes.first() {
Some(change) if format <= reads => {
format!("Saved by a newer {app} (format {format} with `{change}`, which this version doesn't know). If something's missing, update.")
}
_ => format!("Saved by a newer {app} (format {format}, this version reads up to {reads}). If something's missing, update."),
}
}
/// Every line to report: the notice, then what couldn't be read, by name.
pub fn warnings(&self) -> Vec<String> {
let unread = self.not_understood.iter().map(|what| format!("Not read: {what}. Saving keeps it."));
std::iter::once(self.notice()).chain(unread).collect()
}
/// What a reply says about it.
pub fn report(&self) -> Value {
json!({
"format": self.format,
"reads_up_to": self.reads_up_to,
"unknown_changes": self.unknown_changes,
"not_understood": self.not_understood,
"notice": self.notice(),
})
}
/// Whether the next save needs a container to keep what the file holds: plain JSON has no room
/// for parts beside the file's own, nor for the container's own `container.json`.
pub fn needs_container(&self) -> bool {
!self.parts.is_empty() || self.container.is_some()
}
/// Whether anything kept back names this text (a blob's name in a container).
pub fn mentions(&self, text: &str) -> bool {
fn kept(k: &Kept, text: &str) -> bool {
match k {
Kept::Field(v) => value_mentions(v, text),
Kept::Fields(m) => m.values().any(|x| kept(x, text)),
Kept::Items(l) => l.iter().any(|(_, x)| kept(x, text)),
}
}
self.kept.as_ref().is_some_and(|k| kept(k, text))
|| self.sections.iter().any(|s| value_mentions(&s.value, text))
|| self.elements.iter().any(|(_, v)| value_mentions(v, text))
}
/// Say that a section the reader couldn't finish reading is left out. `empty` is what the
/// app writes for the section while it holds nothing, if anything.
pub fn keep_section(&mut self, key: &str, value: Value, empty: Option<Value>, why: &str) {
self.not_understood.push(format!("section `{key}` ({why})"));
self.sections.push(Section { key: key.into(), value, empty });
}
/// Say that an element of the top-level list `key` is left out, as `note` names it; it goes
/// back at the end of the list when the file is saved.
pub fn keep_element(&mut self, key: &str, element: Value, note: String) {
self.not_understood.push(note);
self.elements.push((key.into(), element));
}
/// Compare the file as it reads (`file`, after the same upgrade as what was read) with what was
/// read of it (`known`, its typed record written out): what `known` lacks is kept and named.
/// An object whose `type` is `placeholder_tag` (an element the app kept whole) is not
/// compared; nor are these top-level fields: those in `container_only` (what a container adds
/// beside the file's own), `format` and `format_pending`, and the sections kept whole (they go
/// back whole).
pub fn compare(&mut self, file: &Value, known: &Value, placeholder_tag: &str, container_only: &[&str]) {
let mut paths = Vec::new();
let mut top_only: Vec<&str> = container_only.to_vec();
top_only.extend(["format", "format_pending"]);
top_only.extend(self.sections.iter().map(|s| s.key.as_str()));
// a list typed writing leaves out holds only elements kept on their own: not kept twice
top_only.extend(self.elements.iter().map(|(key, _)| key.as_str()).filter(|key| known.get(*key).is_none()));
let kept = vanished(file, known, "", &mut paths, placeholder_tag, &top_only);
self.kept = kept;
self.not_understood.extend(paths);
for section in &mut self.sections {
section.empty = known.get(&section.key).cloned();
}
}
/// Write back what was kept of the file into `value`, the file as this build writes it.
/// Returns what couldn't go back, because the file was changed around it.
pub fn restore_into(&self, value: &mut Value) -> Vec<String> {
let mut lost = Vec::new();
if let Some(kept) = &self.kept {
apply(kept, value, "", &mut lost);
}
if let Some(top) = value.as_object_mut() {
for section in &self.sections {
if top.get(&section.key) == section.empty.as_ref() {
top.insert(section.key.clone(), section.value.clone());
} else {
lost.push(format!("section `{}`, replaced by what was edited here", section.key));
}
}
// each list's records indexed once, by the identity records are matched by
let mut indexes: HashMap<&str, Positions> = HashMap::new();
for (key, element) in &self.elements {
let name = element.get("name");
let anchor = anchor_of(element);
match top.entry(key.clone()).or_insert_with(|| json!([])) {
Value::Array(list) => {
let index = indexes.entry(key.as_str()).or_insert_with(|| Positions::of(list));
if anchor.as_ref().is_some_and(|a| index.find(list.len(), a).is_some()) {
lost.push(format!(
"`{key}` element {}, replaced by what was made here",
name.and_then(Value::as_str).unwrap_or("unnamed")
));
} else {
index.add(element, list.len());
list.push(element.clone());
}
}
_ => lost.push(format!("`{key}` element {}, replaced by what was made here", name.and_then(Value::as_str).unwrap_or("unnamed"))),
}
}
}
lost
}
}
/// Whether a string anywhere in `v` is `text`; iterative, so no nesting depth overflows the stack.
fn value_mentions(v: &Value, text: &str) -> bool {
let mut todo = vec![v];
while let Some(v) = todo.pop() {
match v {
Value::String(s) if s == text => return true,
Value::Array(a) => todo.extend(a),
Value::Object(o) => todo.extend(o.values()),
_ => {}
}
}
false
}
/// The first line of a reader's error, without the list of every kind it knows, and without the
/// `"<noun> file: "` its reader starts it with.
pub fn short<'a>(why: &'a str, noun: &str) -> &'a str {
let why = why.split(", expected").next().unwrap_or(why);
why.strip_prefix(&format!("{noun} file: ")).unwrap_or(why)
}
/// Leave a section out and keep it. A section the file needs is left empty.
fn move_out(top: &mut Map<String, Value>, key: &str, why: &str, noun: &str, file: &mut NewerFile) {
let Some(value) = top.remove(key) else { return };
file.not_understood.push(format!("section `{key}` ({})", short(why, noun)));
file.sections.push(Section { key: key.into(), value, empty: None });
}
/// Every top-level section of `top` that doesn't read by itself (`piece`, the app's reading of a
/// file holding just that section) is left out and kept in `file`. `noun` is what a file of the
/// app's is called, which its reader's errors start with.
pub fn leave_out_unreadable<E: std::fmt::Display>(
top: &mut Map<String, Value>,
file: &mut NewerFile,
noun: &str,
piece: impl Fn(&str, &Value) -> Result<(), E>,
) {
let keys: Vec<String> = top.keys().cloned().collect();
for key in &keys {
let value = top.get(key).cloned().unwrap_or_default();
if let Err(why) = piece(key, &value) {
move_out(top, key, &why.to_string(), noun, file);
}
}
}
/// Read `top` with `attempt`, leaving out the sections it can't be read with: if it doesn't read,
/// each section but the `core` ones (which the file can't be read without) is tried left out alone,
/// and as a last resort every one of them is. What is left out is kept in `file`. The error is the
/// first attempt's, when even the core alone doesn't read.
pub fn read_around<D, E: std::fmt::Display>(
top: &mut Map<String, Value>,
file: &mut NewerFile,
core: &[&str],
noun: &str,
attempt: impl Fn(&Map<String, Value>) -> Result<D, E>,
) -> Result<D, String> {
let first = match attempt(top) {
Ok(doc) => return Ok(doc),
Err(why) => why.to_string(),
};
// Sections that are fine by themselves but not together with the rest.
let keys: Vec<String> = top.keys().filter(|k| !core.contains(&k.as_str())).cloned().collect();
// Each try reads the whole file: a file of many sections goes straight to the last resort.
for key in keys.iter().filter(|_| keys.len() <= MAX_SECTION_TRIES) {
let mut without = top.clone();
without.remove(key);
if let Ok(doc) = attempt(&without) {
move_out(top, key, &first, noun, file);
return Ok(doc);
}
}
let mut bare = top.clone();
bare.retain(|key, _| core.contains(&key.as_str()));
match attempt(&bare) {
Ok(doc) => {
for key in &keys {
move_out(top, key, &first, noun, file);
}
Ok(doc)
}
Err(_) => Err(first),
}
}
/// A value a writer leaves out without losing anything: not worth telling anyone about.
pub fn looks_default(v: &Value) -> bool {
match v {
Value::Null => true,
Value::Bool(b) => !b,
Value::Number(n) => n.as_f64() == Some(0.0),
Value::String(s) => s.is_empty(),
Value::Array(a) => a.is_empty(),
Value::Object(o) => o.is_empty(),
}
}
/// What `raw` has that `known`, what was read of it, doesn't. `paths` gets those fields' names.
/// `top_only` are top-level keys left out of the comparison.
fn vanished(raw: &Value, known: &Value, path: &str, paths: &mut Vec<String>, placeholder_tag: &str, top_only: &[&str]) -> Option<Kept> {
match (raw, known) {
(Value::Object(raw), Value::Object(known)) => {
if known.get("type").and_then(Value::as_str) == Some(placeholder_tag) {
return None;
}
let mut kept = BTreeMap::new();
for (key, value) in raw {
if path.is_empty() && top_only.contains(&key.as_str()) {
continue;
}
let inner = if path.is_empty() { key.clone() } else { format!("{path}.{key}") };
match known.get(key) {
None => {
if !looks_default(value) {
paths.push(format!("field `{inner}`"));
}
kept.insert(key.clone(), Kept::Field(value.clone()));
}
Some(known) => {
if let Some(k) = vanished(value, known, &inner, paths, placeholder_tag, top_only) {
kept.insert(key.clone(), k);
}
}
}
}
(!kept.is_empty()).then_some(Kept::Fields(kept))
}
(Value::Array(raw), Value::Array(known)) => {
let mut items = Vec::new();
let positions = Positions::of(known);
for (at, element) in raw.iter().enumerate() {
// an identity typed reading kept: an id it dropped falls back to the name
let anchor = surviving_anchor(element, &positions).unwrap_or(Anchor::Index { at, of: raw.len() });
let Some(partner) = positions.find(known.len(), &anchor).and_then(|i| known.get(i)) else { continue };
let label = match (element.get("name").and_then(Value::as_str), &anchor) {
(Some(name), _) => format!("{path}[{name}]"),
(None, Anchor::Id(id)) => format!("{path}[{id}]"),
_ => format!("{path}[{at}]"),
};
if let Some(k) = vanished(element, partner, &label, paths, placeholder_tag, top_only) {
items.push((anchor, k));
}
}
(!items.is_empty()).then_some(Kept::Items(items))
}
_ => None,
}
}
fn anchor_of(element: &Value) -> Option<Anchor> {
if let Some(id) = element.get("id").and_then(Value::as_u64) {
return Some(Anchor::Id(id));
}
element.get("name").and_then(Value::as_str).map(|name| Anchor::Name(name.to_string()))
}
/// The identity of `element` that `known`'s records still carry: its id, or else its name. When
/// typed reading kept neither, there is none, and the record is matched by its place.
fn surviving_anchor(element: &Value, known: &Positions) -> Option<Anchor> {
let id = element.get("id").and_then(Value::as_u64).map(Anchor::Id);
let name = element.get("name").and_then(Value::as_str).map(|n| Anchor::Name(n.to_string()));
[id, name].into_iter().flatten().find(|anchor| known.find(usize::MAX, anchor).is_some())
}
/// Where each id and name first appears in a list, so matching records is not a scan per record.
struct Positions {
ids: HashMap<u64, usize>,
names: HashMap<String, usize>,
}
impl Positions {
fn of(list: &[Value]) -> Positions {
let (mut ids, mut names) = (HashMap::new(), HashMap::new());
for (i, x) in list.iter().enumerate() {
if let Some(id) = x.get("id").and_then(Value::as_u64) {
ids.entry(id).or_insert(i);
}
if let Some(name) = x.get("name").and_then(Value::as_str) {
names.entry(name.to_string()).or_insert(i);
}
}
Positions { ids, names }
}
/// Count `x`, now at `i`, in.
fn add(&mut self, x: &Value, i: usize) {
if let Some(id) = x.get("id").and_then(Value::as_u64) {
self.ids.entry(id).or_insert(i);
}
if let Some(name) = x.get("name").and_then(Value::as_str) {
self.names.entry(name.to_string()).or_insert(i);
}
}
/// The position of the record `anchor` names in a list of `len` records (an index anchor
/// only while the list keeps its length).
fn find(&self, len: usize, anchor: &Anchor) -> Option<usize> {
match anchor {
Anchor::Id(id) => self.ids.get(id).copied(),
Anchor::Name(name) => self.names.get(name).copied(),
Anchor::Index { at, of } => (len == *of && at < of).then_some(*at),
}
}
}
/// Put the kept fields back. An element that is gone was deleted here, its fields with it; one
/// whose place can't be told any more, and a field whose record is gone, go into `lost`.
fn apply(kept: &Kept, value: &mut Value, path: &str, lost: &mut Vec<String>) {
match kept {
Kept::Field(_) => {}
Kept::Fields(fields) => {
let Some(object) = value.as_object_mut() else {
lost.push(format!("field `{path}`"));
return;
};
for (key, sub) in fields {
let inner = if path.is_empty() { key.clone() } else { format!("{path}.{key}") };
match (sub, object.get_mut(key)) {
(Kept::Field(v), None) => {
object.insert(key.clone(), v.clone());
}
// the edited value stays; a retained one it replaced is reported
(Kept::Field(v), Some(existing)) => {
if existing != v {
lost.push(format!("field `{inner}`"));
}
}
(sub, Some(inner_value)) => apply(sub, inner_value, &inner, lost),
// The list it was in is empty and not written: its elements were deleted.
(Kept::Items(_), None) => {}
(_, None) => lost.push(format!("field `{inner}`")),
}
}
}
Kept::Items(items) => {
let Some(list) = value.as_array_mut() else {
lost.push(format!("field `{path}`"));
return;
};
let positions = Positions::of(list);
let len = list.len();
for (anchor, sub) in items {
match (positions.find(len, anchor).and_then(|i| list.get_mut(i)), anchor) {
(Some(element), _) => apply(sub, element, path, lost),
(None, Anchor::Index { at, .. }) => lost.push(format!("element {at} of `{path}`")),
(None, _) => {}
}
}
}
}
}
#[cfg(test)]
#[path = "newer_tests.rs"]
mod tests;
+218
View File
@@ -0,0 +1,218 @@
use super::*;
fn newer() -> Newer {
Newer { format: 9, reads_up_to: 8, unknown_changes: Vec::new() }
}
/// What typed reading dropped is named and goes back on saving, where it was.
#[test]
fn dropped_fields_are_named_and_put_back() {
let file = json!({"name": "A", "format": "app/9", "items": [{"id": 1, "size": 2, "colour": "red"}], "extra": {"x": 1}});
let known = json!({"name": "A", "items": [{"id": 1, "size": 2}]});
let mut said = NewerFile::new("App", &newer());
said.compare(&file, &known, "placeholder", &[]);
assert_eq!(said.not_understood, ["field `extra`", "field `items[1].colour`"]);
let mut saved = json!({"name": "A", "items": [{"id": 1, "size": 3}]});
assert!(said.restore_into(&mut saved).is_empty());
assert_eq!(saved, json!({"name": "A", "items": [{"id": 1, "size": 3, "colour": "red"}], "extra": {"x": 1}}));
assert_eq!(said.notice(), "Saved by a newer App (format 9, this version reads up to 8). If something's missing, update.");
}
/// A section that can't be read is left out, kept, and goes back while it is unchanged here.
#[test]
fn unreadable_sections_are_left_out_and_kept() {
let mut top = match json!({"name": "A", "good": 1, "bad": 2}) {
Value::Object(m) => m,
_ => unreachable!(),
};
let mut said = NewerFile::new("App", &newer());
leave_out_unreadable(&mut top, &mut said, "design", |key: &str, _: &Value| if key == "bad" { Err("design file: no") } else { Ok(()) });
assert!(!top.contains_key("bad"));
assert_eq!(said.not_understood, ["section `bad` (no)"]);
let read =
read_around(
&mut top,
&mut said,
&["name"],
"design",
|top: &Map<String, Value>| {
if top.contains_key("good") { Err("design file: clash") } else { Ok(top.len()) }
},
);
assert_eq!(read, Ok(1));
assert_eq!(said.not_understood, ["section `bad` (no)", "section `good` (clash)"]);
let mut saved = json!({"name": "A"});
said.compare(&saved.clone(), &saved.clone(), "placeholder", &[]);
assert!(said.restore_into(&mut saved).is_empty());
assert_eq!(saved, json!({"name": "A", "good": 1, "bad": 2}));
}
/// Notices, warnings and reports name what was left out, and kept values can be searched.
#[test]
fn warnings_report_and_mentions_cover_everything_kept() {
let mut said = NewerFile::new("App", &Newer { format: 8, reads_up_to: 8, unknown_changes: vec!["curves".into()] });
assert_eq!(said.notice(), "Saved by a newer App (format 8 with `curves`, which this version doesn't know). If something's missing, update.");
assert!(!said.needs_container());
said.keep_section("plugins", json!({"tool": "ruler"}), Some(json!({})), "unknown");
said.keep_element("shapes", json!({"name": "star", "points": ["tip"]}), "shape `star`".into());
let file = json!({"shapes": [{"name": "a", "tags": ["deep"], "more": {"x": "nested"}}], "n": 1});
said.compare(&file, &json!({"shapes": [{"name": "a"}], "n": 1}), "placeholder", &[]);
assert_eq!(said.warnings()[0], said.notice());
assert!(said.warnings().contains(&"Not read: section `plugins` (unknown). Saving keeps it.".to_string()));
let report = said.report();
assert_eq!(report["format"], 8);
assert_eq!(report["unknown_changes"], json!(["curves"]));
assert_eq!(report["notice"], json!(said.notice()));
for text in ["ruler", "tip", "deep", "nested"] {
assert!(said.mentions(text), "{text}");
}
assert!(!said.mentions("absent"));
said.parts.push(("blob".into(), Arc::from(&b"x"[..])));
assert!(said.needs_container());
}
/// A kept section or element that was replaced here is reported lost, not written over.
#[test]
fn replaced_sections_and_elements_are_reported_lost() {
let mut said = NewerFile::new("App", &newer());
said.keep_section("plugins", json!({"tool": "ruler"}), None, "unknown");
said.keep_element("shapes", json!({"name": "star"}), "shape `star`".into());
said.keep_element("shapes", json!({"points": 3}), "an unnamed shape".into());
let mut saved = json!({"plugins": {"edited": true}, "shapes": [{"name": "star"}]});
let lost = said.restore_into(&mut saved);
assert_eq!(lost, ["section `plugins`, replaced by what was edited here", "`shapes` element star, replaced by what was made here"]);
assert_eq!(saved["shapes"], json!([{"name": "star"}, {"points": 3}]));
let mut fresh = json!({});
said.sections.clear();
assert!(said.restore_into(&mut fresh).is_empty());
assert_eq!(fresh["shapes"], json!([{"name": "star"}, {"points": 3}]));
}
/// Retained container metadata alone needs a container to survive the save.
#[test]
fn container_metadata_alone_needs_a_container() {
let mut said = NewerFile::new("App", &newer());
assert!(!said.needs_container());
said.container = Some(json!({"layout": 2}));
assert!(said.needs_container());
}
/// An edit that replaces a retained field keeps the edit and reports the replaced value.
#[test]
fn a_replaced_retained_field_is_reported() {
let mut said = NewerFile::new("App", &newer());
said.compare(&json!({"extra": 1}), &json!({}), "placeholder", &[]);
let mut edited = json!({"extra": 2});
assert_eq!(said.restore_into(&mut edited), ["field `extra`"]);
assert_eq!(edited, json!({"extra": 2}));
let mut same = json!({"extra": 1});
assert!(said.restore_into(&mut same).is_empty());
}
/// Records are matched by id and by name across long lists, and an index anchor only while the
/// list keeps its length.
#[test]
fn records_match_by_id_name_or_unchanged_index() {
let records: Vec<Value> = (0..2000).map(|i| json!({"id": i, "extra": i})).collect();
let known: Vec<Value> = (0..2000).map(|i| json!({"id": i})).collect();
let mut said = NewerFile::new("App", &newer());
said.compare(&json!({"items": records}), &json!({"items": known}), "placeholder", &[]);
let mut saved = json!({"items": (0..2000).rev().map(|i| json!({"id": i})).collect::<Vec<_>>()});
assert!(said.restore_into(&mut saved).is_empty());
assert_eq!(saved["items"][0], json!({"id": 1999, "extra": 1999}));
let mut by_name = NewerFile::new("App", &newer());
by_name.compare(&json!({"l": [{"name": "a", "x": 1}, [1, 2]]}), &json!({"l": [{"name": "a"}, [1]]}), "placeholder", &[]);
let mut renamed = json!({"l": [{"name": "a"}]});
by_name.restore_into(&mut renamed);
assert_eq!(renamed["l"][0], json!({"name": "a", "x": 1}));
}
/// A section kept whole goes back whole, even when this build's record of it has fields.
#[test]
fn a_section_kept_whole_is_not_compared_field_by_field() {
let mut said = NewerFile::new("App", &newer());
said.keep_section("plugins", json!({"mode": "future", "payload": 1}), None, "unreadable");
let file = json!({"name": "A", "plugins": {"mode": "future", "payload": 1}});
said.compare(&file, &json!({"name": "A", "plugins": {"mode": "none"}}), "placeholder", &[]);
let mut saved = json!({"name": "A", "plugins": {"mode": "none"}});
assert!(said.restore_into(&mut saved).is_empty());
assert_eq!(saved, file);
}
/// A kept element goes back only while no record has its id or name.
#[test]
fn a_kept_element_keeps_record_identity() {
let mut said = NewerFile::new("App", &newer());
said.keep_element("items", json!({"id": 7, "kind": "future"}), "element 7".into());
said.keep_element("items", json!({"kind": "anonymous"}), "unnamed".into());
let mut clash = json!({"items": [{"id": 7, "kind": "made here"}]});
assert_eq!(said.restore_into(&mut clash).len(), 1);
assert_eq!(clash, json!({"items": [{"id": 7, "kind": "made here"}, {"kind": "anonymous"}]}));
let mut free = json!({"items": []});
assert!(said.restore_into(&mut free).is_empty());
assert_eq!(free, json!({"items": [{"id": 7, "kind": "future"}, {"kind": "anonymous"}]}));
}
/// Container-only fields are left out at the top level only.
#[test]
fn container_only_fields_are_top_level() {
let mut said = NewerFile::new("App", &newer());
let file = json!({"thumbnail": "t", "layer": {"thumbnail": "nested"}});
said.compare(&file, &json!({"layer": {}}), "placeholder", &["thumbnail"]);
assert_eq!(said.not_understood, ["field `layer.thumbnail`"]);
let mut saved = json!({"layer": {}});
assert!(said.restore_into(&mut saved).is_empty());
assert_eq!(saved, json!({"layer": {"thumbnail": "nested"}}));
}
/// An element kept on its own is not kept again with its list when typed writing leaves the list out.
#[test]
fn a_kept_element_is_not_restored_twice() {
let mut said = NewerFile::new("App", &newer());
said.keep_element("items", json!({"kind": "future"}), "unnamed".into());
said.compare(&json!({"items": [{"kind": "future"}]}), &json!({}), "placeholder", &[]);
let mut saved = json!({});
assert!(said.restore_into(&mut saved).is_empty());
assert_eq!(saved, json!({"items": [{"kind": "future"}]}));
}
/// A record whose id typed reading drops is matched by its name, and its fields go back.
#[test]
fn a_dropped_id_falls_back_to_the_name() {
let mut said = NewerFile::new("App", &newer());
said.compare(&json!({"items": [{"id": 7, "name": "a", "extra": 1}]}), &json!({"items": [{"name": "a"}]}), "placeholder", &[]);
let mut saved = json!({"items": [{"name": "a"}]});
assert!(said.restore_into(&mut saved).is_empty());
assert_eq!(saved, json!({"items": [{"name": "a", "id": 7, "extra": 1}]}));
}
/// Kept elements sharing a list are checked against one index, the ones put back included.
#[test]
fn kept_elements_check_each_other() {
let mut said = NewerFile::new("App", &newer());
said.keep_element("items", json!({"id": 1, "v": "first"}), "1".into());
said.keep_element("items", json!({"id": 1, "v": "again"}), "1 again".into());
let mut saved = json!({"items": []});
assert_eq!(said.restore_into(&mut saved).len(), 1);
assert_eq!(saved, json!({"items": [{"id": 1, "v": "first"}]}));
// deep nesting is searched without recursion
let mut deep = json!("needle");
for _ in 0..20_000 {
deep = Value::Array(vec![deep]);
}
said.keep_section("deep", deep, None, "test");
assert!(said.mentions("needle"));
// serde_json drops deep values recursively; leak it rather than overflow the test thread
std::mem::forget(said);
}
/// A record whose whole identity typed reading drops is matched by its place while the list keeps
/// its length, so an unchanged save keeps its fields.
#[test]
fn a_record_without_a_surviving_identity_is_matched_by_place() {
let mut said = NewerFile::new("App", &newer());
said.compare(&json!({"items": [{"id": 7, "extra": 1}]}), &json!({"items": [{}]}), "placeholder", &[]);
let mut saved = json!({"items": [{}]});
assert!(said.restore_into(&mut saved).is_empty());
assert_eq!(saved, json!({"items": [{"id": 7, "extra": 1}]}));
}
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "craft-gridcraft-format"
description = "GridCraft's native JSON workbook file: its extensions, reader and pretty writer"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
[lints]
workspace = true
[dependencies]
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
+17
View File
@@ -0,0 +1,17 @@
# craft-gridcraft-format
GridCraft's native workbook file is one pretty-printed UTF-8 JSON object, with a two-space indent
and no newline at the end. It is saved as `.json`, or as `.scjson` by older builds.
The workbook is a type parameter. GridCraft owns the model, and after a read it rebuilds the
model's indexes, drops cells outside the grid and reads the macros. This crate owns the bytes:
- `EXTENSIONS` and `is_extension` name the format.
- `read(bytes)` reads a workbook. A failure reads as "not a GridCraft JSON workbook: …".
- `write(workbook)` writes one with `serde_json`'s pretty printer.
- `write_with_kept(workbook, field, kept)` appends entries that a newer version wrote, and this
build kept without reading, to the top-level list `field`, as the file held them. With nothing
kept, the output is exactly `write`'s. Otherwise the workbook goes through a `serde_json::Value`
first, so its object keys come out in map order, as GridCraft has always written them.
There is no `unsafe` and no panics, and it builds for `wasm32-unknown-unknown`.
+59
View File
@@ -0,0 +1,59 @@
//! GridCraft's native workbook file: the workbook as one pretty-printed UTF-8 JSON object,
//! saved as `.json` (or `.scjson`, its older name).
//!
//! GridCraft owns the workbook model and what happens after a read: rebuilding its indexes,
//! dropping cells outside the grid, and reading its macros. This crate owns the bytes: which
//! extensions name the format, how the JSON is read and written, and how entries kept from a
//! newer version are written back into a list as the file held them.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
/// The extensions of the format, lower case. `scjson` is the name older builds saved.
pub const EXTENSIONS: [&str; 2] = ["json", "scjson"];
/// Whether `extension` (without the dot, any case) names the format.
pub fn is_extension(extension: &str) -> bool {
EXTENSIONS.iter().any(|e| e.eq_ignore_ascii_case(extension))
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// The bytes are not a workbook: not JSON, or JSON of another shape.
#[error("not a GridCraft JSON workbook: {0}")]
Read(serde_json::Error),
/// The workbook could not be written as JSON.
#[error("{0}")]
Write(serde_json::Error),
}
/// Read a workbook. Unknown fields are left to the model's own serde rules.
pub fn read<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, Error> {
serde_json::from_slice(bytes).map_err(Error::Read)
}
/// Write a workbook as pretty-printed JSON (two-space indent, no newline at the end).
pub fn write<T: Serialize>(workbook: &T) -> Result<Vec<u8>, Error> {
serde_json::to_vec_pretty(workbook).map_err(Error::Write)
}
/// [`write`], with `kept` appended to the top-level list `field` (made if absent): entries a
/// newer version wrote that this build kept without reading. With nothing kept this is exactly
/// [`write`]. Otherwise the workbook goes through a [`Value`] first, so its object keys are
/// written in `serde_json`'s map order.
pub fn write_with_kept<T: Serialize>(workbook: &T, field: &str, kept: &[Value]) -> Result<Vec<u8>, Error> {
if kept.is_empty() {
return write(workbook);
}
let mut v = serde_json::to_value(workbook).map_err(Error::Write)?;
if let Some(list) = v.as_object_mut().map(|o| o.entry(field).or_insert_with(|| Value::Array(vec![]))).and_then(Value::as_array_mut) {
list.extend(kept.iter().cloned());
}
serde_json::to_vec_pretty(&v).map_err(Error::Write)
}
#[cfg(test)]
mod tests;
+87
View File
@@ -0,0 +1,87 @@
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use serde::Deserialize;
use serde_json::json;
use super::*;
/// A stand-in for an app's workbook: fields in declaration order, one of them a list.
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Book {
sheets: Vec<String>,
active: u32,
#[serde(default)]
macros: Vec<Value>,
}
fn book() -> Book {
Book { sheets: vec!["Sheet1".into(), "Été ✓".into()], active: 1, macros: vec![json!({"v": 1, "name": "Fill"})] }
}
#[test]
fn extensions_are_json_and_scjson_in_any_case() {
for yes in ["json", "scjson", "JSON", "ScJson"] {
assert!(is_extension(yes), "{yes}");
}
for no in ["", "xlsx", "jsonl", ".json", "scjs"] {
assert!(!is_extension(no), "{no}");
}
}
#[test]
fn a_workbook_is_written_pretty_in_field_order() {
let bytes = write(&book()).unwrap();
let text = String::from_utf8(bytes).unwrap();
assert_eq!(
text,
"{\n \"sheets\": [\n \"Sheet1\",\n \"Été ✓\"\n ],\n \"active\": 1,\n \"macros\": [\n {\n \"name\": \"Fill\",\n \"v\": 1\n }\n ]\n}"
);
assert_eq!(read::<Book>(text.as_bytes()).unwrap(), book());
}
#[test]
fn kept_entries_are_appended_as_the_file_held_them() {
let kept = [json!({"v": 9, "name": "Future", "extra": [1, 2]})];
let bytes = write_with_kept(&book(), "macros", &kept).unwrap();
let back: Book = read(&bytes).unwrap();
assert_eq!(back.macros, [json!({"v": 1, "name": "Fill"}), kept[0].clone()]);
// Through a JSON value, keys are in map order: `active` before `macros` before `sheets`.
let text = String::from_utf8(bytes).unwrap();
assert!(text.find("\"active\"") < text.find("\"macros\"") && text.find("\"macros\"") < text.find("\"sheets\""), "{text}");
// With nothing kept, the plain writer's bytes.
assert_eq!(write_with_kept(&book(), "macros", &[]).unwrap(), write(&book()).unwrap());
}
#[test]
fn kept_entries_make_the_list_when_it_is_absent() {
#[derive(Serialize)]
struct Bare {
sheets: Vec<String>,
}
let bytes = write_with_kept(&Bare { sheets: vec![] }, "macros", &[json!(1)]).unwrap();
assert_eq!(serde_json::from_slice::<Value>(&bytes).unwrap(), json!({"sheets": [], "macros": [1]}));
// A field that is not a list is left as it is.
let bytes = write_with_kept(&json!({"macros": "text"}), "macros", &[json!(1)]).unwrap();
assert_eq!(serde_json::from_slice::<Value>(&bytes).unwrap(), json!({"macros": "text"}));
}
#[test]
fn what_is_not_a_workbook_says_so() {
for bad in [&b""[..], b"{", b"[]", b"{\"sheets\": 7, \"active\": 0}", b"\xff\xfe"] {
let err = read::<Book>(bad).unwrap_err();
assert!(matches!(err, Error::Read(_)));
assert!(err.to_string().starts_with("not a GridCraft JSON workbook: "), "{err}");
}
assert_eq!(
read::<Book>(b"{\"sheets\": 7}").unwrap_err().to_string(),
"not a GridCraft JSON workbook: invalid type: integer `7`, expected a sequence at line 1 column 12"
);
}
#[test]
fn a_value_json_cannot_hold_is_a_write_error() {
use std::collections::BTreeMap;
let bad: BTreeMap<Vec<u8>, u8> = [(vec![1], 1)].into();
assert!(matches!(write(&bad), Err(Error::Write(_))));
assert!(matches!(write_with_kept(&bad, "macros", &[json!(1)]), Err(Error::Write(_))));
}
+3
View File
@@ -19,6 +19,9 @@ heic-rs = { version = "=0.1.4", default-features = false, features = ["std"], op
heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true }
rayon = { workspace = true, optional = true }
[dev-dependencies]
proptest = { workspace = true }
[features]
default = ["decode"]
# The decoder (probe, decode, decode_thumbnail, read_metadata): heic-rs for the container and HEVC.
+17 -4
View File
@@ -36,11 +36,24 @@ Errors are `Error::Unsupported` (image sequences, overlays, 4:2:2/4:4:4, …), `
`Error::Malformed`. It never panics: every call into heic-rs runs under `catch_unwind`, and a panic
inside it (PhotoCraft's fuzzing found two in 0.1.1) becomes `Error::Malformed`.
Features: `decode` (default) is the decoder above. `metadata` adds `craft_heif::items::read`: the
first `Exif` item and XMP packet from the box structure alone (`iinf`, `iloc`, `idat`; at most 4096
boxes, 1024 items, 1024 extents per item, 32 MiB per item), without heic-rs. A build with
Features: `decode` (default) is the decoder above. `metadata` adds `craft_heif::items`, which reads
the `Exif` and XMP items from the box structure alone (`pitm`, `iinf`, `iref`, `iloc`, `idat`),
without heic-rs:
- `items::read` returns the photo's own EXIF and XMP: the items `cdsc` ties to the primary image or
to an image it is made from (`dimg`: grid tiles, `iden`, `iovl`, `tmap`), else those tied to no
image. A thumbnail's or depth map's metadata is not the photo's.
- `items::scan` returns every EXIF and XMP item, whichever image it describes, and says when it
can't be sure it saw them all: `Scan::complete` is false for an incomplete or damaged item
catalog, and an item whose bytes can't be read comes back as `Unreadable`. An app that must
prove a file has no location (before an export that removes it) refuses when unsure.
- `items::exif_tiff` finds the TIFF stream in an `Exif` item, with or without a correct offset
field or an `Exif\0\0` prefix.
The reader walks at most 65,536 boxes and walks `iloc` once. It gathers at most 16 MiB per item,
and a scan gathers at most 64 MiB in all. A build with
`default-features = false, features = ["metadata"]` has no heic-rs dependency, and its
`read_metadata` is that reader. With both features, a test checks that the two readers agree.
`read_metadata` is `items::read`. With both features, a test checks that the two readers agree.
Feature `testdata` exposes `craft_heif::testdata`: lossless synthetic HEIF files (PCM-coded
32 × 32 HEVC pictures, grids, every property above) for the tests of the crates above.
+666 -414
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+3
View File
@@ -13,7 +13,10 @@ workspace = true
[features]
corpus = []
default = []
# Opt in to threaded AVIF encoding without enabling AVIF (or assembly) by itself.
threads = ["ravif?/threading", "rav1e?/threading"]
sgi = []
sunraster = []
avif = ["image/avif", "dep:ravif", "dep:rav1e", "dep:avif-serialize"]
heif = ["dep:craft-heif"]
# AVIF decode: craft-video's clean-room pure-Rust AV1 decoder. Native targets only (on wasm32 a
+9 -2
View File
@@ -43,7 +43,7 @@ craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "<
| TIFF | yes | yes | U8, U16, F32 | all six (CMYK, CMYK+A included) | yes | yes (tag 34675) | no | yes (tag 700) | yes | yes (Description, Make, Model, Software, DateTime, Artist, Copyright) | no | `tiff` |
| WebP | yes | yes | U8 | RGB, RGBA | yes | yes | yes | yes | no | no | yes (VP8, when `webp_lossless` is off) | `image-webp` / built-in VP8 |
| GIF | yes | yes | U8 | RGBA | 1-bit | no | no | no | no | no | yes (256-colour palette) | `image` |
| BMP | yes | yes | U8 | RGB, RGBA | yes | no | no | no | no | no | no | `image` |
| BMP | yes | yes | U8 | RGB, RGBA | yes | no | no | no | yes (header pixels per metre) | no | no | `image` |
| TGA | yes | yes | U8 | Gray, GrayA, RGB, RGBA | yes | no | no | no | no | no | no | `image` (read) / built in (RLE write, one scanline per packet) |
| ICO | yes | yes | U8 | RGBA (at most 256×256) | yes | no | no | no | no | no | no | `image` |
| DDS | yes | yes | U8 | Gray, GrayA, RGB, RGBA | yes | no | no | no | no | no | yes (BC1–BC3, when `EncodeOptions::dds` asks for one) | built in |
@@ -57,6 +57,7 @@ craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "<
| Cineon | yes | yes | U16 (10-bit code values read and written exactly through U16) | Gray, RGB | no | no | no | no | no | no | no | built in |
| DICOM | yes | **no** | U8, U16 | Gray, RGB | no | no | no | no | no | no | n/a | built in |
| Amiga IFF (ILBM/PBM) | yes | yes (24-bit ILBM) | U8 | RGB, RGBA | yes (1-bit mask plane on write) | no | no | no | no | no | no | built in |
| Sun Raster (`.ras`) | with feature `sunraster` (incl. RLE and colour maps) | with feature `sunraster` (uncompressed) | U8 | Gray, RGB, RGBA | yes | no | no | no | no | no | no | `sunraster` (off by default) |
| SGI (`.sgi`, `.rgb`, `.bw`) | with feature `sgi` | with feature `sgi` (RLE) | U8, U16 | Gray, Gray+A, RGB, RGBA | yes | no | no | no | no | no | no | `sgi` (off by default) |
| JPEG-LS (`.jls`) | yes (any NEAR; one scan per component) | yes (lossless) | U8, U16 | Gray, RGB | no | no | no | no | no | no | no | built in |
| AVIF | with feature `avif-decode` (native only) | only with feature `avif` | U8, U16 (10/12-bit decodes to U16; PQ/HLG to linear F32) | RGB, RGBA | yes (auxiliary alpha) | read (`colr` prof/rICC) | read | read | no | no | yes | `craft-video` AV1 decoder; `image` + `ravif` to write |
@@ -78,7 +79,8 @@ the same.
Palette BMP and PNG pixels decode as RGB(A) in `Image`; `bmp_palette` and `png_palette` expose the
embedded table (and a PNG's transparent entry) so `photocraft-io` can open them in Indexed Color mode.
`bmp_palette` returns the colours the header declares, not the decoder's 256-entry padding.
`encode_bmp_indexed` writes the inverse: indices plus a table as an 8-bit palette BMP.
`encode_bmp_indexed` writes the inverse: indices plus a table as an 8-bit palette BMP;
`encode_bmp_indexed_with_dpi` also writes a resolution in the header.
## Documented asymmetries and limitations
@@ -235,6 +237,11 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them
the EXIF and XMP resolution are rewritten to the image's (`export_exif`, `export_xmp`): the
RATIONAL values in place, ResolutionUnit set to 2, an entry that can't be rewritten removed
from IFD0 without moving any other data. IFD1 (the thumbnail's) is left as it is.
* **Resolution without decoding** (module `resolution_probe`): `file_resolution(bytes)` reads
the pixels per inch a JPEG, PNG, WebP, BMP or classic TIFF records from its headers alone, for
placing a picture at its physical size before (or without) decoding it. JPEG, PNG, WebP and
TIFF answer as `decode` would; BMP reads the info header's pixels per metre. Values outside
1–100 000 ppi count as none.
* **JPEG**
* 8-bit only. Neither decoder backend supports 12-bit.
* A file cut off inside its image data decodes leniently (a baseline JPEG's missing rows come
+3
View File
@@ -1,6 +1,7 @@
pub(crate) mod avif;
#[cfg(all(feature = "avif-decode", not(target_arch = "wasm32")))]
pub(crate) mod avif_decode;
pub(crate) mod bmp;
pub(crate) mod dds;
pub(crate) mod dds_bc;
pub(crate) mod deep_exr;
@@ -22,6 +23,8 @@ pub(crate) mod png;
pub(crate) mod pnm;
#[cfg(feature = "sgi")]
pub(crate) mod sgi;
#[cfg(feature = "sunraster")]
pub(crate) mod sunraster;
pub(crate) mod tga;
pub(crate) mod tiff;
pub(crate) mod tiff_exif;
Loaded 100 of 341 files, more files were not shown because too many files have changed in this diff. Show more