diff --git a/.config/nextest.toml b/.config/nextest.toml new file mode 100644 index 0000000000..1037b23108 --- /dev/null +++ b/.config/nextest.toml @@ -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" diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 283af50e16..e40c1b4bc8 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -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 diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index 20e9474806..4d717fed82 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -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 diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 43d543062a..ab167207cf 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -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. diff --git a/Cargo.lock b/Cargo.lock index 726b9a3834..d03b13854e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/Cargo.toml b/Cargo.toml index e58ac33cf2..0ed80bda2e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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- = { path = "crates/" }` @@ -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" diff --git a/README.md b/README.md index 6a75cf7827..d84d578521 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/crates/aaf/src/aaf.rs b/crates/aaf/src/aaf.rs index 05894f94e0..efa618fb39 100644 --- a/crates/aaf/src/aaf.rs +++ b/crates/aaf/src/aaf.rs @@ -57,13 +57,56 @@ pub struct WriteOptions<'a> { /// reported. pub fn write(doc: &Document, opts: &WriteOptions<'_>, report: &mut Report) -> Result> { 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 { + 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> { + 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 { - 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 diff --git a/crates/aaf/src/aaf/read.rs b/crates/aaf/src/aaf/read.rs index 31c841c5d1..9739f87baa 100644 --- a/crates/aaf/src/aaf/read.rs +++ b/crates/aaf/src/aaf/read.rs @@ -67,6 +67,7 @@ fn indirect_f64(d: &[u8]) -> Option { struct R<'a> { report: &'a mut Report, + options: super::ReadOptions, mobs: HashMap, essence: HashMap, 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 { +pub(crate) fn read(bytes: &[u8], options: &super::ReadOptions, report: &mut Report) -> Result { 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 { 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 }; diff --git a/crates/aaf/src/aaf/tests.rs b/crates/aaf/src/aaf/tests.rs index 3e77944714..34eb2bbb35 100644 --- a/crates/aaf/src/aaf/tests.rs +++ b/crates/aaf/src/aaf/tests.rs @@ -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 = 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)); +} diff --git a/crates/aaf/src/aaf/write.rs b/crates/aaf/src/aaf/write.rs index 8c9aae88e1..1fcc6a3320 100644 --- a/crates/aaf/src/aaf/write.rs +++ b/crates/aaf/src/aaf/write.rs @@ -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> { +pub(crate) fn write( + doc: &Document, + version: craft_cfb::Version, + identity: &Identity<'_>, + references: &super::ReferenceOptions, + report: &mut Report, +) -> Result> { 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 = 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))])); } diff --git a/crates/aaf/src/lib.rs b/crates/aaf/src/lib.rs index ee7448bc05..4968c5b39b 100644 --- a/crates/aaf/src/lib.rs +++ b/crates/aaf/src/lib.rs @@ -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)] diff --git a/crates/aaf/src/omf/read.rs b/crates/aaf/src/omf/read.rs index d45b6ff639..9e892a0ce8 100644 --- a/crates/aaf/src/omf/read.rs +++ b/crates/aaf/src/omf/read.rs @@ -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>, 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, 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 { + read_with_budget(bytes, report, MAX_COMPONENT_VISITS) +} + +fn read_with_budget(bytes: &[u8], report: &mut Report, budget: usize) -> Result { 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 { 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 { 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 { - 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, 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, 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, + todo: &mut Vec, + queued: &mut usize, + max_visits: usize, + max_pending: usize, + ) -> std::result::Result, 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, 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, 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::>()); + 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 = (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(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 = (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 = (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 = (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::>()); + 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::>()); + assert!(results.iter().all(|r| matches!(r, Ok(None)))); + } +} diff --git a/crates/aaf/src/pcm.rs b/crates/aaf/src/pcm.rs index 789c976a83..9992b2d3be 100644 --- a/crates/aaf/src/pcm.rs +++ b/crates/aaf/src/pcm.rs @@ -4,8 +4,3 @@ pub(crate) fn parse_wav(b: &[u8]) -> Option<(Vec, 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, u16, u32, u16)> { - craft_audio::aiff_pcm(b).map(|p| (p.data, p.channels, p.sample_rate, p.bits)) -} diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 1590372ad5..08b881e17b 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -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 { + 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, 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, /// 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]); } diff --git a/crates/audio/src/essence_pcm.rs b/crates/audio/src/essence_pcm.rs new file mode 100644 index 0000000000..dfb119b8b7 --- /dev/null +++ b/crates/audio/src/essence_pcm.rs @@ -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, 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 { + 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, 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 = (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 = (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])); + } +} diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 93fbec58d3..c7382a973d 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -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; diff --git a/crates/audio/src/lpcm.rs b/crates/audio/src/lpcm.rs new file mode 100644 index 0000000000..5ec13b35df --- /dev/null +++ b/crates/audio/src/lpcm.rs @@ -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 { + 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>> { + 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> { + 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::::new()]); + } +} diff --git a/crates/audio/src/pcm_export.rs b/crates/audio/src/pcm_export.rs new file mode 100644 index 0000000000..618ba281de --- /dev/null +++ b/crates/audio/src/pcm_export.rs @@ -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 { + 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, 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) { + 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, 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, 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, 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()); + } +} diff --git a/crates/cms/src/lib.rs b/crates/cms/src/lib.rs index 1ca07eecd3..2f4abdc502 100644 --- a/crates/cms/src/lib.rs +++ b/crates/cms/src/lib.rs @@ -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; diff --git a/crates/cms/src/normalize.rs b/crates/cms/src/normalize.rs new file mode 100644 index 0000000000..85d6907839 --- /dev/null +++ b/crates/cms/src/normalize.rs @@ -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) -> Vec { + 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 { + 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> { + 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)); + } +} diff --git a/crates/cms/src/normalize_legacy_tests.rs b/crates/cms/src/normalize_legacy_tests.rs new file mode 100644 index 0000000000..dae5c2770b --- /dev/null +++ b/crates/cms/src/normalize_legacy_tests.rs @@ -0,0 +1,43 @@ +//! Encoded ICC normalization extracted from LightCraft. +pub(super) fn align_tags(b: &[u8]) -> Vec { + 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> = (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) -> Vec { + if let Some(date) = b.get_mut(24..36) { + date.fill(0); + } + b +} diff --git a/crates/cms/src/sony_lut.rs b/crates/cms/src/sony_lut.rs new file mode 100644 index 0000000000..cc3f8fb00f --- /dev/null +++ b/crates/cms/src/sony_lut.rs @@ -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 { + 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 { + 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 }) +} diff --git a/crates/cms/tests/sony_lut.rs b/crates/cms/tests/sony_lut.rs new file mode 100644 index 0000000000..065792a270 --- /dev/null +++ b/crates/cms/tests/sony_lut.rs @@ -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]); +} diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml new file mode 100644 index 0000000000..0a18ccc99c --- /dev/null +++ b/crates/control/Cargo.toml @@ -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 } diff --git a/crates/control/src/auth.rs b/crates/control/src/auth.rs new file mode 100644 index 0000000000..bb2cef86b3 --- /dev/null +++ b/crates/control/src/auth.rs @@ -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, `.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, + /// The app's environment variable `name` (`CONTROL_DIR`, `CONTROL_TOKEN`), with the app's prefix. + pub env: fn(&str) -> Option, + /// 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, enabled: bool) -> Option { + 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 { + 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: `/control` (the app's `CONTROL_DIR` replaces it). + fn control_dir(&self) -> Option { + 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 { + (self.env)("CONTROL_DIR").filter(|d| !d.is_empty()) + } + + /// The token file of the app listening on `port`: `/control/.token` + /// (the app's `CONTROL_DIR` replaces the folder). + pub fn token_path(&self, port: u16) -> Option { + 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 { + 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 { + 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 { + 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(¤t, &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 { + (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 { + 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 { + text.trim().parse::().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, + /// 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, + /// From `.pid`: the writer's process id and, on Linux, its start time. + pub writer: Option<(u32, Option)>, +} + +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 { + 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") +} + +/// ` []`; anything else (or no file) is no information. +fn read_pid_file(path: &Path) -> Option<(u32, Option)> { + 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::().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) -> 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 { + #[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::().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 { + #[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 { + 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> { + 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`. + 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(¤t, "27878").unwrap(); + } + // The first closes: the second's files stay. + remove_token_file(&file, &first); + remove_discovery(¤t, &file, 27878, &first); + assert_eq!(read_token(&file).as_deref(), Some(second.as_str())); + assert!(pid_path(&file).exists() && current.exists() && pid_path(¤t).exists()); + // Another port named in the discovery file is another app's too. + remove_discovery(¤t, &file, 27879, &second); + assert!(current.exists()); + // The second closes: nothing of either is left. + remove_token_file(&file, &format!(" {second}\n")); + remove_discovery(¤t, &file, 27878, &second); + assert!(!file.exists() && !pid_path(&file).exists() && !current.exists() && !pid_path(¤t).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(¤t, "27878").unwrap(); + remove_token_file(&file, &second); + remove_discovery(¤t, &file, 27878, &second); + assert!(!current.exists()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/control/src/cancel.rs b/crates/control/src/cancel.rs new file mode 100644 index 0000000000..e030523078 --- /dev/null +++ b/crates/control/src/cancel.rs @@ -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>>, +} + +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() + } +} diff --git a/crates/control/src/client.rs b/crates/control/src/client.rs new file mode 100644 index 0000000000..cbad788504 --- /dev/null +++ b/crates/control/src/client.rs @@ -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 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 { + 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, + 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)>, + /// 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, + /// A request still running in the app; its reply waits on `conn`. + outstanding: Option, + /// An outstanding request's end, once a later call waited for it (for `pending`). + settled: Option, + 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::().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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + let v = self.exchange(request, true)?; + self.outcome(&v) + } +} + +#[cfg(test)] +#[path = "client_tests.rs"] +mod tests; diff --git a/crates/control/src/client_tests.rs b/crates/control/src/client_tests.rs new file mode 100644 index 0000000000..f5af19a004 --- /dev/null +++ b/crates/control/src/client_tests.rs @@ -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 { + None +} + +fn no_env(_: &str) -> Option { + 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::(); + 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}"); +} diff --git a/crates/control/src/effect.rs b/crates/control/src/effect.rs new file mode 100644 index 0000000000..aed5cbe596 --- /dev/null +++ b/crates/control/src/effect.rs @@ -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(), + } + } +} diff --git a/crates/control/src/lib.rs b/crates/control/src/lib.rs new file mode 100644 index 0000000000..26727a97c8 --- /dev/null +++ b/crates/control/src/lib.rs @@ -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:"; diff --git a/crates/control/src/request.rs b/crates/control/src/request.rs new file mode 100644 index 0000000000..b97c90b76c --- /dev/null +++ b/crates/control/src/request.rs @@ -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, + /// Set once the window starts on it; until then it waits its turn (`control.running`, #3654). + pub started: std::sync::Arc, + /// 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>, + /// Where the request is, shared with the connection that sent it so it can cancel it + /// (`control.cancel`, #1989). + pub ticket: std::sync::Arc, + /// 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, params: Value) -> (Self, std::sync::mpsc::Receiver) { + 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>, + 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(); + } +} diff --git a/crates/control/src/server.rs b/crates/control/src/server.rs new file mode 100644 index 0000000000..85664a1aa9 --- /dev/null +++ b/crates/control/src/server.rs @@ -0,0 +1,1433 @@ +//! The loopback JSON-lines control server: one request per line, one reply per line, behind the +//! launch's token (docs/control-protocol.md). Agents and tests drive an app through it (adapted +//! from CADCraft, MIT OR Apache-2.0). What the app's requests mean is the app's [`Protocol`]; the +//! window answers them from the [`ControlRequest`]s it is sent. + +use std::io::{BufRead, BufReader, Write}; +use std::net::{TcpListener, TcpStream}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +use crate::Effect; +use crate::auth::tokens_match; +use crate::cancel::{Cancel, Ticket}; +use crate::request::{ControlRequest, DOCUMENT_WATCH, DocumentWatch, Subscriber}; + +/// What the server needs to know of a request before it sends it to the window: how to name it +/// in messages, what it does if it outlasts its wait, and what `control.running` shows of it. +#[derive(Clone, Debug)] +pub struct Summary { + /// The request in messages ("`engine.execute` (solid.fillet)"). + pub what: String, + /// What it still does when it finishes after its wait. + pub effect: Effect, + /// The command it runs, for `control.running` (never its parameters). + pub command: Option<&'static str>, + /// The number of steps it runs, for `control.running`. + pub steps: Option, + /// It may take as long as a batch. + pub long: bool, +} + +/// What an app's requests mean to its control server. +pub trait Protocol: Send + Sync { + fn summary(&self, method: &str, params: &Value) -> Summary; + /// What the app calls its document in messages ("design"). + fn document(&self) -> &'static str; + /// The event a subscribed connection is sent when the document moves ("design.changed"). + fn change_event(&self) -> &'static str; + /// The method that answers the document's id and revision now ("document.revision"). + fn revision_method(&self) -> &'static str; + /// Where a client reads how to talk to the channel, named when its token is refused + /// ("docs/control-protocol.md"). + fn docs(&self) -> &'static str; + /// The `control.capabilities` result: what this app's channel does beyond the methods every + /// version has, for a client to find out before it relies on it (an older app answers + /// `control.capabilities` with "unknown method"). + fn capabilities(&self) -> Value; +} + +/// An app's control server: its [`Protocol`], how it wakes the window for a request, and the +/// requests every connection of its listeners has the window running (`control.running`). +pub struct Hub { + protocol: Box, + wake: Box, + /// Longest request line accepted. + max_line: usize, + waits: Waits, + watch: &'static DocumentWatch, + running: Arc, + open: AtomicUsize, +} + +impl Hub { + /// A server for `protocol`'s requests; `wake` makes the window look at its requests now. + pub fn new(protocol: impl Protocol + 'static, wake: impl Fn() + Send + Sync + 'static, max_line: usize) -> Self { + Hub { + protocol: Box::new(protocol), + wake: Box::new(wake), + max_line, + waits: Waits::default(), + watch: &DOCUMENT_WATCH, + running: Arc::new(Running::new()), + open: AtomicUsize::new(0), + } + } + + /// Other waits (tests). + pub fn with_waits(mut self, waits: Waits) -> Self { + self.waits = waits; + self + } + + /// Another document watch than the app's [`DOCUMENT_WATCH`] (tests). + pub fn with_watch(mut self, watch: &'static DocumentWatch) -> Self { + self.watch = watch; + self + } + + /// Serve `listener` with `token` on threads of their own, at most [`MAX_CONNECTIONS`] + /// connections at once. `patient`: every request may wait as long as a batch (a person decides + /// on it). A listener that is not on a loopback address is refused: the channel never goes on + /// the network. + pub fn listen(self: &Arc, listener: TcpListener, token: String, requests: Sender, patient: bool) -> std::io::Result<()> { + self.listen_stoppable(listener, token, requests, patient).map(drop) + } + + /// [`Hub::listen`], and a [`Stop`] that closes the listener and the connections it accepted + /// (a channel turned off in the app's settings). Dropping the [`Stop`] leaves it serving. + pub fn listen_stoppable( + self: &Arc, + listener: TcpListener, + token: String, + requests: Sender, + patient: bool, + ) -> std::io::Result { + let addr = listener.local_addr()?; + if !addr.ip().is_loopback() { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("the control channel listens on loopback only, not {addr}"))); + } + let hub = Arc::clone(self); + let token = Arc::new(token); + let shared = Arc::new(Accepted::default()); + let (closed_tx, closed) = channel::<()>(); + let stop = Stop { addr, shared: Arc::clone(&shared), closed }; + std::thread::spawn(move || { + // Dropped when this thread ends, with the listener: `Stop::stop` waits for that. + let _closed = closed_tx; + for stream in listener.incoming().flatten() { + if shared.stopped.load(Ordering::SeqCst) { + break; + } + if hub.open.fetch_add(1, Ordering::Relaxed) >= MAX_CONNECTIONS { + hub.open.fetch_sub(1, Ordering::Relaxed); + let mut refused = stream; + let _ = send(&mut refused, &json!({"ok": false, "error": "too many connections"})); + continue; + } + let id = shared.next.fetch_add(1, Ordering::Relaxed); + if let Ok(copy) = stream.try_clone() { + shared.lock().push((id, copy)); + } + // Stopped while this one was being accepted: it is closed with the rest. + if shared.stopped.load(Ordering::SeqCst) { + shared.close_all(); + } + let (hub, tx, token, shared) = (Arc::clone(&hub), requests.clone(), Arc::clone(&token), Arc::clone(&shared)); + std::thread::spawn(move || { + hub.serve(stream, &token, tx, patient); + hub.open.fetch_sub(1, Ordering::Relaxed); + shared.lock().retain(|(i, _)| *i != id); + }); + } + // A captured value drops after the body's locals, so without this `_closed` would tell + // `Stop::stop` the port is free while the listener still holds it (#14752). + drop(listener); + }); + Ok(stop) + } +} + +/// The connections a stoppable listener accepted, so stopping it can close them too. +#[derive(Default)] +struct Accepted { + stopped: AtomicBool, + next: AtomicU64, + streams: Mutex>, +} + +impl Accepted { + fn lock(&self) -> MutexGuard<'_, Vec<(u64, TcpStream)>> { + self.streams.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn close_all(&self) { + for (_, stream) in self.lock().drain(..) { + let _ = stream.shutdown(std::net::Shutdown::Both); + } + } +} + +/// Stops a listener started with [`Hub::listen_stoppable`]. +pub struct Stop { + addr: std::net::SocketAddr, + shared: Arc, + closed: Receiver<()>, +} + +impl Stop { + /// The port the listener is on. + pub fn port(&self) -> u16 { + self.addr.port() + } + + /// Stop accepting, close the port and end every connection it accepted. Returns once the + /// port is closed (at most a couple of seconds), so the same port can be bound again at once. + pub fn stop(self) { + self.shared.stopped.store(true, Ordering::SeqCst); + // The listener waits in `accept`: a connection of our own wakes it to see the flag. + let _ = TcpStream::connect_timeout(&self.addr, Duration::from_secs(1)); + let _ = self.closed.recv_timeout(Duration::from_secs(2)); + self.shared.close_all(); + } +} + +/// Connections served at once, so a flood must not be able to spawn threads without end. +pub const MAX_CONNECTIONS: usize = 16; +/// Lines that are not JSON before the connection is closed, so garbage cannot loop forever. +const MAX_BAD_LINES: usize = 8; +/// How long a subscribed connection waits after a `design.changed` line before the next: what +/// changes meanwhile (a parameter dragged) goes out as one line, the latest (#6985). +const EVENT_GAP: Duration = Duration::from_millis(100); +/// How long a new connection has to show the token. A client connects when it has a request to +/// send, so this is plenty; one that doesn't send it loses the connection, and its seat among +/// [`MAX_CONNECTIONS`] goes to someone else. +const TOKEN_WAIT: Duration = Duration::from_secs(5); + +/// A new random token: 32 bytes from the operating system, as hex. +pub fn new_token() -> Option { + let mut bytes = [0u8; 32]; + getrandom::fill(&mut bytes).ok()?; + Some(bytes.iter().map(|b| format!("{b:02x}")).collect()) +} + +/// One line without its newline, or `None` at the end of the stream. A client that sends +/// gigabytes with no newline would otherwise make this thread allocate until the process is +/// killed, so the line is refused as soon as it passes `max`. +fn read_line(r: &mut impl BufRead, max: usize) -> std::io::Result>> { + let mut line = Vec::new(); + loop { + let (done, used) = { + let available = r.fill_buf()?; + if available.is_empty() { + return Ok((!line.is_empty()).then_some(line)); + } + match available.iter().position(|b| *b == b'\n') { + Some(i) => { + line.extend_from_slice(available.get(..i).unwrap_or(&[])); + (true, i + 1) + } + None => { + line.extend_from_slice(available); + (false, available.len()) + } + } + }; + r.consume(used); + if done { + return Ok(Some(line)); + } + if line.len() > max { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "request too large")); + } + } +} + +/// A reply line, written to the socket at once. `writeln!` with a JSON value hands the socket each +/// of its pieces apart, a system call for every string, number and comma: half a second for a +/// design's component tree when it has thousands of components. +fn send(out: &mut impl Write, reply: &Value) -> std::io::Result<()> { + let mut line = serde_json::to_vec(reply).map_err(std::io::Error::other)?; + line.push(b'\n'); + out.write_all(&line) +} + +/// The `"token"` of a request line that is a JSON object, read without building the rest of it. +/// Until a connection shows the token, a line costs only its own bytes: parsed whole, a 16 MiB +/// line of `[0,0,…]` is hundreds of MB, and 16 such connections could exhaust memory before any +/// token was checked. +fn token_of(line: &str) -> Option { + struct Token; + impl<'de> serde::de::Visitor<'de> for Token { + type Value = Option; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a request object") + } + fn visit_map>(self, mut map: A) -> Result { + let mut token = None; + while let Some(key) = map.next_key::()? { + if key == "token" { + token = Some(map.next_value::()?); + } else { + map.next_value::()?; + } + } + Ok(token) + } + } + let mut de = serde_json::Deserializer::from_str(line); + let token = serde::Deserializer::deserialize_map(&mut de, Token).ok()?; + de.end().ok()?; + token +} + +/// The reply to a connection that didn't show the token, naming the app's `docs`; the +/// connection is then closed. +fn unauthorized(docs: &str) -> Value { + json!({"ok": false, "error": format!("unauthorized: send the control token as \"token\" (see {docs})")}) +} + +/// Refuse the connection: the reply, then the end of what we send, then what the client had +/// already sent read and dropped (a little, briefly). Closing a socket with unread input resets +/// the connection, and a reset can reach the client before it has read the refusal. +fn refuse(out: &mut TcpStream, reader: &mut BufReader, docs: &str) { + use std::io::Read; + let _ = send(out, &unauthorized(docs)); + let _ = out.shutdown(std::net::Shutdown::Write); + reader.get_mut().deadline = Some(Instant::now() + Duration::from_millis(500)); + let _ = std::io::copy(&mut reader.by_ref().take(64 * 1024), &mut std::io::sink()); +} + +/// What a client sends. Until it shows the token, all of its reads share one deadline, so neither +/// blank lines nor a line sent a byte at a time buy it more time. After that it may stay idle as +/// long as it likes. +struct ClientInput { + socket: TcpStream, + deadline: Option, +} + +impl ClientInput { + /// No deadline any more: the client showed the token. + fn admit(&mut self) -> std::io::Result<()> { + self.deadline = None; + self.socket.set_read_timeout(None) + } +} + +impl std::io::Read for ClientInput { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if let Some(deadline) = self.deadline { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err(std::io::ErrorKind::TimedOut.into()); + } + self.socket.set_read_timeout(Some(left))?; + } + self.socket.read(buf) + } +} + +/// How long a request waits for the app's reply: most requests, and a batch (or every request, +/// on a patient connection); and how long a new connection has to show the token. +#[derive(Clone, Copy, Debug)] +pub struct Waits { + pub short: Duration, + pub long: Duration, + pub token: Duration, +} + +impl Default for Waits { + fn default() -> Self { + Waits { short: Duration::from_secs(60), long: Duration::from_secs(3600), token: TOKEN_WAIT } + } +} + +/// A request that timed out but is still running in the app (#1618): its id and method, and where +/// its reply will land. +struct Pending { + id: Value, + method: String, + /// The request in messages ("`engine.execute` (solid.fillet)"). + what: String, + reply: Receiver, + /// Where it is in the app, to cancel it (`control.cancel`). + job: Arc, +} + +/// `control.cancel {id?}`: cancel the request this connection still waits for (the one +/// `control.pending` reports; `id`, when given, must name it). A connection can only cancel its +/// own requests. Waiting its turn, it is removed; computing off the window thread, it is stopped +/// as the app's Stop stops it. Either way nothing of it is applied and the connection is free. +/// One that runs on the window thread can't be cancelled; one that finished is answered. +fn cancel(pending: &mut Option, late: Option, id: Option<&Value>, document: &str) -> Value { + let id = id.filter(|v| !v.is_null()); + let mine = pending.as_ref().filter(|p| id.is_none_or(|id| *id == p.id)); + let Some(p) = mine else { + return match id { + None => json!({"ok": true, "result": {"cancelled": null, "note": "nothing to cancel: no request of this connection is running"}}), + Some(id) => json!({"ok": false, "error": format!( + "nothing to cancel: request {} is not running on this connection (a connection can only cancel its own requests)", + id.to_string().chars().take(64).collect::() + )}), + }; + }; + let (what, id) = (format!("request {} ({})", p.id, p.what), p.id.clone()); + let finished = |p: Pending, reply: Value| { + json!({"ok": true, "result": {"cancelled": null, "pending": p.id, "method": p.method, "done": true, "reply": reply, + "note": format!("nothing to cancel: {what} had already finished; its reply is here")}}) + }; + if let Some(reply) = late { + return pending.take().map_or(Value::Null, |p| finished(p, reply)); + } + let outcome = p.job.cancel(); + let note = match outcome { + Cancel::Removed => format!("cancelled: {what} was still waiting its turn and will not run; nothing was applied"), + Cancel::Stopped { writes_file: false } => format!("stopped: {what} was computing off the window thread; nothing was applied"), + Cancel::Stopped { writes_file: true } => { + format!("stopped: {what} was computing on a copy of the {document}, which is unchanged; its worker may still write the file") + } + Cancel::Already => format!("{what} was already cancelled or stopped; nothing of it was applied"), + Cancel::Running => { + // It may have just finished. + if let Some(reply) = pending.as_ref().and_then(|p| p.reply.try_recv().ok()) { + return pending.take().map_or(Value::Null, |p| finished(p, reply)); + } + return json!({"ok": false, "cancellable": false, "error": format!( + "cannot be cancelled: {what} already runs in the app (on its window thread, or as a file it opens) and will \ + still finish; ask `control.pending` for its result. Only a request still waiting its turn, or a change or \ + export computing off the window thread, can be cancelled" + )}); + } + }; + let method = pending.take().map(|p| p.method); + let how = match outcome { + Cancel::Removed => "removed", + Cancel::Stopped { .. } => "stopped", + _ => "already", + }; + json!({"ok": true, "result": {"cancelled": id, "method": method, "outcome": how, "note": note}}) +} + +/// Every request the app has been sent and not answered yet, from every connection, for +/// `control.running` (#3654). Each connection's own thread answers that, so it never waits behind +/// a running request. +struct Running { + list: Mutex>, + connections: AtomicU64, + keys: AtomicU64, +} + +/// What `control.running` says about a request: never its parameters beyond the command id. +struct InFlight { + key: u64, + connection: u64, + id: Value, + method: String, + command: Option<&'static str>, + steps: Option, + since: Instant, + started: Arc, +} + +impl Running { + fn new() -> Self { + Running { list: Mutex::new(Vec::new()), connections: AtomicU64::new(0), keys: AtomicU64::new(0) } + } + + fn lock(&self) -> MutexGuard<'_, Vec> { + self.list.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// List `req`, sent on `connection`, until the returned ticket is dropped; `command` and + /// `steps` as the app's [`Protocol`] summarised it. + fn add(self: &Arc, connection: u64, id: &Value, req: &ControlRequest, command: Option<&'static str>, steps: Option) -> Listing { + let key = self.keys.fetch_add(1, Ordering::Relaxed); + // Ids and methods come from the client: only short ones are repeated to the others. + let id = match id { + Value::Number(_) => id.clone(), + Value::String(s) if s.len() <= 64 => id.clone(), + _ => Value::Null, + }; + let method = req.method.chars().take(64).collect(); + let started = req.started.clone(); + self.lock().push(InFlight { key, connection, id, method, command, steps, since: Instant::now(), started }); + Listing { running: Arc::clone(self), key } + } + + /// The `control.running` result, as `asker`'s connection sees it. + fn result(&self, asker: u64) -> Value { + let rows: Vec = self + .lock() + .iter() + .map(|e| { + let mut r = json!({ + "connection": e.connection, + "id": e.id, + "method": e.method, + "running_s": (e.since.elapsed().as_secs_f64() * 10.0).round() / 10.0, + "queued": !e.started.load(Ordering::Relaxed), + }); + if let Some(c) = e.command { + r["command"] = json!(c); + } + if let Some(n) = e.steps { + r["steps"] = json!(n); + } + if e.connection == asker { + r["self"] = json!(true); + } + r + }) + .collect(); + json!({"running": rows}) + } +} + +/// A listed request; dropped when its reply arrives. +struct Listing { + running: Arc, + key: u64, +} + +impl Drop for Listing { + fn drop(&mut self) { + let key = self.key; + self.running.lock().retain(|e| e.key != key); + } +} + +/// The reply to a timed-out request, received on a thread of its own so the request stays listed +/// until the app answers, also once its connection has closed (#3654). +fn watch(reply: Receiver, ticket: Listing) -> Receiver { + let (late_tx, late_rx) = channel(); + // A small thread per timed-out request (each connection has at most one). If none can be + // made, the reply is lost and `control.pending` says the app ended the request without one. + // The reply is passed on before the request leaves the list: once `control.running` no longer + // shows it, its connection's `control.pending` has it. + let _ = std::thread::Builder::new().stack_size(64 * 1024).spawn(move || { + if let Ok(v) = reply.recv() { + let _ = late_tx.send(v); + } + drop(late_tx); + drop(ticket); + }); + late_rx +} + +/// The reply text for a request that outlasts its wait. A request that only reads changes +/// nothing when it finishes; an export or a save still writes its file, and any other request +/// still applies, as it was not cancelled. +pub fn timeout_message(what: &str, effect: Effect, document: &str) -> String { + match effect { + Effect::ReadsOnly => { + format!("timeout: {what} is still running in the app ({}); ask `control.pending` for its answer", effect.when_done(document)) + } + Effect::WritesFile => format!( + "timeout: {what} is still running in the app and will still write the file when it finishes (it was not cancelled: \ + don't send it again; the {document} does not change); ask `control.pending` for its result, or `control.cancel` to \ + cancel it" + ), + Effect::Changes => format!( + "timeout: {what} is still running in the app and will still apply when it finishes (it was not cancelled: don't send it \ + again); ask `control.pending` for its result, or `control.cancel` to cancel it" + ), + } +} + +/// The reply text for a request refused because an earlier one on the connection still runs. +fn busy_message(p: &Pending, method: &str) -> String { + let method: String = method.chars().take(128).collect(); + format!( + "busy: request {} ({}) is still running, so `{method}` was not run; ask `control.pending` for that request's result, then \ + send this one again", + p.id, p.what + ) +} + +/// A subscribed connection's socket, for its replies and its events: each line is written whole +/// and alone, so an event never lands inside a reply (#6985). +struct Lines { + socket: TcpStream, + turn: Mutex<()>, +} + +impl Lines { + fn send(&self, line: &Value) -> std::io::Result<()> { + let _turn = self.turn.lock().unwrap_or_else(PoisonError::into_inner); + send(&mut &self.socket, line) + } +} + +/// A subscribed connection's seat on the watch: it leaves exactly once, whichever thread sees +/// the connection's end first — the connection's own thread at the end of the stream, or the +/// events thread at the first write a closed client refuses. The seat used to wait for the +/// events thread alone, and that thread only leaves its wait when the design moves, so the +/// count could outlive the connection by a second or more (#8315). +struct Seat(Mutex>); + +impl Seat { + fn new(counted: Subscriber) -> Self { + Seat(Mutex::new(Some(counted))) + } + + /// Leave the watch now: the seat goes once, whoever gets here first. + fn release(&self) { + let counted = self.0.lock().unwrap_or_else(PoisonError::into_inner).take(); + drop(counted); + } +} + +impl Drop for Seat { + fn drop(&mut self) { + self.release(); + } +} + +/// A connection's `control.subscribe` (#6985): its `design.changed` lines, sent from a thread of +/// their own until the connection ends. +struct Subscription { + lines: Arc, + stop: Arc, + seat: Arc, +} + +impl Subscription { + /// Write `reply`, the window's answer to `control.subscribe` naming the design `seen`, on + /// `out`, then send `design`'s changes after it: the reply goes out before any event. `None`, + /// with nothing written, when no thread or socket was left for the events. + fn start( + watch: &'static DocumentWatch, + event: &'static str, + counted: Subscriber, + out: &TcpStream, + seen: (String, u64), + reply: &Value, + ) -> Option<(Self, std::io::Result<()>)> { + let lines = Arc::new(Lines { socket: out.try_clone().ok()?, turn: Mutex::new(()) }); + let stop = Arc::new(AtomicBool::new(false)); + let seat = Arc::new(Seat::new(counted)); + let first = lines.turn.lock().unwrap_or_else(PoisonError::into_inner); + let (l, s, watch_seat) = (lines.clone(), stop.clone(), Arc::clone(&seat)); + // The connection's seat on the watch rides the events thread: it leaves when the thread + // does, so the next failed write to a closed client retires it even while the connection's + // own thread is slow to see the end of the stream (#7226). The connection's own thread + // leaves it too, so a closed connection stops counting at once (#8315). + std::thread::Builder::new().stack_size(64 * 1024).spawn(move || send_events(watch, event, &l, &s, seen, watch_seat)).ok()?; + let sent = send(&mut &lines.socket, reply); + drop(first); + Some((Subscription { lines, stop, seat }, sent)) + } +} + +/// The design a `control.subscribe` reply names. +fn document_of(reply: &Value) -> Option<(String, u64)> { + let result = reply.get("result")?; + Some((result.get("document_id")?.as_str()?.to_string(), result.get("revision")?.as_u64()?)) +} + +impl Drop for Subscription { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + // The seat on the watch goes now: the connection is over, and nothing counts it any more + // (#8315). + self.seat.release(); + // The socket closes now, not when the thread next looks; a line blocked on a client that + // stopped reading ends too. + let _ = self.lines.socket.shutdown(std::net::Shutdown::Both); + } +} + +/// The `design.changed` lines of a subscribed connection, each time the design differs from the +/// last one it was told of (`seen`), until `stop`. Holds the connection's seat on the watch +/// (`seat`), which it leaves when the thread ends: on `stop`, or on the first write a closed +/// client refuses (#7226). +fn send_events(watch: &DocumentWatch, event: &str, lines: &Lines, stop: &AtomicBool, mut seen: (String, u64), seat: Arc) { + while !stop.load(Ordering::Relaxed) { + let Some(now) = watch.wait(&seen, stop, Duration::from_secs(1)).filter(|now| *now != seen) else { continue }; + if lines.send(&json!({"event": event, "params": {"document_id": now.0, "revision": now.1}})).is_err() { + break; + } + seen = now; + std::thread::sleep(EVENT_GAP); + } + // The client is gone: it is not counted on the watch any more, whatever the connection's own + // thread still has to notice (#8315). + seat.release(); +} + +/// Write `reply` on the connection: through its subscription once it has one. +fn answer(out: &mut TcpStream, events: Option<&Subscription>, reply: &Value) -> std::io::Result<()> { + match events { + Some(e) => e.lines.send(reply), + None => send(out, reply), + } +} + +impl Hub { + /// Serve one connection until it closes: the token first, then one request per line, each + /// sent to the window on `requests` and its reply written back. + pub fn serve(&self, stream: TcpStream, token: &str, requests: Sender, patient: bool) { + let (waits, running, documents, tx) = (self.waits, &self.running, self.watch, requests); + let connection = running.connections.fetch_add(1, Ordering::Relaxed) + 1; + let Ok(read) = stream.try_clone() else { return }; + let mut out = stream; + let mut reader = BufReader::new(ClientInput { socket: read, deadline: Some(Instant::now() + waits.token) }); + let mut bad = 0usize; + let mut authenticated = false; + let mut pending: Option = None; + let mut events: Option = None; + loop { + // A first `control.subscribe` on its way to the window (#6985). + let mut joining = None; + let line = match read_line(&mut reader, self.max_line) { + Ok(Some(l)) => String::from_utf8_lossy(&l).into_owned(), + Ok(None) => break, + // Closed without a word: a client that connected early and only now sends its first + // request would read a line here as the reply to it. It finds the connection closed + // and opens another. + Err(e) if !authenticated && matches!(e.kind(), std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock) => break, + Err(e) => { + let _ = answer(&mut out, events.as_ref(), &json!({"ok": false, "error": e.to_string()})); + break; + } + }; + if line.trim().is_empty() { + continue; + } + // The first request must carry the token; later ones on the same connection may. + if !authenticated { + match token_of(&line) { + Some(t) if tokens_match(&t, token) => { + if reader.get_mut().admit().is_err() { + break; + } + authenticated = true; + } + _ => { + refuse(&mut out, &mut reader, self.protocol.docs()); + break; + } + } + } + let reply = match serde_json::from_str::(&line) { + Ok(msg) => { + let id = msg.get("id").cloned().unwrap_or(Value::Null); + let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string(); + let params = msg.get("params").cloned().unwrap_or(json!({})); + // A request that timed out may have finished since (#1618). `control.running` and + // `control.capabilities` only look, so they leave that reply where it is. + let late = pending.as_ref().filter(|_| !matches!(method.as_str(), "control.running" | "control.capabilities")).and_then(|p| { + match p.reply.try_recv() { + Ok(reply) => Some(reply), + Err(TryRecvError::Disconnected) => Some(json!({"ok": false, "error": "the app ended the request without a reply"})), + Err(TryRecvError::Empty) => None, + } + }); + let mut r = if method == "control.running" { + json!({"ok": true, "result": running.result(connection)}) + } else if method == "control.capabilities" { + json!({"ok": true, "result": self.protocol.capabilities()}) + } else if method == "control.cancel" { + let r = cancel(&mut pending, late, params.get("id"), self.protocol.document()); + (self.wake)(); + r + } else if method == "control.pending" { + match (pending.take(), late) { + (None, _) => json!({"ok": true, "result": {"pending": null}}), + (Some(p), Some(reply)) => { + json!({"ok": true, "result": {"pending": p.id, "method": p.method, "done": true, "reply": reply}}) + } + (Some(p), None) => { + let r = json!({"ok": true, "result": {"pending": p.id, "method": p.method, "done": false}}); + pending = Some(p); + r + } + } + } else if let Some(p) = pending.as_ref().filter(|_| late.is_none()) { + // Nothing more is queued behind it, to run unseen when it ends. + json!({"ok": false, "busy": true, "error": busy_message(p, &method)}) + } else if method == "control.subscribe" && events.is_some() { + if late.is_some() { + // As below: finished, and the client moved on without asking. + pending = None; + } + // Its events already say how the design moves; a second answer could only + // arrive behind a newer one. + { + let (event, revision, document) = + (self.protocol.change_event(), self.protocol.revision_method(), self.protocol.document()); + json!({"ok": false, "error": format!("already subscribed: this connection is sent {event} lines; ask {revision} for the {document} now")}) + } + } else { + if late.is_some() { + // Finished, and the client moved on without asking: it is dropped. + pending = None; + } + // A batch replaces many short requests: the whole of it may take long (#743). + let Summary { what, effect, command, steps, long } = self.protocol.summary(&method, ¶ms); + let wait = if patient || long { waits.long } else { waits.short }; + // Counted before the window answers, so it publishes every change from its + // answer on. + joining = (method == "control.subscribe").then(|| documents.join()); + let (req, rrx) = ControlRequest::new(method.clone(), params); + let job = Arc::clone(&req.ticket); + let ticket = running.add(connection, &id, &req, command, steps); + if tx.send(req).is_err() { + break; + } + (self.wake)(); + match rrx.recv_timeout(wait) { + Ok(r) => r, + Err(_) => { + let r = json!({"ok": false, "running": true, "error": timeout_message(&what, effect, self.protocol.document())}); + pending = Some(Pending { id: id.clone(), method, what, reply: watch(rrx, ticket), job }); + r + } + } + }; + if let Some(o) = r.as_object_mut() { + o.insert("id".into(), id); + } + r + } + Err(e) => { + bad += 1; + json!({"ok": false, "error": format!("bad JSON: {e}")}) + } + }; + // Subscribed once the window named the design (not when it refused or timed out). + let sent = match joining.zip(document_of(&reply)) { + Some((counted, seen)) => match Subscription::start(documents, self.protocol.change_event(), counted, &out, seen, &reply) { + Some((subscription, sent)) => { + events = Some(subscription); + sent + } + None => send( + &mut out, + &json!({"id": reply.get("id"), "ok": false, "error": "not subscribed: no thread or socket left for the events"}), + ), + }, + None => answer(&mut out, events.as_ref(), &reply), + }; + if sent.is_err() { + break; + } + if bad >= MAX_BAD_LINES { + break; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The longest request line, as an app might accept. + const MAX_LINE: usize = 16 << 20; + + /// An app whose requests all may change its document and take the short wait. + struct Plain; + + impl Protocol for Plain { + 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!({}) + } + } + + /// A server for [`Plain`] with these waits and this document watch. + fn hub(waits: Waits, watch: &'static DocumentWatch) -> Arc { + Arc::new(Hub::new(Plain, || {}, MAX_LINE).with_waits(waits).with_watch(watch)) + } + + /// The channel never goes on the network: a listener on any address but loopback is refused, + /// and nothing is served on it. + #[test] + fn a_listener_off_loopback_is_refused() { + let (tx, _rx) = channel::(); + let open = TcpListener::bind("0.0.0.0:0").unwrap(); + let e = hub(Waits::default(), &DOCUMENT_WATCH).listen(open, "0123456789abcdef0123456789abcdef".into(), tx.clone(), false).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput, "{e}"); + assert!(e.to_string().contains("loopback only"), "{e}"); + let local = TcpListener::bind("127.0.0.1:0").unwrap(); + assert!(hub(Waits::default(), &DOCUMENT_WATCH).listen(local, "0123456789abcdef0123456789abcdef".into(), tx, false).is_ok()); + } + + /// A connection that doesn't show the token in time is closed without a word, however it fills + /// the time. One that does keeps working when it idles for longer than that. + #[test] + fn the_token_has_a_time_limit_and_an_authenticated_client_may_idle() { + use std::io::Read; + let token = "0123456789abcdef0123456789abcdef"; + let limit = Duration::from_millis(500); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + std::thread::spawn(move || { + for req in rx { + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + }); + let waits = Waits { short: Duration::from_secs(10), long: Duration::from_secs(10), token: limit }; + let hub = hub(waits, &DOCUMENT_WATCH); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let (tx, hub) = (tx.clone(), Arc::clone(&hub)); + std::thread::spawn(move || hub.serve(stream, token, tx, false)); + } + }); + let open = || { + let s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(20))).unwrap(); + s + }; + // Sends `drip` every 50 ms until the server closes; what it read, and when it closed. + let closed_after = |drip: &[u8]| { + let mut s = open(); + let start = Instant::now(); + s.set_read_timeout(Some(Duration::from_millis(50))).unwrap(); + let mut got = Vec::new(); + loop { + let mut buf = [0u8; 256]; + match s.read(&mut buf) { + Ok(0) => break, + Ok(n) => got.extend_from_slice(buf.get(..n).unwrap()), + Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => { + assert!(start.elapsed() < Duration::from_secs(20), "still open"); + let _ = s.write_all(drip); + } + Err(_) => break, + } + } + (got, start.elapsed()) + }; + for drip in [&b""[..], b"\n", b"\r\n \n", b" ", b"{"] { + let (got, took) = closed_after(drip); + assert!(got.is_empty(), "{drip:?} was answered: {}", String::from_utf8_lossy(&got)); + assert!(took >= limit.saturating_sub(Duration::from_millis(50)), "{drip:?} closed after {took:?}"); + } + + let mut s = open(); + let mut lines = BufReader::new(s.try_clone().unwrap()); + let mut ask = |line: Value| -> Value { + writeln!(s, "{line}").unwrap(); + let mut l = String::new(); + lines.read_line(&mut l).unwrap(); + serde_json::from_str(&l).unwrap() + }; + assert_eq!(ask(json!({"id": 1, "method": "ui.view", "token": token}))["ok"], true); + std::thread::sleep(limit * 3); + assert_eq!(ask(json!({"id": 2, "method": "ui.view"}))["ok"], true, "idle for longer than the limit"); + + // A wrong token is still answered, at once. + let mut wrong = open(); + writeln!(wrong, "{}", json!({"id": 1, "method": "ui.view", "token": "nope"})).unwrap(); + let mut l = String::new(); + BufReader::new(wrong).read_line(&mut l).unwrap(); + assert!(l.contains("unauthorized"), "{l}"); + } + + /// #1989: `control.cancel` cancels the connection's own outstanding request. One still + /// waiting its turn is removed and never runs, and the connection is free at once; one that + /// already runs in the app can't be, and says so; another connection's request is refused; + /// with nothing outstanding there is nothing to cancel. + #[test] + fn control_cancel_cancels_only_this_connections_request() { + let token = "0123456789abcdef0123456789abcdef"; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + let (gate_tx, gate_rx) = channel::<()>(); + let ran = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let seen = ran.clone(); + // A stand-in for the window thread: `queued` waits behind the others (never taken until + // `slow` is done), `slow` runs until the gate opens. + std::thread::spawn(move || { + let mut held = Vec::new(); + for req in rx { + if req.method == "queued" { + held.push(req); + continue; + } + if !req.ticket.take() { + continue; + } + seen.lock().unwrap().push(req.method.clone()); + if req.method == "slow" { + let _ = gate_rx.recv(); + } + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + if req.method == "slow" { + for req in held.drain(..) { + if req.ticket.take() { + seen.lock().unwrap().push(req.method.clone()); + } + } + } + } + }); + let waits = Waits { short: Duration::from_millis(100), long: Duration::from_millis(100), token: TOKEN_WAIT }; + let hub = hub(waits, &DOCUMENT_WATCH); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let (tx, hub) = (tx.clone(), Arc::clone(&hub)); + std::thread::spawn(move || hub.serve(stream, token, tx, false)); + } + }); + let connect = || { + let s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + let out = s.try_clone().unwrap(); + (out, BufReader::new(s)) + }; + let ask = |(out, lines): &mut (TcpStream, BufReader), v: Value| -> Value { + writeln!(out, "{v}").unwrap(); + let mut l = String::new(); + lines.read_line(&mut l).unwrap(); + serde_json::from_str(&l).unwrap() + }; + let mut a = connect(); + let mut b = connect(); + let r = ask(&mut b, json!({"id": 1, "method": "control.cancel", "token": token})); + assert!(r["ok"] == true && r["result"]["cancelled"].is_null(), "nothing to cancel: {r}"); + + // Waiting its turn: removed, never run, and the connection is free. + let r = ask(&mut a, json!({"id": 1, "method": "queued", "token": token})); + assert_eq!(r["running"], true, "{r}"); + let r = ask(&mut a, json!({"id": 2, "method": "control.cancel", "params": {"id": 1}})); + assert_eq!((&r["ok"], &r["result"]["cancelled"], &r["result"]["outcome"]), (&json!(true), &json!(1), &json!("removed")), "{r}"); + assert!(r["result"]["note"].as_str().is_some_and(|n| n.contains("will not run")), "{r}"); + let r = ask(&mut a, json!({"id": 3, "method": "control.pending"})); + assert_eq!(r["result"]["pending"], Value::Null, "{r}"); + + // Already running in the app: it can't be, and it still answers. + let r = ask(&mut a, json!({"id": 4, "method": "slow"})); + assert_eq!(r["running"], true, "{r}"); + let r = ask(&mut b, json!({"id": 2, "method": "control.cancel", "params": {"id": 4}})); + assert!(r["ok"] == false && r["error"].as_str().is_some_and(|e| e.contains("its own requests")), "another connection's: {r}"); + let r = ask(&mut a, json!({"id": 5, "method": "control.cancel", "params": {"id": 99}})); + assert!(r["ok"] == false && r["error"].as_str().is_some_and(|e| e.starts_with("nothing to cancel")), "{r}"); + let r = ask(&mut a, json!({"id": 6, "method": "control.cancel"})); + assert!(r["ok"] == false && r["cancellable"] == false, "{r}"); + assert!(r["error"].as_str().is_some_and(|e| e.starts_with("cannot be cancelled") && e.contains("control.pending")), "{r}"); + gate_tx.send(()).unwrap(); + let deadline = Instant::now() + Duration::from_secs(10); + let r = loop { + let r = ask(&mut a, json!({"id": 7, "method": "control.pending"})); + if r["result"]["done"] == true || Instant::now() > deadline { + break r; + } + std::thread::sleep(Duration::from_millis(10)); + }; + assert_eq!(r["result"]["reply"]["result"], "slow", "{r}"); + let r = ask(&mut a, json!({"id": 8, "method": "control.cancel"})); + assert!(r["ok"] == true && r["result"]["cancelled"].is_null(), "{r}"); + assert_eq!(*ran.lock().unwrap(), ["slow"], "the cancelled request never ran"); + } + + /// #1618: a request that outlasts its wait says it is still running; the connection keeps its + /// reply for `control.pending`, and refuses other requests as `busy` until it lands, so none + /// is queued to run unseen behind it. + #[test] + fn a_timed_out_request_can_be_asked_for_later() { + let token = "0123456789abcdef0123456789abcdef"; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + // The slow request is held until the test has seen it time out, so the test does not + // race the clock on a loaded machine. + let (gate_tx, gate_rx) = channel::<()>(); + let ran = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let seen = ran.clone(); + std::thread::spawn(move || { + for req in rx { + seen.lock().unwrap().push(req.method.clone()); + if req.method == "slow" { + let _ = gate_rx.recv(); + } + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + }); + let waits = Waits { short: Duration::from_millis(100), long: Duration::from_millis(100), token: TOKEN_WAIT }; + let hub = hub(waits, &DOCUMENT_WATCH); + std::thread::spawn(move || { + if let Some(stream) = listener.incoming().flatten().next() { + hub.serve(stream, token, tx, false); + } + }); + let s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + let mut out = s.try_clone().unwrap(); + let mut lines = BufReader::new(s); + let mut ask = |v: Value| -> Value { + writeln!(out, "{v}").unwrap(); + let mut l = String::new(); + lines.read_line(&mut l).unwrap(); + serde_json::from_str(&l).unwrap() + }; + let r = ask(json!({"id": 1, "method": "slow", "token": token})); + assert!(r["ok"] == false && r["running"] == true && r["error"].as_str().is_some_and(|e| e.starts_with("timeout")), "{r}"); + let r = ask(json!({"id": 2, "method": "ui.view"})); + assert!(r["busy"] == true && r["id"] == 2, "{r}"); + let r = ask(json!({"id": 3, "method": "control.pending"})); + assert_eq!((&r["result"]["pending"], &r["result"]["done"]), (&json!(1), &json!(false)), "{r}"); + gate_tx.send(()).unwrap(); + let deadline = std::time::Instant::now() + Duration::from_secs(10); + let r = loop { + let r = ask(json!({"id": 4, "method": "control.pending"})); + if r["result"]["done"] == true || std::time::Instant::now() > deadline { + break r; + } + std::thread::sleep(Duration::from_millis(10)); + }; + assert_eq!( + (&r["result"]["pending"], &r["result"]["done"], &r["result"]["reply"]["result"]), + (&json!(1), &json!(true), &json!("slow")), + "{r}" + ); + let r = ask(json!({"id": 5, "method": "control.pending"})); + assert_eq!(r["result"]["pending"], Value::Null, "{r}"); + let r = ask(json!({"id": 6, "method": "ui.view"})); + assert_eq!((&r["ok"], &r["result"]), (&json!(true), &json!("ui.view")), "{r}"); + assert_eq!(*ran.lock().unwrap(), ["slow", "ui.view"], "the busy request never reached the app"); + } + + /// #6985: a connection that sends `control.subscribe` gets the design in the reply, then a + /// `design.changed` line each time the window publishes another: never before the reply, + /// none for the same design, the latest after a burst, each line whole between its replies. + /// A second subscribe is refused without reaching the window. A connection that did not + /// subscribe gets no events, and one that closed is no longer counted. + #[test] + fn subscribed_connections_are_told_of_design_changes() { + static WATCH: DocumentWatch = DocumentWatch::new(); + let token = "0123456789abcdef0123456789abcdef"; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + // The window: it answers `control.subscribe` as the app does, publishing the design first; + // then the design changes at once, before the reply may have been written. + std::thread::spawn(move || { + for req in rx { + if req.method == "control.subscribe" { + WATCH.publish("d-1", 3); + let _ = req.reply.send(json!({"ok": true, "result": {"document_id": "d-1", "revision": 3}})); + WATCH.publish("d-1", 4); + } else { + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + } + }); + let hub = hub(Waits::default(), &WATCH); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let (tx, hub) = (tx.clone(), Arc::clone(&hub)); + std::thread::spawn(move || hub.serve(stream, token, tx, false)); + } + }); + let open = || { + let s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + (s.try_clone().unwrap(), BufReader::new(s)) + }; + let next = |lines: &mut BufReader| -> Value { + let mut l = String::new(); + lines.read_line(&mut l).unwrap(); + serde_json::from_str(&l).unwrap() + }; + let changed = |id: &str, revision: u64| json!({"event": "design.changed", "params": {"document_id": id, "revision": revision}}); + + let (mut quiet_out, mut quiet) = open(); + writeln!(quiet_out, "{}", json!({"id": 1, "method": "ui.view", "token": token})).unwrap(); + assert_eq!(next(&mut quiet)["id"], 1); + + let (mut out, mut lines) = open(); + writeln!(out, "{}", json!({"id": 1, "method": "control.subscribe", "token": token})).unwrap(); + assert_eq!(next(&mut lines), json!({"id": 1, "ok": true, "result": {"document_id": "d-1", "revision": 3}})); + assert_eq!(next(&mut lines), changed("d-1", 4), "the change after the window's answer comes after the reply"); + assert!(WATCH.subscribed()); + // The design it was told of is no news; another revision is. + WATCH.publish("d-1", 4); + WATCH.publish("d-1", 5); + assert_eq!(next(&mut lines), changed("d-1", 5)); + // A burst ends with its latest. + for revision in 6..=10 { + WATCH.publish("d-1", revision); + } + let mut last = 5; + while last < 10 { + let e = next(&mut lines); + let revision = e["params"]["revision"].as_u64().unwrap(); + assert!(e["event"] == "design.changed" && revision > last, "{e} after {last}"); + last = revision; + } + // Another tab: another id, whatever its revision. + WATCH.publish("d-2", 2); + assert_eq!(next(&mut lines), changed("d-2", 2)); + // Subscribed already: refused here (the window would have published d-1 again). + writeln!(out, "{}", json!({"id": 2, "method": "control.subscribe"})).unwrap(); + let r = next(&mut lines); + assert!(r["id"] == 2 && r["ok"] == false && r["error"].as_str().is_some_and(|e| e.starts_with("already subscribed")), "{r}"); + // Replies still come, whole, and nothing else was sent meanwhile. + writeln!(out, "{}", json!({"id": 3, "method": "ui.view"})).unwrap(); + assert_eq!(next(&mut lines), json!({"id": 3, "ok": true, "result": "ui.view"})); + writeln!(quiet_out, "{}", json!({"id": 2, "method": "ui.view"})).unwrap(); + assert_eq!(next(&mut quiet), json!({"id": 2, "ok": true, "result": "ui.view"}), "no events without subscribing"); + // Closed, it is no longer counted. Each publish asks the events thread for one more line, + // and its write to the closed connection is what retires the seat; that keeps the wait off + // the connection's own thread, which anything else this process is doing may hold up past + // the deadline (#7226). + drop((out, lines)); + let mut revision = 11; + let deadline = Instant::now() + Duration::from_secs(10); + while WATCH.subscribed() && Instant::now() < deadline { + WATCH.publish("d-1", revision); + revision += 1; + std::thread::sleep(Duration::from_millis(20)); + } + assert!(!WATCH.subscribed()); + } + + /// #8315: a closed connection leaves the watch at once. The seat of a subscribed connection + /// goes when the connection's own thread sees the end of the stream, not only when the + /// events thread notices: that thread waits for the design to move, so a connection that + /// closed while the design stood still kept the watch counting it for a second or more. + #[test] + fn a_closed_connection_leaves_the_watch_at_once() { + static WATCH: DocumentWatch = DocumentWatch::new(); + let token = "0123456789abcdef0123456789abcdef"; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + // The window names the design once and then leaves it alone: nothing moves it, so the + // events thread has nothing to write and only the end of the connection can retire it. + std::thread::spawn(move || { + for req in rx { + if req.method == "control.subscribe" { + WATCH.publish("d-1", 3); + let _ = req.reply.send(json!({"ok": true, "result": {"document_id": "d-1", "revision": 3}})); + } else { + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + } + }); + let hub = hub(Waits::default(), &WATCH); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let (tx, hub) = (tx.clone(), Arc::clone(&hub)); + std::thread::spawn(move || hub.serve(stream, token, tx, false)); + } + }); + let s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + let mut out = s.try_clone().unwrap(); + let mut lines = BufReader::new(s); + writeln!(out, "{}", json!({"id": 1, "method": "control.subscribe", "token": token})).unwrap(); + let mut l = String::new(); + lines.read_line(&mut l).unwrap(); + let reply: Value = serde_json::from_str(&l).unwrap(); + assert!(reply["ok"] == true, "{reply}"); + assert!(WATCH.subscribed(), "the connection is subscribed"); + // Let the events thread settle into its wait: the design stands still, so it has nothing + // to write, and only the end of the connection can retire it. + std::thread::sleep(Duration::from_millis(200)); + // The client goes away without asking anything else. + drop((out, lines)); + let deadline = Instant::now() + Duration::from_millis(400); + while WATCH.subscribed() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + assert!(!WATCH.subscribed(), "a closed connection is not counted on the watch"); + } + + /// The token is read from a request object without building the rest of it: other fields, + /// however large or nested, are only skipped. Anything but an object with a string token is + /// no token. + #[test] + fn token_is_read_without_parsing_the_request() { + assert_eq!(token_of(r#"{"id":1,"token":"abc","params":{"a":[1,[2,{"b":null}]]}}"#).as_deref(), Some("abc")); + let flood = format!(r#"{{"params":[{}0],"token":"t"}}"#, "0,".repeat(1 << 20)); + assert_eq!(token_of(&flood).as_deref(), Some("t")); + for no in [r#"["abc"]"#, r#"{"token":5}"#, r#"{"token":"a"} x"#, r#"{"id":1}"#, "GET / HTTP/1.1", r#""token""#] { + assert_eq!(token_of(no), None, "{no}"); + } + } + + /// #205: a connection runs nothing until a request carries the launch's token; a wrong or + /// missing token, or garbage, is refused and the connection closed. Once shown, the token + /// need not be repeated on that connection. + #[test] + fn requests_run_only_after_the_token() { + use std::io::Read; + let token = "0123456789abcdef0123456789abcdef"; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + let ran = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let seen = ran.clone(); + std::thread::spawn(move || { + for req in rx { + seen.lock().unwrap().push(req.method.clone()); + let _ = req.reply.send(json!({"ok": true, "result": null})); + } + }); + let hub = hub(Waits::default(), &DOCUMENT_WATCH); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let (tx, hub) = (tx.clone(), Arc::clone(&hub)); + std::thread::spawn(move || hub.serve(stream, token, tx, false)); + } + }); + let session = |lines: &[String]| { + let mut s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + for l in lines { + let _ = writeln!(s, "{l}"); + } + let _ = s.shutdown(std::net::Shutdown::Write); + let mut text = String::new(); + let _ = s.read_to_string(&mut text); + text.lines().map(|l| serde_json::from_str::(l).unwrap()).collect::>() + }; + for first in [ + json!({"id": 1, "method": "app.quit", "params": {"force": true}}).to_string(), + json!({"id": 1, "method": "app.quit", "token": "0123456789abcdef0123456789abcdee"}).to_string(), + json!({"id": 1, "method": "app.quit", "token": "0123"}).to_string(), + json!({"id": 1, "method": "app.quit", "token": 7}).to_string(), + "not json".to_string(), + ] { + let replies = session(&[first.clone(), json!({"id": 2, "method": "app.quit", "token": token}).to_string()]); + assert_eq!(replies.len(), 1, "{first}: closed after refusing: {replies:?}"); + assert!(replies[0]["error"].as_str().is_some_and(|e| e.starts_with("unauthorized")), "{first}: {replies:?}"); + } + assert!(ran.lock().unwrap().is_empty(), "nothing ran without the token"); + let replies = session(&[ + json!({"id": 1, "method": "ui.inspect", "token": token}).to_string(), + json!({"id": 2, "method": "engine.commands"}).to_string(), + ]); + assert_eq!(replies.len(), 2, "{replies:?}"); + assert!(replies.iter().all(|r| r["ok"] == true), "{replies:?}"); + assert_eq!(*ran.lock().unwrap(), ["ui.inspect", "engine.commands"]); + } + + /// A request longer than the cap is refused instead of allocated. + #[test] + fn lines_past_the_cap_are_refused() { + let flood = vec![b'A'; MAX_LINE + 2]; + let mut r = BufReader::new(flood.as_slice()); + let e = read_line(&mut r, MAX_LINE).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::InvalidData); + assert!(e.to_string().contains("request too large"), "{e}"); + } + + /// Ordinary framing: lines split on newlines, blank lines kept, no trailing newline needed. + #[test] + fn lines_split_on_newlines() { + let text = b"{\"a\":1}\n\n{\"b\":2}\nlast".to_vec(); + let mut r = BufReader::new(text.as_slice()); + let mut got = Vec::new(); + while let Some(line) = read_line(&mut r, MAX_LINE).unwrap() { + got.push(String::from_utf8(line).unwrap()); + } + assert_eq!(got, vec!["{\"a\":1}", "", "{\"b\":2}", "last"]); + assert!(read_line(&mut r, MAX_LINE).unwrap().is_none()); + } + + /// A line that spans several reads of the underlying stream still arrives whole. + #[test] + fn lines_longer_than_one_buffer_arrive_whole() { + let long = "x".repeat(200_000); + let text = format!("{long}\n{long}\n").into_bytes(); + let mut r = BufReader::with_capacity(64, text.as_slice()); + assert_eq!(read_line(&mut r, MAX_LINE).unwrap().unwrap().len(), long.len()); + assert_eq!(read_line(&mut r, MAX_LINE).unwrap().unwrap().len(), long.len()); + assert!(read_line(&mut r, MAX_LINE).unwrap().is_none()); + // The same line against a smaller cap is refused. + let mut r = BufReader::with_capacity(64, text.as_slice()); + assert!(read_line(&mut r, 1000).is_err()); + } + + /// A large reply reaches the socket in one write, not one per JSON piece (a component tree of + /// thousands of components took half a second to send), and reads back as it was. + #[test] + fn a_large_reply_is_written_at_once() { + struct Counted { + writes: usize, + bytes: Vec, + } + impl Write for Counted { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.writes += 1; + self.bytes.extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let components: Vec = (0..2000).map(|i| json!({"id": i, "name": format!("Part {i}"), "bodies": ["a", "b"], "parent": 0})).collect(); + let reply = json!({"ok": true, "id": 7, "result": {"components": components}}); + let mut out = Counted { writes: 0, bytes: Vec::new() }; + send(&mut out, &reply).unwrap(); + assert_eq!(out.writes, 1); + assert_eq!(out.bytes.last(), Some(&b'\n')); + assert_eq!(serde_json::from_slice::(&out.bytes).unwrap(), reply); + } + + /// A stopped listener frees its port at once and ends the connections it had, so a channel + /// turned off in the settings leaves nothing listening and can be turned on again on the + /// same port. + #[test] + fn a_stopped_listener_closes_its_port_and_its_connections() { + use std::io::Read; + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = listener.local_addr().unwrap().port(); + let (tx, _rx) = channel(); + let stop = hub(Waits::default(), &DOCUMENT_WATCH).listen_stoppable(listener, "0123456789abcdef0123456789abcdef".into(), tx, false).unwrap(); + assert_eq!(stop.port(), port); + let mut client = TcpStream::connect(("127.0.0.1", port)).unwrap(); + client.set_read_timeout(Some(Duration::from_secs(4))).unwrap(); + // Wait until the server holds the connection, so stopping has one to close. + let held = Instant::now(); + while stop.shared.lock().is_empty() && held.elapsed() < Duration::from_secs(4) { + std::thread::sleep(Duration::from_millis(5)); + } + let started = Instant::now(); + stop.stop(); + let mut byte = [0u8; 1]; + match client.read(&mut byte) { + Ok(n) => assert_eq!(n, 0, "the connection ends"), + Err(e) => { + assert!(!matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), "the connection ends, not waits: {e}") + } + } + assert!(started.elapsed() < Duration::from_secs(3), "before the token wait runs out"); + // The listener thread closes its socket when it notices the stop; on a loaded machine that can + // take a moment after `stop()` returns. Wait for the port to be free, not for one instant. + let freed = Instant::now(); + let mut bound = TcpListener::bind(("127.0.0.1", port)); + while bound.is_err() && freed.elapsed() < Duration::from_secs(2) { + std::thread::sleep(Duration::from_millis(10)); + bound = TcpListener::bind(("127.0.0.1", port)); + } + assert!(bound.is_ok(), "the port is free again: {:?}", bound.err()); + } +} diff --git a/crates/docx/src/read/props.rs b/crates/docx/src/read/props.rs index dc61b3a288..4d86ae1641 100644 --- a/crates/docx/src/read/props.rs +++ b/crates/docx/src/read/props.rs @@ -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), _ => {} diff --git a/crates/docx/src/read/shape_style.rs b/crates/docx/src/read/shape_style.rs index 9f28ef2ff2..983218f9e1 100644 --- a/crates/docx/src/read/shape_style.rs +++ b/crates/docx/src/read/shape_style.rs @@ -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, } } diff --git a/crates/docx/src/read/story.rs b/crates/docx/src/read/story.rs index 770375365a..86ceb1651a 100644 --- a/crates/docx/src/read/story.rs +++ b/crates/docx/src/read/story.rs @@ -22,6 +22,7 @@ use craft_wordmodel::wordart::TextWarp; mod blocks; mod drawing; mod fields; +mod locked_canvas; mod runs; mod vml; diff --git a/crates/docx/src/read/story/drawing.rs b/crates/docx/src/read/story/drawing.rs index cb1152da89..e791f1e124 100644 --- a/crates/docx/src/read/story/drawing.rs +++ b/crates/docx/src/read/story/drawing.rs @@ -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 diff --git a/crates/docx/src/read/story/locked_canvas.rs b/crates/docx/src/read/story/locked_canvas.rs new file mode 100644 index 0000000000..59a52cea2c --- /dev/null +++ b/crates/docx/src/read/story/locked_canvas.rs @@ -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 { + 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 = [ + 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 = 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 { + 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 { + 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::().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::().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::().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 { + let color = |e: &El| -> Option { + 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) -> 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() } +} diff --git a/crates/docx/src/write.rs b/crates/docx/src/write.rs index 1d9eb08184..4ba486a6cc 100644 --- a/crates/docx/src/write.rs +++ b/crates/docx/src/write.rs @@ -151,6 +151,11 @@ pub fn write_as(doc: &Document, flavor: Flavor) -> Result, 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 = std::collections::HashSet::new(); for (key, bytes) in &self.doc.media { diff --git a/crates/docx/src/write/props.rs b/crates/docx/src/write/props.rs index 0b92ce1919..fb76da8d8f 100644 --- a/crates/docx/src/write/props.rs +++ b/crates/docx/src/write/props.rs @@ -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) -> &'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()); diff --git a/crates/docx/src/write/story/drawing.rs b/crates/docx/src/write/story/drawing.rs index 7c03cca6ef..3986d79643 100644 --- a/crates/docx/src/write/story/drawing.rs +++ b/crates/docx/src/write/story/drawing.rs @@ -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> { + 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. diff --git a/crates/docx/src/write/story/object.rs b/crates/docx/src/write/story/object.rs index 6cdd54f463..4b0ae856a6 100644 --- a/crates/docx/src/write/story/object.rs +++ b/crates/docx/src/write/story/object.rs @@ -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", diff --git a/crates/docx/src/write/story/para.rs b/crates/docx/src/write/story/para.rs index e0242d8ebd..aa973184e2 100644 --- a/crates/docx/src/write/story/para.rs +++ b/crates/docx/src/write/story/para.rs @@ -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); diff --git a/crates/docx/src/write/styles.rs b/crates/docx/src/write/styles.rs index 3bcf9ab97f..0fddf33b49 100644 --- a/crates/docx/src/write/styles.rs +++ b/crates/docx/src/write/styles.rs @@ -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); diff --git a/crates/docx/src/xml.rs b/crates/docx/src/xml.rs index bb86755d9a..fa50d217a0 100644 --- a/crates/docx/src/xml.rs +++ b/crates/docx/src/xml.rs @@ -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"), diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index 348d6239e1..47663008dc 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -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#"{av}"#); + let gd = |fmla: &str| format!(r#""#); + let body = [geom(&gd("val 2604")), geom(""), geom(&gd("val 90000")), geom(r#""#)] + .iter() + .map(|sppr| anchored_wsp("Frame", 2540000, 1270000, sppr, "", "")) + .collect::(); + let frames = |d: &Document| -> Vec<(ShapeKind, Option)> { + 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!("{body}")); + 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#""#), "{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() { diff --git a/crates/docx/tests/it/kashida.rs b/crates/docx/tests/it/kashida.rs new file mode 100644 index 0000000000..02eaf2a495 --- /dev/null +++ b/crates/docx/tests/it/kashida.rs @@ -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 { + 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 { + let root = r#""#; + let doc = format!( + r#"{body}"# + ); + 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#"{body}"#) +} + +#[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); +} diff --git a/crates/docx/tests/it/locked_canvas.rs b/crates/docx/tests/it/locked_canvas.rs new file mode 100644 index 0000000000..fb01406a4d --- /dev/null +++ b/crates/docx/tests/it/locked_canvas.rs @@ -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 { + let doc = format!(r#"{body}"#); + let types = + r#""#; + let root = r#""#; + let rels = r#""#; + 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#"00{canvas}"# + ) +} + +const OVAL: &str = r#""#; + +/// 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#"Youngkeepers"#; + +const PICTURE: &str = r#""#; + +/// A line glued to the oval by the canvas's own id, which isn't a document shape's. +const LINE: &str = r#""#; + +fn group(d: &Document) -> (f32, f32, Vec) { + 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#"OwnLevelFirst"#; + 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#"PlainCentredOwn"#; + 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> = (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, Option)> = (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#""#.repeat(40), OVAL, "".repeat(40)); + let odd = r#"f"#; + for canvas in ["", deep.as_str(), odd] { + let d = craft_docx::read(&docx(&drawing(canvas))).unwrap(); + let _ = craft_docx::write(&d).unwrap(); + } +} diff --git a/crates/docx/tests/it/main.rs b/crates/docx/tests/it/main.rs index b0bab58331..8d6be8a97f 100644 --- a/crates/docx/tests/it/main.rs +++ b/crates/docx/tests/it/main.rs @@ -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; diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 8f3bbdd0bd..2037f98498 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -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("").map(|(a, _)| (a, a + xml[a..].find("").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 = 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("").unwrap(), "{xml}"); + assert!(begin > boxes[1].1 && end > boxes[3].1 && end < xml.find("").unwrap(), "{xml}"); } #[test] diff --git a/crates/docx/tests/it/text_boxes.rs b/crates/docx/tests/it/text_boxes.rs index 608d22d333..a5824cafcf 100644 --- a/crates/docx/tests/it/text_boxes.rs +++ b/crates/docx/tests/it/text_boxes.rs @@ -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); } diff --git a/crates/docx/tests/it/wps_fallback.rs b/crates/docx/tests/it/wps_fallback.rs new file mode 100644 index 0000000000..9b209082b7 --- /dev/null +++ b/crates/docx/tests/it/wps_fallback.rs @@ -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) -> 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#""#), "{xml}"); + assert!(!xml.contains(""), "no bare Word 2010 shape: {xml}"); + let fallback = &xml[xml.find("").expect("a fallback")..]; + assert!(fallback.starts_with(""#, + r#""#, + ] { + assert!(fallback.contains(want), "{want} in {fallback}"); + } + assert_eq!(xml.matches(">29").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#""#).expect("the outer box's text, turned"); + let rect = &xml[xml[..tb].rfind(" = 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("") && xml.contains(r#""#), "{xml}"); + assert!(!xml.contains(""), "{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("").count(), 1, "{xml}"); + assert_eq!(xml.matches("").count(), 1, "{xml}"); + let fallback = xml.split("").nth(1).unwrap().split("").next().unwrap(); + assert!(fallback.contains(">Independent"), "{fallback}"); + assert!(!fallback.contains("Flows on"), "the chain head must not get an unlinked fallback"); + assert_eq!(xml.matches(">Flows on").count(), 1); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{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"); +} diff --git a/crates/dpx/src/lib.rs b/crates/dpx/src/lib.rs index a762566f8f..26d9e8656f 100644 --- a/crates/dpx/src/lib.rs +++ b/crates/dpx/src/lib.rs @@ -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; diff --git a/crates/dpx/src/rgba8_dpx10.rs b/crates/dpx/src/rgba8_dpx10.rs new file mode 100644 index 0000000000..8dec304eca --- /dev/null +++ b/crates/dpx/src/rgba8_dpx10.rs @@ -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, 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 { + 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, 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, at: usize, v: u32| hd[at..at + 4].copy_from_slice(&v.to_be_bytes()); + let put16 = |hd: &mut Vec, 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)); + } +} diff --git a/crates/drawingml/src/chart.rs b/crates/drawingml/src/chart.rs index e575d10f22..9475d20548 100644 --- a/crates/drawingml/src/chart.rs +++ b/crates/drawingml/src/chart.rs @@ -354,6 +354,10 @@ pub struct Chart { pub legend: Option, /// `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, /// 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, + #[serde(skip_serializing_if = "Option::is_none")] + pub bold: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub color: Option, +} + /// 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, diff --git a/crates/drawingml/src/chart/read.rs b/crates/drawingml/src/chart/read.rs index 38ce9f605d..3f2be736f8 100644 --- a/crates/drawingml/src/chart/read.rs +++ b/crates/drawingml/src/chart/read.rs @@ -143,6 +143,7 @@ fn chart_within(root: &El, mut budget: usize) -> Option { 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 { 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 { + 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 { + fn rec(e: &El, depth: usize) -> Option { + 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 { fn rec(e: &El, depth: usize) -> Option { diff --git a/crates/drawingml/src/chart/write.rs b/crates/drawingml/src/chart/write.rs index d115c4a2cf..6993a6d219 100644 --- a/crates/drawingml/src/chart/write.rs +++ b/crates/drawingml/src/chart/write.rs @@ -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, 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#""# + ) + }; + let xml = format!( + r#"1{}{}"#, + 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("").unwrap()..]; + let (pos, entry0, overlay) = + (legend.find("").unwrap(), legend.find(""#, + r#""#, + 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#""#, "", 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() }; diff --git a/crates/drawingml/src/numfmt.rs b/crates/drawingml/src/numfmt.rs index b5db9667c0..7a7b866650 100644 --- a/crates/drawingml/src/numfmt.rs +++ b/crates/drawingml/src/numfmt.rs @@ -234,16 +234,18 @@ fn sci(toks: &[Tok], v: f64, sep: char, dec: char) -> Option { 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::().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"] { diff --git a/crates/elf/Cargo.toml b/crates/elf/Cargo.toml new file mode 100644 index 0000000000..e982689e4f --- /dev/null +++ b/crates/elf/Cargo.toml @@ -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 } diff --git a/crates/elf/src/bytes.rs b/crates/elf/src/bytes.rs new file mode 100644 index 0000000000..c78b9b5a8e --- /dev/null +++ b/crates/elf/src/bytes.rs @@ -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 { + self.buf.get(at).copied() + } + + fn take(&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); +} diff --git a/crates/elf/src/hex.rs b/crates/elf/src/hex.rs new file mode 100644 index 0000000000..82dfd4bba5 --- /dev/null +++ b/crates/elf/src/hex.rs @@ -0,0 +1,5 @@ +//! Addresses serialised as `0x…` strings, as Craft Anything reports them. + +pub(crate) fn serialize(value: &u64, serializer: S) -> Result { + serializer.serialize_str(&format!("{value:#x}")) +} diff --git a/crates/elf/src/lib.rs b/crates/elf/src/lib.rs new file mode 100644 index 0000000000..b8868f7345 --- /dev/null +++ b/crates/elf/src/lib.rs @@ -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 { + 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 { + if self.le { self.r.u16_le(off) } else { self.r.u16_be(off) } + } + + fn u32(&self, off: usize) -> Option { + if self.le { self.r.u32_le(off) } else { self.r.u32_be(off) } + } + + fn u64(&self, off: usize) -> Option { + if self.le { self.r.u64_le(off) } else { self.r.u64_be(off) } + } + + fn word(&self, off: usize) -> Option { + 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, 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 { + 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, 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; diff --git a/crates/elf/src/tests.rs b/crates/elf/src/tests.rs new file mode 100644 index 0000000000..a5aaf2060f --- /dev/null +++ b/crates/elf/src/tests.rs @@ -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, + 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 { + 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 = + [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 = + (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); + } + } + } + } +} diff --git a/crates/exr/src/decode.rs b/crates/exr/src/decode.rs index ab21064ce4..2797e36414 100644 --- a/crates/exr/src/decode.rs +++ b/crates/exr/src/decode.rs @@ -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) -> (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 { +pub(super) fn read_meta(bytes: &[u8], limits: &Limits) -> Result { 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 { } 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::())) - 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 { + 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 { + 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, size: Vec2| -> Result> { + 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 { 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 }) } diff --git a/crates/exr/src/decode_tests.rs b/crates/exr/src/decode_tests.rs index 54c28d9aa4..89f44d5068 100644 --- a/crates/exr/src/decode_tests.rs +++ b/crates/exr/src/decode_tests.rs @@ -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, 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 { + 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 { + 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 { + 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 = [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 = [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, [[usize; 2]; 2]) { + let (w, h) = (3usize, 2usize); + let mut out = mixed_headers(deep_first, tiled, (w, h)); + let chunks: Vec>> = (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 = (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::>(), ["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 { + 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 = 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()); + } + } +} diff --git a/crates/exr/src/deep.rs b/crates/exr/src/deep.rs index b86d497c80..ad2ab00b5a 100644 --- a/crates/exr/src/deep.rs +++ b/crates/exr/src/deep.rs @@ -391,19 +391,14 @@ fn decode_deep_meta(meta: &MetaData, bytes: &[u8], limits: &Limits) -> Result Result { 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, diff --git a/crates/exr/src/deep_tests.rs b/crates/exr/src/deep_tests.rs index cb17218096..bdbfa0d688 100644 --- a/crates/exr/src/deep_tests.rs +++ b/crates/exr/src/deep_tests.rs @@ -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, 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 = + (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 = [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. diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index 810e67d552..b7204f1bf8 100644 --- a/crates/flow/src/from_doc.rs +++ b/crates/flow/src/from_doc.rs @@ -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, 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, .. } => { diff --git a/crates/flow/src/to_doc.rs b/crates/flow/src/to_doc.rs index ce29a44483..0375c448c2 100644 --- a/crates/flow/src/to_doc.rs +++ b/crates/flow/src/to_doc.rs @@ -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 { diff --git a/crates/font-catalog/Cargo.toml b/crates/font-catalog/Cargo.toml index 1f0830a636..d4620862be 100644 --- a/crates/font-catalog/Cargo.toml +++ b/crates/font-catalog/Cargo.toml @@ -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 } diff --git a/crates/font-catalog/src/face_data.rs b/crates/font-catalog/src/face_data.rs new file mode 100644 index 0000000000..655c2f4084 --- /dev/null +++ b/crates/font-catalog/src/face_data.rs @@ -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>), + 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>, 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::from_index(self.bytes(), self.index).ok() + } + + /// Parse this face for shaping. + pub fn harfrust(&self) -> Option> { + harfrust::FontRef::from_index(self.bytes(), self.index).ok() + } +} + +impl From 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); + } +} diff --git a/crates/font-catalog/src/fallback.rs b/crates/font-catalog/src/fallback.rs new file mode 100644 index 0000000000..2b0d181d00 --- /dev/null +++ b/crates/font-catalog/src/fallback.rs @@ -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 + '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( + cluster: &str, + primary: &F, + map: impl Fn(char) -> char + Copy, + primary_covers: impl Fn(char) -> bool, + mut fallback: impl FnMut(char) -> Option, + 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::(), "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); + } +} diff --git a/crates/font-catalog/src/lib.rs b/crates/font-catalog/src/lib.rs index 3f155d35d4..70aaa19b1f 100644 --- a/crates/font-catalog/src/lib.rs +++ b/crates/font-catalog/src/lib.rs @@ -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; diff --git a/crates/font-catalog/src/ligature.rs b/crates/font-catalog/src/ligature.rs new file mode 100644 index 0000000000..fa9efe5dac --- /dev/null +++ b/crates/font-catalog/src/ligature.rs @@ -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<(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 = 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()); + } +} diff --git a/crates/font-catalog/src/line_break.rs b/crates/font-catalog/src/line_break.rs new file mode 100644 index 0000000000..10983d7170 --- /dev/null +++ b/crates/font-catalog/src/line_break.rs @@ -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)); + } +} diff --git a/crates/font-catalog/src/plan_cache.rs b/crates/font-catalog/src/plan_cache.rs new file mode 100644 index 0000000000..d428de4cd7 --- /dev/null +++ b/crates/font-catalog/src/plan_cache.rs @@ -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>>, +} + +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, + language: Option<&harfrust::Language>, + features: &[harfrust::Feature], + ) -> Arc { + let key = harfrust::ShapePlanKey::new(script, direction).language(language).instance(instance).features(features); + let kept = |plans: &[Arc]| 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 + } +} diff --git a/crates/font-catalog/src/segments.rs b/crates/font-catalog/src/segments.rs new file mode 100644 index 0000000000..e36a051446 --- /dev/null +++ b/crates/font-catalog/src/segments.rs @@ -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 { + face: F, + level: L, + small_caps: bool, + strong_script: Option, +} + +impl SegmentBoundary { + /// 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, 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::::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::::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)); + } +} diff --git a/crates/font-catalog/src/shape.rs b/crates/font-catalog/src/shape.rs new file mode 100644 index 0000000000..966597d3b5 --- /dev/null +++ b/crates/font-catalog/src/shape.rs @@ -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 + + "##; + let checked = crate::tree::preflight(svg, &Limits::default()).unwrap(); + assert_eq!( + checked.unsupported_elements(), + vec![("animate", 2), ("animateTransform", 1), ("foreignObject", 1), ("script", 1), ("set", 1)], + "the XHTML div is not an SVG element" + ); + // The same checked XML still parses. + assert!(checked.parse(&usvg::Options::default()).is_ok()); + let plain = crate::tree::preflight(r#""#, &Limits::default()).unwrap(); + assert!(plain.unsupported_elements().is_empty()); +} + +#[cfg(feature = "tree-text")] +#[test] +fn local_text_is_placed_and_bounded_in_its_parents_frame() { + let mut options = usvg::Options::default(); + let fonts = options.fontdb_mut(); + fonts.load_font_data(include_bytes!("../../../ui/tests/fonts/NotoSans-test.ttf").to_vec()); + let family = fonts.faces().next().unwrap().families[0].0.clone(); + let svg = format!( + r#"Hi"# + ); + let tree = parse(svg.as_bytes(), &Limits::default(), &options).unwrap(); + let local = Document::from_tree_local(&tree, 64); + let absolute = Document::from_tree(&tree, 64); + + let groups = group_ids(&local.nodes); + let text = groups.iter().find(|(id, _)| id == "t").unwrap(); + assert!(close([text.1[0], text.1[3]], [1.0, 1.0]) && close([text.1[4], text.1[5]], [0.0, 0.0]), "text sits in its group's frame: {text:?}"); + + let bounds = |nodes: &[Node]| -> [f64; 4] { + let Node::Group { children, .. } = &nodes[0] else { panic!() }; + let Node::Group { bounds, .. } = &children[0] else { panic!() }; + *bounds + }; + let (l, a) = (bounds(&local.nodes), bounds(&absolute.nodes)); + assert!(close([l[0] + 50.0, l[1]], [a[0], a[1]]) && close([l[2], l[3]], [a[2], a[3]]), "local {l:?} vs absolute {a:?}"); + assert!(l[0] > 0.0 && l[0] < 10.0, "near x=5 in the group's frame: {l:?}"); + + let (mut lp, mut ap) = (Vec::new(), Vec::new()); + document_points(&local.nodes, IDENTITY, true, &mut lp); + document_points(&absolute.nodes, IDENTITY, false, &mut ap); + assert!(!lp.is_empty() && lp.len() == ap.len()); + assert!(lp.iter().zip(&ap).all(|(l, a)| close(*l, *a))); +} diff --git a/crates/svg/src/tree/primitive.rs b/crates/svg/src/tree/primitive.rs new file mode 100644 index 0000000000..a43933ec3c --- /dev/null +++ b/crates/svg/src/tree/primitive.rs @@ -0,0 +1,164 @@ +//! Basic shapes recovered from a scene path. usvg turns `rect`, `circle` and `ellipse` into +//! paths; an app that edits them as shapes (a rectangle with corner radii, an ellipse) gets them +//! back here from the segments alone. +//! +//! A path is a primitive when it is one closed contour whose points all lie on the outline of +//! an axis-aligned (rounded) rectangle or ellipse and that encloses its area. The check works on +//! the segments as given, so use it on a [`Coordinates::Local`](super::document::Coordinates) +//! scene, where a rotated or skewed shape keeps its own axes. + +use super::document::Segment; + +/// An axis-aligned basic shape. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Primitive { + /// A rectangle, with elliptical corners of radii `rx`, `ry` (both 0 for square corners). + Rect { x: f64, y: f64, width: f64, height: f64, rx: f64, ry: f64 }, + /// An ellipse (a circle when `rx == ry`). + Ellipse { cx: f64, cy: f64, rx: f64, ry: f64 }, +} + +/// Most segments a primitive's contour has: usvg writes a rounded rectangle as 4 lines and up to +/// 4 curves per corner. +const MAX_SEGMENTS: usize = 32; +/// Points sampled on each curve, besides its ends: enough that the polygon through them +/// encloses a curved outline's area to well within the area check's 1%. +const SAMPLES: usize = 31; + +/// The curve parameters sampled between a curve's ends. +fn samples() -> impl Iterator { + (1..=SAMPLES).map(|i| i as f64 / (SAMPLES + 1) as f64) +} + +/// The basic shape `segments` draw, if they draw one. +pub fn recognize(segments: &[Segment]) -> Option { + let (ends, points) = contour(segments)?; + let (mut min, mut max) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); + for p in &points { + for axis in 0..2 { + min[axis] = min[axis].min(p[axis]); + max[axis] = max[axis].max(p[axis]); + } + } + let (width, height) = (max[0] - min[0], max[1] - min[1]); + if !(width.is_finite() && height.is_finite()) || width <= 0.0 || height <= 0.0 { + return None; + } + let tol = 1e-3 * width.max(height); + // The straight part of the top edge starts `rx` in; of the left edge, `ry` down. + let rx = ends.iter().filter(|p| (p[1] - min[1]).abs() <= tol).map(|p| p[0] - min[0]).fold(f64::INFINITY, f64::min); + let ry = ends.iter().filter(|p| (p[0] - min[0]).abs() <= tol).map(|p| p[1] - min[1]).fold(f64::INFINITY, f64::min); + let rx = snap(rx, width / 2.0, tol)?; + let ry = snap(ry, height / 2.0, tol)?; + if (rx == 0.0) != (ry == 0.0) { + return None; + } + let inner = ([min[0] + rx, min[1] + ry], [max[0] - rx, max[1] - ry]); + let on_outline = |p: &[f64; 2]| { + let q = [p[0].clamp(inner.0[0], inner.1[0]), p[1].clamp(inner.0[1], inner.1[1])]; + let d = [p[0] - q[0], p[1] - q[1]]; + if rx == 0.0 { + // Square corners: on an edge of the box. + (p[0] - min[0]).abs() <= tol || (p[0] - max[0]).abs() <= tol || (p[1] - min[1]).abs() <= tol || (p[1] - max[1]).abs() <= tol + } else if d == [0.0, 0.0] { + false + } else { + let e = (d[0] / rx).hypot(d[1] / ry); + (e - 1.0).abs() * rx.min(ry) <= tol || (d[0] == 0.0 && (d[1].abs() - ry).abs() <= tol) || (d[1] == 0.0 && (d[0].abs() - rx).abs() <= tol) + } + }; + if !points.iter().all(on_outline) { + return None; + } + // Every point is on the outline; it also has to go all the way round once. + let expected = width * height - (4.0 - std::f64::consts::PI) * rx * ry; + if (area(&points).abs() - expected).abs() > 0.01 * expected { + return None; + } + if (rx - width / 2.0).abs() <= tol && (ry - height / 2.0).abs() <= tol { + return Some(Primitive::Ellipse { cx: min[0] + width / 2.0, cy: min[1] + height / 2.0, rx: width / 2.0, ry: height / 2.0 }); + } + Some(Primitive::Rect { x: min[0], y: min[1], width, height, rx, ry }) +} + +/// `value` within `tol` of 0 or `half` is snapped there; past `half` it isn't a corner radius. +fn snap(value: f64, half: f64, tol: f64) -> Option { + if !value.is_finite() || value < -tol || value > half + tol { + return None; + } + Some(if value <= tol { + 0.0 + } else if (value - half).abs() <= tol { + half + } else { + value + }) +} + +/// Points of a contour. +type Points = Vec<[f64; 2]>; + +/// The segment ends of one closed contour, and all its points (ends and curve samples), or +/// `None` for anything else: several contours, an open one, or too many segments. +fn contour(segments: &[Segment]) -> Option<(Points, Points)> { + if segments.len() > MAX_SEGMENTS + 2 { + return None; + } + let (first, rest) = segments.split_first()?; + let Segment::MoveTo(start) = *first else { return None }; + let mut points = vec![start]; + let mut ends = vec![start]; + let mut at = start; + let mut closed = false; + for segment in rest { + if closed { + return None; + } + match *segment { + Segment::MoveTo(_) => return None, + Segment::LineTo(p) => { + points.push(p); + ends.push(p); + at = p; + } + Segment::QuadTo(c, p) => { + for t in samples() { + let u = 1.0 - t; + points.push([u * u * at[0] + 2.0 * u * t * c[0] + t * t * p[0], u * u * at[1] + 2.0 * u * t * c[1] + t * t * p[1]]); + } + points.push(p); + ends.push(p); + at = p; + } + Segment::CubicTo(c1, c2, p) => { + for t in samples() { + let u = 1.0 - t; + let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t); + points.push([a * at[0] + b * c1[0] + c * c2[0] + d * p[0], a * at[1] + b * c1[1] + c * c2[1] + d * p[1]]); + } + points.push(p); + ends.push(p); + at = p; + } + Segment::Close => closed = true, + } + } + let ends_at_start = (at[0] - start[0]).abs() < 1e-9 && (at[1] - start[1]).abs() < 1e-9; + (closed || ends_at_start).then_some((ends, points)) +} + +/// The signed area of the polygon through `points`. +fn area(points: &[[f64; 2]]) -> f64 { + let n = points.len(); + (0..n) + .map(|i| { + let (a, b) = (points[i], points[(i + 1) % n]); + a[0] * b[1] - b[0] * a[1] + }) + .sum::() + / 2.0 +} + +#[cfg(test)] +#[path = "primitive_tests.rs"] +mod tests; diff --git a/crates/svg/src/tree/primitive_tests.rs b/crates/svg/src/tree/primitive_tests.rs new file mode 100644 index 0000000000..ac417eb6ca --- /dev/null +++ b/crates/svg/src/tree/primitive_tests.rs @@ -0,0 +1,119 @@ +#![allow(clippy::unwrap_used, clippy::panic, clippy::indexing_slicing, clippy::float_cmp)] + +use super::*; +use crate::tree::document::{Document, Node}; +use crate::tree::{Limits, parse, usvg}; + +/// The segments usvg makes of `element`, the only shape in a document. +fn segments(element: &str) -> Vec { + let svg = format!(r#"{element}"#); + let tree = parse(svg.as_bytes(), &Limits::default(), &usvg::Options::default()).unwrap(); + let document = Document::from_tree(&tree, 16); + fn first(nodes: &[Node]) -> Option> { + nodes.iter().find_map(|n| match n { + Node::Path(p) => Some(p.segments.clone()), + Node::Group { children, .. } => first(children), + Node::Image(_) => None, + }) + } + first(&document.nodes).unwrap() +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-3 +} + +#[test] +fn a_rect_is_a_rect() { + let Some(Primitive::Rect { x, y, width, height, rx, ry }) = recognize(&segments(r#""#)) else { + panic!() + }; + assert_eq!((x, y, width, height, rx, ry), (10.0, 20.0, 30.0, 40.0, 0.0, 0.0)); +} + +#[test] +fn a_rounded_rect_keeps_its_radii() { + for (attrs, want) in [(r#"rx="5""#, (5.0, 5.0)), (r#"rx="6" ry="3""#, (6.0, 3.0)), (r#"ry="4""#, (4.0, 4.0))] { + let element = format!(r#""#); + let Some(Primitive::Rect { x, y, width, height, rx, ry }) = recognize(&segments(&element)) else { panic!("{element}") }; + assert!(near(x, 10.0) && near(y, 20.0) && near(width, 30.0) && near(height, 40.0), "{element}"); + assert!(near(rx, want.0) && near(ry, want.1), "{element}: {rx} {ry}"); + } +} + +#[test] +fn circles_and_ellipses_are_ellipses() { + for (element, want) in [ + (r#""#, (50.0, 60.0, 25.0, 25.0)), + (r#""#, (50.0, 60.0, 40.0, 10.0)), + // A rectangle whose corners meet in the middle is an ellipse too. + (r#""#, (10.0, 5.0, 10.0, 5.0)), + ] { + let Some(Primitive::Ellipse { cx, cy, rx, ry }) = recognize(&segments(element)) else { panic!("{element}") }; + assert!(near(cx, want.0) && near(cy, want.1) && near(rx, want.2) && near(ry, want.3), "{element}: {cx} {cy} {rx} {ry}"); + } +} + +#[test] +fn other_paths_are_not_primitives() { + for element in [ + // A triangle on the edges of its box encloses half of it. + r#""#, + // Open, or two contours. + r#""#, + r#""#, + // A rectangle drawn twice, a diamond, a star. + r#""#, + r#""#, + r#""#, + // A curve that bulges past a circle's outline. + r#""#, + ] { + assert_eq!(recognize(&segments(element)), None, "{element}"); + } +} + +#[test] +fn degenerate_and_oversized_input_is_refused() { + assert_eq!(recognize(&[]), None); + assert_eq!(recognize(&[Segment::LineTo([1.0, 1.0])]), None); + assert_eq!(recognize(&[Segment::MoveTo([0.0, 0.0]), Segment::LineTo([10.0, 0.0]), Segment::Close]), None, "no height"); + let nan = [Segment::MoveTo([f64::NAN, 0.0]), Segment::LineTo([1.0, 0.0]), Segment::LineTo([1.0, 1.0]), Segment::Close]; + assert_eq!(recognize(&nan), None); + let mut long = vec![Segment::MoveTo([0.0, 0.0])]; + long.extend((0..100).map(|i| Segment::LineTo([f64::from(i % 2) * 10.0, 0.0]))); + long.push(Segment::Close); + assert_eq!(recognize(&long), None); +} + +#[test] +fn hand_written_segments_are_recognised_too() { + // Square corners written clockwise from the bottom left, closed by returning to the start. + let square = [ + Segment::MoveTo([0.0, 10.0]), + Segment::LineTo([0.0, 0.0]), + Segment::LineTo([10.0, 0.0]), + Segment::LineTo([10.0, 10.0]), + Segment::LineTo([0.0, 10.0]), + ]; + assert_eq!(recognize(&square), Some(Primitive::Rect { x: 0.0, y: 0.0, width: 10.0, height: 10.0, rx: 0.0, ry: 0.0 })); + // A circle from four cubic quarters, through Path::primitive. + let k = 0.552_284_749_830_793_6 * 5.0; + let path = crate::tree::document::Path { + segments: vec![ + Segment::MoveTo([10.0, 5.0]), + Segment::CubicTo([10.0, 5.0 + k], [5.0 + k, 10.0], [5.0, 10.0]), + Segment::CubicTo([5.0 - k, 10.0], [0.0, 5.0 + k], [0.0, 5.0]), + Segment::CubicTo([0.0, 5.0 - k], [5.0 - k, 0.0], [5.0, 0.0]), + Segment::CubicTo([5.0 + k, 0.0], [10.0, 5.0 - k], [10.0, 5.0]), + Segment::Close, + ], + fill: None, + fill_rule: crate::tree::document::FillRule::NonZero, + stroke: None, + source_path: crate::tree::document::NodePath::default(), + id: String::new(), + transform: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], + }; + assert_eq!(path.primitive(), Some(Primitive::Ellipse { cx: 5.0, cy: 5.0, rx: 5.0, ry: 5.0 })); +} diff --git a/crates/svg/src/write.rs b/crates/svg/src/write.rs index 66cb1d6a09..af3eec992b 100644 --- a/crates/svg/src/write.rs +++ b/crates/svg/src/write.rs @@ -258,6 +258,42 @@ pub fn path_data_fixed(path: &BezPath, decimals: usize) -> String { #[derive(Clone, Debug, Default)] pub struct SvgWriter(craft_xml::Writer); +// A subset ends with `] S? >`; quoted entity values, comments and PIs may contain that text. +// Scan once without allocations; malformed unterminated constructs remain the caller's error. +fn closes_internal_subset(internal: &str) -> bool { + let bytes = internal.as_bytes(); + let mut i = 0; + while i < bytes.len() { + if bytes[i..].starts_with(b"") } else { (2, b"?>") }; + let Some(offset) = bytes[i + start..].windows(end.len()).position(|part| part == end) else { + return false; + }; + i += start + offset + end.len(); + } else if matches!(bytes[i], b'\'' | b'"') { + let quote = bytes[i]; + i += 1; + while i < bytes.len() && bytes[i] != quote { + i += 1; + } + if i < bytes.len() { + i += 1; + } + } else if bytes[i] == b']' { + i += 1; + while i < bytes.len() && matches!(bytes[i], b' ' | b'\t' | b'\r' | b'\n') { + i += 1; + } + if bytes.get(i) == Some(&b'>') { + return true; + } + } else { + i += 1; + } + } + false +} + impl SvgWriter { /// A document: starts with the XML declaration. pub fn new() -> SvgWriter { @@ -269,6 +305,41 @@ impl SvgWriter { pub fn fragment() -> SvgWriter { SvgWriter::default() } + /// A document that starts with an XML declaration naming `encoding` (for example `UTF-8` or + /// `ISO-8859-1`) and a newline. Nothing is written for an invalid XML encoding name. + pub fn with_encoding(encoding: &str) -> SvgWriter { + let mut w = SvgWriter::fragment(); + w.decl(encoding, "\n"); + w + } + /// Writes `` followed by `newline`. Nothing is + /// written unless `encoding` starts with an ASCII letter and continues with ASCII letters, + /// digits, `.`, `_`, or `-` (XML EncName). + pub fn decl(&mut self, encoding: &str, newline: &str) { + let mut bytes = encoding.bytes(); + if bytes.next().is_some_and(|b| b.is_ascii_alphabetic()) && bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) { + self.0.raw(&format!("{newline}")); + } + } + /// Writes `` + `newline`. When + /// `internal` is empty, the inner newline is omitted, so a minified document can be + /// `` with no extra breaks. Nothing is written if `name` is not an XML name + /// or `internal` closes the subset outside a quoted value, comment or processing instruction. + /// The caller still supplies valid DTD declarations; this is not a DTD validator. + pub fn doctype_internal(&mut self, name: &str, internal: &str, newline: &str) { + if !craft_xml::is_name(name) || closes_internal_subset(internal) { + return; + } + let mut out = format!(""); + out.push_str(newline); + self.0.raw(&out); + } /// Starts the root tag, ` Tag<'_> { @@ -295,9 +366,13 @@ impl SvgWriter { pub fn raw(&mut self, svg: &str) { self.0.raw(svg); } + /// What has been written so far, including any element that is still open. + pub fn as_str(&self) -> &str { + self.0.as_str() + } /// How many bytes have been written so far. pub fn len(&self) -> usize { - self.0.as_str().len() + self.as_str().len() } /// Has nothing been written yet? pub fn is_empty(&self) -> bool { @@ -362,6 +437,7 @@ mod tests { } #[test] + #[cfg(feature = "paths")] fn writes_a_document_the_reader_reads() { let mut w = SvgWriter::new(); assert!(!w.is_empty()); @@ -412,4 +488,58 @@ mod tests { assert_eq!(w.len(), before + inner.len()); assert_eq!(w.finish(), ""); } + + #[test] + fn declaration_names_the_encoding_and_rejects_a_bad_name() { + assert_eq!(SvgWriter::with_encoding("UTF-8").finish(), "\n"); + assert_eq!(SvgWriter::with_encoding("ISO-8859-1").finish(), "\n"); + assert!(SvgWriter::with_encoding("UTF-8\"").is_empty()); + assert!(SvgWriter::with_encoding("").is_empty()); + for valid in ["A", "a0._-"] { + assert_eq!(SvgWriter::with_encoding(valid).finish(), format!("\n")); + } + for invalid in [":UTF-8", "_UTF8", "1UTF8", "é", "UTF:8", "UTFé", "UTF 8"] { + assert!(SvgWriter::with_encoding(invalid).is_empty(), "{invalid}"); + } + let mut compact = SvgWriter::fragment(); + compact.decl("ISO-8859-1", ""); + compact.root().open(); + assert_eq!(compact.as_str(), ""); + compact.close(); + assert_eq!(compact.finish(), ""); + } + + #[test] + fn doctype_internal_subset_keeps_caller_newlines() { + let mut pretty = SvgWriter::fragment(); + pretty.doctype_internal("svg", " ", "\n"); + pretty.root().open(); + pretty.close(); + assert_eq!(pretty.finish(), "\n]>\n"); + let mut compact = SvgWriter::fragment(); + compact.doctype_internal("svg", "", ""); + assert_eq!(compact.finish(), "]>"); + let mut empty = SvgWriter::fragment(); + empty.doctype_internal("svg", "", "\n"); + assert_eq!(empty.finish(), "\n"); + let mut refused = SvgWriter::fragment(); + refused.doctype_internal("svg", "]]>", "\n"); + refused.doctype_internal("svg", "]>", "?>"] { + let mut writer = SvgWriter::fragment(); + writer.doctype_internal("svg", internal, ""); + assert_eq!(writer.finish(), format!("")); + } + for internal in ["]>", "] >", "]>"] { + let mut writer = SvgWriter::fragment(); + writer.doctype_internal("svg", internal, ""); + assert!(writer.is_empty()); + } + } } diff --git a/crates/tar/Cargo.toml b/crates/tar/Cargo.toml new file mode 100644 index 0000000000..e0628a35a7 --- /dev/null +++ b/crates/tar/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "craft-tar" +description = "TAR (v7, ustar, GNU long names and base-256 sizes, pax overrides) and cpio (newc, crc, odc) member walkers for hostile input: list members and where their data lies, without extracting. From Craft Anything." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +# `serde`: `Serialize` on the listing types, for apps that report listings as JSON. +serde = { workspace = true, optional = true } + +[features] +serde = ["dep:serde"] diff --git a/crates/tar/src/lib.rs b/crates/tar/src/lib.rs new file mode 100644 index 0000000000..7712fc2aa2 --- /dev/null +++ b/crates/tar/src/lib.rs @@ -0,0 +1,911 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! Member walkers for Unix archives: tar (v7, ustar, GNU long names and base-256 sizes, pax path +//! local/global overrides) and cpio (newc, crc and portable odc). They list members and where their data +//! lies; nothing is extracted here, and no input can make them panic or loop forever. + +use std::collections::BTreeSet; + +/// Bounds-checked reads from the archive bytes. +struct Reader<'a> { + data: &'a [u8], +} + +impl<'a> Reader<'a> { + fn new(data: &'a [u8]) -> Self { + Reader { data } + } + + /// `len` bytes at `off`, or `None` when they don't all lie inside the data. + fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { + self.data.get(off..off.checked_add(len)?) + } +} + +/// What a member is. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))] +pub enum MemberKind { + File, + Dir, + Symlink, + Hardlink, + Device, + Fifo, + Other, +} + +/// One archive member. +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct Member { + pub name: String, + pub kind: MemberKind, + pub size: u64, + /// Where the member's data starts, relative to the archive start. + pub data_offset: u64, + #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))] + pub link_target: Option, + pub mode: u32, +} + +/// Why tar name metadata stopped a walk that still retains earlier members. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))] +pub enum StopReason { + GnuMetadataTooLong, + GnuMetadataTruncated, + GlobalNameBudget, +} + +/// The members of an archive. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct Listing { + /// `tar`, `cpio-newc`, `cpio-crc` or `cpio-odc`. + pub format: &'static str, + pub members: Vec, + /// Bytes from the archive start to the end of its last structure (end marker included). + pub length: u64, + /// True when the end-of-archive marker was reached. + pub complete: bool, + /// True when `max_members` stopped the walk. + pub truncated: bool, + /// Name metadata that prevented reading the remaining member identities. + #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))] + pub stop_reason: Option, + pub warnings: Vec, +} + +const BLOCK: usize = 512; +const MAX_NAME: usize = 4096; +const MAX_GLOBAL_NAME_COPIES: usize = 64 << 20; + +fn trim_field(f: &[u8]) -> &[u8] { + let end = f.iter().position(|&b| b == 0).unwrap_or(f.len()); + f.get(..end).unwrap_or(&[]) +} + +fn text(f: &[u8]) -> String { + String::from_utf8_lossy(trim_field(f)).into_owned() +} + +/// An octal number field (spaces and NULs around it are ignored); GNU base-256 when the high bit +/// of the first byte is set. +fn octal(f: &[u8]) -> Option { + if let Some((&first, rest)) = f.split_first() + && first & 0x80 != 0 + { + if first & 0x40 != 0 { + return None; // This field holds an unsigned value. + } + let mut v = u64::from(first & 0x7f); + for &b in rest { + v = v.checked_mul(256)?.checked_add(u64::from(b))?; + } + return Some(v); + } + let padding = |&b: &u8| b == 0 || b == b' '; + let mut digits = f.iter().copied().skip_while(padding).peekable(); + let mut v = 0u64; + while let Some(b) = digits.next_if(|b| !padding(b)) { + if !(b'0'..=b'7').contains(&b) { + return None; + } + v = v.checked_mul(8)?.checked_add(u64::from(b - b'0'))?; + } + digits.all(|b| padding(&b)).then_some(v) +} + +/// True when a 512-byte block is a tar header with a correct checksum. +pub fn tar_header_ok(h: &[u8]) -> bool { + let Some(h) = h.get(..BLOCK) else { return false }; + let Some(stored) = h.get(148..156).and_then(octal) else { return false }; + let mut unsigned = 0u64; + let mut signed = 0i64; + for (i, &b) in h.iter().enumerate() { + let v = if (148..156).contains(&i) { b' ' } else { b }; + unsigned += u64::from(v); + signed += i64::from(v as i8); + } + // An all-zero block sums to 256 (the blank checksum field) and is the end marker, not a header. + unsigned != 256 && (stored == unsigned || i64::try_from(stored).is_ok_and(|s| s == signed)) +} + +fn round_up(v: u64, to: u64) -> Option { + let r = v % to; + if r == 0 { Some(v) } else { v.checked_add(to - r) } +} + +/// Walk a tar archive. `None` when the first block is not a valid header. +pub fn tar(data: &[u8], max_members: usize) -> Option { + tar_with_name_copy_limit(data, max_members, MAX_GLOBAL_NAME_COPIES) +} + +fn tar_with_name_copy_limit(data: &[u8], max_members: usize, mut name_bytes_left: usize) -> Option { + let r = Reader::new(data); + if !tar_header_ok(r.slice(0, BLOCK)?) { + return None; + } + let mut out = Listing { format: "tar", ..Listing::default() }; + let mut pos = 0usize; + let mut long_name: Option = None; + let mut long_link: Option = None; + let mut pax = PaxOverrides::default(); + // Every iteration advances by at least one block, so the walk is bounded by the input size. + 'headers: loop { + let Some(h) = r.slice(pos, BLOCK) else { + out.warnings.push(format!("archive ends inside a header at {pos:#x}")); + out.length = data.len() as u64; + break; + }; + if h.iter().all(|&b| b == 0) { + // End of archive: one or two zero blocks. + let second = r.slice(pos + BLOCK, BLOCK).is_some_and(|b| b.iter().all(|&x| x == 0)); + out.length = (pos + if second { 2 * BLOCK } else { BLOCK }) as u64; + out.complete = true; + break; + } + if !tar_header_ok(h) { + out.warnings.push(format!("invalid header checksum at {pos:#x}; stopping")); + out.length = pos as u64; + break; + } + let typeflag = h.get(156).copied().unwrap_or(0); + let Some(mut size) = h.get(124..136).and_then(octal) else { + out.warnings.push(format!("unreadable size at {pos:#x}")); + out.length = pos as u64; + break; + }; + if !matches!(typeflag, b'x' | b'g' | b'L' | b'K') + && let Some(s) = pax.size.take().or(pax.global_size) + { + size = s; + } + let data_off = pos + BLOCK; + let Some(next) = + round_up(size, BLOCK as u64).and_then(|s| u64::try_from(data_off).ok()?.checked_add(s)).and_then(|n| usize::try_from(n).ok()) + else { + if matches!(typeflag, b'L' | b'K') { + out.stop_reason = Some(StopReason::GnuMetadataTruncated); + } + out.warnings.push(format!("size overflows at {pos:#x}")); + out.length = pos as u64; + break; + }; + let body = r.slice(data_off, usize::try_from(size).unwrap_or(usize::MAX)); + match typeflag { + b'L' | b'K' => { + let Some(body) = body.filter(|_| next <= data.len()) else { + out.stop_reason = Some(StopReason::GnuMetadataTruncated); + out.warnings.push(format!("GNU long-name record ends early at {pos:#x}")); + out.length = data.len() as u64; + break; + }; + let end = body.iter().take(MAX_NAME + 1).position(|&byte| byte == 0).unwrap_or(body.len()); + if end > MAX_NAME { + out.stop_reason = Some(StopReason::GnuMetadataTooLong); + out.warnings.push(format!("GNU long name or link exceeds {MAX_NAME} bytes at {pos:#x}")); + out.length = pos as u64; + break; + } + let value = Some(String::from_utf8_lossy(&body[..end]).into_owned()); + if typeflag == b'L' { + long_name = value; + } else { + long_link = value; + } + } + b'x' | b'g' => { + if let Some(records) = body + && let Err(warning) = pax.apply(records, typeflag == b'g', pos) + { + out.warnings.push(warning); + out.length = pos as u64; + break 'headers; + } + } + _ => { + if out.members.len() >= max_members { + out.truncated = true; + out.length = pos as u64; + break; + } + let linked = matches!(typeflag, b'1' | b'2'); + let copied_path = if pax.path.is_none() { pax.global_path.as_ref().map_or(0, String::len) } else { 0 }; + let copied_link = if linked && pax.link.is_none() { pax.global_link.as_ref().map_or(0, String::len) } else { 0 }; + let Some(remaining) = name_bytes_left.checked_sub(copied_path.saturating_add(copied_link)) else { + out.stop_reason = Some(StopReason::GlobalNameBudget); + out.warnings.push("the retained global pax name-byte budget was reached; later members were omitted".into()); + out.length = pos as u64; + break; + }; + name_bytes_left = remaining; + // Old GNU headers use these bytes for timestamps and sparse-file metadata. + let ustar = h.get(257..263) == Some(b"ustar\0"); + let base = text(h.get(0..100).unwrap_or(&[])); + let prefix = if ustar { text(h.get(345..500).unwrap_or(&[])) } else { String::new() }; + let joined = if prefix.is_empty() { base } else { format!("{prefix}/{base}") }; + // PAX values override header names, including GNU's long-name replacement. + // Consume the one-member GNU records even when a PAX value takes precedence. + let gnu_name = long_name.take(); + let gnu_link = long_link.take(); + let name = pax.path.take().or_else(|| pax.global_path.clone()).or(gnu_name).unwrap_or(joined); + let link = pax + .link + .take() + .or_else(|| if linked { pax.global_link.clone() } else { None }) + .or(gnu_link) + .or_else(|| Some(text(h.get(157..257).unwrap_or(&[])))) + .filter(|l| !l.is_empty()); + let mut kind = tar_kind(typeflag, &name); + if std::mem::take(&mut pax.sparse) || !pax.global_sparse.is_empty() { + kind = MemberKind::Other; + out.warnings.push(format!("{name}: GNU sparse reconstruction is unsupported; stored extents are not the complete file")); + } + let mode = h.get(100..108).and_then(octal).and_then(|m| u32::try_from(m).ok()).unwrap_or(0); + if body.is_none() && kind == MemberKind::File { + out.warnings.push(format!("{name}: data runs past the end of the input")); + } + out.members.push(Member { + name, + kind, + size, + data_offset: data_off as u64, + link_target: if matches!(kind, MemberKind::Symlink | MemberKind::Hardlink) { link } else { None }, + mode, + }); + } + } + if next > data.len() { + out.length = data.len() as u64; + out.warnings.push("archive ends early (no end-of-archive marker)".into()); + break; + } + pos = next; + } + Some(out) +} + +/// What a tar header's typeflag says the member is. +fn tar_kind(typeflag: u8, name: &str) -> MemberKind { + match typeflag { + b'0' | 0 | b'7' => { + if name.ends_with('/') { + MemberKind::Dir + } else { + MemberKind::File + } + } + b'1' => MemberKind::Hardlink, + b'2' => MemberKind::Symlink, + b'3' | b'4' => MemberKind::Device, + b'5' => MemberKind::Dir, + b'6' => MemberKind::Fifo, + _ => MemberKind::Other, + } +} + +/// The pax values that override the next member (local) or every later one (global). +#[derive(Default)] +struct PaxOverrides<'a> { + path: Option, + link: Option, + size: Option, + sparse: bool, + global_path: Option, + global_link: Option, + global_size: Option, + /// Borrow keys from the input: global sparse attributes persist until their own deletion. + global_sparse: BTreeSet<&'a [u8]>, +} + +impl<'a> PaxOverrides<'a> { + /// Apply one extended header's records. `Err` is the warning that stops the walk. + fn apply(&mut self, mut remaining: &'a [u8], global: bool, pos: usize) -> Result<(), String> { + for _ in 0..256 { + if remaining.is_empty() { + break; + } + let Some((key, value, rest)) = pax_record(remaining) else { + return Err(format!("invalid pax record at {pos:#x}")); + }; + if key.starts_with(b"GNU.sparse.") { + if !global { + self.sparse = true; + } else if value.is_empty() { + self.global_sparse.remove(key); + } else { + self.global_sparse.insert(key); + } + } + match key { + b"path" | b"linkpath" | b"GNU.sparse.name" => self.set_name(key, value, global, pos)?, + b"size" => self.set_size(value, global, pos)?, + _ => {} + } + remaining = rest; + } + if remaining.is_empty() { Ok(()) } else { Err(format!("pax record limit reached at {pos:#x}")) } + } + + fn set_name(&mut self, key: &[u8], value: &[u8], global: bool, pos: usize) -> Result<(), String> { + if value.len() > MAX_NAME { + return Err(format!("pax name exceeds {MAX_NAME} bytes at {pos:#x}")); + } + let slot = match (global, key == b"linkpath") { + (true, true) => &mut self.global_link, + (true, false) => &mut self.global_path, + (false, true) => &mut self.link, + (false, false) => &mut self.path, + }; + *slot = if global && value.is_empty() { None } else { Some(String::from_utf8_lossy(value).into_owned()) }; + Ok(()) + } + + fn set_size(&mut self, value: &[u8], global: bool, pos: usize) -> Result<(), String> { + let size = std::str::from_utf8(value).ok().and_then(|s| s.parse().ok()); + if !value.is_empty() && (size.is_none() || !value.iter().all(u8::is_ascii_digit)) { + let scope = if global { "global" } else { "local" }; + return Err(format!("invalid {scope} pax size at {pos:#x}")); + } + if global { + self.global_size = size; + } else { + self.size = size; + } + Ok(()) + } +} + +/// Read one length-prefixed pax record, borrowing even unknown keys and values from the header. +fn pax_record(data: &[u8]) -> Option<(&[u8], &[u8], &[u8])> { + let sp = data.iter().position(|&byte| byte == b' ')?; + let digits = data.get(..sp)?; + if !digits.iter().all(u8::is_ascii_digit) { + return None; + } + let len: usize = std::str::from_utf8(digits).ok()?.parse().ok()?; + let field = data.get(sp + 1..len)?.strip_suffix(b"\n")?; + let eq = field.iter().position(|&byte| byte == b'=')?; + if eq == 0 { + return None; + } + Some((field.get(..eq)?, field.get(eq + 1..)?, data.get(len..)?)) +} + +fn hex_field(f: &[u8]) -> Option { + if !f.iter().all(u8::is_ascii_hexdigit) { + return None; + } + let s = std::str::from_utf8(f).ok()?; + u64::from_str_radix(s, 16).ok() +} + +fn oct_field(f: &[u8]) -> Option { + if !f.iter().all(|b| (b'0'..=b'7').contains(b)) { + return None; + } + let s = std::str::from_utf8(f).ok()?; + u64::from_str_radix(s, 8).ok() +} + +fn mode_kind(mode: u32) -> MemberKind { + match mode & 0o170_000 { + 0o100_000 => MemberKind::File, + 0o040_000 => MemberKind::Dir, + 0o120_000 => MemberKind::Symlink, + 0o020_000 | 0o060_000 => MemberKind::Device, + 0o010_000 => MemberKind::Fifo, + _ => MemberKind::Other, + } +} + +/// Walk a cpio archive (newc `070701`, crc `070702`, odc `070707`). `None` when the first header +/// is not one of these. +pub fn cpio(data: &[u8], max_members: usize) -> Option { + cpio_with_checksum(data, max_members, &mut |body| CpioChecksum::Value(body.iter().fold(0u32, |sum, &byte| sum.wrapping_add(u32::from(byte))))) +} + +/// A checksum sum, or the reason a caller stopped verification before completing it. +#[derive(Clone, Copy)] +pub enum CpioChecksum { + Value(u32), + Skipped, + Cancelled, +} + +/// Let a scanner share its checksum work allowance and cancellation across overlapping probes. +pub fn cpio_with_checksum(data: &[u8], max_members: usize, checksum: &mut dyn FnMut(&[u8]) -> CpioChecksum) -> Option { + let r = Reader::new(data); + let format = match r.slice(0, 6)? { + b"070701" => "cpio-newc", + b"070702" => "cpio-crc", + b"070707" => "cpio-odc", + _ => return None, + }; + let odc = format == "cpio-odc"; + let mut hard_links = std::collections::HashMap::<(u64, u64, u64), Vec>::new(); + let mut out = Listing { format, ..Listing::default() }; + let mut pos = 0usize; + let align = |v: usize| if odc { Some(v) } else { v.checked_add(3).map(|x| x & !3) }; + loop { + let hdr_len = if odc { 76 } else { 110 }; + let Some(h) = r.slice(pos, hdr_len) else { + out.warnings.push(format!("archive ends inside a header at {pos:#x}")); + out.length = data.len() as u64; + break; + }; + if h.get(..6) != r.slice(0, 6) { + out.warnings.push(format!("bad header magic at {pos:#x}; stopping")); + out.length = pos as u64; + break; + } + let fields = if odc { + (h.get(18..24).and_then(oct_field), h.get(59..65).and_then(oct_field), h.get(65..76).and_then(oct_field)) + } else { + (h.get(14..22).and_then(hex_field), h.get(94..102).and_then(hex_field), h.get(54..62).and_then(hex_field)) + }; + let (Some(mode), Some(namesize), Some(filesize)) = fields else { + out.warnings.push(format!("unreadable header fields at {pos:#x}")); + out.length = pos as u64; + break; + }; + let namesize = usize::try_from(namesize).unwrap_or(usize::MAX); + if namesize == 0 || namesize > MAX_NAME { + out.warnings.push(format!("implausible name size at {pos:#x}")); + out.length = pos as u64; + break; + } + let Some(name_bytes) = r.slice(pos + hdr_len, namesize) else { + out.warnings.push(format!("name runs past the end at {pos:#x}")); + out.length = data.len() as u64; + break; + }; + // newc permits extra trailing NULs in namesize for alignment. + let Some(end) = name_bytes.iter().position(|&b| b == 0) else { + out.warnings.push(format!("unterminated member name at {pos:#x}")); + out.length = pos as u64; + break; + }; + if end == 0 || name_bytes.get(end..).is_some_and(|pad| pad.iter().any(|&b| b != 0)) { + out.warnings.push(format!("invalid member name at {pos:#x}")); + out.length = pos as u64; + break; + } + let name = text(name_bytes); + let Some(data_off) = (pos + hdr_len).checked_add(namesize).and_then(align) else { break }; + let size = usize::try_from(filesize).unwrap_or(usize::MAX); + let Some(next) = data_off.checked_add(size).and_then(align) else { + out.warnings.push(format!("size overflows at {pos:#x}")); + out.length = pos as u64; + break; + }; + if name == "TRAILER!!!" { + out.length = next.min(data.len()) as u64; + if size == 0 && next <= data.len() { + out.complete = true; + } else { + out.warnings.push(format!("invalid or truncated trailer at {pos:#x}")); + } + break; + } + let mode = u32::try_from(mode).unwrap_or(0); + let kind = mode_kind(mode); + let link_target = if kind == MemberKind::Symlink { r.slice(data_off, size.min(MAX_NAME)).map(text) } else { None }; + if out.members.len() >= max_members { + out.truncated = true; + out.length = pos as u64; + break; + } + if format == "cpio-crc" { + match h.get(102..110).filter(|field| field.iter().all(u8::is_ascii_hexdigit)).and_then(hex_field).and_then(|n| u32::try_from(n).ok()) { + Some(expected) => { + if let Some(body) = r.slice(data_off, size) { + match checksum(body) { + CpioChecksum::Value(actual) => { + if actual != expected { + out.warnings.push(format!("{name}: data checksum mismatch (stored {expected:08x}, computed {actual:08x})")); + } + } + CpioChecksum::Skipped => out.warnings.push(format!("{name}: data checksum not verified (scan byte budget exhausted)")), + CpioChecksum::Cancelled => return None, + } + } + } + None => out.warnings.push(format!("{name}: unreadable data checksum")), + } + } + // newc stores hard-linked files by device and inode. GNU cpio may put the + // payload on the last name, so identify aliases after scanning the group. + if !odc + && kind == MemberKind::File + && h.get(38..46).and_then(hex_field).is_some_and(|n| n > 1) + && let (Some(ino), Some(major), Some(minor)) = + (h.get(6..14).and_then(hex_field), h.get(62..70).and_then(hex_field), h.get(70..78).and_then(hex_field)) + { + hard_links.entry((major, minor, ino)).or_default().push(out.members.len()); + } + out.members.push(Member { name, kind, size: filesize, data_offset: data_off as u64, link_target, mode }); + if next > data.len() { + out.warnings.push("archive ends early (no trailer)".into()); + out.length = data.len() as u64; + break; + } + pos = next; + } + for group in hard_links.values().filter(|group| group.len() > 1) { + let source = group.iter().rev().copied().find(|&i| out.members.get(i).is_some_and(|m| m.size > 0)).or_else(|| group.first().copied()); + let Some(source) = source else { continue }; + let Some(name) = out.members.get(source).map(|m| m.name.clone()) else { continue }; + for &index in group { + if index != source + && let Some(alias) = out.members.get_mut(index) + && alias.size == 0 + { + alias.kind = MemberKind::Hardlink; + alias.link_target = Some(name.clone()); + } + } + } + Some(out) +} + +/// The data of a member, when it lies inside `data`. +pub fn member_data<'a>(data: &'a [u8], m: &Member) -> Option<&'a [u8]> { + Reader::new(data).slice(usize::try_from(m.data_offset).ok()?, usize::try_from(m.size).ok()?) +} + +#[cfg(test)] +mod tar_tests; +#[cfg(test)] +mod testkit; + +#[cfg(test)] +mod tests { + use super::*; + use crate::testkit as fx; + + #[test] + fn plus_sign_in_cpio_fields_is_rejected() { + assert_eq!(hex_field(b"+000000A"), None); + assert_eq!(oct_field(b"+00012"), None); + assert_eq!(hex_field(b"0000000A"), Some(10)); + assert_eq!(oct_field(b"00012"), Some(10)); + } + + fn global_record(key: &str, value: &str) -> String { + let tail = format!(" {key}={value}\n"); + let mut len = tail.len() + 1; + loop { + let record = format!("{len}{tail}"); + if record.len() == len { + return record; + } + len = record.len(); + } + } + + #[test] + fn global_name_copies_stop_before_spending_the_budget() { + let global = global_record("path", "shared"); + let data = + fx::tar_entries(&[("global", b'g', global.as_bytes(), ""), ("one", b'0', b"", ""), ("two", b'0', b"", ""), ("three", b'0', b"", "")]); + let listing = tar_with_name_copy_limit(&data, 10, 12).unwrap(); + assert_eq!(listing.members.len(), 2); + assert!(listing.members.iter().all(|m| m.name == "shared")); + assert_eq!(listing.stop_reason, Some(StopReason::GlobalNameBudget)); + assert!(!listing.complete && !listing.truncated); + assert!(listing.warnings.iter().any(|w| w.contains("name-byte budget"))); + assert_eq!(listing.length, 2048); + assert!(tar_with_name_copy_limit(&data, 10, 18).unwrap().complete); + } + + #[test] + fn local_names_and_unused_global_links_do_not_spend_copy_bytes() { + let global = global_record("path", "name") + &global_record("linkpath", "unused-link"); + let local = global_record("path", "local-name"); + let data = fx::tar_entries(&[ + ("global", b'g', global.as_bytes(), ""), + ("local", b'x', local.as_bytes(), ""), + ("one", b'0', b"", ""), + ("two", b'0', b"", ""), + ]); + let listing = tar_with_name_copy_limit(&data, 10, 4).unwrap(); + assert!(listing.complete); + assert_eq!(listing.members.iter().map(|m| m.name.as_str()).collect::>(), ["local-name", "name"]); + assert!(listing.members.iter().all(|m| m.link_target.is_none())); + } + + #[test] + fn global_names_and_links_share_the_decoded_byte_budget() { + let global = global_record("path", "é") + &global_record("linkpath", "中"); + let data = fx::tar_entries(&[("global", b'g', global.as_bytes(), ""), ("one", b'2', b"", "fallback"), ("two", b'1', b"", "fallback")]); + let listing = tar_with_name_copy_limit(&data, 10, 5).unwrap(); + assert_eq!(listing.members.len(), 1); + assert_eq!(listing.members[0].link_target.as_deref(), Some("中")); + assert_eq!(listing.stop_reason, Some(StopReason::GlobalNameBudget)); + assert!(tar_with_name_copy_limit(&data, 10, 10).unwrap().complete); + } + + #[test] + fn oversized_gnu_names_do_not_alias_their_truncated_prefix() { + for kind in *b"LK" { + let mut long = vec![b'n'; MAX_NAME + 1]; + long.push(0); + let data = fx::tar_entries(&[ + ("before", b'0', b"kept", ""), + ("././@LongLink", kind, &long, ""), + ("short", if kind == b'K' { b'2' } else { b'0' }, b"", "fallback"), + ]); + let listing = tar(&data, 10).unwrap(); + assert!(!listing.complete); + assert_eq!(listing.stop_reason, Some(StopReason::GnuMetadataTooLong)); + assert_eq!(listing.members.len(), 1); + assert_eq!(listing.members[0].name, "before"); + assert_eq!(member_data(&data, &listing.members[0]).unwrap(), b"kept"); + assert!(listing.warnings.iter().any(|warning| warning.contains("GNU long name or link exceeds"))); + } + } + + #[test] + fn gnu_long_names_keep_exact_limits_and_short_terminated_values() { + for kind in *b"LK" { + for terminated in [false, true] { + let mut long = vec![b'n'; MAX_NAME]; + if terminated { + long.push(0); + } + let data = fx::tar_entries(&[("././@LongLink", kind, &long, ""), ("short", if kind == b'K' { b'2' } else { b'0' }, b"", "fallback")]); + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete, "{:?}", listing.warnings); + let member = &listing.members[0]; + let name = if kind == b'L' { member.name.as_str() } else { member.link_target.as_deref().unwrap() }; + assert_eq!(name, "n".repeat(MAX_NAME)); + } + } + let mut padded = b"short\0".to_vec(); + padded.resize(MAX_NAME + 100, 0); + let data = fx::tar_entries(&[("././@LongLink", b'L', &padded, ""), ("fallback", b'0', b"payload", "")]); + assert_eq!(tar(&data, 10).unwrap().members[0].name, "short"); + } + + fn sparse_pax_record(key: &str, value: &str) -> Vec { + let field = format!(" {key}={value}\n"); + let mut length = field.len() + 1; + loop { + let actual = field.len() + length.to_string().len(); + if actual == length { + return format!("{length}{field}").into_bytes(); + } + length = actual; + } + } + + #[test] + fn gnu_sparse_pax_members_are_not_regular_file_bytes() { + for fields in [ + vec![("GNU.sparse.size", "100"), ("GNU.sparse.numblocks", "1"), ("GNU.sparse.offset", "50"), ("GNU.sparse.numbytes", "3")], + vec![("GNU.sparse.size", "100"), ("GNU.sparse.map", "50,3"), ("GNU.sparse.name", "original.bin")], + vec![("GNU.sparse.major", "1"), ("GNU.sparse.minor", "0"), ("GNU.sparse.realsize", "100"), ("GNU.sparse.name", "original.bin")], + ] { + let metadata: Vec = fields.iter().flat_map(|(key, value)| sparse_pax_record(key, value)).collect(); + let version_one = fields.iter().any(|(key, _)| *key == "GNU.sparse.major"); + let mut sparse_body = if version_one { b"1\n50\n3\n".to_vec() } else { Vec::new() }; + if version_one { + sparse_body.resize(512, 0); + } + sparse_body.extend_from_slice(b"abc"); + let data = + fx::tar_entries(&[("metadata", b'x', &metadata, ""), ("stored-name", b'0', &sparse_body, ""), ("normal", b'0', b"ordinary", "")]); + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete, "{:?}", listing.warnings); + assert_eq!(listing.members.len(), 2); + assert_eq!(listing.members[0].kind, MemberKind::Other); + let named = fields.iter().any(|(key, _)| *key == "GNU.sparse.name"); + assert_eq!(listing.members[0].name, if named { "original.bin" } else { "stored-name" }); + assert_eq!(listing.members[1].kind, MemberKind::File); + assert_eq!(member_data(&data, &listing.members[1]).unwrap(), b"ordinary"); + assert_eq!(listing.warnings.len(), 1); + assert!(listing.warnings[0].contains("sparse reconstruction is unsupported")); + } + } + + #[test] + fn sparse_metadata_survives_other_extension_headers() { + let sparse = sparse_pax_record("GNU.sparse.map", "0,3"); + let path = sparse_pax_record("path", "renamed"); + let data = fx::tar_entries(&[ + ("sparse", b'x', &sparse, ""), + ("name", b'L', b"long-name\0", ""), + ("path", b'x', &path, ""), + ("header", b'0', b"abc", ""), + ("next", b'0', b"ok", ""), + ]); + let listing = tar(&data, 10).unwrap(); + assert_eq!(listing.members[0].name, "renamed"); + assert_eq!(listing.members[0].kind, MemberKind::Other); + assert_eq!(listing.members[1].kind, MemberKind::File); + } + + #[test] + fn gnu_metadata_stop_reasons_keep_partial_listings_and_marker_compatibility() { + for kind in *b"LK" { + let mut data = + fx::tar_entries(&[("before", b'0', b"kept", ""), ("././@LongLink", kind, b"long\0", ""), ("fallback", b'0', b"later", "")]); + data.truncate(3 * BLOCK + 2); + let listing = tar(&data, 10).unwrap(); + assert_eq!(listing.stop_reason, Some(StopReason::GnuMetadataTruncated)); + assert!(!listing.complete); + assert!(!listing.truncated); + assert_eq!(listing.members.len(), 1); + assert_eq!(member_data(&data, &listing.members[0]).unwrap(), b"kept"); + } + let mut data = fx::tar_entries(&[("file", b'0', b"kept", "")]); + data.truncate(2 * BLOCK); + let listing = tar(&data, 10).unwrap(); + assert!(!listing.complete); + assert_eq!(listing.stop_reason, None); + assert_eq!(member_data(&data, &listing.members[0]).unwrap(), b"kept"); + let cpio_listing = cpio(&fx::cpio_newc(&[("file", b"kept", 0o100644)]), 10).unwrap(); + assert_eq!(cpio_listing.stop_reason, None); + } + + #[test] + fn gnu_metadata_requires_its_complete_padded_record() { + let body = b"next\0"; + for kind in *b"LK" { + let data = fx::tar_entries(&[ + ("before", b'0', b"kept", ""), + ("././@LongLink", kind, body, ""), + ("fallback", if kind == b'L' { b'0' } else { b'2' }, b"", "fallback"), + ]); + for padding in [0, 1, BLOCK - body.len() - 1] { + let short = &data[..3 * BLOCK + body.len() + padding]; + let listing = tar(short, 10).unwrap(); + assert_eq!(listing.stop_reason, Some(StopReason::GnuMetadataTruncated)); + assert!(!listing.complete); + assert_eq!(listing.members.len(), 1); + assert_eq!(member_data(short, &listing.members[0]).unwrap(), b"kept"); + } + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete); + assert_eq!(listing.stop_reason, None); + assert_eq!(listing.members.len(), 2); + } + } + + #[test] + fn walks_tar() { + let t = fx::tar(&[("etc/passwd", b"root:x:0:0\n"), ("bin/", b""), ("long/".repeat(30).as_str(), b"deep")]); + let l = tar(&t, 100).unwrap(); + assert!(l.complete, "{:?}", l.warnings); + assert_eq!(l.members.len(), 3); + assert_eq!(l.members[0].name, "etc/passwd"); + assert_eq!(member_data(&t, &l.members[0]).unwrap(), b"root:x:0:0\n"); + assert_eq!(l.members[1].kind, MemberKind::Dir); + assert!(l.members[2].name.starts_with("long/long/")); + assert_eq!(l.length, t.len() as u64); + let l2 = tar(&t, 1).unwrap(); + assert!(l2.truncated); + assert_eq!(l2.members.len(), 1); + } + + #[test] + fn cpio_names_and_trailers_must_be_complete() { + let bytes = fx::cpio_newc(&[("abc", b"x", 0o100644)]); + let trailer = bytes.windows(6).rposition(|b| b == b"070701").unwrap(); + for (offset, byte) in [(113, b'x'), (111, 0)] { + let mut damaged = bytes.clone(); + damaged[offset] = byte; + let listed = cpio(&damaged, 10).unwrap(); + assert!(!listed.complete); + assert!(listed.members.is_empty()); + } + let mut padded_name = bytes.clone(); + padded_name[112] = 0; + assert_eq!(cpio(&padded_name, 10).unwrap().members[0].name, "ab"); + let mut with_payload = bytes.clone(); + with_payload[trailer + 61] = b'1'; + assert!(!cpio(&with_payload, 10).unwrap().complete); + assert!(!cpio(&bytes[..bytes.len() - 1], 10).unwrap().complete); + } + + #[test] + fn cpio_hard_link_aliases_do_not_appear_as_empty_files() { + for content_first in [true, false] { + let data = if content_first { [b"abc".as_slice(), b""] } else { [b"".as_slice(), b"abc"] }; + let mut archive = fx::cpio_newc(&[("one", data[0], 0o100644), ("two", data[1], 0o100644), ("separate", b"", 0o100644)]); + let starts: Vec<_> = archive.windows(6).enumerate().filter(|(_, bytes)| *bytes == b"070701").map(|(i, _)| i).collect(); + for &start in &starts[..3] { + archive[start + 6..start + 14].copy_from_slice(b"00000015"); + archive[start + 38..start + 46].copy_from_slice(b"00000002"); + } + archive[starts[2] + 70..starts[2] + 78].copy_from_slice(b"00000001"); + let (file, alias) = if content_first { (0, 1) } else { (1, 0) }; + for crc in [false, true] { + if crc { + for &start in &starts { + archive[start..start + 6].copy_from_slice(b"070702"); + } + archive[starts[file] + 102..starts[file] + 110].copy_from_slice(b"00000126"); + } + let listing = cpio(&archive, 10).unwrap(); + assert_eq!(listing.members[file].kind, MemberKind::File); + assert_eq!(member_data(&archive, &listing.members[file]), Some(b"abc".as_slice())); + assert_eq!(listing.members[alias].kind, MemberKind::Hardlink); + assert_eq!(listing.members[alias].link_target.as_deref(), Some(listing.members[file].name.as_str())); + assert_eq!(listing.members[2].kind, MemberKind::File); + assert!(listing.warnings.is_empty()); + } + } + } + + #[test] + fn walks_cpio() { + let c = fx::cpio_newc(&[("init", b"#!/bin/sh\n", 0o100755), ("dev", b"", 0o040755), ("sh", b"busybox", 0o120777)]); + let l = cpio(&c, 100).unwrap(); + assert!(l.complete); + assert_eq!(l.members.len(), 3); + assert_eq!(member_data(&c, &l.members[0]).unwrap(), b"#!/bin/sh\n"); + assert_eq!(l.members[2].kind, MemberKind::Symlink); + assert_eq!(l.members[2].link_target.as_deref(), Some("busybox")); + assert_eq!(l.length, c.len() as u64); + } + + #[test] + fn octal_fields() { + assert_eq!(octal(b"0000644 \0"), Some(0o644)); + assert_eq!(octal(b" \0"), Some(0)); + assert_eq!(octal(b"9"), None); + assert_eq!(octal(&[0x80, 0, 0, 1, 0]), Some(256)); + assert_eq!(octal(&[0xff; 8]), None); + assert_eq!(octal(&[0xff; 12]), None); + } + + #[test] + fn hostile_archives_do_not_panic() { + let t = fx::tar(&[("a", b"hello"), ("b/c", b"world")]); + let c = fx::cpio_newc(&[("a", b"hello", 0o100644)]); + for s in [&t, &c] { + for m in fx::mutations(s) { + let _ = tar(&m, 10); + let _ = cpio(&m, 10); + } + for n in 0..s.len().min(800) { + let _ = tar(&s[..n], 10); + let _ = cpio(&s[..n], 10); + } + } + for seed in 0..50 { + let n = fx::noise(seed, 2048); + let _ = tar(&n, 10); + let _ = cpio(&n, 10); + } + assert!(pax_record(b"12 path=abc\n").is_some()); + assert!(pax_record(b"9999999999999999999999 x").is_none()); + } +} diff --git a/crates/tar/src/tar_tests.rs b/crates/tar/src/tar_tests.rs new file mode 100644 index 0000000000..38f72abd92 --- /dev/null +++ b/crates/tar/src/tar_tests.rs @@ -0,0 +1,404 @@ +// ---- from Craft Anything crates/formats/tests/tar_gnu_names.rs +mod tar_gnu_names { + use crate::testkit as fx; + use crate::{member_data, tar}; + + fn checksum(header: &mut [u8]) { + header[148..156].fill(b' '); + let sum: u32 = header.iter().map(|&b| u32::from(b)).sum(); + header[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); + } + + #[test] + fn old_gnu_timestamps_are_not_posix_path_prefixes() { + let mut archive = fx::tar(&[("program", b"payload")]); + let header = &mut archive[..512]; + header[257..265].copy_from_slice(b"ustar \0"); + header[345..357].copy_from_slice(b"00000000123\0"); + header[357..369].copy_from_slice(b"00000000456\0"); + checksum(header); + let listing = tar(&archive, 10).unwrap(); + assert!(listing.complete); + assert_eq!(listing.members[0].name, "program"); + assert_eq!(member_data(&archive, &listing.members[0]), Some(b"payload".as_slice())); + } + + #[test] + fn posix_ustar_prefixes_are_still_joined() { + let mut archive = fx::tar(&[("program", b"payload")]); + let header = &mut archive[..512]; + header[345..352].copy_from_slice(b"usr/bin"); + checksum(header); + assert_eq!(tar(&archive, 10).unwrap().members[0].name, "usr/bin/program"); + } +} + +// ---- from Craft Anything crates/formats/tests/tar_local_pax_size.rs +mod tar_local_pax_size { + use crate::testkit::tar_entries; + use crate::{member_data, tar}; + + /// Encode the decimal byte count that includes the PAX record itself. + fn record(value: &str) -> String { + let body = format!(" size={value}\n"); + let mut size = body.len() + 1; + loop { + let result = format!("{size}{body}"); + if result.len() == size { + return result; + } + size = result.len(); + } + } + + /// Invalid local sizes cannot silently fall back to a plausible member header. + #[test] + fn malformed_local_sizes_stop_before_the_affected_member() { + for value in ["no", "-1", "+3", " 3", "3 ", "3.0", "18446744073709551616"] { + let pax = record(value); + let bytes = tar_entries(&[("keep", b'0', b"ok", ""), ("PaxHeader", b'x', pax.as_bytes(), ""), ("affected", b'0', b"abc", "")]); + let report = tar(&bytes, 10).unwrap(); + assert!(!report.complete, "size={value}"); + assert_eq!(report.members.len(), 1); + assert_eq!(report.members[0].name, "keep"); + assert_eq!(member_data(&bytes, &report.members[0]), Some(b"ok".as_slice())); + assert!(report.warnings.iter().any(|w| w.contains("pax size"))); + } + } + + /// Decimal sizes, zero, and the existing empty override behavior still work. + #[test] + fn valid_local_sizes_remain_readable() { + for (size, body) in [("3", b"abc".as_slice()), ("0003", b"abc"), ("0", b""), ("", b"abc")] { + let pax = record(size); + let bytes = tar_entries(&[("PaxHeader", b'x', pax.as_bytes(), ""), ("file", b'0', body, "")]); + let report = tar(&bytes, 10).unwrap(); + assert!(report.complete, "{:?}", report.warnings); + assert_eq!(member_data(&bytes, &report.members[0]), Some(body)); + } + } +} + +// ---- from Craft Anything crates/formats/tests/tar_pax_size.rs +mod tar_pax_size { + use crate::testkit as fx; + use crate::{member_data, tar}; + + fn clear_member_size(archive: &mut [u8], offset: usize) { + let header = &mut archive[offset..offset + 512]; + header[124..136].copy_from_slice(b"00000000000\0"); + header[148..156].fill(b' '); + let sum: u32 = header.iter().map(|&b| u32::from(b)).sum(); + header[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); + } + + #[test] + fn pax_size_survives_a_gnu_long_name_record() { + let mut archive = fx::tar_entries(&[ + ("PaxHeader", b'x', b"10 size=3\n", ""), + ("././@LongLink", b'L', b"renamed\0", ""), + ("short", b'0', b"abc", ""), + ("next", b'0', b"later", ""), + ]); + clear_member_size(&mut archive, 2048); + let listing = tar(&archive, 10).unwrap(); + assert!(listing.complete, "{:?}", listing.warnings); + assert_eq!(listing.members.len(), 2); + assert_eq!(listing.members[0].name, "renamed"); + assert_eq!(listing.members[0].size, 3); + assert_eq!(member_data(&archive, &listing.members[0]), Some(b"abc".as_slice())); + assert_eq!(listing.members[1].size, 5); + assert_eq!(member_data(&archive, &listing.members[1]), Some(b"later".as_slice())); + } + + #[test] + fn pax_size_without_intervening_metadata_still_applies_once() { + let mut archive = fx::tar_entries(&[("PaxHeader", b'x', b"10 size=3\n", ""), ("short", b'0', b"abc", ""), ("next", b'0', b"later", "")]); + clear_member_size(&mut archive, 1024); + let listing = tar(&archive, 10).unwrap(); + assert!(listing.complete); + assert_eq!(listing.members.iter().map(|m| m.size).collect::>(), vec![3, 5]); + } + + fn pax_record(key: &str, value: &str) -> String { + let content = format!(" {key}={value}\n"); + let mut len = content.len() + 1; + loop { + let record = format!("{len}{content}"); + if record.len() == len { + return record; + } + len = record.len(); + } + } + + #[test] + fn malformed_pax_framing_stops_the_listing() { + for invalid in [b"10 size=3!".as_slice(), b"10 size=3!\n", b"20 size=3\n", b"+12 path=no\n", b"5 =x\n", b"12 path=a=b\n11 path=bad"] { + let archive = fx::tar_entries(&[("keep", b'0', b"one", ""), ("PaxHeader", b'x', invalid, ""), ("after", b'0', b"two", "")]); + let listing = tar(&archive, 10).unwrap(); + assert!(!listing.complete); + assert_eq!(listing.members.len(), 1); + assert_eq!(listing.members[0].name, "keep"); + assert!(listing.warnings.iter().any(|s| s.contains("pax"))); + } + } + + #[test] + fn pax_path_can_contain_an_equals_sign() { + let archive = fx::tar_entries(&[("PaxHeader", b'x', b"12 path=a=b\n", ""), ("short", b'0', b"ok", "")]); + let listing = tar(&archive, 10).unwrap(); + assert!(listing.complete); + assert_eq!(listing.members[0].name, "a=b"); + } + + #[test] + fn the_name_limit_applies_only_to_pax_fields_kept_as_names() { + let exact = "a".repeat(4096); + let large = "b".repeat(100_000); + let pax = pax_record("comment", &large) + &pax_record("path", &exact); + let archive = fx::tar_entries(&[("PaxHeader", b'x', pax.as_bytes(), ""), ("short", b'0', b"ok", "")]); + let listing = tar(&archive, 10).unwrap(); + assert!(listing.complete); + assert_eq!(listing.members[0].name, exact); + for key in ["path", "linkpath"] { + let pax = pax_record(key, &large); + let archive = fx::tar_entries(&[("PaxHeader", b'x', pax.as_bytes(), ""), ("short", b'2', b"", "link")]); + let listing = tar(&archive, 10).unwrap(); + assert!(!listing.complete); + assert!(listing.members.is_empty()); + assert!(listing.warnings.iter().any(|s| s.contains("4096"))); + } + } + + #[test] + fn empty_pax_values_remove_an_earlier_override() { + let pax = pax_record("path", "other") + &pax_record("path", "") + &pax_record("linkpath", "first") + &pax_record("linkpath", ""); + let archive = fx::tar_entries(&[("PaxHeader", b'x', pax.as_bytes(), ""), ("original", b'2', b"", "target")]); + let listing = tar(&archive, 10).unwrap(); + assert!(listing.complete); + assert!(listing.members[0].name.is_empty()); + assert!(listing.members[0].link_target.is_none()); + } + + #[test] + fn tar_sizes_allow_outer_padding_but_do_not_join_separated_digits() { + for (field, valid) in [(b" 000000001\0 ", true), (b" 0000 0001\0 ", false), (b" 0000\x000001\0 ", false)] { + let mut archive = fx::tar_entries(&[("one", b'0', b"1", ""), ("two", b'0', b"2", "")]); + let header = &mut archive[..512]; + header[124..136].copy_from_slice(field); + header[148..156].fill(b' '); + let sum: u32 = header.iter().map(|&b| u32::from(b)).sum(); + header[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); + let listing = tar(&archive, 10).unwrap(); + assert_eq!(listing.complete, valid); + assert_eq!(listing.members.len(), if valid { 2 } else { 0 }); + } + } + + #[test] + fn excess_pax_records_do_not_hide_a_later_override() { + let mut records = pax_record("comment", "").repeat(256); + for excess in [false, true] { + if excess { + records.push_str(&pax_record("size", "9999")); + } + let archive = fx::tar_entries(&[("PaxHeader", b'x', records.as_bytes(), ""), ("member", b'0', b"ok", "")]); + let listing = tar(&archive, 10).unwrap(); + assert_eq!(listing.complete, !excess); + assert_eq!(listing.members.len(), usize::from(!excess)); + } + } +} + +// ---- from Craft Anything crates/formats/tests/tar_global_pax.rs +mod tar_global_pax { + use crate::testkit as fx; + use crate::{MemberKind, member_data, tar}; + + fn record(key: &str, value: &str) -> String { + let tail = format!(" {key}={value}\n"); + let mut len = tail.len() + 1; + loop { + let record = format!("{len}{tail}"); + if record.len() == len { + return record; + } + len = record.len(); + } + } + + fn clear_size(data: &mut [u8], at: usize) { + let header = &mut data[at..at + 512]; + header[124..136].copy_from_slice(b"00000000000\0"); + header[148..156].fill(b' '); + let sum: u32 = header.iter().map(|&b| u32::from(b)).sum(); + header[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); + } + + #[test] + fn global_path_and_size_persist_across_members_and_metadata() { + let global = record("path", "global-name") + &record("size", "3"); + let local = record("comment", "unrelated"); + let mut data = fx::tar_entries(&[ + ("global", b'g', global.as_bytes(), ""), + ("first", b'0', b"abc", ""), + ("metadata", b'x', local.as_bytes(), ""), + ("second", b'0', b"def", ""), + ]); + clear_size(&mut data, 1024); + clear_size(&mut data, 3072); + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete, "{:?}", listing.warnings); + assert_eq!(listing.members.len(), 2); + assert!(listing.members.iter().all(|member| member.name == "global-name" && member.size == 3)); + assert_eq!(member_data(&data, &listing.members[0]), Some(b"abc".as_slice())); + assert_eq!(member_data(&data, &listing.members[1]), Some(b"def".as_slice())); + } + + #[test] + fn local_attributes_override_only_one_member() { + let global = record("path", "inherited") + &record("size", "3"); + let local = record("path", "one-member") + &record("size", "0"); + let data = fx::tar_entries(&[ + ("global", b'g', global.as_bytes(), ""), + ("local", b'x', local.as_bytes(), ""), + ("first", b'0', b"", ""), + ("second", b'0', b"abc", ""), + ]); + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete); + assert_eq!(listing.members.iter().map(|m| (m.name.as_str(), m.size)).collect::>(), [("one-member", 0), ("inherited", 3)]); + } + + #[test] + fn later_global_records_update_and_delete_only_their_keys() { + let first = record("path", "first-global") + &record("size", "3"); + let second = record("path", "second-global"); + let remove = record("path", "") + &record("size", ""); + let data = fx::tar_entries(&[ + ("global", b'g', first.as_bytes(), ""), + ("one", b'0', b"abc", ""), + ("global", b'g', second.as_bytes(), ""), + ("two", b'0', b"def", ""), + ("global", b'g', remove.as_bytes(), ""), + ("plain", b'0', b"normal", ""), + ]); + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete); + assert_eq!( + listing.members.iter().map(|m| (m.name.as_str(), m.size)).collect::>(), + [("first-global", 3), ("second-global", 3), ("plain", 6)] + ); + } + + #[test] + fn global_link_names_persist_until_deleted() { + let global = record("linkpath", "shared-target"); + let local = record("linkpath", "local-target"); + let remove = record("linkpath", ""); + let data = fx::tar_entries(&[ + ("global", b'g', global.as_bytes(), ""), + ("one", b'2', b"", "fallback"), + ("local", b'x', local.as_bytes(), ""), + ("two", b'1', b"", "fallback"), + ("three", b'2', b"", "fallback"), + ("global", b'g', remove.as_bytes(), ""), + ("four", b'2', b"", "original"), + ]); + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete); + assert_eq!( + listing.members.iter().map(|m| m.link_target.as_deref()).collect::>(), + [Some("shared-target"), Some("local-target"), Some("shared-target"), Some("original")] + ); + } + + #[test] + fn malformed_or_excess_global_records_do_not_claim_complete_members() { + for metadata in [String::from("10 size=3!"), record("comment", "").repeat(257), record("path", &"a".repeat(4097))] { + let data = fx::tar_entries(&[("keep", b'0', b"ok", ""), ("global", b'g', metadata.as_bytes(), ""), ("after", b'0', b"later", "")]); + let listing = tar(&data, 10).unwrap(); + assert!(!listing.complete); + assert_eq!(listing.members.len(), 1); + assert_eq!(listing.members[0].name, "keep"); + assert!(listing.warnings.iter().any(|warning| warning.contains("pax"))); + } + } + + #[test] + fn global_sparse_metadata_keeps_stored_extents_out_of_regular_files() { + let global = record("GNU.sparse.map", "0,3"); + let remove = record("GNU.sparse.map", ""); + let data = fx::tar_entries(&[ + ("global", b'g', global.as_bytes(), ""), + ("one", b'0', b"abc", ""), + ("two", b'0', b"def", ""), + ("global", b'g', remove.as_bytes(), ""), + ("plain", b'0', b"ghi", ""), + ]); + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete); + assert_eq!(listing.members.iter().map(|m| m.kind).collect::>(), [MemberKind::Other, MemberKind::Other, MemberKind::File]); + assert_eq!(listing.warnings.iter().filter(|warning| warning.contains("sparse")).count(), 2); + } + + #[test] + fn unrelated_global_fields_preserve_local_and_gnu_names() { + let global = record("comment", "not a member name"); + let local = record("path", "local"); + let data = fx::tar_entries(&[ + ("local", b'x', local.as_bytes(), ""), + ("global", b'g', global.as_bytes(), ""), + ("first", b'0', b"one", ""), + ("././@LongLink", b'L', b"gnu-name\0", ""), + ("second", b'0', b"two", ""), + ]); + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete && listing.warnings.is_empty()); + assert_eq!(listing.members.iter().map(|m| m.name.as_str()).collect::>(), ["local", "gnu-name"]); + } + + #[test] + fn global_names_obey_the_existing_member_limit() { + let path = "a".repeat(4096); + let global = record("path", &path); + let data = fx::tar_entries(&[("global", b'g', global.as_bytes(), ""), ("one", b'0', b"abc", ""), ("two", b'0', b"def", "")]); + let listing = tar(&data, 1).unwrap(); + assert!(listing.truncated && !listing.complete); + assert_eq!(listing.members.len(), 1); + assert_eq!(listing.members[0].name, path); + } + + #[test] + fn global_pax_names_override_and_consume_gnu_name_records() { + let global = record("path", "global") + &record("linkpath", "global-target"); + let remove = record("path", "") + &record("linkpath", ""); + let data = fx::tar_entries(&[ + ("global", b'g', global.as_bytes(), ""), + ("LongLink", b'L', b"gnu-name\0", ""), + ("LongLink", b'K', b"gnu-target\0", ""), + ("first", b'2', b"", "fallback"), + ("global", b'g', remove.as_bytes(), ""), + ("plain", b'2', b"", "original"), + ]); + let listing = tar(&data, 10).unwrap(); + assert!(listing.complete); + assert_eq!( + listing.members.iter().map(|m| (m.name.as_str(), m.link_target.as_deref())).collect::>(), + [("global", Some("global-target")), ("plain", Some("original"))] + ); + } + + #[test] + fn nonempty_global_sizes_must_be_unsigned_decimal_numbers() { + for size in ["+3", "-3", "3x", " 3", "18446744073709551616"] { + let global = record("size", size); + let data = fx::tar_entries(&[("keep", b'0', b"abc", ""), ("global", b'g', global.as_bytes(), ""), ("after", b'0', b"def", "")]); + let listing = tar(&data, 10).unwrap(); + assert!(!listing.complete); + assert_eq!(listing.members.len(), 1); + assert!(listing.warnings.iter().any(|warning| warning.contains("global pax size"))); + } + } +} diff --git a/crates/tar/src/testkit.rs b/crates/tar/src/testkit.rs new file mode 100644 index 0000000000..828644a4b4 --- /dev/null +++ b/crates/tar/src/testkit.rs @@ -0,0 +1,135 @@ +//! Archive builders and damage generators for the tests, from Craft Anything's testkit. + +#![allow(clippy::indexing_slicing, clippy::cast_possible_truncation)] + +fn tar_header(name: &str, typeflag: u8, size: usize, link: &str) -> Vec { + let mut h = vec![0u8; 512]; + let n = name.as_bytes(); + h[..n.len().min(100)].copy_from_slice(&n[..n.len().min(100)]); + h[100..108].copy_from_slice(b"0000644\0"); + h[108..116].copy_from_slice(b"0000000\0"); + h[116..124].copy_from_slice(b"0000000\0"); + h[124..136].copy_from_slice(format!("{size:011o}\0").as_bytes()); + h[136..148].copy_from_slice(b"00000000000\0"); + h[156] = typeflag; + let l = link.as_bytes(); + h[157..157 + l.len().min(100)].copy_from_slice(&l[..l.len().min(100)]); + h[257..263].copy_from_slice(b"ustar\0"); + h[263..265].copy_from_slice(b"00"); + h[148..156].copy_from_slice(b" "); + let sum: u32 = h.iter().map(|&b| u32::from(b)).sum(); + h[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); + h +} + +fn pad512(v: &mut Vec) { + while !v.len().is_multiple_of(512) { + v.push(0); + } +} + +/// A tar entry for [`tar_entries`]: (name, typeflag, data, link target). +pub type TarEntry<'a> = (&'a str, u8, &'a [u8], &'a str); + +/// A ustar archive from raw entries; names longer than 100 bytes get a GNU long-name record. +pub fn tar_entries(entries: &[TarEntry<'_>]) -> Vec { + let mut out = Vec::new(); + for (name, flag, data, link) in entries { + if name.len() > 100 { + let mut long = name.as_bytes().to_vec(); + long.push(0); + out.extend(tar_header("././@LongLink", b'L', long.len(), "")); + out.extend_from_slice(&long); + pad512(&mut out); + } + out.extend(tar_header(name, *flag, data.len(), link)); + out.extend_from_slice(data); + pad512(&mut out); + } + out.extend(vec![0u8; 1024]); + out +} + +/// A ustar archive of files (names ending in `/` become folders). +pub fn tar(files: &[(&str, &[u8])]) -> Vec { + let e: Vec> = files.iter().map(|(n, d)| (*n, if n.ends_with('/') { b'5' } else { b'0' }, *d, "")).collect(); + tar_entries(&e) +} + +/// A cpio newc archive from (name, data, mode). Symlinks (mode 0o120000) store the target as data. +pub fn cpio_newc(files: &[(&str, &[u8], u32)]) -> Vec { + let mut out = Vec::new(); + let mut push = |name: &str, data: &[u8], mode: u32, ino: u32| { + let hdr = format!( + "070701{ino:08x}{mode:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}{:08x}", + 0, + 0, + 1, + 0, + data.len(), + 0, + 0, + 0, + 0, + name.len() + 1, + 0 + ); + out.extend_from_slice(hdr.as_bytes()); + out.extend_from_slice(name.as_bytes()); + out.push(0); + while !out.len().is_multiple_of(4) { + out.push(0); + } + out.extend_from_slice(data); + while !out.len().is_multiple_of(4) { + out.push(0); + } + }; + for (i, (n, d, m)) in files.iter().enumerate() { + push(n, d, *m, i as u32 + 1); + } + push("TRAILER!!!", b"", 0, 0); + out +} + +/// Deterministic pseudo-random bytes (xorshift) for fuzz-like loops. +pub fn noise(seed: u64, len: usize) -> Vec { + let mut x = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; + (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x as u8 + }) + .collect() +} + +/// Every way to damage a sample used by robustness tests: truncations at many lengths and +/// single-byte corruptions spread across the file. +pub fn mutations(sample: &[u8]) -> Vec> { + let mut out = Vec::new(); + let n = sample.len(); + let step = (n / 64).max(1); + let mut len = 0; + while len < n { + out.push(sample[..len].to_vec()); + len += step; + } + for (i, seed) in (0..n).step_by(step).zip(1u64..) { + let mut m = sample.to_vec(); + let noise = noise(seed, 8); + for (j, v) in noise.iter().enumerate() { + if let Some(b) = m.get_mut(i + j) { + *b = *v; + } + } + out.push(m); + let mut m = sample.to_vec(); + if let Some(b) = m.get_mut(i) { + *b = 0xff; + } + out.push(m); + } + out +} diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index ae32a1157c..a37a4c114f 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -11,6 +11,7 @@ description = "Text processing below the Craft composer: hyphenation with a bund workspace = true [dependencies] +kurbo = { workspace = true, optional = true } hypher = { version = "0.1.8", default-features = false, features = ["alloc"], optional = true } miniz_oxide = { version = "0.8", optional = true } unicode-general-category = { version = "1.1", optional = true } @@ -28,6 +29,7 @@ name = "hyphgen" required-features = ["generator"] [features] +positioned = ["dep:kurbo"] default = ["hyphen", "bidi", "segment", "linebreak"] # Hyphenation points; English (bundled dictionary and patterns) needs no further feature. hyphen = ["dep:hypher", "dep:miniz_oxide", "dep:unicode-general-category"] diff --git a/crates/text/src/composer.rs b/crates/text/src/composer.rs new file mode 100644 index 0000000000..fc2067f3fb --- /dev/null +++ b/crates/text/src/composer.rs @@ -0,0 +1,529 @@ +//! Every-line composer: a Knuth–Plass style total-fit line breaker. +//! +//! Boxes are the paragraph's glyphs, glue is its spaces, and penalties are break opportunities +//! after hyphens/dashes/CJK and at hyphenation points. The breaks minimise the sum of squared +//! (badness + penalty) demerits over the whole paragraph, plus a demerit when neighbouring lines +//! fall in fitness classes more than one apart (a tight line next to a loose one). +//! +//! - **Justified** lines: word spacing, letter spacing and glyph scaling may stretch and shrink +//! within the paragraph's Justification options (each glyph's [`Flexibility`]); the badness comes from +//! the stretch/shrink ratio, so loose lines are traded for evenly spaced ones. +//! - **Ragged** lines (left/centre/right aligned): spaces keep their width, so a line never +//! shrinks (it must fit). The badness comes from the line's leftover space measured against a +//! rag zone of a sixth of the line width, so the rag is even rather than full lines followed by +//! a short one, and hyphenating costs less. The last line costs nothing unless it is shorter +//! than a third of the width (a word or two left dangling). + +/// Glyph measurements needed by the paragraph composer. +pub trait Glyph { + fn advance(&self) -> f64; + fn is_space(&self) -> bool; + fn is_soft_hyphen(&self) -> bool; +} + +/// Stretch and shrink available for a glyph. +pub trait Flexibility { + fn stretch(&self) -> f64; + fn shrink(&self) -> f64; +} + +const HYPHEN_PENALTY: f64 = 50.0; +const DOUBLE_HYPHEN_DEMERITS: f64 = 3000.0; +const LINE_PENALTY: f64 = 10.0; +/// Demerits for adjacent lines whose fitness classes differ by more than one. +const ADJ_DEMERITS_JUSTIFIED: f64 = 10_000.0; +const ADJ_DEMERITS_RAGGED: f64 = 1_000.0; +/// Ragged lines only gain from hyphenation by filling the rag, so it costs less than in +/// justified text (where it also evens the word spacing). +const HYPHEN_PENALTY_RAGGED: f64 = 25.0; +/// Ragged text: leftover space is measured in units of this fraction of the line width. +const RAG_ZONE: f64 = 1.0 / 6.0; +/// Ragged text: a last line shorter than this fraction of the width is penalised, by how much +/// shorter it is in units of `SHORT_LAST_ZONE` of the width. +const SHORT_LAST: f64 = 1.0 / 3.0; +const SHORT_LAST_ZONE: f64 = 1.0 / 3.0; +/// Give up (fall back to the single-line composer) beyond this many active breakpoints. +const MAX_ACTIVE: usize = 4096; +const EPS: f64 = 1e-6; + +/// A place a line may end: glyph index `end` (exclusive), plus the width of the hyphen that is +/// added when breaking there (0 = no hyphen). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Breakpoint { + pub end: usize, + pub hyphen: f64, +} + +/// How a paragraph is composed. +#[derive(Clone, Copy, Debug)] +pub struct Params { + /// The last line is justified too (Justify All). + pub justify_last: bool, + /// Left/centre/right aligned text: spaces keep their width and lines are scored by their rag. + pub ragged: bool, + /// Maximum stretch ratio (justified) or leftover space in rag zones (ragged) of a line. + pub tolerance: f64, + /// Lines from this index on all have the same width, so their line numbers are interchangeable + /// (keeps the number of active breakpoints small). + pub uniform_from: usize, + /// Hyphen Limit: the most consecutive lines that may end with a hyphen before a hyphenation + /// point is no longer a break; 0 sets no limit. A soft hyphen stays a break and counts. + pub hyphen_limit: usize, +} + +/// The search gave up: it ran past its budget ([`Measure::line`]). +#[derive(Debug)] +pub struct Exhausted; + +/// Where each line of a paragraph goes and how wide it is: the measure a line gets may depend on +/// the lines set above it (their heights move it down a shaped frame, or past a wrap object). +pub trait Measure { + /// What the measure of the next line depends on; breaks reached with equal states are + /// interchangeable from there on. + type State: Clone + PartialEq; + /// The state of the paragraph's first line. + fn first(&mut self) -> Self::State; + /// The width of the line of glyphs `pos..end` set from `state`, and the state of the line + /// after it; `Ok(None)` when the line can't be set (the frame is full), and [`Exhausted`] when + /// the search is to stop. + fn line(&mut self, state: &Self::State, pos: usize, end: usize) -> Result, Exhausted>; + /// Whether a line from `state` longer than `pos..end`, which [`Measure::line`] just measured, + /// may get more room than it. While it may, a line from `state` that is too long, or that + /// can't be set, does not end the reach of `state`. Lines from a state are all as wide by + /// default. + fn may_widen(&mut self, _state: &Self::State, _pos: usize, _end: usize) -> bool { + false + } +} + +/// Line widths by line number: `width(k)` for line `k`, lines from `uniform_from` on all as wide. +struct ByLine<'a> { + width: &'a dyn Fn(usize) -> f64, + uniform_from: usize, +} + +impl Measure for ByLine<'_> { + type State = usize; + fn first(&mut self) -> usize { + 0 + } + fn line(&mut self, &line: &usize, _: usize, _: usize) -> Result, Exhausted> { + Ok(Some(((self.width)(line), (line + 1).min(self.uniform_from)))) + } +} + +struct Node { + pos: usize, + /// The measure of the next line (its line number, clamped to `uniform_from`, for [`compose`]). + state: S, + fitness: u8, + demerits: f64, + /// Lines in a row ending with a hyphen up to this break (at most `hyphen_limit`, or 1 with no + /// limit); 0 when this break has no hyphen. + hyphens: usize, + prev: Option, +} + +/// Fitness class 0 (tight) … 3 (very loose) of a line with adjustment ratio `r`. +fn fitness(r: f64, ragged: bool) -> u8 { + let bounds = if ragged { [0.15, 0.4, 0.75] } else { [-0.5, 0.5, 1.0] }; + if r < bounds[0] { + 0 + } else if r <= bounds[1] { + 1 + } else if r <= bounds[2] { + 2 + } else { + 3 + } +} + +/// Adjustment ratio for a candidate line; `None` means a ragged line is already too long. +fn adjustment_ratio(natural: f64, width: f64, stretch: f64, shrink: f64, last: bool, p: &Params) -> Option { + if p.ragged { + if natural > width + EPS { + return None; + } + return Some(if last && !p.justify_last { + ((width * SHORT_LAST - natural) / (width * SHORT_LAST_ZONE).max(1.0)).max(0.0) + } else { + (width - natural).max(0.0) / (width * RAG_ZONE).max(1.0) + }); + } + Some(if natural < width { + if last && !p.justify_last { + 0.0 + } else if stretch > EPS { + (width - natural) / stretch + } else { + f64::INFINITY + } + } else if natural > width { + if shrink > EPS { (width - natural) / shrink } else { f64::NEG_INFINITY } + } else { + 0.0 + }) +} + +/// Compose the paragraph `g` into lines. `width(k)` is the available width of line `k`; +/// `start_credit(i)` is the width a wrapped line starting at glyph `i` gives back (Mojikumi sets +/// an opening bracket there flush with the line's start); `end_credit(t)` is the width a line whose +/// last character is glyph `t - 1` gives back (Mojikumi sets a closing mark there half width), at +/// most that glyph's advance, and nothing at a hyphenation point; `cands` are the break opportunities +/// in increasing order (the paragraph end is added); `flex` holds how far each glyph may stretch +/// and shrink in a justified line. +/// Returns `(end, hyphen)` per line, or `None` if no set of breaks fits within the tolerance +/// (the caller then falls back to single-line breaking). +pub fn compose( + g: &[G], + width: &dyn Fn(usize) -> f64, + start_credit: &dyn Fn(usize) -> f64, + end_credit: &dyn Fn(usize) -> f64, + cands: &[Breakpoint], + flex: &[F], + p: &Params, +) -> Option> { + compose_with(g, &mut ByLine { width, uniform_from: p.uniform_from }, start_credit, end_credit, cands, flex, p) +} + +/// [`compose`] with each line's width from `measure`, which follows where the lines above it went. +pub fn compose_with( + g: &[G], + measure: &mut M, + start_credit: &dyn Fn(usize) -> f64, + end_credit: &dyn Fn(usize) -> f64, + cands: &[Breakpoint], + flex: &[F], + p: &Params, +) -> Option> { + let n = g.len(); + // The search assumes increasing break positions when indexing its prefix sums. + // Reject malformed candidates before they can make a later line run backwards. + if cands.windows(2).any(|pair| pair[0].end > pair[1].end) { + return None; + } + if n == 0 { + return Some(vec![]); + } + // Prefix sums of advances and of how far the glyphs may stretch and shrink. + let mut w = vec![0.0; n + 1]; + let mut st = vec![0.0; n + 1]; + let mut sh = vec![0.0; n + 1]; + for (i, gl) in g.iter().enumerate() { + let f = flex.get(i); + w[i + 1] = w[i] + gl.advance(); + st[i + 1] = st[i] + f.map_or(0.0, Flexibility::stretch); + sh[i + 1] = sh[i] + f.map_or(0.0, Flexibility::shrink); + } + if !w[n].is_finite() { + return None; + } + // Trailing spaces are dropped at a break. + let trim = |mut b: usize, a: usize| { + while b > a && g.get(b - 1).is_some_and(Glyph::is_space) { + b -= 1; + } + b + }; + let line_end_credit = |t: usize| { + let credit = end_credit(t); + let most = t.checked_sub(1).and_then(|k| g.get(k)).map_or(0.0, |gl| gl.advance().max(0.0)); + if credit.is_finite() { credit.clamp(0.0, most) } else { 0.0 } + }; + let mut all: Vec = cands.iter().copied().filter(|c| c.end > 0 && c.end < n).collect(); + all.push(Breakpoint { end: n, hyphen: 0.0 }); + let (adj_demerits, hyphen_penalty) = + if p.ragged { (ADJ_DEMERITS_RAGGED, HYPHEN_PENALTY_RAGGED) } else { (ADJ_DEMERITS_JUSTIFIED, HYPHEN_PENALTY) }; + let mut nodes = vec![Node { pos: 0, state: measure.first(), fitness: 1, demerits: 0.0, hyphens: 0, prev: None }]; + let mut active: Vec = vec![0]; + for bp in &all { + let last = bp.end == n; + let hyphen = bp.hyphen > 0.0; + // `automatic` is true for a hyphenation point and false for a soft hyphen typed in the text. + let automatic = hyphen && !bp.end.checked_sub(1).and_then(|k| g.get(k)).is_some_and(Glyph::is_soft_hyphen); + let mut best: Vec<(M::State, u8, usize, f64, usize)> = vec![]; // (state, fitness, hyphens, demerits, from) + let mut keep = Vec::with_capacity(active.len()); + for &ai in &active { + let Some(a) = nodes.get(ai) else { continue }; + let t = trim(bp.end, a.pos); + let credit = if a.pos > 0 { start_credit(a.pos) } else { 0.0 }; + // A line that ends with a hyphen ends with it, not with its last character. At most the + // last glyph's advance, so a longer line from the same node is never narrower. + let end = if hyphen || t <= a.pos { 0.0 } else { line_end_credit(t) }; + let natural = w[t] - w[a.pos] - credit - end + bp.hyphen; + // A line that can't be set (no room left in the frame) ends this node's reach, unless a + // longer line may be placed elsewhere (a taller line steps down the frame by its own + // leading). + let Some((lw, next)) = measure.line(&a.state, a.pos, bp.end).ok()? else { + if measure.may_widen(&a.state, a.pos, bp.end) { + keep.push(ai); + } + continue; + }; + // Adjustment ratio, badness and whether the line ends the active node's reach. + let ratio = adjustment_ratio(natural, lw, st[t] - st[a.pos], sh[t] - sh[a.pos], last, p); + let Some(ratio) = ratio.filter(|&r| r >= -1.0 || r.is_nan()) else { + // Too long already; longer lines from this node only get worse, unless they may + // get more room (a taller line set lower down a shaped frame). + if measure.may_widen(&a.state, a.pos, bp.end) { + keep.push(ai); + } + continue; + }; + keep.push(ai); + if automatic && p.hyphen_limit > 0 && a.hyphens >= p.hyphen_limit { + continue; + } + let free_last = last && (p.ragged || !p.justify_last); + // A line that can't stretch at all (no word spaces, nor letter spacing or glyph scaling + // to vary) never fills its measure, however loose the tolerance. + if (ratio > p.tolerance || ratio == f64::INFINITY) && !(last && (p.ragged || (ratio.is_infinite() && p.justify_last))) { + continue; + } + // Justified lines aren't capped: past a ratio of 4.6 (only reached in the unbounded pass) + // a looser line must still score worse than a less loose one. + let cap = if p.ragged { 10_000.0 } else { f64::INFINITY }; + let badness = if ratio.is_finite() { (100.0 * ratio.abs().powi(3)).min(cap) } else { 10_000.0 }; + let penalty = if hyphen { hyphen_penalty } else { 0.0 }; + let mut d = (LINE_PENALTY + badness).powi(2) + penalty * penalty; + if hyphen && a.hyphens > 0 { + d += DOUBLE_HYPHEN_DEMERITS; + } + // A ragged last line's length says nothing about the rag: it keeps its neighbour's class. + let fit = if p.ragged && free_last { a.fitness } else { fitness(ratio, p.ragged) }; + if a.prev.is_some() && fit.abs_diff(a.fitness) > 1 { + d += adj_demerits; + } + let total = a.demerits + d; + // With a limit, breaks reached with different runs of hyphenated lines stay apart. + let hyphens = match (hyphen, p.hyphen_limit) { + (false, _) => 0, + (true, 0) => 1, + (true, limit) => (a.hyphens + 1).min(limit), + }; + match best.iter_mut().find(|b| b.0 == next && b.1 == fit && b.2 == hyphens) { + Some(b) if b.3 <= total => {} + Some(b) => *b = (next, fit, hyphens, total, ai), + None => best.push((next, fit, hyphens, total, ai)), + } + } + active = keep; + for (state, fitness, hyphens, demerits, from) in best { + nodes.push(Node { pos: bp.end, state, fitness, demerits, hyphens, prev: Some(from) }); + active.push(nodes.len() - 1); + } + if active.is_empty() || active.len() > MAX_ACTIVE { + return None; + } + } + let end = nodes.iter().enumerate().filter(|(_, nd)| nd.pos == n && nd.prev.is_some()).min_by(|a, b| a.1.demerits.total_cmp(&b.1.demerits))?.0; + let mut out = vec![]; + let mut cur = Some(end); + while let Some(i) = cur { + let nd = nodes.get(i)?; + if nd.prev.is_some() { + out.push((nd.pos, nd.hyphens > 0)); + } + cur = nd.prev; + if out.len() > n { + return None; + } + } + out.reverse(); + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + struct Unit(char); + impl Glyph for Unit { + fn advance(&self) -> f64 { + 1.0 + } + fn is_space(&self) -> bool { + self.0 == ' ' + } + fn is_soft_hyphen(&self) -> bool { + self.0 == '\u{ad}' + } + } + struct Rigid; + impl Flexibility for Rigid { + fn stretch(&self) -> f64 { + 0.0 + } + fn shrink(&self) -> f64 { + 0.0 + } + } + #[test] + fn rejects_breaks_that_move_backwards() { + let glyphs: Vec<_> = "abcd".chars().map(Unit).collect(); + let candidates = [Breakpoint { end: 3, hyphen: 0.0 }, Breakpoint { end: 1, hyphen: 0.0 }]; + let params = Params { justify_last: false, ragged: true, tolerance: 100.0, uniform_from: 0, hyphen_limit: 0 }; + assert_eq!(compose(&glyphs, &|_| 3.0, &|_| 0.0, &|_| 0.0, &candidates, &[] as &[Rigid], ¶ms), None); + } + + #[test] + fn composes_ragged_paragraph_and_trims_spaces() { + let glyphs: Vec<_> = "aa bb cc".chars().map(Unit).collect(); + let candidates = [Breakpoint { end: 3, hyphen: 0.0 }, Breakpoint { end: 6, hyphen: 0.0 }]; + let params = Params { justify_last: false, ragged: true, tolerance: 100.0, uniform_from: 0, hyphen_limit: 0 }; + let result = compose(&glyphs, &|_| 3.0, &|_| 0.0, &|_| 0.0, &candidates, &[] as &[Rigid], ¶ms); + assert_eq!(result, Some(vec![(3, false), (6, false), (8, false)])); + } + struct Flex(f64, f64); + impl Flexibility for Flex { + fn stretch(&self) -> f64 { + self.0 + } + fn shrink(&self) -> f64 { + self.1 + } + } + struct Wide(f64); + impl Glyph for Wide { + fn advance(&self) -> f64 { + self.0 + } + fn is_space(&self) -> bool { + false + } + fn is_soft_hyphen(&self) -> bool { + false + } + } + fn justified() -> Params { + Params { justify_last: false, ragged: false, tolerance: 10.0, uniform_from: 0, hyphen_limit: 0 } + } + fn units(text: &str) -> Vec { + text.chars().map(Unit).collect() + } + fn brk(end: usize, hyphen: f64) -> Breakpoint { + Breakpoint { end, hyphen } + } + + #[test] + fn fitness_classes_and_adjustment_ratios() { + assert_eq!([-0.6, 0.0, 0.7, 2.0].map(|r| fitness(r, false)), [0, 1, 2, 3]); + assert_eq!([0.1, 0.3, 0.5, 0.9].map(|r| fitness(r, true)), [0, 1, 2, 3]); + let j = justified(); + assert_eq!(adjustment_ratio(8.0, 10.0, 4.0, 0.0, false, &j), Some(0.5)); + assert_eq!(adjustment_ratio(8.0, 10.0, 0.0, 0.0, false, &j), Some(f64::INFINITY)); + assert_eq!(adjustment_ratio(8.0, 10.0, 4.0, 0.0, true, &j), Some(0.0)); + assert_eq!(adjustment_ratio(12.0, 10.0, 0.0, 4.0, false, &j), Some(-0.5)); + assert_eq!(adjustment_ratio(12.0, 10.0, 0.0, 0.0, false, &j), Some(f64::NEG_INFINITY)); + assert_eq!(adjustment_ratio(10.0, 10.0, 0.0, 0.0, false, &j), Some(0.0)); + let all = Params { justify_last: true, ..j }; + assert_eq!(adjustment_ratio(8.0, 10.0, 4.0, 0.0, true, &all), Some(0.5)); + let ragged = Params { ragged: true, ..j }; + assert_eq!(adjustment_ratio(11.0, 10.0, 0.0, 0.0, false, &ragged), None); + } + + #[test] + fn empty_and_unmeasurable_paragraphs() { + let none: [Unit; 0] = []; + assert_eq!(compose(&none, &|_| 3.0, &|_| 0.0, &|_| 0.0, &[], &[] as &[Rigid], &justified()), Some(vec![])); + let huge = [Wide(f64::INFINITY)]; + assert_eq!(compose(&huge, &|_| 3.0, &|_| 0.0, &|_| 0.0, &[], &[] as &[Rigid], &justified()), None); + } + + #[test] + fn justified_lines_stretch_and_shrink_within_tolerance() { + let glyphs = units("a a b b"); + let flex: Vec<_> = glyphs.iter().map(|g| if g.0 == ' ' { Flex(1.0, 0.5) } else { Flex(0.0, 0.0) }).collect(); + let cands = [brk(4, 0.0)]; + // "a a" (the trailing space is dropped) stretches its inner space to fill 4 units... + let lines = compose(&glyphs, &|_| 4.0, &|_| 0.0, &|_| 0.0, &cands, &flex, &justified()); + assert_eq!(lines, Some(vec![(4, false), (7, false)])); + // ...or shrinks it into 2.75. + let lines = compose(&glyphs, &|_| 2.75, &|_| 0.0, &|_| 0.0, &cands, &flex, &justified()); + assert_eq!(lines, Some(vec![(4, false), (7, false)])); + // Rigid glyphs can't fill a wider line except the last, so there is no fit. + let rigid: Vec<_> = glyphs.iter().map(|_| Rigid).collect(); + assert_eq!(compose(&glyphs, &|_| 4.0, &|_| 0.0, &|_| 0.0, &cands, &rigid, &justified()), None); + // Justify All lets an unstretchable last line through. + let all = Params { justify_last: true, ..justified() }; + let word = units("ab"); + assert_eq!(compose(&word, &|_| 4.0, &|_| 0.0, &|_| 0.0, &[], &[Rigid, Rigid], &all), Some(vec![(2, false)])); + } + + #[test] + fn hyphen_limit_and_soft_hyphens() { + // "ab-cd-ef" with hyphenation points after each pair: every line wants a hyphen. + let glyphs = units("abcdef"); + let cands = [brk(2, 1.0), brk(4, 1.0)]; + let ragged = Params { justify_last: false, ragged: true, tolerance: 100.0, uniform_from: 0, hyphen_limit: 0 }; + let free = compose(&glyphs, &|_| 3.0, &|_| 0.0, &|_| 0.0, &cands, &[] as &[Rigid], &ragged).unwrap(); + assert_eq!(free, vec![(2, true), (4, true), (6, false)]); + // A limit of one hyphenated line in a row forbids the second automatic hyphen. + let limited = Params { hyphen_limit: 1, ..ragged }; + assert_eq!(compose(&glyphs, &|_| 3.0, &|_| 0.0, &|_| 0.0, &cands, &[] as &[Rigid], &limited), None); + // A typed soft hyphen stays a break regardless of the limit. + let soft = units("ab\u{ad}cd\u{ad}ef"); + let cands = [brk(3, 1.0), brk(6, 1.0)]; + let out = compose(&soft, &|_| 4.0, &|_| 0.0, &|_| 0.0, &cands, &[] as &[Rigid], &limited).unwrap(); + assert_eq!(out, vec![(3, true), (6, true), (8, false)]); + } + + #[test] + fn credits_are_clamped_to_the_glyph_and_ignored_when_not_finite() { + let glyphs = units("aa bb"); + let cands = [brk(3, 0.0)]; + let ragged = Params { justify_last: false, ragged: true, tolerance: 100.0, uniform_from: 0, hyphen_limit: 0 }; + for credit in [f64::NAN, 5.0, -1.0] { + let out = compose(&glyphs, &|_| 2.0, &|_| 0.0, &|_| credit, &cands, &[] as &[Rigid], &ragged); + assert_eq!(out, Some(vec![(3, false), (5, false)]), "{credit}"); + } + // A start credit gives a wrapped line room back. + let out = compose(&units("aa bbb"), &|_| 2.0, &|_| 1.0, &|_| 0.0, &cands, &[] as &[Rigid], &ragged); + assert_eq!(out, Some(vec![(3, false), (6, false)])); + } + + /// Two lines of width 2, then the frame is full; a line may widen when the frame says so. + struct Frame { + widen: bool, + calls: usize, + } + impl Measure for Frame { + type State = usize; + fn first(&mut self) -> usize { + 0 + } + fn line(&mut self, &k: &usize, _: usize, _: usize) -> Result, Exhausted> { + self.calls += 1; + if self.calls > 1_000 { + return Err(Exhausted); + } + Ok((k < 2).then_some((2.0, k + 1))) + } + fn may_widen(&mut self, _: &usize, _: usize, _: usize) -> bool { + self.widen + } + } + + #[test] + fn measure_can_end_reach_widen_or_exhaust() { + let ragged = Params { justify_last: false, ragged: true, tolerance: 100.0, uniform_from: 0, hyphen_limit: 0 }; + let two = units("aa bb"); + let cands = [brk(3, 0.0)]; + let mut frame = Frame { widen: false, calls: 0 }; + assert_eq!(compose_with(&two, &mut frame, &|_| 0.0, &|_| 0.0, &cands, &[] as &[Rigid], &ragged), Some(vec![(3, false), (5, false)])); + // A third line can't be set: no fit, whether or not the frame may widen. + let three = units("aa bb cc"); + let cands = [brk(3, 0.0), brk(6, 0.0)]; + for widen in [false, true] { + let mut frame = Frame { widen, calls: 0 }; + assert_eq!(compose_with(&three, &mut frame, &|_| 0.0, &|_| 0.0, &cands, &[] as &[Rigid], &ragged), None); + } + // Too long for the line, but the frame may widen: the node stays active. + let long = units("aaa b"); + let mut frame = Frame { widen: true, calls: 0 }; + assert_eq!(compose_with(&long, &mut frame, &|_| 0.0, &|_| 0.0, &[brk(4, 0.0)], &[] as &[Rigid], &ragged), None); + // The measure may stop the search. + let mut frame = Frame { widen: false, calls: 1_000 }; + assert_eq!(compose_with(&two, &mut frame, &|_| 0.0, &|_| 0.0, &[brk(3, 0.0)], &[] as &[Rigid], &ragged), None); + } +} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 07795c3135..62e8d0eb7b 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -15,6 +15,9 @@ //! Language features (`spanish`, `german`, …, `all-languages`) add data for that language and //! turn on the modules that use it. +#[cfg(feature = "positioned")] +pub mod positioned; + #[cfg(feature = "bidi")] pub mod bidi; #[cfg(feature = "hyphen")] @@ -23,3 +26,6 @@ pub mod hyphen; pub mod linebreak; #[cfg(feature = "segment")] pub mod segment; + +/// Paragraph-wide line composition with stateful line measurement. +pub mod composer; diff --git a/crates/text/src/positioned.rs b/crates/text/src/positioned.rs new file mode 100644 index 0000000000..cb749cac58 --- /dev/null +++ b/crates/text/src/positioned.rs @@ -0,0 +1,212 @@ +//! A placed glyph with source mapping, geometry and optional application-owned artwork. + +use kurbo::{Affine, BezPath, Point}; + +/// Application-owned payloads and conversion to document artwork. +pub trait Artwork { + /// Bitmap glyph data. + type Image: Clone + std::fmt::Debug; + /// Colour glyph data. + type Colour: Clone + std::fmt::Debug; + /// Curved-baseline metadata. + type Bend: Clone + std::fmt::Debug; + /// Application document node. + type Node; + /// Transform from image pixels to font space. + fn image_transform(image: &Self::Image) -> Affine; + /// Place a bitmap in document space. + fn image_node(image: &Self::Image, transform: Affine) -> Self::Node; + /// Place colour artwork in document space. + fn colour_node(colour: &Self::Colour, transform: Affine) -> Self::Node; +} + +/// A glyph after shaping and composition. Coordinates are in the composer's text space; +/// `xf`, `pivot` and `unturned` refer to font space. Image, colour artwork and bend metadata +/// stay generic so the model does not own an application's document or rendering types. +#[derive(Clone, Debug)] +pub struct PositionedGlyph { + /// Outline in text space. + pub outline: BezPath, + /// Source style run index. + pub run: usize, + /// Source cluster's byte offset. + pub byte: usize, + /// Pen position on the baseline. + pub origin: Point, + /// Advance including composition spacing. + pub advance: f64, + /// Number of source bytes in the cluster. + pub len: usize, + /// Baseline angle in radians. + pub angle: f64, + /// Composed line index. + pub line: usize, + /// Identity of the resolved face. + pub font_id: u32, + /// Glyph identifier in that face. + pub gid: u32, + /// Transform from glyph font space to text space. + pub xf: Affine, + /// Whether the logical leading edge is on the right. + pub rtl: bool, + /// Paragraph glyph scaling factor. + pub scale: f64, + /// Optional bitmap artwork. + pub image: Option, + /// Optional colour artwork. + pub colour: Option, + /// Optional curved-baseline geometry. + pub bend: Option, + /// Transform restoring the glyph before character rotation. + pub unturned: Affine, + /// Character rotation pivot in font space. + pub pivot: Point, + /// Source-byte caret stops and their fractions of the glyph width. + pub carets: Vec<(usize, f64)>, + /// Glyph width excluding composition spacing. + pub width: f64, + /// Offset from the left end of the advance to the glyph width. + pub width_start: f64, + /// Source byte identifying a warichu block, when present. + pub warichu: Option, + /// Warichu block baseline offset. + pub warichu_line: f64, + /// Glyph lies before an open path and is retained for caret mapping only. + pub off_path: bool, +} + +impl PositionedGlyph { + /// Source caret stops as fractions of glyph width. + pub fn width_stops(&self) -> impl Iterator + '_ { + std::iter::once((self.byte, 0.0)).chain(self.carets.iter().copied()).chain(std::iter::once((self.byte + self.len, 1.0))) + } + + /// Source caret stops measured from the logical leading edge. + pub fn stops_along(&self, extent: f64) -> impl Iterator + '_ { + let (width, start) = if self.width > 0.0 && self.width.is_finite() { + (self.width, if self.width_start.is_finite() { self.width_start } else { 0.0 }) + } else { + (extent, 0.0) + }; + let ends = (self.byte, self.byte + self.len); + self.width_stops().map(move |(b, f)| { + if b == ends.0 { + (b, 0.0) + } else if b == ends.1 { + (b, extent) + } else if self.rtl { + (b, extent - start - (1.0 - f) * width) + } else { + (b, start + f * width) + } + }) + } + + /// Distance from the logical leading edge to the source byte's caret. + pub fn caret_offset(&self, byte: usize, extent: f64) -> f64 { + if byte <= self.byte || self.len == 0 { + return 0.0; + } + let mut from = (self.byte, 0.0); + for (b, d) in self.stops_along(extent).skip(1) { + if byte <= b { + let span = b.saturating_sub(from.0).max(1) as f64; + return from.1 + (d - from.1) * (byte - from.0) as f64 / span; + } + from = (b, d); + } + extent + } + + /// Bitmap data and its transform into text space. + pub fn placed_image(&self) -> Option<(&A::Image, Affine)> { + self.image.as_ref().map(|image| (image, self.xf * A::image_transform(image))) + } + + /// Bitmap artwork placed in document space. + pub fn placed_image_node(&self, to_doc: Affine) -> Option { + let (image, to_text) = self.placed_image()?; + Some(A::image_node(image, to_doc * to_text)) + } + + /// Colour artwork placed in document space. + pub fn placed_colour(&self, to_doc: Affine) -> Option { + Some(A::colour_node(self.colour.as_ref()?, to_doc * self.xf)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Clone, Debug)] + struct TestArt; + impl Artwork for TestArt { + type Image = Affine; + type Colour = (); + type Bend = (); + type Node = Affine; + fn image_transform(image: &Affine) -> Affine { + *image + } + fn image_node(_: &Affine, transform: Affine) -> Affine { + transform + } + fn colour_node(_: &(), transform: Affine) -> Affine { + transform + } + } + fn glyph() -> PositionedGlyph { + PositionedGlyph { + outline: BezPath::new(), + run: 0, + byte: 3, + origin: Point::ZERO, + advance: 12.0, + len: 4, + angle: 0.0, + line: 0, + font_id: 1, + gid: 4, + xf: Affine::translate((3.0, 5.0)), + rtl: false, + scale: 1.0, + image: Some(Affine::scale(2.0)), + colour: Some(()), + bend: None, + unturned: Affine::IDENTITY, + pivot: Point::ZERO, + carets: vec![(5, 0.5)], + width: 10.0, + width_start: 1.0, + warichu: None, + warichu_line: 0.0, + off_path: false, + } + } + #[test] + fn caret_mapping_tracks_ligatures_rtl_and_kerning() { + let mut g = glyph(); + assert_eq!((g.caret_offset(3, 12.0), g.caret_offset(5, 12.0), g.caret_offset(7, 12.0)), (0.0, 6.0, 12.0)); + assert_eq!(g.caret_offset(4, 12.0), 3.0); + g.rtl = true; + assert_eq!(g.caret_offset(5, 12.0), 6.0); + assert_eq!(g.caret_offset(5, 8.0), 2.0); + g.width = f64::NAN; + assert_eq!(g.caret_offset(5, 8.0), 4.0); + } + #[test] + fn artwork_uses_the_same_composition_order() { + let g = glyph(); + let doc = Affine::translate((10.0, 20.0)); + let (_, image) = g.placed_image().unwrap(); + assert_eq!(image, g.xf * Affine::scale(2.0)); + assert_eq!(g.placed_image_node(doc), Some(doc * image)); + assert_eq!(g.placed_colour(doc), Some(doc * g.xf)); + let mut empty = g; + empty.image = None; + empty.colour = None; + assert!(empty.placed_image_node(doc).is_none()); + assert!(empty.placed_colour(doc).is_none()); + } +} diff --git a/crates/texture/README.md b/crates/texture/README.md index 724d72bad2..d9fda84c56 100644 --- a/crates/texture/README.md +++ b/crates/texture/README.md @@ -25,7 +25,16 @@ network I/O and has no `unsafe` code. (). Repeat keeps its period at any finite coordinate. A NaN or infinite coordinate gives `[0, 0, 0, 1]`. Bilinear sums are taken in `f64` and clamped to the `f32` range, so finite - texels give a finite sample. + texels give a finite sample. `sample_axes`, `sample_nearest_axes` and `get_axes` take + `tiling: [bool; 2]`, the wrap mode of `u` and of `v` on their own, as glTF's `wrapS` and + `wrapT`; with equal entries they give the same results as the forms with one `tile`. +- **Stored sampling.** `sample_stored` is the texture read of MaterialCraft's function graphs. It + rounds the bilinear weights to multiples of 1/256 and blends the texels by linear interpolation + in `f32`. When the image's integer-sampling flag is on (`with_integer_sampling(true)`, read with + `integer_sampling()`), it then clamps each channel to `0..=1` and rounds it to a multiple of + 1/65535. A channel whose interpolation is not finite is taken from the `f64` weighted sum + instead, so finite texels give a finite sample. New images start with the flag off, clones keep + it, and two images are equal only when their flags are equal. - **Other operations.** `get` reads one texel, `map`, `to_gray`, `to_color` and `to_kind` convert, `resize` box-averages whole-factor shrinks and samples bilinearly otherwise, and `to_rgba8_display` encodes 8-bit sRGB RGBA. `linear_to_srgb`, `srgb_to_linear` and `luminance` @@ -78,7 +87,8 @@ Without `parallel` the crate builds for `wasm32-unknown-unknown`, the decoding f | Part | Source | |---|---| | `Image`, `Kind`, sampling, resizing, conversions, sRGB helpers, resource keys and the six tests `sample_survives_huge_coordinates`, `resource_keys_round_trip`, `sample_wraps_and_clamps`, `resize_box_and_bilinear`, `hostile_sizes_are_clamped`, `conversions` | MaterialCraft `crates/image/src/lib.rs` at [3133062](https://github.com/storytold/materialcraft/commit/3133062968b8a1566eda12a357cb06062db16687) | -| `Limits`, the `try_` constructors, `from_data`, private fields with getters, the `parallel` feature | written here | +| `get_axes`, `sample_axes`, `sample_nearest_axes`, `sample_stored` and the integer-sampling flag | MaterialCraft `crates/image/src/lib.rs` at [6c3b35c](https://github.com/storytold/materialcraft/commit/6c3b35c39632feafcda3d7a90ff18242f3ad910f), on this crate's coordinate reduction and `f64` bilinear sum | +| `Limits`, the `try_` constructors, `from_data`, private fields with getters, the `parallel` feature, `with_integer_sampling` and `integer_sampling` | written here | | the `decode` module and its features | written here, on `craft-image-codecs`, `craft-hdr` and `craft-exr` | ## Migration @@ -94,5 +104,7 @@ For MaterialCraft: | --- | --- | | `image.w`, `image.h`, `image.kind`, `image.data` | `width()`, `height()`, `kind()`, `data()` and `shared_data()` | | `Image { w, h, kind, data }` built by hand | `Image::from_data(w, h, kind, data, &Limits::default())` | +| `image.integer_sampling = on` and `Image { integer_sampling, .. }` | `image.with_integer_sampling(on)`; read it with `integer_sampling()` | +| `sample_axes` blends with `a + (b − a)t` in `f32` | it sums the weighted texels in `f64`, as `sample` does; the results differ by rounding | | `rayon` always on | the `parallel` feature | | `linear_to_srgb(NaN)` returned −0.055 | it returns NaN | diff --git a/crates/texture/src/lib.rs b/crates/texture/src/lib.rs index af4b07f1a1..704e0218a7 100644 --- a/crates/texture/src/lib.rs +++ b/crates/texture/src/lib.rs @@ -12,6 +12,10 @@ //! [`Image::sample_nearest`] and [`Image::sample`] (bilinear) use the texel coordinates, wrapping //! and weights of the Vulkan specification, sections 20.4.1, 20.6.1 and 20.6.3 //! (). +//! [`Image::get_axes`], [`Image::sample_axes`] and [`Image::sample_nearest_axes`] take the wrap +//! mode of each axis on its own. [`Image::sample_stored`] is MaterialCraft's function-graph texture +//! read: bilinear with weights rounded to eight fractional bits, and with its result rounded to 16 +//! bits when the image's integer-sampling flag is on ([`Image::with_integer_sampling`]). //! //! Sizes are bounded. [`Limits`] caps the side, the pixel count and the bytes, and the `try_` //! constructors return an [`ImageError`] before allocating anything over them. A plane is also @@ -139,15 +143,18 @@ pub struct Image { w: u32, h: u32, kind: Kind, + /// Whether [`Image::sample_stored`] rounds its result to 16 bits, as for a normalized integer + /// texture. Off for every new image. + integer_sampling: bool, /// Row-major, `kind.channels()` floats per pixel. data: Arc>, } -/// Images are equal when their size, kind and floats are equal. Floats compare as `f32` does, so -/// an image holding NaN is unequal to every image, its clones included. +/// Images are equal when their size, kind, integer-sampling flag and floats are equal. Floats +/// compare as `f32` does, so an image holding NaN is unequal to every image, its clones included. impl PartialEq for Image { fn eq(&self, o: &Image) -> bool { - self.w == o.w && self.h == o.h && self.kind == o.kind && self.data == o.data + self.w == o.w && self.h == o.h && self.kind == o.kind && self.integer_sampling == o.integer_sampling && self.data == o.data } } @@ -196,6 +203,13 @@ fn reduce(t: f32, tile: bool) -> Option { Some(if tile { t.rem_euclid(1.0).min(BELOW_ONE) } else { t.clamp(-1.0, 2.0) }) } +/// A bilinear sum taken in `f64` as an `f32`: a finite sum clamped to the `f32` range, and an +/// infinite or NaN sum as it is. +#[inline] +fn f32_of_sum(v: f64) -> f32 { + if v.is_finite() { v.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32 } else { v as f32 } +} + /// Fill `data` row by row with `f(x, y)`, keeping the first `c` channels of each result. fn fill [f32; 4] + Sync>(data: &mut [f32], w: u32, c: usize, f: &F) { let row_len = (w as usize).max(1) * c; @@ -218,7 +232,7 @@ impl Image { let (w, h, len) = bounded_size(w, h, kind, MAX_ALLOC_BYTES); let mut data = vec![0.0f32; len]; fill(&mut data, w, kind.channels(), &f); - Image { w, h, kind, data: Arc::new(data) } + Image { w, h, kind, integer_sampling: false, data: Arc::new(data) } } /// An image checked against `limits`, with its memory reserved before any pixel is generated. @@ -228,7 +242,7 @@ impl Image { data.try_reserve_exact(len).map_err(|_| ImageError::OutOfMemory(w, h))?; data.resize(len, 0.0); fill(&mut data, w, kind.channels(), &f); - Ok(Image { w, h, kind, data: Arc::new(data) }) + Ok(Image { w, h, kind, integer_sampling: false, data: Arc::new(data) }) } /// A constant image, each side clamped to `1..=MAX_SIDE`. @@ -281,7 +295,21 @@ impl Image { if data.len() != expected { return Err(ImageError::BadDataLength { expected, found: data.len() }); } - Ok(Image { w, h, kind, data }) + Ok(Image { w, h, kind, integer_sampling: false, data }) + } + + /// This image with the integer-sampling flag set to `on`. The flag only changes + /// [`Image::sample_stored`], which then rounds its result to 16 bits. Clones keep the flag. + /// [`Image::map`], [`Image::resize`] to a new size and the other operations that make a new + /// buffer return an image with the flag off. The pixels are not changed or copied. + pub fn with_integer_sampling(mut self, on: bool) -> Image { + self.integer_sampling = on; + self + } + + /// Whether [`Image::sample_stored`] rounds its result to 16 bits. + pub fn integer_sampling(&self) -> bool { + self.integer_sampling } pub fn width(&self) -> u32 { @@ -317,7 +345,14 @@ impl Image { /// The pixel at integer coordinates (wrapped or clamped), as RGBA (gray → `[v, v, v, 1]`). #[inline] pub fn get(&self, x: i64, y: i64, tile: bool) -> [f32; 4] { - let (x, y) = (wrap(x, self.w, tile), wrap(y, self.h, tile)); + self.get_axes(x, y, [tile; 2]) + } + + /// [`Image::get`] with the wrap mode of each axis given on its own: `tiling[0]` repeats `x` + /// and `tiling[1]` repeats `y`; an axis whose entry is `false` is clamped to its edge texels. + #[inline] + pub fn get_axes(&self, x: i64, y: i64, tiling: [bool; 2]) -> [f32; 4] { + let (x, y) = (wrap(x, self.w, tiling[0]), wrap(y, self.h, tiling[1])); let i = y * self.w as usize + x; match self.kind { Kind::Gray => { @@ -348,7 +383,15 @@ impl Image { /// leaves a sample at a texel center unchanged. NaN or infinite coordinates give `[0, 0, 0, 1]`. #[inline] pub fn sample(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { - let (Some(u), Some(v)) = (reduce(u, tile), reduce(v, tile)) else { + self.sample_axes(u, v, [tile; 2]) + } + + /// [`Image::sample`] with the wrap mode of each axis given on its own: `tiling[0]` for `u` and + /// `tiling[1]` for `v`, as glTF samplers set `wrapS` and `wrapT` separately. With both entries + /// equal the result is the same as [`Image::sample`] with that `tile`. + #[inline] + pub fn sample_axes(&self, u: f32, v: f32, tiling: [bool; 2]) -> [f32; 4] { + let (Some(u), Some(v)) = (reduce(u, tiling[0]), reduce(v, tiling[1])) else { return [0.0, 0.0, 0.0, 1.0]; }; let fx = u * self.w as f32 - 0.5; @@ -365,12 +408,12 @@ impl Image { if weight == 0.0 { continue; } - let p = self.get(x, y, tile); + let p = self.get_axes(x, y, tiling); for (o, p) in o.iter_mut().zip(p) { *o += f64::from(weight) * f64::from(p); } } - o.map(|v| if v.is_finite() { v.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32 } else { v as f32 }) + o.map(f32_of_sum) } #[inline] @@ -382,18 +425,73 @@ impl Image { } } + /// Bilinear sample at normalized `(u, v)` with filter weights of eight fractional bits, the + /// texture read of MaterialCraft's function graphs. The texel coordinate and wrapping are those + /// of [`Image::sample`]. Each fractional part `α` and `β` is rounded to the nearest multiple of + /// 1/256 (a half rounds away from zero), and the four texels are blended by linear + /// interpolation in `f32`: `a + (b − a)α` along each of the two rows, then the same between + /// the rows with `β`. When the image's integer-sampling flag is on + /// ([`Image::with_integer_sampling`]), each channel is then clamped to `0..=1` and rounded to + /// the nearest multiple of 1/65535, as a filtered 16-bit texel. A NaN channel stays NaN. + /// + /// A channel whose interpolation is infinite or NaN is computed again as the weighted sum of + /// [`Image::sample`], skipping texels of weight 0 and clamping a finite sum to the `f32` + /// range, so finite texels give a finite sample. NaN or infinite coordinates give + /// `[0, 0, 0, 1]`. + #[inline] + pub fn sample_stored(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { + let pixel = self.sample_fixed_weights(u, v, tile); + if self.integer_sampling { pixel.map(|value| (value.clamp(0.0, 1.0) * 65535.0).round() / 65535.0) } else { pixel } + } + + /// The bilinear interpolation of [`Image::sample_stored`] before its 16-bit rounding. + #[inline] + fn sample_fixed_weights(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { + let (Some(u), Some(v)) = (reduce(u, tile), reduce(v, tile)) else { + return [0.0, 0.0, 0.0, 1.0]; + }; + let fx = u * self.w as f32 - 0.5; + let fy = v * self.h as f32 - 0.5; + let (x0, y0) = (fx.floor(), fy.floor()); + let tx = ((fx - x0) * 256.0).round() / 256.0; + let ty = ((fy - y0) * 256.0).round() / 256.0; + let (x0, y0) = (x0 as i64, y0 as i64); + let (a, b, c, d) = (self.get(x0, y0, tile), self.get(x0 + 1, y0, tile), self.get(x0, y0 + 1, tile), self.get(x0 + 1, y0 + 1, tile)); + let mut o = [0.0f32; 4]; + for (k, o) in o.iter_mut().enumerate() { + let top = a[k] + (b[k] - a[k]) * tx; + let bot = c[k] + (d[k] - c[k]) * tx; + *o = top + (bot - top) * ty; + if !o.is_finite() { + let taps = [((1.0 - tx) * (1.0 - ty), a[k]), (tx * (1.0 - ty), b[k]), ((1.0 - tx) * ty, c[k]), (tx * ty, d[k])]; + let sum = taps.iter().filter(|(weight, _)| *weight != 0.0).map(|(weight, p)| f64::from(*weight) * f64::from(*p)).sum(); + *o = f32_of_sum(sum); + } + } + o + } + /// Nearest sample at normalized `(u, v)`: the texel `floor(u × w)`, wrapped or clamped. NaN or /// infinite coordinates give `[0, 0, 0, 1]`. #[inline] pub fn sample_nearest(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { - let (Some(u), Some(v)) = (reduce(u, tile), reduce(v, tile)) else { + self.sample_nearest_axes(u, v, [tile; 2]) + } + + /// [`Image::sample_nearest`] with the wrap mode of each axis given on its own: `tiling[0]` for + /// `u` and `tiling[1]` for `v`. With both entries equal the result is the same as + /// [`Image::sample_nearest`] with that `tile`. + #[inline] + pub fn sample_nearest_axes(&self, u: f32, v: f32, tiling: [bool; 2]) -> [f32; 4] { + let (Some(u), Some(v)) = (reduce(u, tiling[0]), reduce(v, tiling[1])) else { return [0.0, 0.0, 0.0, 1.0]; }; let (x, y) = ((u * self.w as f32).floor() as i64, (v * self.h as f32).floor() as i64); // A repeated coordinate is below 1, so its texel is below the size even where `u × w` // rounds up to it. - let (x, y) = if tile { (x.min(i64::from(self.w) - 1), y.min(i64::from(self.h) - 1)) } else { (x, y) }; - self.get(x, y, tile) + let x = if tiling[0] { x.min(i64::from(self.w) - 1) } else { x }; + let y = if tiling[1] { y.min(i64::from(self.h) - 1) } else { y }; + self.get_axes(x, y, tiling) } /// Map every pixel (as RGBA) to a new image of `kind`, same size. When a result of that size @@ -901,4 +999,247 @@ mod tests { assert_eq!(half.data(), &[0.5, 0.5, 0.0, 1.0, 2.5, 0.5, 0.0, 1.0]); assert_eq!(img.to_gray().width(), 4); } + + /// The four wrap combinations of the two axes. + const TILINGS: [[bool; 2]; 4] = [[false, false], [true, true], [true, false], [false, true]]; + + /// Gray texels of 8-bit values, `k / 255`. + fn gray8() -> Image { + Image::gray(5, 3, |x, y| ((x * 37 + y * 91 + 13) % 256) as f32 / 255.0) + } + + /// Color texels from −2.5 to 3.42, with negative values and values above 1. + fn color() -> Image { + Image::generate(4, 3, Kind::Color, |x, y| { + let s = |k: u32| ((x * 7 + y * 13 + k * 5) % 17) as f32 * 0.37 - 2.5; + [s(0), s(1), s(2), s(3)] + }) + } + + /// 65 even steps from `lo` to `hi`, then the texel centers and edges of sides 3, 4 and 5. + fn coordinates(lo: f32, hi: f32) -> Vec { + let mut v: Vec = (0..=64).map(|i| lo + (hi - lo) * i as f32 / 64.0).collect(); + for side in [3u32, 4, 5] { + v.extend((0..=2 * side).map(|i| i as f32 / (2 * side) as f32)); + } + v + } + + /// FNV-1a over the bits of every channel. + fn hash(h: &mut u64, p: [f32; 4]) { + for b in p.iter().flat_map(|v| v.to_bits().to_le_bytes()) { + *h ^= u64::from(b); + *h = h.wrapping_mul(0x100_0000_01b3); + } + } + + const FNV_START: u64 = 0xcbf2_9ce4_8422_2325; + + /// Hash of `f(u, v)` over every pair of `coordinates`. + fn hash_grid(us: &[f32], f: impl Fn(f32, f32) -> [f32; 4]) -> u64 { + let mut h = FNV_START; + for &u in us { + for &v in us { + hash(&mut h, f(u, v)); + } + } + h + } + + /// Hashes of `sample_stored`, `sample_nearest_axes` and `get_axes` computed with MaterialCraft's + /// `crates/image` at storytold/materialcraft `6c3b35c396`, over the fixtures and grids above. + #[test] + fn stored_and_axis_reads_match_materialcraft() { + // (range, image, integer sampling, tile, sample_stored hash) + let stored = [ + ("unit", "gray8", false, false, 0x702b_0f81_2833_5e06u64), + ("unit", "gray8", false, true, 0x4ac5_b29c_45b2_d0ca), + ("unit", "gray8", true, false, 0x8400_a867_00fc_389a), + ("unit", "gray8", true, true, 0x47ea_befd_7fd6_cc5e), + ("unit", "color", false, false, 0x25f6_2544_f084_4182), + ("unit", "color", false, true, 0x607f_3c9f_896b_5975), + ("unit", "color", true, false, 0x0261_02eb_451b_36d6), + ("unit", "color", true, true, 0x51f8_9417_f5e9_2341), + ("wide", "gray8", false, false, 0xb0e7_096c_c64b_0f72), + ("wide", "gray8", false, true, 0x7a8a_4059_68ac_2a07), + ("wide", "gray8", true, false, 0x418c_9c08_2718_2171), + ("wide", "gray8", true, true, 0xe0b7_0088_256f_ccb2), + ("wide", "color", false, false, 0x51b4_8bb3_2885_f844), + ("wide", "color", false, true, 0xab4b_72d5_25ff_aaed), + ("wide", "color", true, false, 0x6570_eaa2_25f3_4d29), + ("wide", "color", true, true, 0x15a3_5aa7_7f50_4f92), + ]; + // (range, image, sample_nearest_axes hash for each entry of TILINGS) + let nearest = [ + ("unit", "gray8", [0xe427_9012_572d_b173u64, 0x76b9_e33c_849f_069d, 0x42ab_5ecd_8f1a_5dd2, 0x190c_23b8_f3e9_a2e5]), + ("unit", "color", [0x6a0e_0370_810d_1ad9, 0x0ab0_d62b_8308_4f9d, 0xa839_3cdf_db7d_844a, 0x1fc4_027e_bb8d_7c45]), + ("wide", "gray8", [0xd1cf_daaf_d7db_239c, 0x1d22_a6db_ad03_0960, 0x754e_fabf_5203_d6a0, 0xfe73_7385_df89_4dd4]), + ("wide", "color", [0xb894_834b_96fe_684d, 0x7eb4_0a21_3a51_c6bc, 0x2443_5503_2fea_4068, 0x4705_30d0_9afc_dc75]), + ]; + // (image, get_axes hash over x and y in -12..12 for each entry of TILINGS) + let get = [ + ("gray8", [0x6c95_1e05_c9c6_8f21u64, 0xac4a_e19a_4da7_b625, 0xcee5_f582_facb_f043, 0x7f1d_ff0e_357b_5eb5]), + ("color", [0x21af_a81f_327a_d3af, 0x9cf4_2557_9880_5345, 0x9b58_bde1_8021_2779, 0x6bb0_a98f_13d5_6635]), + ]; + let image = |name: &str| if name == "gray8" { gray8() } else { color() }; + let grid = |range: &str| if range == "unit" { coordinates(0.0, 0.99) } else { coordinates(-2.5, 3.5) }; + for (range, name, integer, tile, expected) in stored { + let img = image(name).with_integer_sampling(integer); + let h = hash_grid(&grid(range), |u, v| img.sample_stored(u, v, tile)); + assert_eq!(h, expected, "sample_stored {range} {name} integer {integer} tile {tile}"); + } + for (range, name, expected) in nearest { + let img = image(name); + for (tiling, expected) in TILINGS.into_iter().zip(expected) { + let h = hash_grid(&grid(range), |u, v| img.sample_nearest_axes(u, v, tiling)); + assert_eq!(h, expected, "sample_nearest_axes {range} {name} {tiling:?}"); + } + } + for (name, expected) in get { + let img = image(name); + for (tiling, expected) in TILINGS.into_iter().zip(expected) { + let mut h = FNV_START; + for x in -12..12 { + for y in -12..12 { + hash(&mut h, img.get_axes(x, y, tiling)); + } + } + assert_eq!(h, expected, "get_axes {name} {tiling:?}"); + } + } + } + + /// Values of MaterialCraft's `sample_axes` at storytold/materialcraft `6c3b35c396`. It blends + /// by linear interpolation in `f32`, and this crate sums the weighted texels in `f64`, so the + /// results differ by rounding only. + #[test] + fn axis_bilinear_matches_materialcraft_up_to_rounding() { + let img = color(); + let cases = [ + (0.3, 0.7, [true, false], [1.473_799_7, -0.072_800_055, 0.645_000_2, 0.733_799_8]), + (0.3, 0.7, [false, true], [1.473_799_7, -0.072_800_055, 0.645_000_2, 0.733_799_8]), + (1.2, -0.4, [true, false], [-1.722_999_5, 0.127_000_57, 0.089_999_32, 1.939_999_3]), + (1.2, -0.4, [false, true], [-1.057_000_3, -1.094, 0.756_000_1, 2.606_000_2]), + (-0.15, 1.1, [true, false], [2.051, -1.76, 0.090_000_15, 1.311_000_1]), + (-0.15, 1.1, [false, true], [-1.834_000_6, 0.015_999_317, 0.608_000_5, 2.458_000_7]), + (0.95, 0.05, [true, false], [-1.464, 0.386_000_04, 2.236_000_3, -0.317_000_15]), + (0.95, 0.05, [false, true], [0.145_500_18, -0.206_000_21, 1.644_000_2, -0.594_499_8]), + ]; + for (u, v, tiling, expected) in cases { + let p = img.sample_axes(u, v, tiling); + for (p, e) in p.iter().zip(expected) { + assert!((p - e).abs() <= 2.0e-6, "u {u} v {v} {tiling:?}: {p} against {e}"); + } + } + } + + #[test] + fn equal_axes_give_the_shared_results() { + let us = coordinates(-2.5, 3.5); + for img in [gray8(), color()] { + for tile in [false, true] { + for &u in &us { + for &v in &us { + assert_eq!(img.sample_axes(u, v, [tile; 2]).map(f32::to_bits), img.sample(u, v, tile).map(f32::to_bits)); + assert_eq!(img.sample_nearest_axes(u, v, [tile; 2]).map(f32::to_bits), img.sample_nearest(u, v, tile).map(f32::to_bits)); + } + } + for x in -12..12 { + assert_eq!(img.get_axes(x, -x, [tile; 2]), img.get(x, -x, tile)); + } + } + } + } + + #[test] + fn axes_wrap_independently() { + // Texel (x, y) holds x + 10y. + let img = Image::gray(4, 2, |x, y| (x + 10 * y) as f32); + assert_eq!(img.get_axes(-1, -1, [true, false])[0], 3.0); + assert_eq!(img.get_axes(-1, -1, [false, true])[0], 10.0); + assert_eq!(img.get_axes(5, 3, [true, false])[0], 11.0); + assert_eq!(img.sample_nearest_axes(1.1, 1.5, [true, false])[0], 10.0); + assert_eq!(img.sample_nearest_axes(1.1, 1.5, [false, true])[0], 13.0); + // v = 0.25 is the center of row 0; u = 1 is halfway between texels 3 and 0 when repeating. + assert!((img.sample_axes(1.0, 0.25, [true, false])[0] - 1.5).abs() < 1e-6); + assert_eq!(img.sample_axes(1.0, 0.25, [false, true])[0], 3.0); + assert_eq!(img.sample_axes(f32::NAN, 0.5, [false, true]), [0.0, 0.0, 0.0, 1.0]); + assert_eq!(img.sample_nearest_axes(0.5, f32::INFINITY, [true, false]), [0.0, 0.0, 0.0, 1.0]); + } + + #[test] + fn stored_sampling_rounds_weights_to_eight_bits() { + let img = Image::gray(2, 1, |x, _| x as f32); + // u × 2 − 0.5 = 0.3: the weight 0.3 rounds to 77/256. + assert_eq!(img.sample_stored(0.4, 0.5, false)[0], 77.0 / 256.0); + assert!((img.sample(0.4, 0.5, false)[0] - 0.3).abs() < 1e-6); + // A fraction of 255.5/256 or more rounds up to the next texel. + assert_eq!(img.sample_stored((1.5 - 0.25 / 256.0) / 2.0, 0.5, false)[0], 1.0); + assert_eq!(img.sample_stored(f32::NAN, 0.5, true), [0.0, 0.0, 0.0, 1.0]); + assert_eq!(img.sample_stored(0.5, f32::NEG_INFINITY, false), [0.0, 0.0, 0.0, 1.0]); + } + + #[test] + fn integer_sampling_rounds_stored_samples_to_sixteen_bits() { + let img = Image::gray(2, 1, |x, _| x as f32); + assert!(!img.integer_sampling()); + let int = img.clone().with_integer_sampling(true); + assert!(int.integer_sampling()); + // 77/256 × 65535 = 19711.64, which rounds to 19712. + assert_eq!(int.sample_stored(0.4, 0.5, false)[0], 19_712.0 / 65_535.0); + assert_eq!(int.sample(0.4, 0.5, false), img.sample(0.4, 0.5, false)); + assert_eq!(int.sample_nearest(0.4, 0.5, false), img.sample_nearest(0.4, 0.5, false)); + let l = Limits::default(); + let Ok(wide) = Image::from_data(3, 1, Kind::Gray, vec![-0.5, 2.0, f32::NAN], &l) else { panic!("valid 3 x 1 image") }; + let wide = wide.with_integer_sampling(true); + assert_eq!(wide.sample_stored(0.5 / 3.0, 0.5, false)[0], 0.0); + assert_eq!(wide.sample_stored(1.5 / 3.0, 0.5, false)[0], 1.0); + assert!(wide.sample_stored(2.5 / 3.0, 0.5, false)[0].is_nan()); + assert_eq!(wide.sample_stored(0.5 / 3.0, 0.5, false)[3], 1.0); + } + + #[test] + fn integer_sampling_follows_clones_and_not_new_buffers() { + let img = Image::gray(4, 2, |x, y| (x + y) as f32 / 8.0).with_integer_sampling(true); + let plain = img.clone().with_integer_sampling(false); + assert_eq!(img.clone(), img); + assert_ne!(img, plain); + assert_eq!(img.data(), plain.data()); + assert!(img.clone().integer_sampling()); + assert!(img.to_gray().integer_sampling()); + assert!(img.resize(4, 2, false).integer_sampling()); + assert!(!img.resize(2, 1, false).integer_sampling()); + assert!(!img.map(Kind::Gray, |p| p).integer_sampling()); + assert!(!img.to_color().integer_sampling()); + assert!(img.try_to_kind(Kind::Gray, &Limits::default()).is_ok_and(|i| i.integer_sampling())); + assert!(Arc::ptr_eq(img.shared_data(), plain.shared_data())); + } + + #[test] + fn stored_sampling_keeps_finite_texels_finite() { + let l = Limits::default(); + let Ok(inf) = Image::from_data(2, 1, Kind::Gray, vec![1.0, f32::INFINITY], &l) else { panic!("valid 2 x 1 image") }; + // The center of texel 0 gives texel 0, though its neighbor is infinite. + assert_eq!(inf.sample_stored(0.25, 0.5, false)[0], 1.0); + assert_eq!(inf.sample_stored(0.5, 0.5, false)[0], f32::INFINITY); + let Ok(hdr) = Image::from_data(2, 1, Kind::Gray, vec![f32::MAX, -f32::MAX], &l) else { panic!("valid 2 x 1 image") }; + assert_eq!(hdr.sample_stored(0.5, 0.5, false)[0], 0.0); + assert_eq!(hdr.clone().with_integer_sampling(true).sample_stored(0.5, 0.5, false)[0], 0.0); + let max = Image::filled(2, 2, Kind::Gray, [f32::MAX; 4]); + for tile in [false, true] { + assert_eq!(max.sample_stored(0.3, 0.6, tile)[0], f32::MAX, "tile = {tile}"); + } + } + + #[test] + fn stored_sampling_keeps_the_repeat_period_at_large_coordinates() { + let img = stripe(); + let at_zero = img.sample_stored(0.0, 0.5, true)[0]; + assert_eq!(at_zero, 0.5); + for u in [1.0e9_f32, -1.0e9, 4.0e9, 3.0e12, f32::MAX] { + assert_eq!(img.sample_stored(u, 0.5, true)[0], at_zero, "u = {u}"); + let edge = if u > 0.0 { 1.0 } else { 0.0 }; + assert_eq!(img.sample_stored(u, 0.5, false)[0], edge, "u = {u}"); + } + } } diff --git a/crates/tga/src/lib.rs b/crates/tga/src/lib.rs index ac9d21497b..cf968cf573 100644 --- a/crates/tga/src/lib.rs +++ b/crates/tga/src/lib.rs @@ -18,6 +18,11 @@ //! Input is treated as hostile: the picture size is capped by [`Limits`], and a run-length file //! must be long enough to hold the pixels its header declares before anything is allocated. +/// Uncompressed RGBA8-to-Targa encoding. +pub mod rgba8_raw; + +#[cfg(test)] +mod metadata_tests; #[cfg(test)] mod tests; @@ -57,11 +62,13 @@ pub type Result = std::result::Result; pub struct Limits { /// Most pixels (width × height) a picture may have. Default 2^28 (16384 × 16384). pub max_pixels: u64, + /// Maximum combined palette, stored-pixel and RGBA allocation bytes. Default 256 MiB. + pub max_decoded_bytes: usize, } impl Default for Limits { fn default() -> Self { - Self { max_pixels: 1 << 28 } + Self { max_pixels: 1 << 28, max_decoded_bytes: 256 << 20 } } } @@ -180,6 +187,102 @@ impl Stored { } } +fn metadata_offset(body: &[u8], offset: usize, first_pixel: usize) -> Option { + // Optional metadata cannot replace the header, image ID, or colour map. + (offset >= first_pixel && offset < body.len()).then_some(offset) +} + +/// The start of every developer-directory payload with a nonzero length, from the directory at +/// `directory` in `body` (none when that offset holds no readable directory). +fn developer_payload_starts(body: &[u8], directory: usize) -> Vec { + let Some(count) = + body.get(directory..directory.saturating_add(2)).and_then(|v| v.first_chunk::<2>()).map(|v| usize::from(u16::from_le_bytes(*v))) + else { + return Vec::new(); + }; + let Some(fields) = body.get(directory.saturating_add(2)..) else { return Vec::new() }; + fields + .chunks(10) + .take(count) + .filter_map(|field| { + let start = field.get(2..6).and_then(|v| v.first_chunk::<4>()).map(|v| u32::from_le_bytes(*v) as usize)?; + let length = field.get(6..10).and_then(|v| v.first_chunk::<4>()).map(|v| u32::from_le_bytes(*v))?; + (length != 0).then_some(start) + }) + .collect() +} + +fn image_data_end(bytes: &[u8], first_pixel: usize) -> Result { + if !bytes.ends_with(SIGNATURE) { + return Ok(bytes.len()); + } + // A TGA 2.0 footer cannot begin inside the mandatory header. A legacy image + // may end with the same signature as pixel bytes. + let Some(footer) = bytes.len().checked_sub(SIGNATURE.len() + 8).filter(|&at| at >= HEADER) else { + return Ok(bytes.len()); + }; + let offsets = bytes.get(footer..footer + 8).and_then(|b| b.first_chunk::<8>()).ok_or(Error::Malformed("truncated footer"))?; + let extension = offsets.first_chunk::<4>().map(|v| u32::from_le_bytes(*v) as usize).ok_or(Error::Malformed("truncated footer"))?; + let directory = + offsets.get(4..).and_then(|v| v.first_chunk::<4>()).map(|v| u32::from_le_bytes(*v) as usize).ok_or(Error::Malformed("truncated footer"))?; + let body = bytes.get(..footer).ok_or(Error::Malformed("truncated footer"))?; + let mut end = footer; + + if let Some(offset) = metadata_offset(body, extension, first_pixel) { + // An in-body reference is a conservative image boundary, even if it overlaps + // required pixels. Those bytes cannot be distinguished from a truncated image + // whose missing pixels are supplied by metadata. + end = end.min(offset); + // TGA 2.0 extension fields at byte offsets 482, 486 and 490 point to the colour + // correction, postage-stamp and scan-line tables. The record's first two bytes give + // its size (495 in TGA 2.0); a shorter record has no such fields, and a record never + // reaches into a developer directory that follows it, so those bytes are not read as + // table offsets. Tables may precede the record. + let declared = + body.get(offset..offset.saturating_add(2)).and_then(|v| v.first_chunk::<2>()).map_or(0, |v| usize::from(u16::from_le_bytes(*v))); + let mut record_end = offset.saturating_add(declared.min(495)); + // The developer directory and its payloads may sit anywhere after the pixels, a payload + // before its directory included; whichever starts first after the extension ends it. + // A directory offset of zero means there is none: the header is not read as one. + let payloads = metadata_offset(body, directory, first_pixel).map(|d| developer_payload_starts(body, d)).unwrap_or_default(); + for next in std::iter::once(directory).chain(payloads) { + if next > offset { + record_end = record_end.min(next); + } + } + if let Some(area) = body.get(offset..record_end.min(body.len())) { + for field in [482, 486, 490] { + if let Some(value) = area.get(field..field + 4).and_then(|v| v.first_chunk::<4>()) + && let Some(table) = metadata_offset(body, u32::from_le_bytes(*value) as usize, first_pixel) + { + end = end.min(table); + } + } + } + } + + if let Some(offset) = metadata_offset(body, directory, first_pixel) { + end = end.min(offset); + if let Some(count) = + body.get(offset..offset.saturating_add(2)).and_then(|v| v.first_chunk::<2>()).map(|v| usize::from(u16::from_le_bytes(*v))) + && let Some(fields) = body.get(offset.saturating_add(2)..) + { + // A corrupt count or final entry does not hide earlier payload offsets. Each + // entry has a 2-byte tag followed by a 4-byte offset and 4-byte length. + for field in fields.chunks(10).take(count) { + if let Some(value) = field.get(2..6).and_then(|v| v.first_chunk::<4>()) + && let Some(length) = field.get(6..10).and_then(|v| v.first_chunk::<4>()) + && u32::from_le_bytes(*length) != 0 + && let Some(payload) = metadata_offset(body, u32::from_le_bytes(*value) as usize, first_pixel) + { + end = end.min(payload); + } + } + } + } + Ok(end) +} + /// Decodes a Targa file to straight-alpha RGBA8, top row first. pub fn decode(bytes: &[u8], limits: &Limits) -> Result { let err = Error::Malformed; @@ -208,13 +311,14 @@ pub fn decode(bytes: &[u8], limits: &Limits) -> Result { } else { None }; - let mut at = HEADER + id_len; - if let Some(l) = map_entry { - let end = at + map_len * l.bytes(); - let map = bytes.get(at..end).ok_or(err("truncated colour map"))?; - palette = map.chunks_exact(l.bytes()).map(|e| l.rgba(e)).collect(); - at = end; - } + let map_start = HEADER + id_len; + let first_pixel = match map_entry { + Some(layout) => map_start.checked_add(map_len * layout.bytes()).ok_or(err("colour map"))?, + None => map_start, + }; + let end = image_data_end(bytes, first_pixel)?; + let bytes = bytes.get(..end).ok_or(err("truncated image data"))?; + let at = first_pixel; let (stored_as, mapped) = match kind & 7 { 1 => { if map_type != 1 || !matches!(depth, 8 | 16) { @@ -232,14 +336,35 @@ pub fn decode(bytes: &[u8], limits: &Limits) -> Result { }; let data = bytes.get(at..).unwrap_or_default(); let bpp = stored_as.bytes(); + let stored_bytes = pixels.checked_mul(bpp).ok_or(Error::LimitExceeded("image size"))?; + let rgba_bytes = pixels.checked_mul(4).ok_or(Error::LimitExceeded("image size"))?; + let palette_bytes = if map_entry.is_some() { map_len * 4 } else { 0 }; + let aggregate = + stored_bytes.checked_add(rgba_bytes).and_then(|n| n.checked_add(palette_bytes)).ok_or(Error::LimitExceeded("decode allocation bytes"))?; + if aggregate > limits.max_decoded_bytes { + return Err(Error::LimitExceeded("decode allocation bytes")); + } + if let Some(layout) = map_entry { + let map = bytes.get(map_start..first_pixel).ok_or(err("truncated colour map"))?; + palette.try_reserve_exact(map_len).map_err(|_| Error::LimitExceeded("allocation failed"))?; + palette.extend(map.chunks_exact(layout.bytes()).map(|entry| layout.rgba(entry))); + } // The stored values, in file order. let stored: Vec = if rle { unpack_rle(data, pixels, bpp)? } else { let n = pixels.checked_mul(bpp).ok_or(Error::LimitExceeded("image size"))?; - data.get(..n).ok_or(err("truncated pixel data"))?.to_vec() + { + let source = data.get(..n).ok_or(err("truncated pixel data"))?; + let mut values = Vec::new(); + values.try_reserve_exact(n).map_err(|_| Error::LimitExceeded("allocation failed"))?; + values.extend_from_slice(source); + values + } }; - let mut rgba = vec![0u8; pixels.checked_mul(4).ok_or(Error::LimitExceeded("image size"))?]; + let mut rgba = Vec::new(); + rgba.try_reserve_exact(rgba_bytes).map_err(|_| Error::LimitExceeded("allocation failed"))?; + rgba.resize(rgba_bytes, 0u8); for (i, v) in stored.chunks_exact(bpp).enumerate().take(pixels) { let (x, y) = (i % w, i / w); let x = if right_to_left { w - 1 - x } else { x }; @@ -283,7 +408,8 @@ fn unpack_rle(mut data: &[u8], pixels: usize, bpp: usize) -> Result> { return Err(short); } let total = pixels.checked_mul(bpp).ok_or(Error::LimitExceeded("image size"))?; - let mut out = Vec::with_capacity(total); + let mut out = Vec::new(); + out.try_reserve_exact(total).map_err(|_| Error::LimitExceeded("allocation failed"))?; while out.len() < total { let (&head, rest) = data.split_first().ok_or(short.clone())?; let count = usize::from(head & 0x7F) + 1; diff --git a/crates/tga/src/metadata_tests.rs b/crates/tga/src/metadata_tests.rs new file mode 100644 index 0000000000..85c434bf4d --- /dev/null +++ b/crates/tga/src/metadata_tests.rs @@ -0,0 +1,425 @@ +//! Metadata-boundary regressions ported from FilmCraft #1932 (nuclearspike). +use super::*; +fn header(kind: u8, w: u16, h: u16, depth: u8, descriptor: u8) -> Vec { + let mut b = vec![0, 0, kind, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + b.extend_from_slice(&w.to_le_bytes()); + b.extend_from_slice(&h.to_le_bytes()); + b.extend_from_slice(&[depth, descriptor]); + b +} +fn dec(bytes: &[u8]) -> Result { + decode(bytes, &Limits::default()) +} +#[test] +fn legacy_pixels_that_end_in_signature_are_not_a_footer_before_header() { + for prefix in [0usize, 7] { + let width = (prefix + SIGNATURE.len()) as u16; + let mut file = header(3, width, 1, 8, 0x20); + file.extend(vec![0; prefix]); + file.extend_from_slice(SIGNATURE); + let image = dec(&file).unwrap(); + assert_eq!((image.width, image.height), (u32::from(width), 1)); + let pixels: Vec = std::iter::repeat_n(0, prefix).chain(SIGNATURE.iter().copied()).flat_map(|gray| [gray, gray, gray, 255]).collect(); + assert_eq!(image.rgba, pixels); + let source = dec(&file).unwrap(); + assert_eq!(source.rgba, pixels); + } +} + +#[test] +fn short_extension_followed_by_a_developer_payload_keeps_the_pixels() { + // a 482-byte extension whose size field still says 495, then a developer payload whose + // first bytes land where a full extension keeps its colour-correction offset, then the + // directory that points back at that payload + let mut file = header(2, 1, 1, 24, 0x20); + file.extend_from_slice(&[10, 20, 30]); + let extension = file.len() as u32; + let mut area = vec![0; 482]; + area[..2].copy_from_slice(&495u16.to_le_bytes()); + file.extend_from_slice(&area); + let payload = file.len() as u32; + file.extend_from_slice(&18u32.to_le_bytes()); + file.extend_from_slice(&[0; 14]); + let directory = file.len() as u32; + file.extend_from_slice(&1u16.to_le_bytes()); + file.extend_from_slice(&0u16.to_le_bytes()); + file.extend_from_slice(&payload.to_le_bytes()); + file.extend_from_slice(&18u32.to_le_bytes()); + file.extend_from_slice(&extension.to_le_bytes()); + file.extend_from_slice(&directory.to_le_bytes()); + file.extend_from_slice(SIGNATURE); + let source = dec(&file).expect("the image decodes"); + assert_eq!((source.width, source.height), (1, 1)); + assert_eq!(source.rgba, vec![30, 20, 10, 255]); +} + +#[test] +fn a_footer_without_a_directory_does_not_read_the_header_as_one() { + // no developer directory (offset 0). Read as one, the header's three-byte image ID + // length is an entry count, and the third "entry" is the first words of a colour + // correction table that sits right after a short pixel area; the extension points at + // that table, so the image is incomplete and must stay so. + let mut file = header(2, 2, 1, 24, 0x20); + file[0] = 3; + file.extend_from_slice(&[7, 8, 9]); + file.extend_from_slice(&[0, 0, 255]); + let table = file.len() as u32; + let mut words = vec![0; 2048]; + words[..4].copy_from_slice(&2074u32.to_le_bytes()); + words[4..8].copy_from_slice(&1u32.to_le_bytes()); + file.extend_from_slice(&words); + let extension = file.len() as u32; + let mut area = vec![0; 495]; + area[..2].copy_from_slice(&495u16.to_le_bytes()); + area[482..486].copy_from_slice(&table.to_le_bytes()); + file.extend_from_slice(&area); + file.extend_from_slice(&extension.to_le_bytes()); + file.extend_from_slice(&0u32.to_le_bytes()); + file.extend_from_slice(SIGNATURE); + let decoded = dec(&file); + assert!(decoded.is_err(), "the second pixel is missing"); +} + +#[test] +fn short_extension_followed_by_a_developer_directory_keeps_the_pixels() { + // a complete 1x1 image, a 482-byte extension (its size says so) and right after it a + // developer directory whose entry's length lands where a full extension keeps its + // scan-line table offset; reading it as one would move the image end into the header + let mut file = header(2, 1, 1, 24, 0x20); + file.extend_from_slice(&[10, 20, 30]); + let extension = file.len() as u32; + let mut area = vec![0; 482]; + area[..2].copy_from_slice(&482u16.to_le_bytes()); + file.extend_from_slice(&area); + let directory = file.len() as u32; + let payload = directory + 2 + 10; + file.extend_from_slice(&1u16.to_le_bytes()); + file.extend_from_slice(&0u16.to_le_bytes()); + file.extend_from_slice(&payload.to_le_bytes()); + file.extend_from_slice(&18u32.to_le_bytes()); + file.extend_from_slice(&[0; 18]); + file.extend_from_slice(&extension.to_le_bytes()); + file.extend_from_slice(&directory.to_le_bytes()); + file.extend_from_slice(SIGNATURE); + let source = dec(&file).expect("the image decodes"); + assert_eq!((source.width, source.height), (1, 1)); +} + +#[test] +fn importing_truncated_pixels_does_not_consume_tga_footer() { + for (kind, data) in [(2, vec![0, 0, 255]), (10, vec![0x80, 0, 0, 255])] { + for metadata in [None, Some(0usize), Some(1)] { + let mut file = header(kind, 2, 1, 24, 0x20); + file.extend_from_slice(&data); // only the first of two pixels + let mut offsets = [0u8; 8]; + if let Some(field) = metadata { + let offset = file.len() as u32; + offsets[field * 4..field * 4 + 4].copy_from_slice(&offset.to_le_bytes()); + let mut area = vec![0; 495]; + if field == 0 { + area[..2].copy_from_slice(&495u16.to_le_bytes()); + } + file.extend_from_slice(&area); // optional metadata is not pixel data + } + file.extend_from_slice(&offsets); + file.extend_from_slice(SIGNATURE); + let result = dec(&file); + assert!(result.is_err(), "kind {kind}, metadata {metadata:?}: metadata is not a second pixel"); + } + } + for kind in [1, 9] { + let mut file = header(kind, 1, 1, 8, 0x20); + file[1] = 1; + file[5] = 1; + file[7] = 24; + file.extend_from_slice(&[0, 0]); // missing third palette byte and the index + file.extend_from_slice(&[0; 8]); + file.extend_from_slice(SIGNATURE); + let result = dec(&file); + assert!(result.is_err(), "kind {kind}: the footer is not colour-map data"); + } +} + +#[test] +fn complete_tga_footer_and_metadata_do_not_change_pixels() { + for metadata in [None, Some(0usize), Some(1)] { + let mut file = header(2, 1, 1, 24, 0x20); + file.extend_from_slice(&[0, 0, 255]); + let mut offsets = [0u8; 8]; + if let Some(field) = metadata { + let offset = file.len() as u32; + offsets[field * 4..field * 4 + 4].copy_from_slice(&offset.to_le_bytes()); + let mut area = vec![0; 495]; + if field == 0 { + area[..2].copy_from_slice(&495u16.to_le_bytes()); + } + file.extend_from_slice(&area); + } + file.extend_from_slice(&offsets); + file.extend_from_slice(SIGNATURE); + let source = dec(&file).unwrap(); + assert_eq!(source.rgba, [255, 0, 0, 255]); + } +} + +fn preceding_metadata(complete: bool, metadata: usize) -> Vec { + assert!(metadata <= 3, "test metadata selector must be 0..=3"); + let mut file = header(2, if complete { 1 } else { 2 }, 1, 24, 0x20); + file.extend_from_slice(&[0, 0, 255]); + let payload_offset = file.len() as u32; + let mut offsets = [0u8; 8]; + if metadata == 0 { + file.extend_from_slice(&[0, 255, 0]); + let directory_offset = file.len() as u32; + file.extend_from_slice(&1u16.to_le_bytes()); + file.extend_from_slice(&1u16.to_le_bytes()); + file.extend_from_slice(&payload_offset.to_le_bytes()); + file.extend_from_slice(&3u32.to_le_bytes()); + offsets[4..].copy_from_slice(&directory_offset.to_le_bytes()); + } else { + match metadata { + 1 => file.extend_from_slice(&[0; 2048]), + 2 => file.extend_from_slice(&[1, 1, 0, 255, 0]), + 3 => file.extend_from_slice(&18u32.to_le_bytes()), + _ => {} + } + let extension_offset = file.len() as u32; + let mut extension = [0; 495]; + extension[..2].copy_from_slice(&495u16.to_le_bytes()); + let field = [0, 482, 486, 490][metadata]; + extension[field..field + 4].copy_from_slice(&payload_offset.to_le_bytes()); + file.extend_from_slice(&extension); + offsets[..4].copy_from_slice(&extension_offset.to_le_bytes()); + } + file.extend_from_slice(&offsets); + file.extend_from_slice(SIGNATURE); + file +} + +#[test] +fn preceding_metadata_cannot_supply_missing_pixels() { + let mut accepted = Vec::new(); + for metadata in 0..4 { + let result = dec(&preceding_metadata(false, metadata)); + if result.is_ok() { + accepted.push(metadata); + } + } + assert!(accepted.is_empty(), "metadata payloads supplied missing pixels: {accepted:?}"); +} + +#[test] +fn complete_pixels_before_metadata_keep_their_colour() { + for metadata in 0..4 { + let source = dec(&preceding_metadata(true, metadata)).unwrap(); + assert_eq!(source.rgba, [255, 0, 0, 255], "metadata {metadata}"); + } + let mut file = preceding_metadata(true, 1); + let footer = file.len() - SIGNATURE.len() - 8; + let extension = u32::from_le_bytes(file[footer..footer + 4].try_into().unwrap()) as usize; + file[extension..extension + 2].copy_from_slice(&496u16.to_le_bytes()); + file.insert(footer, 0); + let source = dec(&file).unwrap(); + assert_eq!(source.rgba, [255, 0, 0, 255], "larger complete extensions preserve pixels"); +} + +#[test] +fn malformed_optional_metadata_keeps_complete_pixels_readable() { + let accept = |file: Vec| { + let source = dec(&file).unwrap(); + assert_eq!(source.rgba, [255, 0, 0, 255]); + }; + for field in [0, 4] { + let mut file = preceding_metadata(true, 0); + let footer = file.len() - SIGNATURE.len() - 8; + file[footer + field..footer + field + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + accept(file); + } + for metadata in 1..4 { + let mut file = preceding_metadata(true, metadata); + let footer = file.len() - SIGNATURE.len() - 8; + let extension = u32::from_le_bytes(file[footer..footer + 4].try_into().unwrap()) as usize; + let field = [0, 482, 486, 490][metadata]; + file[extension + field..extension + field + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + accept(file); + } + let mut file = preceding_metadata(true, 0); + let footer = file.len() - SIGNATURE.len() - 8; + let directory = u32::from_le_bytes(file[footer + 4..footer + 8].try_into().unwrap()) as usize; + file.drain(directory + 2..footer); + accept(file); + let mut file = preceding_metadata(true, 0); + let footer = file.len() - SIGNATURE.len() - 8; + let directory = u32::from_le_bytes(file[footer + 4..footer + 8].try_into().unwrap()) as usize; + file[directory + 8..directory + 12].copy_from_slice(&u32::MAX.to_le_bytes()); + accept(file); + let mut file = preceding_metadata(true, 0); + let footer = file.len() - SIGNATURE.len() - 8; + let directory = u32::from_le_bytes(file[footer + 4..footer + 8].try_into().unwrap()) as usize; + file[directory..directory + 2].copy_from_slice(&2u16.to_le_bytes()); + accept(file); + // A zero-length entry cannot mark a payload boundary, even if its offset overlaps pixels. + let mut file = preceding_metadata(true, 0); + let footer = file.len() - SIGNATURE.len() - 8; + let directory = u32::from_le_bytes(file[footer + 4..footer + 8].try_into().unwrap()) as usize; + file[directory + 4..directory + 8].copy_from_slice(&19u32.to_le_bytes()); + file[directory + 8..directory + 12].copy_from_slice(&0u32.to_le_bytes()); + accept(file); + let mut file = preceding_metadata(true, 2); + file[21..23].copy_from_slice(&[255, 255]); + accept(file); + let mut file = preceding_metadata(true, 2); + let footer = file.len() - SIGNATURE.len() - 8; + let extension = u32::from_le_bytes(file[footer..footer + 4].try_into().unwrap()) as usize; + file[extension..extension + 2].copy_from_slice(&494u16.to_le_bytes()); + accept(file); + let mut file = preceding_metadata(true, 2); + let footer = file.len() - SIGNATURE.len() - 8; + file.remove(footer - 1); // extension is physically short, but its postage offset remains + accept(file); +} + +#[test] +fn malformed_metadata_offsets_inside_id_or_palette_keep_complete_pixels() { + let mut file = header(1, 1, 1, 8, 0x20); + file[0] = 4; // image ID length + file[1] = 1; // colour map present + file[5..7].copy_from_slice(&1u16.to_le_bytes()); + file[7] = 24; // one BGR palette entry + file.extend_from_slice(&[7, 8, 9, 10]); // image ID + file.extend_from_slice(&[0, 0, 255]); // red palette entry + file.push(0); // palette index + for (field, offset) in [(0, HEADER + 1), (4, HEADER + 4 + 1)] { + let mut candidate = file.clone(); + let mut footer_offsets = [0u8; 8]; + footer_offsets[field..field + 4].copy_from_slice(&(offset as u32).to_le_bytes()); + candidate.extend_from_slice(&footer_offsets); + candidate.extend_from_slice(SIGNATURE); + let image = dec(&candidate).unwrap(); + assert_eq!(image.rgba, [255, 0, 0, 255], "footer field {field}"); + } +} + +#[test] +fn malformed_optional_metadata_cannot_supply_missing_pixels() { + let mut file = preceding_metadata(false, 0); + let footer = file.len() - SIGNATURE.len() - 8; + let directory = u32::from_le_bytes(file[footer + 4..footer + 8].try_into().unwrap()) as usize; + file[directory + 8..directory + 12].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(dec(&file).is_err()); + + // The declared entry count exceeds the bytes before the footer, but the first entry's + // payload still precedes the directory and cannot be used as a second pixel. + let mut file = preceding_metadata(false, 0); + let footer = file.len() - SIGNATURE.len() - 8; + let directory = u32::from_le_bytes(file[footer + 4..footer + 8].try_into().unwrap()) as usize; + file[directory..directory + 2].copy_from_slice(&2u16.to_le_bytes()); + assert!(dec(&file).is_err()); + + let mut file = preceding_metadata(false, 2); + let footer = file.len() - SIGNATURE.len() - 8; + let extension = u32::from_le_bytes(file[footer..footer + 4].try_into().unwrap()) as usize; + file[extension..extension + 2].copy_from_slice(&494u16.to_le_bytes()); + assert!(dec(&file).is_err()); + let mut file = preceding_metadata(false, 2); + let footer = file.len() - SIGNATURE.len() - 8; + file.remove(footer - 1); + assert!(dec(&file).is_err()); +} + +#[test] +fn valid_developer_directory_with_overlapping_payload_rejects_pixels() { + let mut file = preceding_metadata(true, 0); + let footer = file.len() - SIGNATURE.len() - 8; + let directory = u32::from_le_bytes(file[footer + 4..footer + 8].try_into().unwrap()) as usize; + file[directory..directory + 2].copy_from_slice(&2u16.to_le_bytes()); + let mut extra = [0u8; 10]; + extra[..2].copy_from_slice(&2u16.to_le_bytes()); + extra[2..6].copy_from_slice(&(HEADER as u32).to_le_bytes()); + extra[6..10].copy_from_slice(&1u32.to_le_bytes()); + file.splice(footer..footer, extra); + let moved_footer = file.len() - SIGNATURE.len() - 8; + assert_eq!(u32::from_le_bytes(file[moved_footer + 4..moved_footer + 8].try_into().unwrap()), directory as u32); + assert_eq!(u16::from_le_bytes(file[directory..directory + 2].try_into().unwrap()), 2); + assert_eq!(&file[directory + 12..directory + 22], &extra); + assert!(dec(&file).is_err()); +} + +#[test] +fn nonempty_developer_reference_inside_pixels_rejects_the_whole_image() { + let mut file = header(2, 2, 1, 24, 0x20); + file.extend_from_slice(&[0, 0, 255, 0, 255, 0]); + let directory = file.len() as u32; + file.extend_from_slice(&1u16.to_le_bytes()); + file.extend_from_slice(&1u16.to_le_bytes()); + file.extend_from_slice(&(HEADER as u32 + 3).to_le_bytes()); + file.extend_from_slice(&1u32.to_le_bytes()); + file.extend_from_slice(&0u32.to_le_bytes()); + file.extend_from_slice(&directory.to_le_bytes()); + file.extend_from_slice(SIGNATURE); + assert!(dec(&file).is_err(), "an overlapping reference must not return a partial image"); +} + +#[test] +fn inflated_developer_count_scans_the_next_chunk_as_an_entry_and_rejects_its_pixel_payload() { + // a directory claiming two entries over one real entry: the ten bytes after it, scanned as + // the second entry, name a payload inside the pixels, which is refused like any other + let mut file = header(2, 2, 1, 24, 0x20); + file.extend_from_slice(&[0, 0, 255, 0, 255, 0]); + let directory = file.len() as u32; + file.extend_from_slice(&2u16.to_le_bytes()); + file.extend_from_slice(&1u16.to_le_bytes()); + file.extend_from_slice(&(directory + 22).to_le_bytes()); + file.extend_from_slice(&0u32.to_le_bytes()); + file.extend_from_slice(&2u16.to_le_bytes()); + file.extend_from_slice(&(HEADER as u32 + 3).to_le_bytes()); + file.extend_from_slice(&1u32.to_le_bytes()); + file.extend_from_slice(&0u32.to_le_bytes()); + file.extend_from_slice(&directory.to_le_bytes()); + file.extend_from_slice(SIGNATURE); + assert!(dec(&file).is_err(), "a scanned entry's payload inside the pixels is refused"); +} + +#[test] +fn legacy_pixels_that_end_in_signature_at_or_after_the_header_are_read_as_a_footer() { + // a footerless 36×1 grayscale image whose last 26 bytes happen to be eight zeros and the + // signature: the putative trailer begins at byte 28, so it is taken for a footer and the + // image, left with 10 pixel bytes, is rejected as truncated (the ambiguity the body states) + let prefix = 18usize; + let width = (prefix + SIGNATURE.len()) as u16; + let mut file = header(3, width, 1, 8, 0x20); + file.extend(vec![0; prefix]); + file.extend_from_slice(SIGNATURE); + assert!(dec(&file).is_err()); +} + +#[test] +fn mutated_tga_footer_files_never_panic() { + let mut file = header(2, 2, 1, 24, 0x20); + file.extend_from_slice(&[0, 0, 255, 0, 255, 0]); + file.extend_from_slice(&[0; 8]); + file.extend_from_slice(SIGNATURE); + for end in 0..file.len() { + assert!(std::panic::catch_unwind(|| dec(&file[..end])).is_ok(), "truncation at {end}"); + } + for at in 0..file.len() { + let mut mutated = file.clone(); + mutated[at] ^= 0xFF; + assert!(std::panic::catch_unwind(|| dec(&mutated)).is_ok(), "mutation at {at}"); + } + for metadata in 0..4 { + let file = preceding_metadata(true, metadata); + assert!(dec(&file).is_ok()); + let footer = file.len() - SIGNATURE.len() - 8; + for end in 0..footer { + let mut truncated = file[..end].to_vec(); + truncated.extend_from_slice(&file[footer..]); + assert!(std::panic::catch_unwind(|| dec(&truncated)).is_ok(), "metadata {metadata}, footer-preserving truncation at {end}"); + } + for at in 0..file.len() { + let mut mutated = file.clone(); + mutated[at] ^= 0xFF; + assert!(std::panic::catch_unwind(|| dec(&mutated)).is_ok(), "metadata {metadata}, mutation at {at}"); + } + } +} diff --git a/crates/tga/src/rgba8_raw.rs b/crates/tga/src/rgba8_raw.rs new file mode 100644 index 0000000000..a671462c90 --- /dev/null +++ b/crates/tga/src/rgba8_raw.rs @@ -0,0 +1,77 @@ +//! 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 16-bit Targa header. + Dimensions, + /// The output buffer could not be allocated. + OutOfMemory, +} +/// An empty buffer with room for `len` bytes, or [`Rgba8EncodeError::OutOfMemory`] when the +/// allocation fails (instead of aborting the process). +fn output_buffer(len: usize) -> std::result::Result, Rgba8EncodeError> { + let mut out = Vec::new(); + out.try_reserve_exact(len).map_err(|_| Rgba8EncodeError::OutOfMemory)?; + Ok(out) +} +fn checked_len(rgba: &[u8], w: u32, h: u32) -> std::result::Result { + 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) +} +/// An uncompressed Targa file: 24-bit BGR, or 32-bit BGRA with `alpha` (straight alpha, as the +/// frame carries it). +pub fn encode_rgba8_raw(rgba: &[u8], w: u32, h: u32, alpha: bool) -> std::result::Result, Rgba8EncodeError> { + checked_len(rgba, w, h)?; + let (tw, th) = match (u16::try_from(w), u16::try_from(h)) { + (Ok(tw), Ok(th)) => (tw, th), + _ => return Err(Rgba8EncodeError::Dimensions), + }; + let bpp: usize = if alpha { 4 } else { 3 }; + let row = w as usize * 4; + // The caller already holds the frame; reserve the second, output-sized buffer fallibly so a + // large export reports an error instead of aborting the process. + let len = (w as usize * h as usize).checked_mul(bpp).and_then(|n| n.checked_add(18 + 26)).ok_or(Rgba8EncodeError::FrameSize)?; + let mut out = output_buffer(len)?; + out.extend_from_slice(&[0, 0, 2]); // no ID, no colour map, uncompressed true-colour + out.extend_from_slice(&[0; 5]); // colour map specification (unused) + out.extend_from_slice(&[0, 0, 0, 0]); // x / y origin + out.extend_from_slice(&tw.to_le_bytes()); + out.extend_from_slice(&th.to_le_bytes()); + out.push(if alpha { 32 } else { 24 }); + out.push(if alpha { 8 } else { 0 }); // attribute bits; bottom-left origin + // bottom-left origin: the last frame row comes first + for line in rgba.chunks_exact(row).rev() { + for &[r, g, b, a] in line.as_chunks::<4>().0 { + out.extend_from_slice(&[b, g, r]); + if alpha { + out.push(a); + } + } + } + // TGA 2.0 footer without extension or developer areas + out.extend_from_slice(&[0; 8]); + out.extend_from_slice(b"TRUEVISION-XFILE.\0"); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn raw_round_trip() { + let bytes = encode_rgba8_raw(&[1, 2, 3, 4], 1, 1, true).unwrap(); + assert_eq!(&bytes[18..22], &[3, 2, 1, 4]); + assert_eq!(&bytes[bytes.len() - 18..], b"TRUEVISION-XFILE.\0"); + assert_eq!(encode_rgba8_raw(&[], 0, 1, false), Err(Rgba8EncodeError::FrameSize)); + } + #[test] + fn a_failed_output_allocation_is_an_error() { + assert_eq!(output_buffer(usize::MAX), Err(Rgba8EncodeError::OutOfMemory)); + assert!(output_buffer(16).is_ok_and(|b| b.is_empty() && b.capacity() >= 16)); + } +} diff --git a/crates/tga/src/tests.rs b/crates/tga/src/tests.rs index 06109a1794..bec6b69726 100644 --- a/crates/tga/src/tests.rs +++ b/crates/tga/src/tests.rs @@ -92,6 +92,11 @@ fn hostile_headers_fail_without_allocating() { assert_eq!(dec(&f), Err(Error::LimitExceeded("pixel count"))); let mut f = header(10, 16384, 16384, 32, 0); f.extend_from_slice(&[0xFF, 1, 2, 3, 4]); + // The aggregate decoded-storage budget rejects this before any allocation. + assert_eq!(dec(&f), Err(Error::LimitExceeded("decode allocation bytes"))); + // Under budget, an incomplete RLE stream must still fail as truncated. + let mut f = header(10, 16, 16, 32, 0); + f.extend_from_slice(&[0xFF, 1, 2, 3, 4]); // only 128 of 256 pixels assert_eq!(dec(&f), Err(Error::Malformed("truncated run-length data"))); let mut f = header(2, 4, 4, 24, 0); f.extend_from_slice(&[0; 10]); @@ -116,8 +121,8 @@ fn hostile_headers_fail_without_allocating() { fn the_pixel_limit_is_checked() { let mut f = header(3, 2, 2, 8, 0); f.extend_from_slice(&[0; 4]); - assert!(decode(&f, &Limits { max_pixels: 4 }).is_ok()); - assert_eq!(decode(&f, &Limits { max_pixels: 3 }), Err(Error::LimitExceeded("pixel count"))); + assert!(decode(&f, &Limits { max_pixels: 4, ..Limits::default() }).is_ok()); + assert_eq!(decode(&f, &Limits { max_pixels: 3, ..Limits::default() }), Err(Error::LimitExceeded("pixel count"))); } #[test] @@ -235,3 +240,30 @@ fn written_files_read_back() { assert_eq!(r.rgba, want, "{layout:?}"); } } + +#[test] +fn aggregate_decode_budget_applies_before_rle_expansion() { + let mut file = header(10, 16, 16, 32, 0x28); + file.extend_from_slice(&[255, 0, 0, 255, 255, 255, 0, 0, 255, 255]); + let mut limits = Limits { max_decoded_bytes: 2047, ..Limits::default() }; + assert_eq!(decode(&file, &limits), Err(Error::LimitExceeded("decode allocation bytes"))); + limits.max_decoded_bytes = 2048; + assert_eq!(decode(&file, &limits).unwrap().rgba.len(), 1024); +} +#[test] +fn default_budget_rejects_large_rle_header_without_large_fixture() { + let file = header(10, 16384, 16384, 32, 0x28); + assert_eq!(decode(&file, &Limits::default()), Err(Error::LimitExceeded("decode allocation bytes"))); +} +#[test] +fn aggregate_decode_budget_counts_raw_and_palette_storage() { + let mut file = header(1, 1, 1, 8, 0x20); + file[1] = 1; + file[5] = 1; + file[7] = 24; + file.extend_from_slice(&[0, 0, 255, 0]); + let mut limits = Limits { max_decoded_bytes: 8, ..Limits::default() }; + assert_eq!(decode(&file, &limits), Err(Error::LimitExceeded("decode allocation bytes"))); + limits.max_decoded_bytes = 9; + assert_eq!(decode(&file, &limits).unwrap().rgba, [255, 0, 0, 255]); +} diff --git a/crates/tiff/src/lib.rs b/crates/tiff/src/lib.rs index 0e9d595c73..5d6d78a213 100644 --- a/crates/tiff/src/lib.rs +++ b/crates/tiff/src/lib.rs @@ -28,6 +28,7 @@ pub mod classic; pub mod image; pub mod makernote; pub mod packbits; +pub mod probe; mod reader; pub mod tags; pub mod writer; diff --git a/crates/tiff/src/probe.rs b/crates/tiff/src/probe.rs new file mode 100644 index 0000000000..9ed4f3bb1e --- /dev/null +++ b/crates/tiff/src/probe.rs @@ -0,0 +1,111 @@ +//! Allocation-free classic TIFF compression inspection. + +/// Return the first image's compression, or 1 when its tag is absent. +/// +/// Only classic TIFF is accepted. A duplicate Compression tag, non-scalar value, +/// unsupported field type, out-of-range LONG, or unreadable required field returns +/// `None`. Duplicate tags are refused rather than choosing one: decoders may use +/// a different copy, bypassing a caller's compression/resource policy. +/// +/// This inspects only compression, not image validity. Unrelated tag payloads, +/// next-IFD pointers and image data are not read. The caller chooses allowed +/// compression values and must still validate/decode the image with its limits. +/// No allocation occurs; at most 65,535 first-directory entries are inspected. +pub fn first_image_compression(bytes: &[u8]) -> Option { + let le = match bytes.get(..4)? { + b"II*\0" => true, + b"MM\0*" => false, + _ => return None, + }; + let u16_at = |at: usize| -> Option { + let b = [*bytes.get(at)?, *bytes.get(at.checked_add(1)?)?]; + Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }) + }; + let u32_at = |at: usize| -> Option { + let b: [u8; 4] = bytes.get(at..at.checked_add(4)?)?.try_into().ok()?; + Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }) + }; + let ifd = usize::try_from(u32_at(4)?).ok()?; + let mut found = None; + for i in 0..usize::from(u16_at(ifd)?) { + let entry = ifd.checked_add(2)?.checked_add(i.checked_mul(12)?)?; + if u16_at(entry)? != 259 { + continue; + } + if found.is_some() || u32_at(entry.checked_add(4)?)? != 1 { + return None; + } + found = Some(match u16_at(entry.checked_add(2)?)? { + 3 => u16_at(entry.checked_add(8)?)?, + 4 => u16::try_from(u32_at(entry.checked_add(8)?)?).ok()?, + _ => return None, + }); + } + Some(found.unwrap_or(1)) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + use crate::ByteOrder; + + fn fixture(order: ByteOrder, entries: &[(u16, u16, u32, u32)]) -> Vec { + let mut bytes = match order { + ByteOrder::Little => b"II*\0".to_vec(), + ByteOrder::Big => b"MM\0*".to_vec(), + }; + order.put_u32(&mut bytes, 8); + order.put_u16(&mut bytes, u16::try_from(entries.len()).unwrap()); + for &(tag, ty, count, value) in entries { + order.put_u16(&mut bytes, tag); + order.put_u16(&mut bytes, ty); + order.put_u32(&mut bytes, count); + if ty == 3 { + order.put_u16(&mut bytes, u16::try_from(value).unwrap()); + order.put_u16(&mut bytes, 0); + } else { + order.put_u32(&mut bytes, value); + } + } + bytes + } + + #[test] + fn both_byte_orders_and_scalar_types() { + for order in [ByteOrder::Little, ByteOrder::Big] { + assert_eq!(first_image_compression(&fixture(order, &[])), Some(1)); + for ty in [3, 4] { + for value in [1, 5, 6, 7, 32773] { + let bytes = fixture(order, &[(259, ty, 1, value)]); + assert_eq!(first_image_compression(&bytes), u16::try_from(value).ok()); + // Every prefix missing a required byte is refused; SHORT padding and + // the next-IFD pointer are intentionally unnecessary for this probe. + let needed = if ty == 3 { 20 } else { 22 }; + for end in 0..needed { + assert_eq!(first_image_compression(&bytes[..end]), None); + } + } + } + } + } + + #[test] + fn ambiguous_compression_is_refused() { + for order in [ByteOrder::Little, ByteOrder::Big] { + for pair in [(1, 7), (7, 1), (1, 1)] { + assert_eq!(first_image_compression(&fixture(order, &[(259, 3, 1, pair.0), (259, 3, 1, pair.1)])), None); + } + for entry in [(259, 3, 0, 1), (259, 3, 2, 1), (259, 1, 1, 1), (259, 4, 1, 65536)] { + assert_eq!(first_image_compression(&fixture(order, &[entry])), None); + } + // Unrelated values are not decoded or allocated, including unknown types. + assert_eq!(first_image_compression(&fixture(order, &[(999, 65535, u32::MAX, u32::MAX)])), Some(1)); + let mut absent = fixture(order, &[(999, 4, 1, 0)]); + absent.truncate(12); // Only the unrelated tag is needed, matching Word's probe. + assert_eq!(first_image_compression(&absent), Some(1)); + } + assert_eq!(first_image_compression(b"II+\0\x08\0\0\0"), None); + assert_eq!(first_image_compression(b"II*\0\xff\xff\xff\xff"), None); + } +} diff --git a/crates/timeline/src/edl.rs b/crates/timeline/src/edl.rs index 84251fece0..02970785db 100644 --- a/crates/timeline/src/edl.rs +++ b/crates/timeline/src/edl.rs @@ -156,6 +156,10 @@ pub struct Edl { /// Read a list. Never fails: lines that cannot be read are named in `report` and skipped. pub fn parse(text: &str, report: &mut Report) -> Edl { + parse_with_report_limit(text, report, None) +} +/// Parse an EDL with an optional limit on distinct warning messages. +pub fn parse_with_report_limit(text: &str, report: &mut Report, report_limit: Option) -> Edl { let mut p = Edl { title: None, events: Vec::new(), any_df: false, max_ff: 0 }; let mut df = false; let mut skip_metadata = false; @@ -224,7 +228,7 @@ pub fn parse(text: &str, report: &mut Report) -> Edl { if (1..=99).contains(&n) { extra.push(Channel::A(n)); } else { - report.warn(format!("EDL AUD channel {n} is outside 1..99; ignored")); + report.warn_limited(report_limit, format!("EDL AUD channel {n} is outside 1..99; ignored")); } } if let Some(line) = p.events.last_mut().and_then(|e| e.lines.last_mut()) { @@ -233,7 +237,7 @@ pub fn parse(text: &str, report: &mut Report) -> Edl { continue; } if upper.starts_with("SPLIT:") { - report.warn("EDL split (L-cut/J-cut) lines are not supported; the split was ignored"); + report.warn_limited(report_limit, "EDL split (L-cut/J-cut) lines are not supported; the split was ignored"); continue; } if let Some(line) = parse_event_line(l) { @@ -256,7 +260,7 @@ pub fn parse(text: &str, report: &mut Report) -> Edl { // Comments and auxiliary lines after a rejected event do not belong to the previous one. skip_metadata = true; } - report.warn(format!("unrecognised EDL line ignored: {}", l.chars().take(60).collect::())); + report.warn_limited(report_limit, format!("unrecognised EDL line ignored: {}", l.chars().take(60).collect::())); } p } @@ -586,3 +590,20 @@ M2 A001 -012.0 00;00;00;00\n\ assert_eq!(channel_name(Channel::A(7)), "A7"); } } + +#[cfg(test)] +mod report_limit_tests { + use super::*; + + #[test] + fn caps_distinct_unrecognized_lines_without_changing_default() { + let text = (0..10).map(|i| format!("unrecognized-{i}\n")).collect::(); + let mut limited = Report::default(); + let _ = parse_with_report_limit(&text, &mut limited, Some(2)); + assert_eq!(limited.entries.len(), 3); + assert!(limited.mentions("further diagnostics omitted")); + let mut ordinary = Report::default(); + let _ = parse(&text, &mut ordinary); + assert_eq!(ordinary.entries.len(), 10); + } +} diff --git a/crates/timeline/src/fcp7.rs b/crates/timeline/src/fcp7.rs index 82ff410f97..b528e43c48 100644 --- a/crates/timeline/src/fcp7.rs +++ b/crates/timeline/src/fcp7.rs @@ -69,7 +69,7 @@ const BLEND_XML: &[(&str, u32)] = &[ /// The generator of a `generatoritem`: an application's own payload (`:` as /// the effect id), one of the generators every editor has by name, or one the catalog knows. -fn generator_from(name: &str, id: &str, opts: &ImportOptions, report: &mut Report) -> Generator { +fn generator_from(name: &str, id: &str, opts: &ImportOptions, report: &mut Report, limit: Option) -> Generator { if let Some(data) = id.strip_prefix(opts.namespace).and_then(|rest| rest.strip_prefix(':')) && !opts.namespace.is_empty() { @@ -85,7 +85,7 @@ fn generator_from(name: &str, id: &str, opts: &ImportOptions, report: &mut Repor if let Some(g) = opts.catalog.generator_by_name(n) { return g; } - report.warn(format!("generator \"{name}\" is not supported; imported as Black Video")); + report.warn_limited(limit, format!("generator \"{name}\" is not supported; imported as Black Video")); Generator::BlackVideo } } @@ -124,6 +124,7 @@ struct Imp<'a, 'c, 'r> { b: Builder<'c>, opts: &'a ImportOptions<'a>, report: &'r mut Report, + report_limit: Option, files: HashMap>, seq_defs: HashMap>, file_items: HashMap, @@ -160,6 +161,10 @@ fn node_key(n: Node) -> String { /// Read an `xmeml` document. Media paths are resolved against `opts.base_dir`; effects the format /// does not name itself are looked up in `opts.catalog`. What cannot be represented is in `report`. pub fn import(text_in: &str, opts: &ImportOptions, report: &mut Report) -> Result { + import_with_report_limit(text_in, opts, report, None) +} +/// Read FCP7 XML with an optional distinct-diagnostic limit. +pub fn import_with_report_limit(text_in: &str, opts: &ImportOptions, report: &mut Report, report_limit: Option) -> Result { let doc = crate::xml::parse(text_in).map_err(|e| Error::parse(Format::Fcp7Xml, e))?; let root = Node(&doc); if root.name() != "xmeml" { @@ -169,7 +174,7 @@ pub fn import(text_in: &str, opts: &ImportOptions, report: &mut Report) -> Resul .descendants() .any(|n| n.has_tag_name("timebase") && n.text().and_then(|t| t.trim().parse::().ok()).is_some_and(|tb| tb > MAX_RATE as f64)) { - report.warn(format!("a timebase above {MAX_RATE} per second is not a frame rate; it was limited to {MAX_RATE}")); + report.warn_limited(report_limit, format!("a timebase above {MAX_RATE} per second is not a frame rate; it was limited to {MAX_RATE}")); } let mut imp = Imp { b: Builder::new( @@ -178,6 +183,7 @@ pub fn import(text_in: &str, opts: &ImportOptions, report: &mut Report) -> Resul ), opts, report, + report_limit, files: HashMap::new(), seq_defs: HashMap::new(), file_items: HashMap::new(), @@ -224,7 +230,7 @@ pub fn import(text_in: &str, opts: &ImportOptions, report: &mut Report) -> Resul return Err(Error::Empty); } let mut imported = imp.b.finish(); - imported.bound(report); + imported.bound_with_report_limit(report, report_limit); Ok(imported) } @@ -342,7 +348,7 @@ impl<'a> Imp<'a, '_, '_> { self.b.file_media(&format!("file:{p}"), &name, &p, &spec, bin) } None => { - self.report.warn(format!("file \"{name}\" has no pathurl; imported offline")); + self.report.warn_limited(self.report_limit, format!("file \"{name}\" has no pathurl; imported offline")); let p = resolve_path(&name, self.opts.base_dir); let id = self.b.file_media(&format!("fileid:{key}"), &name, &p, &spec, bin); if let Some(m) = self.b.p.item_mut(id).and_then(|i| i.as_media_mut()) { @@ -366,7 +372,7 @@ impl<'a> Imp<'a, '_, '_> { return Some(*id); } if self.reimports_left == 0 { - self.report.warn("truncated nested sequence kept incomplete after the re-import limit was reached"); + self.report.warn_limited(self.report_limit, "truncated nested sequence kept incomplete after the re-import limit was reached"); return Some(*id); } self.reimports_left -= 1; @@ -375,12 +381,12 @@ impl<'a> Imp<'a, '_, '_> { let def = if child(n, "media").is_some() { n } else { *self.seq_defs.get(&key)? }; if depth >= MAX_NESTING_DEPTH { self.depth_hits += 1; - self.report.warn("nested sequence is nested too deeply; imported as a gap"); + self.report.warn_limited(self.report_limit, "nested sequence is nested too deeply; imported as a gap"); return None; } let hits_before = self.depth_hits; if !self.in_progress.insert(key.clone()) { - self.report.warn("recursive nested sequence ignored"); + self.report.warn_limited(self.report_limit, "recursive nested sequence ignored"); return None; } let name = child_text(def, "name").unwrap_or("Sequence").to_string(); @@ -421,7 +427,7 @@ impl<'a> Imp<'a, '_, '_> { let Some(m) = media.and_then(|m| child(m, tag)) else { continue }; for (ti, tn) in children(m, "track").enumerate() { if !self.b.ensure_tracks(&mut seq, kind, ti + 1) { - self.report.warn(format!("FCP7 {kind:?} tracks beyond {MAX_IMPORTED_TRACKS} were skipped")); + self.report.warn_limited(self.report_limit, format!("FCP7 {kind:?} tracks beyond {MAX_IMPORTED_TRACKS} were skipped")); break; } self.track(&mut seq, id, kind, ti, tn, TrackFormat { rate, frame: (w, h) }); @@ -462,10 +468,13 @@ impl<'a> Imp<'a, '_, '_> { } let t = &mut seq.tracks_mut(kind)[ti]; if t.items.iter().any(|o| o.start < ti_item.end() && ti_item.start < o.end()) { - self.report.warn("overlapping clip items on one track; the later one was moved to a new track"); + self.report + .warn_limited(self.report_limit, "overlapping clip items on one track; the later one was moved to a new track"); if self.b.place(seq, kind, ti + 1, ti_item).is_none() { - self.report - .warn(format!("FCP7 {kind:?} track exceeds the {MAX_IMPORTED_TRACKS}-track import limit; clip was skipped")); + self.report.warn_limited( + self.report_limit, + format!("FCP7 {kind:?} track exceeds the {MAX_IMPORTED_TRACKS}-track import limit; clip was skipped"), + ); } } else { t.items.push(ti_item); @@ -507,7 +516,7 @@ impl<'a> Imp<'a, '_, '_> { (seq_rate.tick_of(end) - d, d) } (false, false) => { - self.report.warn(format!("clip \"{name}\" has neither start nor end; skipped")); + self.report.warn_limited(self.report_limit, format!("clip \"{name}\" has neither start nor end; skipped")); return None; } }; @@ -532,7 +541,7 @@ impl<'a> Imp<'a, '_, '_> { match BLEND_XML.iter().find(|(n, _)| n.eq_ignore_ascii_case(mode)) { Some((_, v)) if *v != 0 => set_param(self.b.catalog, &mut ti, "opacity", "blend", Param::new(ParamValue::Choice(*v))), Some(_) => {} - None => self.report.warn(format!("composite mode \"{mode}\" is not supported")), + None => self.report.warn_limited(self.report_limit, format!("composite mode \"{mode}\" is not supported")), } } ti.markers = read_markers(c, rate, &mut self.b); @@ -549,7 +558,7 @@ impl<'a> Imp<'a, '_, '_> { let eff = child(c, "effect"); let gname = eff.and_then(|e| child_text(e, "name")).unwrap_or(name).to_string(); let gid = eff.and_then(|e| child_text(e, "effectid")).unwrap_or("").to_string(); - let mut g = generator_from(&gname, &gid, self.opts, self.report); + let mut g = generator_from(&gname, &gid, self.opts, self.report, self.report_limit); if let (Generator::ColorMatte { color }, Some(e)) = (&mut g, eff) && let Some(v) = e.descendants().find(|d| d.has_tag_name("value") && child(*d, "red").is_some()) { @@ -563,7 +572,7 @@ impl<'a> Imp<'a, '_, '_> { match self.file(f, Some(name), None) { Some(item) => Some(item), None => { - self.report.warn(format!("clip \"{name}\" refers to a file the document does not define; skipped")); + self.report.warn_limited(self.report_limit, format!("clip \"{name}\" refers to a file the document does not define; skipped")); None } } @@ -571,10 +580,10 @@ impl<'a> Imp<'a, '_, '_> { if let Some(id) = self.sequence(s, None) { return Some(id); } - self.report.warn(format!("clip \"{name}\" refers to a nested sequence that was left out; imported offline")); + self.report.warn_limited(self.report_limit, format!("clip \"{name}\" refers to a nested sequence that was left out; imported offline")); Some(self.offline_media(kind, seq_rate, frame, name)) } else { - self.report.warn(format!("clip \"{name}\" has no media reference; imported offline")); + self.report.warn_limited(self.report_limit, format!("clip \"{name}\" has no media reference; imported offline")); Some(self.offline_media(kind, seq_rate, frame, name)) } } @@ -612,12 +621,16 @@ impl<'a> Imp<'a, '_, '_> { remap.reverse |= v < 0.0; } if child(p, "keyframe").is_some() { - self.report.warn("variable speed (time remap keyframes) is not supported; a constant speed was used"); + self.report.warn_limited( + self.report_limit, + "variable speed (time remap keyframes) is not supported; a constant speed was used", + ); } } Some("reverse") => remap.reverse |= child_bool(p, "value").unwrap_or(false), Some("variablespeed") if child_bool(p, "value") == Some(true) || child_f64(p, "value").is_some_and(|v| v != 0.0) => { - self.report.warn("variable speed (time remap keyframes) is not supported; a constant speed was used"); + self.report + .warn_limited(self.report_limit, "variable speed (time remap keyframes) is not supported; a constant speed was used"); } _ => {} } @@ -718,7 +731,7 @@ impl<'a> Imp<'a, '_, '_> { let catalog = self.b.catalog; let def = catalog.effect(id).filter(|d| !d.intrinsic).or_else(|| catalog.effect_by_name(name).filter(|d| !d.intrinsic)); let Some(def) = def else { - self.report.warn(format!("effect \"{name}\" is not supported and was skipped")); + self.report.warn_limited(self.report_limit, format!("effect \"{name}\" is not supported and was skipped")); return; }; let mut inst = def.instance(); @@ -750,7 +763,13 @@ impl<'a> Imp<'a, '_, '_> { } let eff = child(c, "effect"); let name = eff.and_then(|x| child_text(x, "name")).or_else(|| eff.and_then(|x| child_text(x, "effectid"))).unwrap_or("Cross Dissolve"); - let effect = transition_effect(self.b.catalog, name, kind == TrackKind::Audio, self.report); + let mut temporary = Report::default(); + let effect = transition_effect(self.b.catalog, name, kind == TrackKind::Audio, &mut temporary); + for e in temporary.entries { + for _ in 0..e.count { + self.report.warn_limited(self.report_limit, &e.message); + } + } let align_s = child_text(c, "alignment").unwrap_or("").to_ascii_lowercase(); let track = &mut seq.tracks_mut(kind)[ti]; let (mut from, mut to) = (None, None); @@ -771,7 +790,7 @@ impl<'a> Imp<'a, '_, '_> { } } if from.is_none() && to.is_none() { - self.report.warn(format!("transition \"{name}\" at frame {start} has no adjacent clip; skipped")); + self.report.warn_limited(self.report_limit, format!("transition \"{name}\" at frame {start} has no adjacent clip; skipped")); return; } let cut = from.map(|f| f.1).or(to.map(|t| t.1)).unwrap_or(s); @@ -911,6 +930,7 @@ struct Exp<'a, 'r> { p: &'a Project, opts: &'a ExportOptions<'a>, report: &'r mut Report, + report_limit: Option, w: XmlWriter, file_ids: HashMap, seq_ids: HashMap, @@ -921,11 +941,22 @@ struct Exp<'a, 'r> { } pub fn export(p: &Project, seq_id: ItemId, opts: &ExportOptions, report: &mut Report) -> Result { + export_with_report_limit(p, seq_id, opts, report, None) +} +/// Write FCP7 XML with an optional distinct-diagnostic limit. +pub fn export_with_report_limit( + p: &Project, + seq_id: ItemId, + opts: &ExportOptions, + report: &mut Report, + report_limit: Option, +) -> Result { p.sequence(seq_id).ok_or(Error::NoSequence(seq_id))?; let mut x = Exp { p, opts, report, + report_limit, w: XmlWriter::new(Some("xmeml")), file_ids: HashMap::new(), seq_ids: HashMap::new(), @@ -1000,11 +1031,11 @@ impl Exp<'_, '_> { } // Each clip lists every member of its group, so a group of n clips writes n * n links. if let Some(n) = link_members.values().map(Vec::len).filter(|&n| n > MAX_LINK_MEMBERS).max() { - self.report.warn(format!("a link group of {n} clips was exported with its first {MAX_LINK_MEMBERS} members")); + self.report.warn_limited(self.report_limit, format!("a link group of {n} clips was exported with its first {MAX_LINK_MEMBERS} members")); link_members.values_mut().for_each(|m| m.truncate(MAX_LINK_MEMBERS)); } if seq.all_tracks().any(|t| t.items.iter().any(|i| i.group.is_some())) { - self.report.info("clip groups have no FCP7 XML equivalent and were not exported"); + self.report.info_limited(self.report_limit, "clip groups have no FCP7 XML equivalent and were not exported"); } for kind in [TrackKind::Video, TrackKind::Audio] { let tag = if kind == TrackKind::Video { "video" } else { "audio" }; @@ -1061,7 +1092,7 @@ impl Exp<'_, '_> { fn write_transition(&mut self, tr: &Transition, kind: TrackKind, rate: FrameRate, t: &crate::model::Track) { if !on_frame(rate, tr.start) || !on_frame(rate, tr.duration) { - self.report.warn("sub-frame transition positions were rounded to frames"); + self.report.warn_limited(self.report_limit, "sub-frame transition positions were rounded to frames"); } let align = match (tr.from, tr.to, tr.align) { (None, Some(_), _) => "start-black", @@ -1147,12 +1178,13 @@ impl Exp<'_, '_> { fn write_clip(&mut self, c: &TrackItem, kind: TrackKind, seq: &Sequence, xid: &str, links: &[(String, TrackKind, usize, usize)]) { let rate = seq.settings.frame_rate; if !on_frame(rate, c.start) || !on_frame(rate, c.duration) { - self.report.warn("sub-frame clip positions were rounded to frames"); + self.report.warn_limited(self.report_limit, "sub-frame clip positions were rounded to frames"); } if let Some(clip) = crate::build::uncarried_clip(self.p, c, rate) { - self.report.warn(format!( - "{clip} has no Final Cut Pro 7 XML equivalent: it is written as a clip item without media and is not read back on import" - )); + self.report.warn_limited( + self.report_limit, + format!("{clip} has no Final Cut Pro 7 XML equivalent: it is written as a clip item without media and is not read back on import"), + ); } let base = base_item(self.p, c.item); let generator = crate::build::generator_of(self.p, base).cloned(); @@ -1198,7 +1230,7 @@ impl Exp<'_, '_> { if let Some(blend) = param(c, "opacity", "blend").and_then(|p| p.value.as_f64()).map(|v| v as u32).filter(|v| *v != 0) { match BLEND_XML.iter().find(|(_, v)| *v == blend) { Some((n, _)) => self.w.text("compositemode", n), - None => self.report.warn("blend mode not representable in FCP7 XML; Normal used"), + None => self.report.warn_limited(self.report_limit, "blend mode not representable in FCP7 XML; Normal used"), } } self.write_filters(c, kind, seq, base); @@ -1244,7 +1276,8 @@ impl Exp<'_, '_> { self.w.text("effectid", g.label()); } Generator::Other { name, data } => { - self.report.info(format!("generator \"{name}\" is written with an effect id only {} reads", self.opts.namespace)); + self.report + .info_limited(self.report_limit, format!("generator \"{name}\" is written with an effect id only {} reads", self.opts.namespace)); self.w.text("name", name); self.w.text("effectid", format!("{}:{data}", self.opts.namespace)); } @@ -1323,7 +1356,7 @@ impl Exp<'_, '_> { if param_modified(self.opts.catalog, c, "motion", "scale_width") || param(c, "motion", "uniform_scale").and_then(|p| p.value.as_bool()) == Some(false) { - self.report.warn("non-uniform scale is not supported by FCP7 Basic Motion; uniform scale written"); + self.report.warn_limited(self.report_limit, "non-uniform scale is not supported by FCP7 Basic Motion; uniform scale written"); } let enabled = c.effect("motion").is_none_or(|e| e.enabled); self.open_effect("Basic Motion", "basic", "motion", "motion", "video", enabled); @@ -1370,7 +1403,7 @@ impl Exp<'_, '_> { } if c.speed != 1.0 || c.reverse || c.frame_hold.is_some() { if param(c, "time_remap", "speed").is_some_and(|p| p.is_animated()) { - self.report.warn("speed ramps (time remapping keyframes) are not exported to FCP7 XML"); + self.report.warn_limited(self.report_limit, "speed ramps (time remapping keyframes) are not exported to FCP7 XML"); } self.open_effect("Time Remap", "timeremap", "motion", "motion", "video", true); let sp = if c.frame_hold.is_some() { 0.0 } else { c.speed * 100.0 }; @@ -1382,7 +1415,7 @@ impl Exp<'_, '_> { } } else { if c.gain_db != 0.0 { - self.report.info("clip gain was folded into Audio Levels"); + self.report.info_limited(self.report_limit, "clip gain was folded into Audio Levels"); } if param_modified(self.opts.catalog, c, "volume", "level") || c.gain_db != 0.0 { let g = c.gain_db; @@ -1405,7 +1438,7 @@ impl Exp<'_, '_> { self.close_effect(); } if param_modified(self.opts.catalog, c, "channel_volume", "left") || param_modified(self.opts.catalog, c, "channel_volume", "right") { - self.report.warn("Channel Volume is not supported by FCP7 XML and was not exported"); + self.report.warn_limited(self.report_limit, "Channel Volume is not supported by FCP7 XML and was not exported"); } } for e in standard_effects(self.opts.catalog, c) { @@ -1489,7 +1522,7 @@ impl Exp<'_, '_> { self.w.close(); } _ => { - self.report.info("Bezier keyframe easing is written as FCP curve keyframes (handles not preserved)"); + self.report.info_limited(self.report_limit, "Bezier keyframe easing is written as FCP curve keyframes (handles not preserved)"); self.w.open("interpolation", &[]); self.w.text("name", "FCPCurve"); self.w.close(); @@ -1507,7 +1540,7 @@ impl Exp<'_, '_> { for k in &p.keyframes { let Some(v) = val(&k.value) else { continue }; if !on_frame(rate, k.time) { - self.report.info("sub-frame keyframes were rounded to frames"); + self.report.info_limited(self.report_limit, "sub-frame keyframes were rounded to frames"); } self.w.open("keyframe", &[]); self.w.text("when", frames_round(rate, k.time)); @@ -1519,7 +1552,7 @@ impl Exp<'_, '_> { fn generic_effect(&mut self, e: &EffectInstance, kind: TrackKind, rate: FrameRate) { let Some(def) = self.opts.catalog.effect(&e.effect) else { - self.report.warn(format!("unknown effect \"{}\" was not exported", e.effect)); + self.report.warn_limited(self.report_limit, format!("unknown effect \"{}\" was not exported", e.effect)); return; }; let media = if kind == TrackKind::Video { "video" } else { "audio" }; @@ -1547,7 +1580,7 @@ impl Exp<'_, '_> { self.w.close(); self.w.close(); if p.is_animated() { - self.report.warn(format!("point keyframes of \"{}\" were not exported", def.name)); + self.report.warn_limited(self.report_limit, format!("point keyframes of \"{}\" were not exported", def.name)); } } ParamValue::Bool(b) => self.simple_param(&pd.id, &pd.label, bool_str(*b)), @@ -1561,7 +1594,7 @@ impl Exp<'_, '_> { self.w.close(); } ParamValue::Opaque(_) => { - self.report.warn(format!("curve parameters of \"{}\" are not supported by FCP7 XML", def.name)); + self.report.warn_limited(self.report_limit, format!("curve parameters of \"{}\" are not supported by FCP7 XML", def.name)); } } } diff --git a/crates/timeline/src/fcpxml.rs b/crates/timeline/src/fcpxml.rs index 4a255ba430..8a002689e8 100644 --- a/crates/timeline/src/fcpxml.rs +++ b/crates/timeline/src/fcpxml.rs @@ -139,6 +139,7 @@ struct Imp<'a, 'c, 'r> { b: Builder<'c>, opts: &'a ImportOptions<'a>, report: &'r mut Report, + report_limit: Option, formats: HashMap, asset_nodes: HashMap>, assets: HashMap, @@ -181,6 +182,10 @@ struct Ctx { /// Read an FCPXML document. Media paths are resolved against `opts.base_dir`; filters are looked /// up in `opts.catalog` by name. What cannot be represented is in `report`. pub fn import(text: &str, opts: &ImportOptions, report: &mut Report) -> Result { + import_with_report_limit(text, opts, report, None) +} +/// Read FCPXML with an optional distinct-diagnostic limit. +pub fn import_with_report_limit(text: &str, opts: &ImportOptions, report: &mut Report, report_limit: Option) -> Result { let doc = crate::xml::parse(text).map_err(|e| Error::parse(Format::Fcpxml, e))?; let root = Node(&doc); if root.name() != "fcpxml" { @@ -189,7 +194,7 @@ pub fn import(text: &str, opts: &ImportOptions, report: &mut Report) -> Result().ok()).unwrap_or(0); if !v.starts_with("1.") || minor > 11 { - report.info(format!("FCPXML version {v} is newer than 1.11; unknown elements were ignored")); + report.info_limited(report_limit, format!("FCPXML version {v} is newer than 1.11; unknown elements were ignored")); } } let lib_name = child(root, "library").and_then(|l| child(l, "event")).and_then(|e| e.attribute("name")).unwrap_or("Imported FCPXML"); @@ -197,6 +202,7 @@ pub fn import(text: &str, opts: &ImportOptions, report: &mut Report) -> Result Result { let rate = match r.attribute("frameDuration") { Some(fd) => rate_from_frame_duration(fd).unwrap_or_else(|| { - imp.report.warn(format!("format \"{id}\" has an invalid frameDuration \"{fd}\"; the default frame rate was used")); + imp.report.warn_limited( + imp.report_limit, + format!("format \"{id}\" has an invalid frameDuration \"{fd}\"; the default frame rate was used"), + ); FrameRate::default() }), None => FrameRate::default(), @@ -274,7 +283,7 @@ pub fn import(text: &str, opts: &ImportOptions, report: &mut Report) -> Result Imp<'a, '_, '_> { self.b.file_media(&format!("file:{p}"), &name, &p, &spec, bin) } None => { - self.report.warn(format!("asset \"{name}\" has no media; imported offline")); + self.report.warn_limited(self.report_limit, format!("asset \"{name}\" has no media; imported offline")); let p = resolve_path(&name, self.opts.base_dir); let it = self.b.file_media(&format!("asset:{id}"), &name, &p, &spec, bin); if let Some(m) = self.b.p.item_mut(it).and_then(|i| i.as_media_mut()) { @@ -365,7 +374,7 @@ impl<'a> Imp<'a, '_, '_> { // Check before the cache: a truncated resource may already have an item while it // is being rebuilt, but a back-edge must never turn that item into a self-cycle. if self.media_active.contains(id) { - self.report.warn(format!("recursive FCPXML media resource {id:?} ignored")); + self.report.warn_limited(self.report_limit, format!("recursive FCPXML media resource {id:?} ignored")); return None; } let depth = self.media_active.len(); @@ -381,9 +390,10 @@ impl<'a> Imp<'a, '_, '_> { if !shallower || self.reimports_left == 0 { if self.cache_reaches_active(i) { self.depth_hits += 1; - self.report.warn(format!( - "FCPXML cached media {id:?} could form a recursive graph or exceeds the cache traversal budget; imported as a gap" - )); + self.report.warn_limited( + self.report_limit, + format!("FCPXML cached media {id:?} could form a recursive graph or exceeds the cache traversal budget; imported as a gap"), + ); return None; } return Some(i); @@ -397,7 +407,7 @@ impl<'a> Imp<'a, '_, '_> { // would otherwise recurse once per resource. if depth >= MAX_MEDIA_DEPTH { self.depth_hits += 1; - self.report.warn(format!("FCPXML media resource {id:?} is nested too deeply; imported as a gap")); + self.report.warn_limited(self.report_limit, format!("FCPXML media resource {id:?} is nested too deeply; imported as a gap")); return None; } self.media_active.insert(id.into()); @@ -445,7 +455,10 @@ impl<'a> Imp<'a, '_, '_> { fn storyline(&mut self, seq: &mut Sequence, ctx: &Ctx, spine: Node<'a>, origin: Tick, lane: i32, primary: bool) { if self.depth >= MAX_XML_DEPTH { self.depth_hits += 1; - self.report.warn(format!("XML storylines are nested too deeply (more than {MAX_XML_DEPTH}); deeper clips were skipped")); + self.report.warn_limited( + self.report_limit, + format!("XML storylines are nested too deeply (more than {MAX_XML_DEPTH}); deeper clips were skipped"), + ); return; } self.depth += 1; @@ -471,7 +484,7 @@ impl<'a> Imp<'a, '_, '_> { let vidx = if lane >= 0 { lane as usize } else { usize::MAX }; for (pos, el) in transitions { if vidx == usize::MAX { - self.report.warn("transitions on audio storylines are not supported"); + self.report.warn_limited(self.report_limit, "transitions on audio storylines are not supported"); continue; } let start = origin + attr_time(el, "offset").unwrap_or(Tick::ZERO); @@ -499,7 +512,13 @@ impl<'a> Imp<'a, '_, '_> { } else { TransitionAlign::CenterAtCut }; - let effect = transition_effect(self.b.catalog, &name, false, self.report); + let mut temporary = Report::default(); + let effect = transition_effect(self.b.catalog, &name, false, &mut temporary); + for e in temporary.entries { + for _ in 0..e.count { + self.report.push_limited(e.level, self.report_limit, &e.message); + } + } let id = TransitionId(self.b.alloc()); // The clips may have been moved to another track by placement; find the track holding them. let clip = from.or(to).map(|c| c.0); @@ -525,7 +544,10 @@ impl<'a> Imp<'a, '_, '_> { fn element(&mut self, seq: &mut Sequence, ctx: &Ctx, el: Node<'a>, t0: Tick, lane: i32, primary: bool) -> (Tick, Option) { if self.depth >= MAX_XML_DEPTH { self.depth_hits += 1; - self.report.warn(format!("XML elements are nested too deeply (more than {MAX_XML_DEPTH}); deeper clips were skipped")); + self.report.warn_limited( + self.report_limit, + format!("XML elements are nested too deeply (more than {MAX_XML_DEPTH}); deeper clips were skipped"), + ); return (t0, None); } self.depth += 1; @@ -554,7 +576,8 @@ impl<'a> Imp<'a, '_, '_> { .flatten() .filter(|a| a.has_video); if asset.is_none() { - self.report.warn(format!("FCPXML