diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 66897e207a..b80d10d34c 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -70,6 +70,7 @@ workflows: - 'actions/checkout@v7.0.1' - 'dtolnay/rust-toolchain@stable' '.github/workflows/nightly.yml': [] + '.github/workflows/pbr.yml': [] '.github/workflows/pcraft-format.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' diff --git a/.github/workflows/pbr.yml b/.github/workflows/pbr.yml new file mode 100644 index 0000000000..51c3a62daa --- /dev/null +++ b/.github/workflows/pbr.yml @@ -0,0 +1,29 @@ +name: PBR feature tests + +on: + workflow_dispatch: + push: + branches: [main, next] + paths: ['crates/pbr/**', 'crates/texture/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pbr.yml'] + pull_request: + paths: ['crates/pbr/**', 'crates/texture/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pbr.yml'] + +permissions: + contents: read + +jobs: + features: + name: PBR ${{ matrix.mode }} tests + strategy: + fail-fast: false + matrix: + include: + - { mode: serial, arguments: '' } + - { mode: parallel, arguments: '--features parallel' } + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["ubuntu-latest"]' + craft-fonts-ref: '' + require-craft-fonts: false + timeout-minutes: 30 + command: cargo test -p craft-pbr --locked ${{ matrix.arguments }} diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 112bfe4e93..12edfaf047 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -27,6 +27,7 @@ author, source and license. Library code and original assets are under the repos | `crates/text/assets/hyphen/en-us.pat` | DesignCraft contributors, trained from the Moby Hyphenator II list | `crates/text/examples/hyphgen.rs` | CC0-1.0 | | Patterns embedded through `hypher` (optional `craft-text` language features) | hyph-utf8 authors, per language | [tex-hyphen](https://github.com/hyphenation/tex-hyphen), as packaged in [hypher](https://github.com/typst/hypher/tree/main/patterns) | Per file header: LPPL, MIT, BSD-3-Clause, Unlicense or a permit-any-use notice (or a choice including one); Slovak (`hyph-sk.tex`, embedded whenever `hypher/slovak` is on: feature `slovak-gpl`, or another dependency through feature unification) is GPL-2.0-or-later; Spanish (`hyph-es.tex` 5.0, Javier Bezos, CervanTeX) is MIT | | Word-break dictionaries and LSTM models embedded through `icu_segmenter_data` (optional `craft-text` features `thai`, `lao`, `khmer`, `burmese`) | Unicode, Inc. and ICU4X contributors | [ICU4X](https://github.com/unicode-org/icu4x) | Unicode-3.0 | +| MikkTSpace tangent generation compiled in through `mikktspace` (`craft-mesh-ops`) | Benjamin Wasty, David Harvey-Macaulay and Layl Bongers; translated from the C original by Morten S. Mikkelsen | [mikktspace 0.3.0](https://crates.io/crates/mikktspace/0.3.0), [gltf-rs/mikktspace](https://github.com/gltf-rs/mikktspace) | MIT OR Apache-2.0 (the package's `license` field); its `src/generated.rs` also carries the C original's 2011 notice, reproduced in [`crates/mesh-ops/ATTRIBUTION.md`](crates/mesh-ops/ATTRIBUTION.md) | | `crates/ui/tests/fonts/NotoSansArabic-test.ttf` (subset to the test strings, default weight set to 100, width axis dropped) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) | | `crates/ui/tests/fonts/NotoSansCJKsc-test.otf` (subset to the test strings) | The Noto Project Authors (Adobe, Google) | [notofonts/noto-cjk@f8d1575 `Sans/OTF/SimplifiedChinese`](https://github.com/notofonts/noto-cjk/tree/f8d157532fbfaeda587e826d4cd5b21a49186f7c/Sans/OTF/SimplifiedChinese), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansCJK.txt`) | | `crates/imaging/tests/fonts/NotoSansArabic-digits.ttf` (instance at weight 400 and width 100, subset to the Arabic-Indic digits and separators U+0660–U+066C) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) | @@ -39,6 +40,7 @@ author, source and license. Library code and original assets are under the repos | `crates/font-subset/tests/data/{abeezee,abel,bbhbartle,librefranklin,orbitron,sarabun}/` (unmodified; each with its `OFL.txt`) | The ABeeZee, Abel, BBH, Libre Franklin, Orbitron and Sarabun Project Authors | [google/fonts@e7db6ca `ofl/`](https://github.com/google/fonts/tree/e7db6ca/ofl) | OFL-1.1 | | `crates/font-subset/tests/data/ubuntu/Ubuntu-Regular.ttf` (unmodified; with `LICENCE.txt`) | Canonical Ltd. (Dalton Maag) | [google/fonts@e7db6ca `ufl/ubuntu`](https://github.com/google/fonts/tree/e7db6ca/ufl/ubuntu) | Ubuntu-font-1.0 | | `crates/font-subset/tests/data/notosanscjk/NotoSansCJKsc-test.otf` (subset to the test strings; with `OFL.txt`) | The Noto Project Authors (Adobe, Google) | [notofonts/noto-cjk@f8d1575 `Sans/OTF/SimplifiedChinese`](https://github.com/notofonts/noto-cjk/tree/f8d157532fbfaeda587e826d4cd5b21a49186f7c/Sans/OTF/SimplifiedChinese), via storytold/font-preview-service | OFL-1.1 | +| `crates/ui-contract/fonts/inter/Inter-Regular.ttf`, `crates/ui-contract/fonts/inter/Inter-SemiBold.ttf` (subset to 1,298 Latin, Greek, and Cyrillic codepoints with `fontTools` 4.62.1: `hinting=True`, `notdef_outline=True`, `layout_features=["*"]`, `name_IDs=["*"]`, `glyph_names=False`) | The Inter Project Authors | `storytold/craft-fonts` (`fonts/inter/Inter-Regular.ttf` sha256 `40d692fce188e4471e2b3cba937be967878f631ad3ebbbdcd587687c7ebe0c82`, `fonts/inter/Inter-SemiBold.ttf` sha256 `78a843fade9d4612a5567302fb595b56976eb5fcebf4fea5a5912d638bafcde3`, Inter 4.001 `git-9221beed3`) | OFL-1.1 (`crates/ui-contract/fonts/inter/OFL.txt`) | Original assets are covered by the repository licence. @@ -174,6 +176,10 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. `crates/har` preserves Craft Anything `crates/formats/src/har.rs` from `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the typed reader in `f64ae3bf3c8863a982af1304e06de20653803968`; BFlat added UTF-8 BOM compatibility in `cb0bb9d8fa4536ba44ef2c86f5ed759b879cc2d3`. Both source snapshots retain primary author attribution. Shared wiring, explicit byte admission and its tests are subsequent Dylan M. Taylor changes. Redaction and analysis remain app-owned. +## GPU device selection + +`crates/gpu-device`'s adapter rule and driver corrections come from FilmCraft `crates/gpu/src/adapter.rs` at `93a88a839aae370740b09434fdec410abb8c24ca`, and its device health from PhotoCraft `crates/gpu/src/health.rs` at `01a5b5a389acc93f081e5ce6a8d0580d6438774a`, both MIT OR Apache-2.0; `crates/gpu-device/NOTICE` names both. + ## Dalvik DEX inspection `crates/dex` extracts Craft Anything `crates/formats/src/dex.rs` and `dex_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Five source-history ports preserve Brandon Thomas, BFlat and Afloat as primary authors. Five regression imports retain BFlat/Afloat authors and exact source revisions. The checked byte-reader/MUTF-8 subset and synthetic DEX fixture come from that app's `bytes.rs` and `testkit/src/android.rs`; deterministic noise/mutations come from its testkit. No application file I/O, APK logic or execution is imported. Shared neutral errors and workspace wiring are subsequent changes; existing per-file strings, member/handler and bytecode payload budgets are retained. diff --git a/CHANGELOG.md b/CHANGELOG.md index 31364ecf95..c2e3228555 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ All crates share the workspace version. See [the versioning policy](docs/versioning.md). +## Unreleased + +### StencilCraft document model + +- Geometry is stored once in `Document.shapes`. Organizational layers reference shape IDs + through `Layer.members`, and the independent, ordered `Document.operations` hold production + passes with their own `OperationSettings` and shape memberships. Guide operations are non-output. +- The native header now uses format version 2. This pre-release format supersedes the earlier + schema: readers reject version 1 and other unsupported versions. Builds predating this change + cannot open version 2 files. + ## v0.1.0 — 2026-10-12 First coordinated Git release of craft-libs. Applications can pin a named baseline instead of diff --git a/Cargo.lock b/Cargo.lock index c55d85870e..07c3fd7ab8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1819,9 +1819,11 @@ dependencies = [ "craft-geom", "craft-gif", "craft-gpu", + "craft-gpu-device", "craft-gpu-null", "craft-gpu-providers", "craft-gpu-wgpu", + "craft-gpu-yuv", "craft-gridcraft-format", "craft-gzip", "craft-har", @@ -1863,6 +1865,7 @@ dependencies = [ "craft-media-source", "craft-menu", "craft-mesh", + "craft-mesh-ops", "craft-metadata", "craft-metafile", "craft-midi", @@ -1905,6 +1908,7 @@ dependencies = [ "craft-review", "craft-rtf", "craft-sbs", + "craft-scopes", "craft-score", "craft-scraft-format", "craft-settings", @@ -2284,7 +2288,6 @@ dependencies = [ "craft-flags", "craft-platform", "dirs", - "getrandom 0.3.4", "log", "proptest", "serde", @@ -2297,6 +2300,7 @@ dependencies = [ name = "craft-control-protocol" version = "0.1.0" dependencies = [ + "getrandom 0.3.4", "serde_json", "subtle", ] @@ -2502,6 +2506,7 @@ dependencies = [ "chrono", "craft-cfb", "craft-drawingml", + "craft-flow", "craft-math", "craft-offcrypto", "craft-opc", @@ -2920,6 +2925,18 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-gpu-device" +version = "0.1.0" +dependencies = [ + "craft-gpu", + "log", + "pollster 0.4.0", + "serde", + "serde_json", + "wgpu", +] + [[package]] name = "craft-gpu-null" version = "0.1.0" @@ -2945,6 +2962,17 @@ dependencies = [ "wgpu", ] +[[package]] +name = "craft-gpu-yuv" +version = "0.1.0" +dependencies = [ + "craft-gpu", + "craft-gpu-null", + "pollster 0.4.0", + "wgpu", + "yuv", +] + [[package]] name = "craft-gridcraft-format" version = "0.1.0" @@ -3418,6 +3446,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-mesh-ops" +version = "0.1.0" +dependencies = [ + "glam 0.30.10", + "mikktspace", + "rayon", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-metadata" version = "0.1.0" @@ -3580,6 +3619,8 @@ version = "0.1.0" name = "craft-pbr" version = "0.1.0" dependencies = [ + "craft-materialx", + "craft-mesh", "craft-pbr", "craft-texture", "glam 0.30.10", @@ -4041,6 +4082,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-scopes" +version = "0.1.0" +dependencies = [ + "craft-color", + "serde", + "serde_json", +] + [[package]] name = "craft-score" version = "0.1.0" @@ -4294,7 +4344,14 @@ dependencies = [ name = "craft-testkit" version = "0.1.0" dependencies = [ + "libc", + "png 0.18.1", "rustix 1.1.6", + "serde_json", + "sha2 0.10.9", + "skrifa 0.47.0", + "tempfile", + "toml", ] [[package]] @@ -4328,8 +4385,12 @@ name = "craft-texture" version = "0.1.0" dependencies = [ "bytemuck", + "craft-exr", + "craft-hdr", + "craft-image-codecs", "dds", "half", + "png 0.18.1", "rayon", "thiserror 2.0.21", ] @@ -4674,11 +4735,13 @@ dependencies = [ name = "craft-update" version = "0.1.0" dependencies = [ + "base64 0.22.1", "chrono", "craft-host", "craft-theme", "craft-ui", "dunce", + "ed25519-dalek 2.2.0", "egui", "flate2", "image", @@ -4691,6 +4754,7 @@ dependencies = [ "sha2 0.10.9", "tar", "tempfile", + "toml", "ureq", "verifysign", "winreg", @@ -4928,9 +4992,14 @@ name = "craft-xtask" version = "0.1.0" dependencies = [ "craft-atomic", + "flate2", "libc", "serde_json", + "sha2 0.10.9", + "tar", "tempfile", + "toml_edit", + "unicode-normalization", ] [[package]] @@ -5656,7 +5725,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", "emath", @@ -5712,7 +5781,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -5747,7 +5816,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "accesskit", "ahash", @@ -5766,7 +5835,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -5785,7 +5854,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5805,7 +5874,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", "egui", @@ -5818,7 +5887,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "eframe", "egui", @@ -5895,7 +5964,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", ] @@ -5968,7 +6037,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -5994,7 +6063,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[package]] name = "equator" @@ -6804,6 +6873,12 @@ dependencies = [ "xml-rs", ] +[[package]] +name = "glam" +version = "0.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3abb554f8ee44336b72d522e0a7fe86a29e09f839a36022fa869a7dfe941a54b" + [[package]] name = "glam" version = "0.25.0" @@ -6815,6 +6890,9 @@ name = "glam" version = "0.30.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9" +dependencies = [ + "serde_core", +] [[package]] name = "glifo" @@ -8343,8 +8421,6 @@ dependencies = [ [[package]] name = "kurbo" version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" dependencies = [ "arrayvec", "euclid", @@ -8660,6 +8736,15 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74" +[[package]] +name = "mikktspace" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d0b56b403871a8f992ca626d52cc0a690d4841baea8955dc4af6304ac62f8b0" +dependencies = [ + "glam 0.15.2", +] + [[package]] name = "mime" version = "0.3.17" @@ -15033,6 +15118,15 @@ dependencies = [ "synstructure 0.14.0", ] +[[package]] +name = "yuv" +version = "0.8.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d109d1eacc7b034329873d2d848039b365c65ab7d751b19ee84e4921c62c607" +dependencies = [ + "num-traits", +] + [[package]] name = "zbus" version = "5.19.0" @@ -15317,19 +15411,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" diff --git a/Cargo.toml b/Cargo.toml index ed10972d58..136df2be6f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "3" members = ["crates/*"] -exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu"] +exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu", "vendor/kurbo"] [workspace.package] version = "0.1.0" @@ -37,7 +37,9 @@ acadrust = "=0.6.6" log = "0.4" # internal: add each crate here as `craft- = { path = "crates/" }` craft-plist = { path = "crates/plist" } +craft-gpu-device = { path = "crates/gpu-device" } craft-wasm = { path = "crates/wasm" } +craft-gpu-yuv = { path = "crates/gpu-yuv" } craft-platform = { path = "crates/platform" } craft-png = { path = "crates/png" } craft-aep = { path = "crates/aep" } @@ -82,6 +84,7 @@ craft-cloud = { path = "crates/cloud" } craft-cloud-local = { path = "crates/cloud-local" } craft-cloud-ui = { path = "crates/cloud-ui" } craft-color = { path = "crates/color" } +craft-scopes = { path = "crates/scopes" } craft-color-ui = { path = "crates/color-ui" } craft-color-transform = { path = "crates/color-transform" } craft-frame = { path = "crates/frame" } @@ -133,6 +136,7 @@ craft-gcode = { path = "crates/gcode" } craft-gif = { path = "crates/gif" } craft-hdr = { path = "crates/hdr" } craft-mesh = { path = "crates/mesh" } +craft-mesh-ops = { path = "crates/mesh-ops" } craft-html = { path = "crates/html" } craft-ipp = { path = "crates/ipp" } craft-heif = { path = "crates/heif" } @@ -321,20 +325,21 @@ hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +kurbo = { path = "vendor/kurbo" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid diff --git a/NOTICE b/NOTICE index 4a2d1084e4..baa994eb47 100644 --- a/NOTICE +++ b/NOTICE @@ -63,6 +63,10 @@ craft-proof Language data, embedded at build time from craft-i18n's language-dat THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +mikktspace 0.3.0 (https://crates.io/crates/mikktspace/0.3.0), a dependency of crates/mesh-ops, + is MIT OR Apache-2.0. Its src/generated.rs, a translation of Morten S. Mikkelsen's C + MikkTSpace, carries that original's 2011 zlib-style notice, which must not be removed or + altered; crates/mesh-ops/ATTRIBUTION.md reproduces it in full. crates/text/assets/hyphen/en-us.pat: CC0-1.0, trained from en-us.dic by DesignCraft's trainer. crates/text/assets/spell/en-us-scowl-50.txt.deflate: SCOWL (Spell Checker Oriented Word Lists) 2020.12.07, size 50, American English, Copyright 2000-2018 by Kevin Atkinson, http://wordlist.aspell.net/. @@ -229,6 +233,17 @@ The colour management module in crates/cms is extracted from: Licensed MIT OR Apache-2.0. Its generated ICC profile is dedicated to the public domain (CC0-1.0); see ATTRIBUTION.md. +The mesh operations in crates/mesh-ops are moved from: +- TextureCraft, crates/geom (src/mesh.rs, bvh.rs, primitives.rs, gbuffer.rs, unwrap.rs, + camera.rs and their tests), revision 386630ee85cb22679295b24013575d1aecb39ad2. + https://github.com/storytold/texturecraft + Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors. +- MaterialCraft, crates/geom/src/mesh.rs (subdivision and its test), revision + 3133062968b8a1566eda12a357cb06062db16687. + https://github.com/storytold/materialcraft + Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors. + All licensed MIT OR Apache-2.0. + The image-based lighting in crates/pbr (craft-pbr) is adapted from: - TextureCraft, crates/render/src/ibl.rs, revision fe8ee1bdb0243335560d3e726633cc0433ee99fc, copied without its tests to crates/pbr/tests/it/reference/texturecraft.rs. @@ -288,11 +303,18 @@ applications retain their own document-font selection and licensing policy. linesweeper linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in -vendor/linesweeper with its upstream license files and local patches, to src/sweep/sweep_line.rs, -src/segments.rs, src/curve/transverse.rs, src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its -manifest names Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See +vendor/linesweeper with its upstream license files and local changes. Its manifest names Joe Neeman +as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local -patches and the files left out. +changes and the files left out. + +kurbo + +kurbo 0.13.1 (https://crates.io/crates/kurbo/0.13.1, https://github.com/linebender/kurbo), MIT OR +Apache-2.0, is stored in vendor/kurbo with its upstream license files and local patches, to +src/stroke.rs. Its source files carry "Copyright the Kurbo Authors" lines (2018 to 2026), +and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/kurbo/README.craft.md and +vendor/kurbo/SOURCE.json for provenance and the local patches. Platform lifecycle source provenance diff --git a/README.md b/README.md index 6e841b7157..8169bedf9a 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-automation`](crates/automation/README.md): drive a running app from tests, agents and the CLI: control channel, screenshot queue, frame profiler and trace (native only); recorded actions, their playback and the Actions panel (every target). - [`craft-atomic`](crates/atomic/README.md): Crash-safe atomic file writing and replacement with same-directory staging, directory fsync, Apple `F_FULLFSYNC` fallback, transient lock backoff, and fault injection for the Craft suite. -- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), an optional slot lock held across processes and an optional per-step JSON report. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft. +- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), the asset attribution check, an optional slot lock held across processes, an optional per-step JSON report, and PNG images packed into `.ico` and `.icns` files. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft; icon packing for DeckCraft, CADCraft, craft-launcher and MaterialCraft. - [`craft-captions`](crates/captions/README.md): caption and subtitle files behind one neutral model (cues with exact tick times): SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and TTML / IMSC1 / DFXP readers and writers, and CEA-608 / CEA-708 byte-pair coding. Carved from @@ -211,6 +211,17 @@ 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-gpu-yuv`](crates/gpu-yuv/README.md): the `craft.yuv` GPU provider. It converts RGBA to + NV12, P010 and I420, scaled to the output size, in BT.601, BT.709 and BT.2020 at limited or full + range, through the `craft-gpu` job registry on the null context or on a device. Each output texel + averages the part of the source it covers. The crate also has the render passes for a caller's + own encoder, read-back layouts with unpacking to a packed frame, and the same conversion on the + CPU. Encoders and scopes stay in each app. +- [`craft-gpu-device`](crates/gpu-device/README.md): choosing and opening a wgpu device: Auto, + low power, a named adapter that survives a reordered list and a driver update, or software; + corrections for drivers that crash; the next adapter and then a software one when a device fails + to open; a capability report; device-loss and error recording without panics; and what to reopen + after a loss. Settings pages and the window stay in each app. - [`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. @@ -318,6 +329,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit of polygons with per-corner indices, materials, a node hierarchy): STL, OBJ with MTL, PLY, glTF 2.0 / GLB, FBX and 3MF, one feature each. Readers are bounded by `Limits`, never open a file themselves and never panic. Carved from EffectCraft, SolidCraft, TextureCraft and MaterialCraft. +- [`craft-mesh-ops`](crates/mesh-ops/README.md): operations on triangle meshes: smooth normals, + MikkTSpace tangents, welding, UV unwrapping, a UV-space G-buffer, primitives with UVs and a + BVH for ray casts, and an orbit camera. From TextureCraft and MaterialCraft. - [`craft-midi`](crates/midi/README.md): Standard MIDI Files: a bounded reader for formats 0, 1 and 2 and a format-1 writer, over a neutral model of notes and channel events in ticks at 960 per quarter note. From SoundCraft. @@ -412,11 +426,17 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit reference picking, selection statistics, error tags and filter buttons (`ui` feature). - [`craft-testkit`](crates/testkit/README.md): test support for the apps' own tests. Its `guards` module reports source patterns that broke platforms before: muda's predefined Quit item, WGSL float literals - out of range, and `std::time::Instant` in code the web build runs. Its `deadline` module fails a test - whose body runs past a limit, or whose condition does not hold in time; a variable the caller names - replaces each limit. Its `hostile` module runs a parser on every truncation and on seeded damaged - copies of a valid input, and fails the test with the case that panicked or did not finish. Its `rng` - module holds two seeded generators for repeatable test input. Not published. + out of range, and `std::time::Instant` in code the web build runs. Its `fonts` module makes test fonts + from font bytes the caller supplies: a face with a renamed family and a TrueType collection. Its + `deadline` module fails a test whose body runs past a limit, or whose condition does not hold in time; + a variable the caller names replaces each limit. Its `hostile` module runs a parser on every truncation + and on seeded damaged copies of a valid input, and fails the test with the case that panicked or did + not finish. Its `rng` module holds two seeded generators for repeatable test input. Its `skip` module + prints a `SKIPPED:` line when a test lacks a program, a corpus or the craft-fonts faces, or fails the + test when the variable the caller names is `1`. Any other value of that variable except empty fails + the test as a configuration error. Its `corpus` module (the `corpus` feature) checks a corpus folder + against a pinned SHA-256 list. Its `fixtures` module (native targets only) generates test fixtures + under `target/fixtures` and publishes each one under a lock. Not published. - [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns for 47 more languages (one cargo feature each). With `ui`, the canvas text editor, Character and @@ -424,8 +444,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit (ruler, Tabs, Paragraph, Columns and Hyperlink dialogs, notes editor, find); `spell` and `find` (regex) are features. - [`craft-texture`](crates/texture/README.md): linear float image planes, gray or RGBA, with - nearest and bilinear sampling that repeats or clamps, resizing and display conversion. Sizes are - bounded by `Limits`. From MaterialCraft. + nearest and bilinear sampling that repeats or clamps, resizing and display conversion, and + (optional features) PNG, TIFF, Radiance HDR and OpenEXR decoding that keeps 16-bit and float + samples. Sizes are bounded by `Limits`. From MaterialCraft. - [`craft-timeline`](crates/timeline/README.md): timelines: exact media time, frame rates, timecode, the playback clock, a frame cache and frame server, and editorial interchange (ALE, CMX 3600 EDL, Final Cut Pro 7 XML, FCPXML, OpenTimelineIO), all egui-free; the timeline panel, diff --git a/crates/affinity/src/synth.rs b/crates/affinity/src/synth.rs index 5b75ca0bff..a25cba792b 100644 --- a/crates/affinity/src/synth.rs +++ b/crates/affinity/src/synth.rs @@ -257,3 +257,11 @@ pub fn container(entries: &[(&str, &[u8], Method)], thumbnail_png: Option<&[u8]> } out } + +/// What `f` gives, and how many paragraph ends the reader looked up on this thread while it ran +/// to give each character run its paragraph's format. +pub fn count_paragraph_lookups(f: impl FnOnce() -> T) -> (T, usize) { + crate::text::MATCH_READS.with(|reads| reads.set(0)); + let value = f(); + (value, crate::text::MATCH_READS.with(std::cell::Cell::get)) +} diff --git a/crates/affinity/src/text.rs b/crates/affinity/src/text.rs index c74dc287f6..f645d66857 100644 --- a/crates/affinity/src/text.rs +++ b/crates/affinity/src/text.rs @@ -240,12 +240,26 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec = paragraphs.iter().map(|(end, _)| *end).filter(|e| *e < chars.len()).collect(); cuts.dedup(); let push = |r: &mut Reader, runs: &mut Vec, attrs: Option, from: usize, to: usize, budget: &mut Option| { // Split at paragraph ends so every run has one paragraph format. - let inside = cuts.get(cuts.partition_point(|c| *c <= from)..cuts.partition_point(|c| *c < to)).unwrap_or_default(); + let first = cuts.partition_point(|c| { + count_match_read(); + *c <= from + }); + let past = cuts.partition_point(|c| { + count_match_read(); + *c < to + }); + let inside = cuts.get(first..past).unwrap_or_default(); let mut a = from; for &c in inside.iter().chain(std::iter::once(&to)) { push_run(r, runs, attrs, characters(&chars, a, c), world, budget, align_at(a)); @@ -282,6 +296,18 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec = const { std::cell::Cell::new(0) }; +} + +#[inline] +fn count_match_read() { + #[cfg(any(test, feature = "synth"))] + MATCH_READS.with(|reads| reads.set(reads.get().saturating_add(1))); +} + fn characters(chars: &[char], start: usize, end: usize) -> String { chars.get(start..end).unwrap_or_default().iter().filter(|c| **c != '\0' && **c != '\u{FFFC}').collect() } diff --git a/crates/affinity/tests/it/import_limits.rs b/crates/affinity/tests/it/import_limits.rs index f08c044298..9924125d9d 100644 --- a/crates/affinity/tests/it/import_limits.rs +++ b/crates/affinity/tests/it/import_limits.rs @@ -111,25 +111,32 @@ fn a_shared_story_is_read_within_the_characters_of_one_document() { #[test] fn many_paragraphs_and_runs_are_matched_in_about_linear_time() { - // 200 000 paragraphs, each with its own run and format. - let n = 200_000; - let text = "a\u{2029}".repeat(n); - let fmt = - |end: usize| vec![(tag(b"Indx"), F::I32(end as i32)), (tag(b"Item"), F::Obj(tag(b"PAtt"), vec![(tag(b"Ints"), array_i32(b"Ints", &[1]))]))]; - let blk = F::Obj( - tag(b"StBl"), - vec![ - (tag(b"Glyp"), utf8(&text)), - (tag(b"GAtt"), F::Obj(tag(b"GlAS"), vec![(tag(b"Runs"), F::Objs(tag(b"GlAR"), (1..=n).map(|i| run(2 * i as i32, None)).collect()))])), - (tag(b"PAtt"), F::Obj(tag(b"PaAS"), vec![(tag(b"Runs"), F::Objs(tag(b"PaAR"), (1..=n).map(|i| fmt(2 * i)).collect()))])), - ], - ); - let started = std::time::Instant::now(); - let d = open(vec![artistic(F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(vec![blk]))]))]); - let Kind::Text(t) = &d.spreads[0].nodes[0].kind else { panic!("text") }; - assert_eq!(t.runs.len(), n); - // (About half a second; quadratic matching took over half a minute on the same machine.) - assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed()); + // `n` paragraphs, each with its own run and format, and how many paragraph ends matching + // them looks up. + let lookups = |n: usize| { + let text = "a\u{2029}".repeat(n); + let fmt = |end: usize| { + vec![(tag(b"Indx"), F::I32(end as i32)), (tag(b"Item"), F::Obj(tag(b"PAtt"), vec![(tag(b"Ints"), array_i32(b"Ints", &[1]))]))] + }; + let blk = F::Obj( + tag(b"StBl"), + vec![ + (tag(b"Glyp"), utf8(&text)), + (tag(b"GAtt"), F::Obj(tag(b"GlAS"), vec![(tag(b"Runs"), F::Objs(tag(b"GlAR"), (1..=n).map(|i| run(2 * i as i32, None)).collect()))])), + (tag(b"PAtt"), F::Obj(tag(b"PaAS"), vec![(tag(b"Runs"), F::Objs(tag(b"PaAR"), (1..=n).map(|i| fmt(2 * i)).collect()))])), + ], + ); + let story = artistic(F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(vec![blk]))])); + let (d, lookups) = synth::count_paragraph_lookups(|| open(vec![story])); + let Kind::Text(t) = &d.spreads[0].nodes[0].kind else { panic!("text") }; + assert_eq!(t.runs.len(), n); + lookups + }; + // Four times the paragraphs and runs: a few binary searches each, so about four times the + // lookups (a little more for the longer searches), where matching each run against every + // paragraph is sixteen times. + let (quarter, full) = (lookups(50_000), lookups(200_000)); + assert!(full <= 5 * quarter, "{quarter} lookups for 50,000 paragraphs, {full} for 200,000"); } /// A shape node of `size` px. diff --git a/crates/audio-dsp/README.md b/crates/audio-dsp/README.md index ce6724bb8e..48daa625b1 100644 --- a/crates/audio-dsp/README.md +++ b/crates/audio-dsp/README.md @@ -12,8 +12,19 @@ and contains no `unsafe` code. (compressor, expander and gate, limiter, maximizer, multiband and tube-modeled compressors), delays and reverbs (including convolution and surround), modulation, restoration (denoise, dehum, click remover, de-esser, de-reverb, speech enhancement), channel tools, distortion, - dither, a signal generator, a loudness meter, and a pitch shifter for a live voice with 10 ms - of latency. + dither, a signal generator, a loudness meter, a pitch shifter for a live voice with 10 ms of + latency, a formant shifter for a live voice with 10.7 ms of latency, and noise suppression for + a live voice with 5.3 ms of latency that follows the noise floor without first learning it. + These latencies are at 48 kHz (the STFT sizes depend on the sample rate; `latency()` reports + them in samples). The pitch shifter's Keep Formants switch adds the formant shifter's latency, + and `latency()` reports it while the switch is on. A ring modulator for robotic and metallic + voices (ring, frequency modulation, and positive or negative comb resonators, with the + frequency moved by an LFO, the input's level or a sample-and-hold source) adds no latency, and + neither does a bitcrusher that takes one sample in every 1 to 50 and rounds it to 1 to 16 bits, + or a tremolo that lowers the gain once per cycle of a sine, triangle or square LFO. A vibrato + that swings the pitch by up to 100 cents through a delay moved by a sine or triangle LFO adds + no latency either: the delay is 0 at the start of each cycle, except while it glides to new + settings. - `loudness`: an ITU-R BS.1770-4 / EBU R128 meter with momentary, short-term and integrated loudness, loudness range (EBU Tech 3342), sample peak and true peak. - `pan`: stereo pan laws, a surround panner over any layout of up to 16 speakers, and first-order @@ -28,6 +39,14 @@ and contains no `unsafe` code. - `biquad` and `design`: biquad filters with their magnitude response, and IIR filter design from Butterworth, Bessel, Chebyshev and elliptic prototypes. +`noise_suppression` estimates the noise floor from minimum spectral power over 1.5 s. The first +noise estimate after a reset starts from the median bin's power. Each bin's value is clamped +between 30 dB below its own estimate and its own estimate. Windows that overlap a run of at +least one hop of zeros (64 samples at 48 kHz) do not enter the noise estimate. The gain floor +moves from 0 dB toward the attenuation set by `reduction` during the first search window +of sound. Continuous voiced or tonal audio present from startup can enter the noise estimate +and be attenuated afterward. + ## Conventions Audio is planar `f32`: one slice per channel, all the same length. `AudioEffect::process`, @@ -79,7 +98,8 @@ The crate combines two crates from the ArtCraft apps, with changes: offline resampler. - [storytold/soundcraft](https://github.com/storytold/soundcraft) `crates/dsp` at `915481be1b49d7e0502e07b059d0c0198c61911a`: the two crossfaded read taps of the voice pitch - shifter (`src/plugins/pitch.rs`) and its YIN pitch tracker (`src/pitch_detect.rs`). + shifter (`src/plugins/pitch.rs`) and its YIN pitch tracker (`src/pitch_detect.rs`), and the + ring modulator (`src/plugins/modulation.rs`). `NOTICE` keeps the copyright notices of both projects. diff --git a/crates/audio-dsp/src/effects.rs b/crates/audio-dsp/src/effects.rs index 42ec2261ce..0ea9055b1f 100644 --- a/crates/audio-dsp/src/effects.rs +++ b/crates/audio-dsp/src/effects.rs @@ -1,6 +1,7 @@ //! Audio effects and their registry. pub(crate) mod channel; +pub(crate) mod character; pub(crate) mod declick; pub(crate) mod dither; pub(crate) mod dynamics; @@ -15,11 +16,13 @@ pub(crate) mod restoration; pub(crate) mod reverbs; pub(crate) mod special; mod stft; +pub(crate) mod suppress; pub(crate) mod time; pub(crate) mod util; pub(crate) mod voice; pub(crate) use channel::{Amplify, Balance, ChannelVolume, Invert, Route, Routing}; +pub use character::{Bitcrusher, RingMod, Tremolo, Vibrato}; pub(crate) use declick::ClickRemover; pub use dither::Dither; pub use dynamics::{Compressor, Gate, Limiter, Maximizer}; @@ -35,8 +38,9 @@ pub(crate) use restoration::{DeHum, DeNoise}; pub(crate) use reverbs::{ConvolutionReverb, SurroundReverb}; pub use special::LoudnessMeterFx; pub(crate) use special::{AmbisonicsPanner, Binauralizer, ChannelMixer, Distortion, GuitarSuite, Mastering, Mute, StereoExpander, VocalEnhancer}; +pub use suppress::NoiseSuppression; pub(crate) use time::{Delay, Reverb}; -pub use voice::VoicePitch; +pub use voice::{VoiceFormant, VoicePitch}; use crate::{AudioEffect, ParamSpec, sane_channels, sane_sample_rate}; @@ -125,8 +129,10 @@ static REGISTRY: &[EffectInfo] = &[ }, entry!("dehum", "DeHum", Restoration, DeHum), entry!("denoise", "DeNoise", Restoration, DeNoise), + entry!("noise_suppression", "Noise Suppression", Restoration, NoiseSuppression), entry!("pitch_shifter", "Pitch Shifter", Pitch, PitchShifter), entry!("voice_pitch", "Voice Pitch", Pitch, VoicePitch), + entry!("voice_formant", "Voice Formant", Pitch, VoiceFormant), entry!("deesser", "DeEsser", Restoration, DeEsser), entry!("dereverb", "DeReverb", Restoration, DeReverb), entry!("speech_enhance", "Enhance Speech", Filter, SpeechEnhance), @@ -144,6 +150,9 @@ static REGISTRY: &[EffectInfo] = &[ entry!("chorus_flanger", "Chorus/Flanger", Modulation, ChorusFlanger), entry!("flanger", "Flanger", Modulation, Flanger), entry!("phaser", "Phaser", Modulation, Phaser), + entry!("ring_mod", "Ring Modulator", Modulation, RingMod), + entry!("tremolo", "Tremolo", Modulation, Tremolo), + entry!("vibrato", "Vibrato", Modulation, Vibrato), entry!("analog_delay", "Analog Delay", Time, AnalogDelay), entry!("multitap_delay", "Multitap Delay", Time, MultitapDelay), entry!("convolution_reverb", "Convolution Reverb", Reverb, ConvolutionReverb), @@ -151,6 +160,7 @@ static REGISTRY: &[EffectInfo] = &[ entry!("click_remover", "Automatic Click Remover", Restoration, ClickRemover), entry!("channel_mixer", "Channel Mixer", Channel, ChannelMixer), entry!("distortion", "Distortion", Special, Distortion), + entry!("bitcrusher", "Bitcrusher", Special, Bitcrusher), entry!("guitar_suite", "GuitarSuite", Special, GuitarSuite), entry!("mastering", "Mastering", Special, Mastering), entry!("vocal_enhancer", "Vocal Enhancer", Special, VocalEnhancer), diff --git a/crates/audio-dsp/src/effects/behavior_tests.rs b/crates/audio-dsp/src/effects/behavior_tests.rs index 662046f75c..6433aa26c7 100644 --- a/crates/audio-dsp/src/effects/behavior_tests.rs +++ b/crates/audio-dsp/src/effects/behavior_tests.rs @@ -132,9 +132,11 @@ fn every_effect_is_deterministic_and_latency_is_constant() { f }; let lat0 = (e.create)(SR, 2).latency(); + // Keep Formants adds voice_pitch's formant stage; no other parameter changes a latency. + let want = if e.id == "voice_pitch" { lat0 + voice::VoiceFormant::new(SR, 2).latency() } else { lat0 }; let mut a = mk(); let mut b = mk(); - assert_eq!(a.latency(), lat0, "{}: latency depends on parameters", e.id); + assert_eq!(a.latency(), want, "{}: latency depends on parameters", e.id); let ya = run(a.as_mut(), &l, &r); let yb = run(b.as_mut(), &l, &r); assert!(ya.0 == yb.0 && ya.1 == yb.1, "{}: not deterministic", e.id); @@ -147,7 +149,14 @@ fn latency_is_where_the_impulse_lands() { // settings (FFT filter / convolution / existing STFT effects). The click remover repairs a // lone impulse in silence as a click, so its latency is checked on noise by // `neutral_settings_are_delayed_identity`. - for (id, p) in [("fft_filter", vec![]), ("convolution_reverb", vec![("mix", 0.0)]), ("voice_pitch", vec![])] { + for (id, p) in [ + ("fft_filter", vec![]), + ("convolution_reverb", vec![("mix", 0.0)]), + ("voice_pitch", vec![]), + ("voice_pitch", vec![("formant_follow", 1.0)]), + ("voice_formant", vec![]), + ("noise_suppression", vec![("reduction", 0.0)]), + ] { let mut e = fx(id, &p); let lat = e.latency(); assert!(lat > 0, "{id}"); @@ -906,6 +915,8 @@ fn delays_and_reverbs_report_their_tails() { ("chorus_flanger", &[("mode", 1.0), ("width", 100.0), ("intensity", 100.0), ("mix", 100.0)][..]), ("chorus_flanger", &[("width", 100.0), ("intensity", 100.0), ("mix", 100.0)][..]), ("flanger", &[("final_delay", 20.0), ("feedback", 100.0), ("mix", 100.0)][..]), + ("ring_mod", &[("effect", 2.0), ("frequency", 100.0), ("resonance", 90.0)][..]), + ("ring_mod", &[("effect", 3.0), ("frequency", 60.0), ("resonance", 95.0), ("mod_source", 1.0), ("mod_depth", 100.0)][..]), ] { let mut e = fx(id, params); let tail = e.tail_samples(); @@ -977,6 +988,12 @@ fn direct_constructors_cap_the_channel_count() { filters::FullParametricEq, pitch::PitchShifter, voice::VoicePitch, + voice::VoiceFormant, + suppress::NoiseSuppression, + character::RingMod, + character::Bitcrusher, + character::Tremolo, + character::Vibrato, ); } diff --git a/crates/audio-dsp/src/effects/character.rs b/crates/audio-dsp/src/effects/character.rs new file mode 100644 index 0000000000..eb623f0870 --- /dev/null +++ b/crates/audio-dsp/src/effects/character.rs @@ -0,0 +1,1487 @@ +//! Character effects for a live voice. None of them adds latency. +//! +//! The ring modulator (`ring_mod`) has four effects: +//! +//! - Ring multiplies the input by a sine carrier at the frequency, which moves each partial of a +//! voice to the sum and the difference of its frequency and the carrier's. +//! - Frequency Mod reads the input through a delay that the carrier swings between 2 samples and +//! 2 samples plus 2 ms. +//! - Resonator + and Resonator - feed the output back after one period of the frequency, with a +//! positive or a negative sign, so the input rings at the frequency and its multiples (Resonator +//! +) or at its odd half multiples (Resonator -). The output is scaled by `1 - resonance`, so the +//! peak gain at resonance is unity. +//! +//! An LFO, an envelope follower (5 ms attack, 100 ms release) or a sample-and-hold source moves the +//! frequency by up to two octaves either way at 100 % depth. The envelope follower moves it up +//! only. +//! +//! The bitcrusher (`bitcrusher`) takes one input sample every `rate_divide` samples, holds it until +//! the next one, and rounds it to a word length of 1 to 16 bits. +//! +//! The tremolo (`tremolo`) lowers the gain of every channel by up to `depth` once per cycle of a +//! sine, triangle or square LFO at `rate`. +//! +//! The vibrato (`vibrato`) reads the input through a delay that grows from 0 and shrinks back once +//! per cycle of a sine or triangle LFO at `rate`, so the pitch swings by up to `depth` cents. While +//! no glide to new settings is in progress, the delay is 0 at the start of each cycle. + +use super::util::{DelayLine, Envelope, Lfo, Prng, coef, delay_line_len, echo_tail, uni_sine, uni_tri}; +use crate::{AudioEffect, ParamSpec, ParamValues, Smoothed, Unit, block_len, flush32, param_plumbing}; +use std::f64::consts::TAU; + +fn blend(dry: f64, wet: f64, mix: f64) -> f64 { + (1.0 - mix) * dry + mix * wet +} + +/// Smoothing time of the frequency, resonance, depth and mix, in ms. +const SM: f32 = 20.0; +const RING_EFFECTS: &[&str] = &["Ring", "Frequency Mod", "Resonator +", "Resonator -"]; +const RING_SOURCES: &[&str] = &["LFO", "Envelope", "Sample & Hold"]; +/// Lowest frequency the control reaches. +const MIN_HZ: f32 = 20.0; +/// Octaves the frequency moves at full modulation depth. +const MOD_OCTAVES: f32 = 2.0; +/// Peak delay swing of Frequency Mod, in ms. +const FM_SWING_MS: f32 = 1.0; +/// Shortest delay of Frequency Mod, in samples (room for the interpolated read). +const FM_BASE: f32 = 2.0; +/// Sample-and-hold seed (the same sequence after every reset). +const SEED: u64 = 0x5EED_1234; +/// Highest frequency the modulation reaches, as a fraction of the sample rate. +const MAX_FRACTION: f32 = 0.45; +const TREMOLO_SHAPES: &[&str] = &["Sine", "Triangle", "Square"]; +/// Length of each edge of the tremolo's square, in ms. +const EDGE_MS: f64 = 2.0; +const VIBRATO_SHAPES: &[&str] = &["Sine", "Triangle"]; +/// Lowest rate of the vibrato, in Hz. +const VIBRATO_MIN_RATE: f32 = 1.0; +/// Greatest depth of the vibrato, in cents. +const VIBRATO_MAX_CENTS: f32 = 100.0; +/// Most the vibrato's glide moves the delay per sample on top of the curve. +const VIBRATO_GLIDE_SLOPE: f32 = 1.0 / 32.0; + +/// Ring modulation, frequency modulation and positive or negative comb resonators, with the +/// frequency moved by an LFO, an envelope follower or a sample-and-hold source. +pub struct RingMod { + pv: ParamValues, + sr: f32, + lines: Vec, + carrier: Lfo, + lfo: Lfo, + rng: Prng, + env: Envelope, + env_attack: f32, + env_release: f32, + held: f32, + hold_left: usize, + /// Effect the lines hold state for. + effect: usize, + freq: Smoothed, + res: Smoothed, + depth: Smoothed, + mix: Smoothed, +} + +impl RingMod { + pub const PARAMS: &'static [ParamSpec] = &[ + ParamSpec::choice("effect", "Effect", RING_EFFECTS, 0), + ParamSpec::log("frequency", "Frequency", MIN_HZ, 5000.0, 440.0, Unit::Hertz), + ParamSpec::new("resonance", "Resonance", 0.0, 95.0, 50.0, Unit::Percent), + ParamSpec::choice("mod_source", "Mod Source", RING_SOURCES, 0), + ParamSpec::log("mod_rate", "Mod Rate", 0.05, 20.0, 1.0, Unit::Hertz), + ParamSpec::new("mod_depth", "Mod Depth", 0.0, 100.0, 0.0, Unit::Percent), + ParamSpec::new("mix", "Mix", 0.0, 100.0, 100.0, Unit::Percent), + ]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let ch = crate::sane_channels(channels); + // One period of the lowest frequency the modulation reaches, or the widest Frequency Mod + // delay, whichever is longer. + let longest_ms = (1000.0 / (MIN_HZ * (-MOD_OCTAVES).exp2())).max(2.0 * FM_SWING_MS) + 1.0; + let len = delay_line_len(longest_ms, sample_rate, ch); + let sm = |v| Smoothed::with_ms(v, sample_rate, SM); + let mut s = RingMod { + pv: ParamValues::new(Self::PARAMS), + sr: sample_rate, + lines: vec![DelayLine::new(len); ch], + carrier: Lfo::default(), + lfo: Lfo::default(), + rng: Prng::new(SEED), + env: Envelope::default(), + env_attack: coef(5.0, sample_rate), + env_release: coef(100.0, sample_rate), + held: 0.0, + hold_left: 0, + effect: 0, + freq: sm(440.0), + res: sm(0.0), + depth: sm(0.0), + mix: sm(1.0), + }; + s.apply_params(true); + s.effect = s.pv.idx("effect"); + s + } + + fn apply_params(&mut self, snap: bool) { + self.freq.set(self.pv.v("frequency")); + self.res.set(self.pv.v("resonance") / 100.0); + self.depth.set(self.pv.v("mod_depth") / 100.0); + self.mix.set(self.pv.v("mix") / 100.0); + if snap { + for s in [&mut self.freq, &mut self.res, &mut self.depth, &mut self.mix] { + s.snap(); + } + } + } + + /// One period of the lowest frequency the modulation reaches, in ms, from the settings and from + /// the values still ramping toward them. The envelope follower moves the frequency up only, so + /// with it the lowest is the frequency. The frequency is held within the same range as in + /// [`AudioEffect::process`]. + fn longest_period_ms(&self) -> f32 { + let down = if self.pv.idx("mod_source") == 1 { 0.0 } else { self.depth.value().max(self.depth.target()) }; + let lowest = self.freq.value().min(self.freq.target()) * (-MOD_OCTAVES * down).exp2(); + 1000.0 / lowest.clamp(1.0, self.sr * MAX_FRACTION) + } +} + +impl AudioEffect for RingMod { + param_plumbing!("ring_mod"); + /// Ring has no tail. Frequency Mod holds up to its widest delay. The resonators ring until + /// the feedback has fallen by 60 dB at the longest period the modulation reaches, at the higher + /// of the resonance setting and the value still ramping toward it. + fn tail_samples(&self) -> usize { + match self.pv.idx("effect") { + 1 => (FM_BASE + 2.0 * FM_SWING_MS * 0.001 * self.sr).ceil() as usize + 1, + 2 | 3 => echo_tail(self.longest_period_ms(), self.res.value().max(self.res.target()), self.sr), + _ => 0, + } + } + fn reset(&mut self) { + self.lines.iter_mut().for_each(DelayLine::reset); + self.carrier.reset(); + self.lfo.reset(); + self.rng = Prng::new(SEED); + self.env.env = 0.0; + self.held = 0.0; + self.hold_left = 0; + self.effect = self.pv.idx("effect"); + for s in [&mut self.freq, &mut self.res, &mut self.depth, &mut self.mix] { + s.snap(); + } + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let n = block_len(channels); + if n == 0 { + return; + } + let nch = channels.len().min(self.lines.len()); + let effect = self.pv.idx("effect"); + if effect != self.effect { + // The lines hold the previous effect's state. + self.lines.iter_mut().for_each(DelayLine::reset); + self.effect = effect; + } + let source = self.pv.idx("mod_source"); + let rate = self.pv.v("mod_rate"); + let hold = ((self.sr / rate.max(0.05)) as usize).max(1); + // A faster rate cuts the value being held short, instead of holding it for the old length. + self.hold_left = self.hold_left.min(hold); + let highest = self.sr * MAX_FRACTION; + let swing = FM_SWING_MS * 0.001 * self.sr; + let sign = if effect == 3 { -1.0 } else { 1.0 }; + for i in 0..n { + let level = channels[..nch].iter().map(|c| c[i]).filter(|x| x.is_finite()).fold(0.0f32, |m, x| m.max(x.abs())); + let env = self.env.tick(self.env_attack, self.env_release, level); + let m = match source { + 1 => env.min(1.0), + 2 => { + if self.hold_left == 0 { + self.held = self.rng.uniform(); + self.hold_left = hold; + } + self.hold_left -= 1; + self.held + } + _ => (TAU * self.lfo.phase(0.0)).sin() as f32, + }; + self.lfo.advance(rate, self.sr); + let f = (self.freq.tick() * (MOD_OCTAVES * self.depth.tick() * m).exp2()).clamp(1.0, highest); + let fb = self.res.tick(); + let mix = self.mix.tick(); + let carrier = (TAU * self.carrier.phase(0.0)).sin() as f32; + self.carrier.advance(f, self.sr); + // The read happens before this sample's push, so one period back is `period - 1`. + let back = self.sr / f - 1.0; + for (ch, line) in self.lines.iter_mut().enumerate() { + // A non-finite sample is taken as silence. A channel the block leaves out is fed + // silence, so it holds none of its earlier audio when it comes back. + let dry = match channels.get(ch).filter(|_| ch < nch) { + Some(c) if c[i].is_finite() => c[i], + _ => 0.0, + }; + let wet = match effect { + 1 => { + line.push(dry); + // The read interpolates in f64, as Vibrato's does, so neighboring samples + // near the f32 limit with opposite signs do not overflow. + let d = (FM_BASE + swing * (1.0 + carrier)).clamp(0.0, line.max_delay()); + let (di, frac) = (d.floor() as usize, f64::from(d - d.floor())); + let (a, b) = (f64::from(line.tap(di)), f64::from(line.tap(di + 1))); + (a + (b - a) * frac) as f32 + } + 2 | 3 => { + let y = flush32(dry + sign * fb * line.read(back)); + line.push(y); + y * (1.0 - fb) + } + _ => dry * carrier, + }; + if ch < nch { + let (dry, wet) = (dry as f64, wet as f64); + channels[ch][i] = blend(dry, wet, f64::from(mix)) as f32; + } + } + } + } +} + +/// Bit-depth and sample-rate reduction. The input is sampled once every `rate_divide` samples and +/// held in between; a fractional value alternates between the two nearest whole hold lengths, so +/// the holds average it. Each held sample is rounded to the nearest multiple of the step +/// `2^(1 - bits)`, so silence stays silence and the range -1 ..= 1 takes `2^bits + 1` levels; +/// fractional bits give steps between the whole-bit ones. Bits and Rate Divide take effect from +/// the next sample: a new Bits rounds the sample being held again, and a shorter hold cuts the +/// one in progress short. Mix moves to a new value over 20 ms. +pub struct Bitcrusher { + pv: ParamValues, + /// The input sample each channel holds, before rounding. + held: Vec, + /// Samples since the last capture, counted so that a capture happens when it reaches the hold + /// length. Infinite after a reset, so the next sample is captured. + since: f64, + mix: Smoothed, +} + +impl Bitcrusher { + pub const PARAMS: &'static [ParamSpec] = &[ + ParamSpec::new("bits", "Bits", 1.0, 16.0, 8.0, Unit::None), + ParamSpec::new("rate_divide", "Rate Divide", 1.0, 50.0, 4.0, Unit::None), + ParamSpec::new("mix", "Mix", 0.0, 100.0, 100.0, Unit::Percent), + ]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let ch = crate::sane_channels(channels); + let mut s = Bitcrusher { + pv: ParamValues::new(Self::PARAMS), + held: vec![0.0; ch], + since: f64::INFINITY, + mix: Smoothed::with_ms(1.0, sample_rate, SM), + }; + s.apply_params(true); + s + } + + fn apply_params(&mut self, snap: bool) { + self.mix.set(self.pv.v("mix") / 100.0); + if snap { + self.mix.snap(); + } + } +} + +impl AudioEffect for Bitcrusher { + param_plumbing!("bitcrusher"); + /// A held sample lasts at most the hold length rounded up, so it sounds for up to that many + /// samples less one after the input ends. + fn tail_samples(&self) -> usize { + (self.pv.v("rate_divide").ceil() as usize).saturating_sub(1) + } + fn reset(&mut self) { + self.held.fill(0.0); + self.since = f64::INFINITY; + self.mix.snap(); + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let n = block_len(channels); + let nch = channels.len().min(self.held.len()); + let hold = f64::from(self.pv.v("rate_divide")); + // The rounding and the mix run in f64, so a finite input near the f32 limit stays finite. + let step = (1.0 - f64::from(self.pv.v("bits"))).exp2(); + let limit = f64::from(f32::MAX); + for i in 0..n { + let capture = self.since >= hold; + if capture { + // On schedule, less than one sample is left over. More is left after a reset or + // after the hold got shorter; the new holds then count from this capture. + let left = self.since - hold; + self.since = if left < 1.0 { left } else { 0.0 }; + } + self.since += 1.0; + let mix = f64::from(self.mix.tick()); + for (ch, held) in self.held.iter_mut().enumerate() { + // A non-finite sample is taken as silence. A channel the block leaves out holds + // silence from its first left-out sample on, so it holds none of its earlier audio + // when it comes back. + let dry = match channels.get(ch).filter(|_| ch < nch) { + Some(c) if c[i].is_finite() => f64::from(c[i]), + _ => 0.0, + }; + if capture || ch >= nch { + *held = dry as f32; + } + if ch < nch { + // The held input is rounded at the current step, so a change of Bits also + // applies to the hold in progress. + let crushed = ((f64::from(*held) / step).round() * step).clamp(-limit, limit); + channels[ch][i] = blend(dry, crushed, mix) as f32; + } + } + } + } +} + +/// Amplitude modulation. The gain is `1 - depth * m`, where the LFO value `m` runs from 0 at the +/// start of each cycle to 1 at its middle and back, as a sine, a triangle or a square. The square +/// holds 0 and 1 for half a cycle each and moves between them along a raised-cosine edge 2 ms long, +/// centered on the quarter and three-quarter points, so it does not click. Rate takes effect from +/// the next sample with the phase kept. A change of Shape, or of Rate while the shape is the +/// square, glides from the last LFO value to the new curve over 20 ms, with the value kept within +/// 0 ..= 1. Depth moves to a new value over 20 ms. +pub struct Tremolo { + pv: ParamValues, + sr: f32, + channels: usize, + lfo: Lfo, + /// Shape the LFO value follows. + shape: usize, + /// Length of the square's edges, in cycles, for the rate of the last block. + edge: f64, + /// LFO value of the last sample. + last: f32, + /// Difference between the last LFO value and the new curve at a change of Shape, or of the + /// square's edges. It fades to zero over `glide_len` samples. + glide: f32, + glide_left: usize, + glide_len: usize, + depth: Smoothed, +} + +impl Tremolo { + pub const PARAMS: &'static [ParamSpec] = &[ + ParamSpec::log("rate", "Rate", 0.1, 20.0, 5.0, Unit::Hertz), + ParamSpec::new("depth", "Depth", 0.0, 100.0, 50.0, Unit::Percent), + ParamSpec::choice("shape", "Shape", TREMOLO_SHAPES, 0), + ]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let mut s = Tremolo { + pv: ParamValues::new(Self::PARAMS), + sr: sample_rate, + channels: crate::sane_channels(channels), + lfo: Lfo::default(), + shape: 0, + edge: 0.0, + last: 0.0, + glide: 0.0, + glide_left: 0, + glide_len: ((SM * 0.001 * sample_rate) as usize).max(1), + depth: Smoothed::with_ms(0.5, sample_rate, SM), + }; + s.apply_params(true); + s.shape = s.pv.idx("shape"); + s.edge = s.edge_len(); + s + } + + /// Length of the square's edges at the current rate, in cycles. + fn edge_len(&self) -> f64 { + (EDGE_MS * 0.001 * f64::from(self.pv.v("rate"))).clamp(1e-9, 0.25) + } + + fn apply_params(&mut self, snap: bool) { + self.depth.set(self.pv.v("depth") / 100.0); + if snap { + self.depth.snap(); + } + } + + /// LFO value of `shape` at phase `p` (cycles), with square edges `edge` cycles long. + fn shape_value(shape: usize, p: f64, edge: f64) -> f32 { + match shape { + 1 => uni_tri(p), + 2 => { + // The triangle crosses 1/2 at the edges' centers with a slope of 2 per cycle, so an + // edge `edge` cycles long spans `2 * edge` of it. + let tri = if p < 0.5 { 2.0 * p } else { 2.0 - 2.0 * p }; + let u = ((tri - 0.5) / (2.0 * edge) + 0.5).clamp(0.0, 1.0); + (0.5 - 0.5 * (std::f64::consts::PI * u).cos()) as f32 + } + _ => uni_sine(p), + } + } +} + +impl AudioEffect for Tremolo { + param_plumbing!("tremolo"); + fn reset(&mut self) { + self.lfo.reset(); + self.shape = self.pv.idx("shape"); + self.edge = self.edge_len(); + self.last = 0.0; + self.glide = 0.0; + self.glide_left = 0; + self.depth.snap(); + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let n = block_len(channels); + if n == 0 { + // No sample used the current settings, so a glide in progress goes on unchanged. + return; + } + let nch = channels.len().min(self.channels); + let rate = self.pv.v("rate"); + let edge = self.edge_len(); + let shape = self.pv.idx("shape"); + if shape != self.shape || (shape == 2 && edge != self.edge) { + self.glide = self.last - Self::shape_value(shape, self.lfo.phase(0.0), edge); + self.glide_left = self.glide_len; + self.shape = shape; + } + self.edge = edge; + for i in 0..n { + let mut m = Self::shape_value(shape, self.lfo.phase(0.0), edge); + if self.glide_left > 0 { + m = (m + self.glide * self.glide_left as f32 / self.glide_len as f32).clamp(0.0, 1.0); + self.glide_left -= 1; + } + self.last = m; + self.lfo.advance(rate, self.sr); + let gain = 1.0 - self.depth.tick() * m; + for c in channels[..nch].iter_mut() { + // A non-finite sample is taken as silence. + c[i] = if c[i].is_finite() { c[i] * gain } else { 0.0 }; + } + } + } +} + +/// Pitch modulation. The input is read through a delay of `swing * m` samples, where the LFO value +/// `m` runs from 0 at the start of each cycle to 1 at its middle and back, as a sine or a triangle. +/// The swing is set so that the pitch falls by `depth` cents while the delay grows, and rises by a +/// little less while it shrinks: the read moves at `1 -/+ d` samples per sample, with +/// `d = 1 - 2^(-depth / 1200)`. A sine reaches `d` at its steepest point, and a triangle holds it +/// for each half of the cycle. While no glide is in progress, the delay is 0 at the start of each +/// cycle. Rate takes effect from the next sample with the phase kept. A change of Rate, Depth or +/// Shape glides the delay from its last value to the new curve, moving it by at most 1/32 sample +/// per sample on top of the curve, so the output neither clicks nor jumps in pitch. A glide can run +/// past the start of a cycle, and the delay there stays above 0 until the glide ends. +pub struct Vibrato { + pv: ParamValues, + sr: f32, + lines: Vec, + lfo: Lfo, + /// Shape the delay follows. + shape: usize, + /// Peak delay of the curve, in samples, for the settings of the last block. + swing: f32, + /// Delay of the last sample, in samples. + last: f32, + /// Difference between the last delay and the new curve at a change of the settings. It fades + /// to zero over `glide_len` samples. + glide: f32, + glide_left: usize, + glide_len: usize, +} + +impl Vibrato { + pub const PARAMS: &'static [ParamSpec] = &[ + ParamSpec::log("rate", "Rate", VIBRATO_MIN_RATE, 14.0, 6.0, Unit::Hertz), + ParamSpec::new("depth", "Depth (cents)", 0.0, VIBRATO_MAX_CENTS, 40.0, Unit::None), + ParamSpec::choice("shape", "Shape", VIBRATO_SHAPES, 0), + ]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let ch = crate::sane_channels(channels); + // The widest swing is the triangle's at the lowest rate and the greatest depth. A glide + // can add up to one more swing on top of the curve. + let widest_ms = (1000.0 * Self::slope(VIBRATO_MAX_CENTS) / (2.0 * f64::from(VIBRATO_MIN_RATE))) as f32; + let len = delay_line_len(2.0 * widest_ms + 1.0, sample_rate, ch); + let mut s = Vibrato { + pv: ParamValues::new(Self::PARAMS), + sr: sample_rate, + lines: vec![DelayLine::new(len); ch], + lfo: Lfo::default(), + shape: 0, + swing: 0.0, + last: 0.0, + glide: 0.0, + glide_left: 0, + glide_len: 1, + }; + s.shape = s.pv.idx("shape"); + s.swing = s.swing_len(); + s + } + + fn apply_params(&mut self, _snap: bool) {} + + /// Samples the read moves per sample, away from 1, at a depth of `cents`. + fn slope(cents: f32) -> f64 { + 1.0 - (-f64::from(cents) / 1200.0).exp2() + } + + /// Peak delay of the curve for the current settings, in samples. + fn swing_len(&self) -> f32 { + let (d, rate, sr) = (Self::slope(self.pv.v("depth")), f64::from(self.pv.v("rate")), f64::from(self.sr)); + // The sine's delay `swing * (1 - cos(2 pi p)) / 2` moves by at most `swing * pi * rate / sr` + // per sample, and the triangle's moves by `swing * 2 * rate / sr`. + let swing = if self.pv.idx("shape") == 1 { d * sr / (2.0 * rate) } else { d * sr / (std::f64::consts::PI * rate) }; + (swing as f32).min(self.max_delay()) + } + + fn max_delay(&self) -> f32 { + self.lines.first().map_or(0.0, DelayLine::max_delay) + } + + /// LFO value of `shape` at phase `p` (cycles). + fn shape_value(shape: usize, p: f64) -> f32 { + if shape == 1 { uni_tri(p) } else { uni_sine(p) } + } +} + +impl AudioEffect for Vibrato { + param_plumbing!("vibrato"); + /// The input sounds until the delay has passed it. The delay reaches at most the new curve's + /// swing plus the last delay, so the tail covers both. + fn tail_samples(&self) -> usize { + (self.swing_len() + self.last).min(self.max_delay()).ceil() as usize + 1 + } + fn reset(&mut self) { + self.lines.iter_mut().for_each(DelayLine::reset); + self.lfo.reset(); + self.shape = self.pv.idx("shape"); + self.swing = self.swing_len(); + self.last = 0.0; + self.glide = 0.0; + self.glide_left = 0; + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let n = block_len(channels); + if n == 0 { + // No sample uses the new settings, so no glide starts. + return; + } + let nch = channels.len().min(self.lines.len()); + let rate = self.pv.v("rate"); + let shape = self.pv.idx("shape"); + let swing = self.swing_len(); + if shape != self.shape || swing != self.swing { + self.glide = self.last - swing * Self::shape_value(shape, self.lfo.phase(0.0)); + self.glide_len = ((self.glide.abs() / VIBRATO_GLIDE_SLOPE).ceil() as usize).max(1); + self.glide_left = if self.glide == 0.0 { 0 } else { self.glide_len }; + self.shape = shape; + self.swing = swing; + } + let max = self.max_delay(); + for i in 0..n { + let mut d = swing * Self::shape_value(shape, self.lfo.phase(0.0)); + if self.glide_left > 0 { + d = (d + self.glide * self.glide_left as f32 / self.glide_len as f32).clamp(0.0, max); + self.glide_left -= 1; + } + self.last = d; + self.lfo.advance(rate, self.sr); + // The read interpolates in f64, so neighboring samples near the f32 limit with opposite + // signs do not overflow. + let d = if d.is_nan() { 0.0 } else { d.clamp(0.0, max) }; + let (di, frac) = (d.floor() as usize, f64::from(d - d.floor())); + for (ch, line) in self.lines.iter_mut().enumerate() { + // A non-finite sample is taken as silence. A channel the block leaves out is fed + // silence, so it holds none of its earlier audio when it comes back. + let dry = match channels.get(ch).filter(|_| ch < nch) { + Some(c) if c[i].is_finite() => c[i], + _ => 0.0, + }; + line.push(dry); + if ch < nch { + let (a, b) = (f64::from(line.tap(di)), f64::from(line.tap(di + 1))); + channels[ch][i] = (a + (b - a) * frac) as f32; + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + + const SR: f32 = 48000.0; + + fn ring(params: &[(&str, f32)], channels: usize) -> RingMod { + let mut r = RingMod::new(SR, channels); + for (id, v) in params { + assert!(r.set_param(id, *v), "{id}"); + } + r.reset(); + r + } + + /// Ring moves a tone to the sum and the difference of its frequency and the carrier's, each + /// at half the tone's amplitude, and leaves nothing at the tone's own frequency. + #[test] + fn ring_moves_a_tone_to_the_sum_and_difference_frequencies() { + let mut r = ring(&[("frequency", 300.0)], 1); + let mut x = sine(1000.0, 0.5, SR as f64, SR as usize, 0.0); + r.process(&mut [&mut x]); + for (f, want) in [(700.0, 0.25), (1300.0, 0.25), (1000.0, 0.0), (300.0, 0.0)] { + let a = tone_amplitude(&x, f, SR as f64); + assert!((a - want).abs() < 0.005, "{f} Hz: {a}, want {want}"); + } + } + + /// Resonator + repeats an impulse once per period of its frequency, each repeat lower by the + /// resonance, and Resonator - flips the sign of each repeat. + #[test] + fn resonators_repeat_an_impulse_once_per_period() { + for (effect, sign) in [(2.0, 1.0f32), (3.0, -1.0)] { + let mut r = ring(&[("effect", effect), ("frequency", 500.0), ("resonance", 80.0)], 1); + let mut x = vec![0.0f32; 1000]; + x[10] = 1.0; + r.process(&mut [&mut x]); + // 96 samples per period at 500 Hz. + for k in 0..8 { + let i = 10 + 96 * k; + let want = 0.2 * (sign * 0.8).powi(k as i32); + assert!((x[i] - want).abs() < 1e-5, "effect {effect}, repeat {k} at {i}: {}, want {want}", x[i]); + } + let others = x.iter().enumerate().filter(|(i, _)| *i < 10 || (*i - 10) % 96 != 0).fold(0.0f32, |m, (_, v)| m.max(v.abs())); + assert!(others < 1e-5, "effect {effect}: {others} between the repeats"); + } + } + + /// Frequency Mod delays the input by 2 samples to 2 samples plus 2 ms, swinging across the + /// whole range at the carrier's rate. + #[test] + fn frequency_mod_swings_the_delay_by_two_ms() { + let mut r = ring(&[("effect", 1.0), ("frequency", 440.0)], 1); + let slope = 1e-4f32; + let mut x: Vec = (0..4800).map(|i| i as f32 * slope).collect(); + r.process(&mut [&mut x]); + let delays: Vec = x.iter().enumerate().skip(200).map(|(i, y)| (i as f32 * slope - y) / slope).collect(); + let (lo, hi) = delays.iter().fold((f32::MAX, f32::MIN), |(lo, hi), d| (lo.min(*d), hi.max(*d))); + assert!((1.99..2.1).contains(&lo), "shortest delay {lo}"); + assert!((97.9..=98.01).contains(&hi), "longest delay {hi}"); + } + + /// With the envelope as the source, a steady input at full level moves the frequency up by + /// the depth: two octaves at 100 %. + #[test] + fn envelope_moves_the_frequency_up_with_the_level() { + let mut r = ring(&[("frequency", 100.0), ("mod_source", 1.0), ("mod_depth", 100.0)], 1); + let n = SR as usize; + let mut x = vec![1.0f32; n]; + r.process(&mut [&mut x]); + let tail = &x[n / 2..]; + assert!(tone_amplitude(tail, 400.0, SR as f64) > 0.99, "400 Hz: {}", tone_amplitude(tail, 400.0, SR as f64)); + assert!(tone_amplitude(tail, 100.0, SR as f64) < 0.01, "100 Hz: {}", tone_amplitude(tail, 100.0, SR as f64)); + } + + /// A resonator's tail covers the longest period the modulation reaches: four times as long at + /// full depth with the LFO or sample and hold, which move the frequency down two octaves, and + /// unchanged with the envelope, which moves it up only. + #[test] + fn resonator_tail_follows_the_lowest_frequency_the_modulation_reaches() { + let tail = |source: f32, depth: f32| { + ring(&[("effect", 2.0), ("frequency", 200.0), ("resonance", 90.0), ("mod_source", source), ("mod_depth", depth)], 1).tail_samples() as f32 + }; + let still = tail(0.0, 0.0); + for source in [0.0, 2.0] { + let ratio = tail(source, 100.0) / still; + assert!((ratio - 4.0).abs() < 0.01, "source {source}: {ratio}"); + } + assert_eq!(tail(1.0, 100.0), still); + } + + /// While the resonance ramps down to a new setting, the tail still covers the higher value, + /// and it shrinks to the new setting's tail once the ramp has ended. + #[test] + fn resonator_tail_covers_a_resonance_still_ramping_down() { + let mut r = ring(&[("effect", 2.0), ("frequency", 200.0), ("resonance", 95.0)], 1); + let high = r.tail_samples(); + assert!(r.set_param("resonance", 0.0)); + assert_eq!(r.tail_samples(), high); + let mut x = vec![0.0f32; 4800]; + r.process(&mut [&mut x]); + let low = ring(&[("effect", 2.0), ("frequency", 200.0), ("resonance", 0.0)], 1).tail_samples(); + assert_eq!(r.tail_samples(), low); + assert!(low * 10 < high, "{low} vs {high}"); + } + + /// At a low sample rate the resonators ring at the highest frequency processing reaches, not + /// at the setting above it, and the tail covers that ring. A setting below that frequency + /// keeps the tail of its own period. + #[test] + fn resonator_tail_covers_a_frequency_held_at_the_rate_limit() { + let sr = 1000.0f32; + let mut r = RingMod::new(sr, 1); + for (id, v) in [("effect", 2.0), ("frequency", 5000.0), ("resonance", 95.0)] { + assert!(r.set_param(id, v), "{id}"); + } + r.reset(); + let tail = r.tail_samples(); + let mut x = vec![0.0f32; tail + 200]; + x[0] = 1.0; + r.process(&mut [&mut x]); + let after = x[tail + 1..].iter().fold(0.0f32, |m, v| m.max(v.abs())); + assert!(after <= 1e-3 * x[0].abs(), "tail {tail}: {after} after it, against {} at the impulse", x[0]); + let mut below = RingMod::new(sr, 1); + for (id, v) in [("effect", 2.0), ("frequency", 400.0), ("resonance", 95.0)] { + assert!(below.set_param(id, v), "{id}"); + } + below.reset(); + assert_eq!(below.tail_samples(), echo_tail(1000.0 / 400.0, 0.95, sr)); + } + + /// Frequency Mod reads between two of the largest samples of opposite sign without + /// overflowing. + #[test] + fn frequency_mod_reads_between_huge_samples_of_opposite_sign() { + let mut r = ring(&[("effect", 1.0), ("frequency", 500.0)], 1); + let mut x = vec![0.0f32; 200]; + x[6] = -f32::MAX; + x[7] = f32::MAX; + r.process(&mut [&mut x]); + assert!(x.iter().all(|v| v.is_finite()), "{:?}", x.iter().position(|v| !v.is_finite())); + } + + #[test] + fn frequency_mod_full_mix_keeps_a_small_delayed_sample() { + let mut r = ring(&[("effect", 1.0), ("frequency", 500.0), ("mix", 100.0)], 1); + let mut x = vec![0.5f32; 600]; + x[500] = f32::MAX; + r.process(&mut [&mut x]); + assert_eq!(x[500], 0.5, "the delayed sample was lost at full mix"); + } + + /// Mixing a dry and a wet sample of opposite sign at the largest level stays finite: a mix of + /// 0 gives the input, and every mix gives the result at a level of 1 scaled up. + #[test] + fn mixing_huge_samples_of_opposite_sign_stays_finite() { + for mix in [0.0f32, 50.0, 100.0] { + let run = |level: f32| { + let mut r = ring(&[("frequency", 5000.0), ("mix", mix)], 1); + let mut x = vec![level; 480]; + r.process(&mut [&mut x]); + x + }; + let (huge, unit) = (run(f32::MAX), run(1.0)); + assert!(huge.iter().all(|v| v.is_finite()), "mix {mix}"); + for (i, (h, u)) in huge.iter().zip(&unit).enumerate() { + let want = *u as f64 * f32::MAX as f64; + assert!((*h as f64 - want).abs() <= 1e-5 * f32::MAX as f64, "mix {mix}, sample {i}: {h} against {want}"); + } + if mix == 0.0 { + assert!(huge.iter().all(|v| *v == f32::MAX)); + } + } + } + + /// At a mix of 100% the output is the wet sample even when the dry sample is far larger. + #[test] + fn full_mix_keeps_a_small_wet_sample_beside_a_huge_dry_one() { + let mut c = crush(&[("mix", 100.0), ("bits", 16.0), ("rate_divide", 4.0)], 1); + let mut y = vec![0.5, f32::MAX, f32::MAX, f32::MAX, 0.25]; + c.process(&mut [&mut y]); + assert_eq!(y[1], 0.5, "the held sample was lost at full mix: {y:?}"); + } + + /// Raising the sample-and-hold rate takes effect within one new hold, instead of after the + /// value already held at the slow rate runs out. + #[test] + fn sample_and_hold_follows_a_faster_rate_at_once() { + let mut r = ring(&[("mod_source", 2.0), ("mod_rate", 0.05), ("mod_depth", 100.0)], 1); + let mut x = vec![0.0f32; 480]; + r.process(&mut [&mut x]); + let first = r.held; + assert!(r.set_param("mod_rate", 20.0)); + // A hold lasts 2,400 samples at 20 Hz and 960,000 at 0.05 Hz. + let mut x = vec![0.0f32; 4800]; + r.process(&mut [&mut x]); + assert_ne!(r.held, first, "the slow hold kept its value"); + } + + /// At a mix of 0 every effect passes the input through unchanged. + #[test] + fn mix_zero_passes_the_input_through() { + for effect in 0..4 { + let mut r = ring(&[("effect", effect as f32), ("mix", 0.0), ("mod_depth", 50.0)], 2); + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + let (mut l, mut rr) = (x.clone(), x.clone()); + r.process(&mut [&mut l, &mut rr]); + assert!(l == x && rr == x, "effect {effect}"); + } + } + + /// A block that leaves a channel out feeds it silence, so a resonator's ring on that channel + /// keeps decaying instead of waiting for the channel to come back. + #[test] + fn channels_a_block_leaves_out_are_fed_silence() { + let p = [("effect", 2.0), ("frequency", 100.0), ("resonance", 90.0)]; + let (mut left_out, mut silent) = (ring(&p, 2), ring(&p, 2)); + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + for r in [&mut left_out, &mut silent] { + let (mut l, mut rr) = (x.clone(), x.clone()); + r.process(&mut [&mut l, &mut rr]); + } + for _ in 0..10 { + let mut l = vec![0.0f32; 480]; + left_out.process(&mut [&mut l]); + let (mut l, mut rr) = (vec![0.0f32; 480], vec![0.0f32; 480]); + silent.process(&mut [&mut l, &mut rr]); + } + let (mut la, mut ra) = (vec![0.0f32; 4800], vec![0.0f32; 4800]); + left_out.process(&mut [&mut la, &mut ra]); + let (mut lb, mut rb) = (vec![0.0f32; 4800], vec![0.0f32; 4800]); + silent.process(&mut [&mut lb, &mut rb]); + assert!(rms(&rb) > 1e-3, "the ring has already died out: {}", rms(&rb)); + let worst = ra.iter().zip(&rb).fold(0.0f32, |m, (a, b)| m.max((a - b).abs())); + assert!(worst < 1e-6, "the left-out channel differs by {worst}"); + assert_eq!(la, lb); + } + + /// A non-finite input sample comes out as silence and leaves no NaN in the resonator. + #[test] + fn a_non_finite_sample_leaves_the_state_finite() { + for effect in 0..4 { + let mut r = ring(&[("effect", effect as f32), ("resonance", 95.0)], 1); + let mut x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + x[100] = f32::NAN; + x[200] = f32::INFINITY; + r.process(&mut [&mut x]); + assert!(x.iter().all(|v| v.is_finite()), "effect {effect}"); + } + } + + /// An empty block does not take up a change of effect, so a resonator switched away from and + /// back before the next sample keeps its ring. + #[test] + fn an_empty_block_keeps_the_resonator_ring() { + let p = [("effect", 2.0), ("frequency", 500.0), ("resonance", 80.0)]; + let (mut r, mut still) = (ring(&p, 1), ring(&p, 1)); + for f in [&mut r, &mut still] { + let mut x = vec![0.0f32; 50]; + x[10] = 1.0; + f.process(&mut [&mut x]); + } + assert!(r.set_param("effect", 0.0)); + let mut empty: [f32; 0] = []; + r.process(&mut [&mut empty[..]]); + r.process(&mut []); + assert!(r.set_param("effect", 2.0)); + let (mut a, mut b) = (vec![0.0f32; 500], vec![0.0f32; 500]); + r.process(&mut [&mut a]); + still.process(&mut [&mut b]); + assert!(rms(&b) > 1e-3, "the ring has already died out"); + assert_eq!(a, b); + } + + /// Neighboring samples at the f32 limit with opposite signs come out finite from every effect + /// at every mix, through Frequency Mod's fractional and whole-sample reads, and a mix of 0 + /// passes them through unchanged. + #[test] + fn samples_at_the_f32_limit_stay_finite() { + let edge: Vec = (0..4800).map(|i| if i % 2 == 0 { f32::MAX } else { -f32::MAX }).collect(); + for effect in 0..4 { + for mix in [0.0, 50.0, 100.0] { + let mut r = ring(&[("effect", effect as f32), ("frequency", 5000.0), ("mix", mix)], 1); + let mut y = edge.clone(); + r.process(&mut [&mut y]); + assert!(y.iter().all(|v| v.is_finite()), "effect {effect}, mix {mix}"); + if mix == 0.0 { + assert_eq!(y, edge, "effect {effect}"); + } + } + } + // At 48 kHz Frequency Mod's first read is 50 samples back, a whole number, and the next + // ones fall between samples. + let mut r = ring(&[("effect", 1.0)], 1); + let mut y = edge.clone(); + r.process(&mut [&mut y]); + assert!(y[60..].iter().any(|v| v.abs() > 1e30 && v.abs() < f32::MAX), "no fractional read near the limit"); + } + + fn crush(params: &[(&str, f32)], channels: usize) -> Bitcrusher { + let mut c = Bitcrusher::new(SR, channels); + for (id, v) in params { + assert!(c.set_param(id, *v), "{id}"); + } + c.reset(); + c + } + + /// Indices of the samples where the output changes, with the first sample counted. + fn changes(x: &[f32]) -> Vec { + (0..x.len()).filter(|&i| i == 0 || x[i] != x[i - 1]).collect() + } + + /// Every output sample is the multiple of `2^(1 - bits)` nearest the input, and silence stays + /// silence. + #[test] + fn bitcrusher_rounds_to_the_word_length() { + for (bits, step) in [(1.0, 1.0f32), (3.0, 0.25), (5.5, 2f32.powf(-4.5))] { + let mut c = crush(&[("bits", bits), ("rate_divide", 1.0)], 1); + let x: Vec = (0..2000).map(|i| -1.0 + i as f32 / 1000.0).collect(); + let mut y = x.clone(); + c.process(&mut [&mut y]); + for (a, b) in x.iter().zip(&y) { + let k = b / step; + assert!((k - k.round()).abs() < 1e-3, "bits {bits}: {b} is not a multiple of {step}"); + assert!((a - b).abs() <= step / 2.0 + 1e-6, "bits {bits}: {a} became {b}"); + } + let mut z = vec![0.0f32; 480]; + c.process(&mut [&mut z]); + assert!(z.iter().all(|v| *v == 0.0), "bits {bits}"); + } + } + + /// The input is taken once every `rate_divide` samples and held: a whole value holds each + /// sample for exactly that many samples, and 2.5 alternates holds of 3 and 2. + #[test] + fn bitcrusher_holds_each_sample_for_the_rate_divide() { + let x: Vec = (0..200).map(|i| (i + 1) as f32 / 1024.0).collect(); + for (divide, want) in [(1.0, vec![1usize]), (5.0, vec![5]), (2.5, vec![3, 2])] { + let mut c = crush(&[("bits", 16.0), ("rate_divide", divide)], 1); + let mut y = x.clone(); + c.process(&mut [&mut y]); + let mut expected = vec![0usize]; + while let Some(&last) = expected.last() { + let next = last + want[(expected.len() - 1) % want.len()]; + if next >= x.len() { + break; + } + expected.push(next); + } + assert_eq!(changes(&y), expected, "divide {divide}"); + assert!(expected.iter().all(|&i| y[i] == x[i]), "divide {divide}: a hold does not start with the input"); + } + } + + /// A shorter rate divide cuts the hold in progress short, and the holds after it have the new + /// length from the first one on. + #[test] + fn bitcrusher_follows_a_shorter_hold_at_once() { + let mut c = crush(&[("bits", 16.0), ("rate_divide", 50.0)], 1); + let mut a: Vec = (0..10).map(|i| (i + 1) as f32 / 1024.0).collect(); + c.process(&mut [&mut a]); + assert!(c.set_param("rate_divide", 2.0)); + let input: Vec = (10..40).map(|i| (i + 1) as f32 / 1024.0).collect(); + let mut b = input.clone(); + c.process(&mut [&mut b]); + // `changes` counts the first sample whatever it holds, so the capture is checked apart. + assert_eq!(b[0], input[0], "the hold in progress was not cut short"); + assert_eq!(changes(&b), (0..30).step_by(2).collect::>()); + assert!((0..30).step_by(2).all(|i| b[i] == input[i])); + } + + /// A new Bits rounds the sample being held again from the next sample on, from the input it + /// took rather than from its rounded value, and the hold keeps its length. + #[test] + fn bitcrusher_rounds_the_hold_in_progress_at_new_bits() { + let mut c = crush(&[("bits", 16.0), ("rate_divide", 4.0)], 1); + let mut a = [0.3f32]; + c.process(&mut [&mut a]); + assert!((a[0] - 0.3).abs() < 1e-4); + assert!(c.set_param("bits", 1.0)); + let mut b = [0.9f32]; + c.process(&mut [&mut b]); + assert_eq!(b[0], 0.0, "1 bit did not round the held 0.3 to 0"); + assert!(c.set_param("bits", 16.0)); + let mut d = [0.9f32, 0.9, 0.7]; + c.process(&mut [&mut d]); + assert!((d[0] - 0.3).abs() < 1e-4 && d[0] == d[1], "the held input was lost: {d:?}"); + assert_eq!(changes(&[a[0], b[0], d[0], d[1], d[2]]), vec![0, 1, 2, 4], "the hold did not keep its length"); + } + + /// A channel left out of one block of a single sample, between two captures, holds silence + /// when it comes back instead of the sample it held before. + #[test] + fn bitcrusher_clears_a_channel_left_out_for_one_sample() { + let mut c = crush(&[("bits", 8.0), ("rate_divide", 4.0)], 2); + let (mut l, mut r) = ([1.0f32], [1.0f32]); + c.process(&mut [&mut l, &mut r]); + assert_eq!(r[0], 1.0); + let mut l = [0.0f32]; + c.process(&mut [&mut l]); + let (mut l, mut r) = ([0.0f32; 2], [0.0f32; 2]); + c.process(&mut [&mut l, &mut r]); + assert_eq!(r, [0.0, 0.0], "the channel came back with its earlier hold"); + assert_eq!(l, [1.0, 1.0], "the channel kept in the block lost its hold"); + } + + /// A held sample sounds for no longer than the tail reports after the input ends. + #[test] + fn bitcrusher_tail_covers_the_hold() { + for divide in [1.0, 4.0, 7.5, 50.0] { + let mut c = crush(&[("bits", 4.0), ("rate_divide", divide)], 1); + let tail = c.tail_samples(); + let mut x = vec![0.0f32; 200]; + x[0] = 0.5; + c.process(&mut [&mut x]); + let last = x.iter().rposition(|v| *v != 0.0).unwrap_or(0); + assert_eq!(last, tail, "divide {divide}"); + } + } + + /// A block that leaves a channel out feeds it silence, so the channel holds none of its earlier + /// audio when it comes back. + #[test] + fn bitcrusher_feeds_channels_a_block_leaves_out_silence() { + let p = [("bits", 6.0), ("rate_divide", 7.0)]; + let (mut left_out, mut silent) = (crush(&p, 2), crush(&p, 2)); + let x = sine(220.0, 0.5, SR as f64, 4801, 0.0); + for c in [&mut left_out, &mut silent] { + let (mut l, mut r) = (x.clone(), x.clone()); + c.process(&mut [&mut l, &mut r]); + } + let mut l = x[..10].to_vec(); + left_out.process(&mut [&mut l]); + let (mut l, mut r) = (x[..10].to_vec(), vec![0.0f32; 10]); + silent.process(&mut [&mut l, &mut r]); + let (mut la, mut ra) = (vec![0.0f32; 480], vec![0.0f32; 480]); + left_out.process(&mut [&mut la, &mut ra]); + let (mut lb, mut rb) = (vec![0.0f32; 480], vec![0.0f32; 480]); + silent.process(&mut [&mut lb, &mut rb]); + assert_eq!(ra, rb); + assert_eq!(la, lb); + } + + /// At a mix of 0 the input passes through unchanged, and a non-finite sample comes out finite. + #[test] + fn bitcrusher_mix_zero_and_non_finite_input() { + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + let mut c = crush(&[("mix", 0.0), ("bits", 2.0), ("rate_divide", 9.0)], 2); + let (mut l, mut r) = (x.clone(), x.clone()); + c.process(&mut [&mut l, &mut r]); + assert!(l == x && r == x); + let mut c = crush(&[("bits", 2.0), ("rate_divide", 3.0)], 1); + let mut y = x.clone(); + y[99] = f32::NAN; + y[200] = f32::INFINITY; + c.process(&mut [&mut y]); + assert!(y.iter().all(|v| v.is_finite())); + } + + /// Finite samples at the f32 limit, held while the input swings to the other limit, come out + /// finite at every mix. + #[test] + fn bitcrusher_keeps_samples_at_the_f32_limit_finite() { + for mix in [0.0, 50.0, 100.0] { + for bits in [1.0, 7.3, 16.0] { + let mut c = crush(&[("mix", mix), ("bits", bits), ("rate_divide", 3.0)], 1); + let mut y: Vec = (0..30).map(|i| if i % 2 == 0 { f32::MAX } else { -f32::MAX }).collect(); + c.process(&mut [&mut y]); + assert!(y.iter().all(|v| v.is_finite()), "mix {mix}, bits {bits}: {y:?}"); + } + } + } + + fn tremolo(params: &[(&str, f32)], channels: usize) -> Tremolo { + let mut t = Tremolo::new(SR, channels); + for (id, v) in params { + assert!(t.set_param(id, *v), "{id}"); + } + t.reset(); + t + } + + /// The gain of a tremolo over `n` samples, read from a constant input of 1. + fn gains(t: &mut Tremolo, n: usize) -> Vec { + let mut x = vec![1.0f32; n]; + t.process(&mut [&mut x]); + x + } + + /// At full depth the gain is 1 at the start of each cycle and 0 at its middle. The sine and the + /// triangle follow their curves, the square holds each level for most of half a cycle, and + /// half depth swings the gain between 1 and 1/2. + #[test] + fn tremolo_gain_follows_the_shape() { + let period = 9600; + for shape in 0..3 { + let mut t = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", shape as f32)], 1); + let g = gains(&mut t, 2 * period); + for (i, v) in g.iter().enumerate() { + let p = (i % period) as f64 / period as f64; + let want = match shape { + 0 => 0.5 + 0.5 * (TAU * p).cos(), + 1 => 1.0 - 2.0 * p.min(1.0 - p), + _ if !(0.24..=0.26).contains(&p) && !(0.74..=0.76).contains(&p) => { + if (0.25..0.75).contains(&p) { + 0.0 + } else { + 1.0 + } + } + _ => continue, + }; + assert!((f64::from(*v) - want).abs() < 1e-4, "shape {shape} at {i}: {v}, want {want}"); + } + let mut t = tremolo(&[("rate", 5.0), ("depth", 50.0), ("shape", shape as f32)], 1); + let g = gains(&mut t, period); + let (lo, hi) = g.iter().fold((f32::MAX, f32::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + assert!((lo - 0.5).abs() < 1e-4 && (hi - 1.0).abs() < 1e-6, "shape {shape}: {lo} ..= {hi}"); + } + } + + /// The square's edges are 2 ms raised-cosine ramps at every rate, centered on the quarter and + /// three-quarter points of the cycle. + #[test] + fn tremolo_square_edges_do_not_click() { + let edge = (0.002 * SR) as usize; + for rate in [0.1f32, 1.0, 20.0] { + let mut t = tremolo(&[("rate", rate), ("depth", 100.0), ("shape", 2.0)], 1); + let g = gains(&mut t, (SR / rate) as usize); + let worst = g.windows(2).map(|w| (w[1] - w[0]).abs()).fold(0.0f32, f32::max); + // A raised cosine over `edge` samples moves at most pi / 2 / edge per sample. + assert!(worst <= std::f32::consts::FRAC_PI_2 / edge as f32 * 1.01, "rate {rate}: step {worst}"); + let moving = g.windows(2).filter(|w| w[1] != w[0]).count(); + assert!(moving <= 2 * edge + 2, "rate {rate}: the gain moves on {moving} samples"); + let quarter = (SR / rate / 4.0) as usize; + assert!((g[quarter] - 0.5).abs() < 0.02, "rate {rate}: {} at the quarter point", g[quarter]); + } + } + + /// A new rate takes effect from the next sample, with the phase kept. + #[test] + fn tremolo_rate_change_keeps_the_phase() { + let mut t = tremolo(&[("rate", 5.0), ("depth", 100.0)], 1); + let a = gains(&mut t, 2400); + assert!(t.set_param("rate", 10.0)); + let b = gains(&mut t, 2400); + // A quarter of a cycle at 5 Hz, then a quarter at 10 Hz ends at the middle of the cycle. + assert!((a[2399] - 0.5).abs() < 1e-3 && (b[0] - a[2399]).abs() < 1e-3, "{} then {}", a[2399], b[0]); + assert!(b[1199] < 1e-3 && b[1201] < 1e-3, "{} {}", b[1199], b[1201]); + } + + /// A change of shape glides from where the old shape was to the new one over 20 ms, so the + /// gain does not jump, and the new shape is followed exactly afterward. + #[test] + fn tremolo_shape_change_glides() { + let glide = (0.02 * SR) as usize; + let mut t = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", 0.0)], 1); + let mut s = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", 2.0)], 1); + // 2,000 samples in, the sine has the gain at 0.63 and the square at 1. + let a = gains(&mut t, 2000); + gains(&mut s, 2000); + assert!(t.set_param("shape", 2.0)); + let b = gains(&mut t, 2 * glide); + let want = gains(&mut s, 2 * glide); + // The square's own edge moves the gain by up to pi / 2 / 96 (0.0164) per sample. + let step = (b[0] - a[1999]).abs(); + assert!(step < 0.02, "the gain jumped by {step}"); + assert!(b.windows(2).all(|w| (w[1] - w[0]).abs() < 0.02), "the glide jumped"); + assert_eq!(b[glide..], want[glide..]); + assert!((b[0] - want[0]).abs() > 0.2, "{} {}", b[0], want[0]); + } + + /// A shape that only an empty block saw does not restart a glide in progress: the glide goes + /// on as if the shape had not changed. + #[test] + fn tremolo_empty_block_keeps_the_glide() { + let glide = (0.02 * SR) as usize; + let mut t = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", 0.0)], 1); + let mut s = tremolo(&[("rate", 5.0), ("depth", 100.0), ("shape", 0.0)], 1); + for fx in [&mut t, &mut s] { + gains(fx, 2000); + assert!(fx.set_param("shape", 2.0)); + gains(fx, 100); + } + assert!(t.set_param("shape", 1.0)); + let mut empty: [f32; 0] = []; + t.process(&mut [&mut empty[..]]); + assert!(t.set_param("shape", 2.0)); + assert_eq!(gains(&mut t, 2 * glide), gains(&mut s, 2 * glide)); + } + + /// A new rate moves the square's edges to a new share of the cycle. Changed just before an + /// edge, from 0.1 Hz (where the edge is still ahead) to 20 Hz (where the phase is inside it), + /// the gain glides instead of jumping. + #[test] + fn tremolo_square_rate_change_glides() { + let mut t = tremolo(&[("rate", 0.1), ("depth", 100.0), ("shape", 2.0)], 1); + // Phase 0.249 at 0.1 Hz. + let a = gains(&mut t, 119_520); + assert_eq!(a[119_519], 1.0); + assert!(t.set_param("rate", 20.0)); + let b = gains(&mut t, 2000); + let step = (b[0] - a[119_519]).abs(); + assert!(step < 0.02, "the gain jumped by {step}"); + assert!(b.windows(2).all(|w| (w[1] - w[0]).abs() < 0.02), "the glide jumped"); + } + + /// At zero depth the input passes unchanged, a non-finite sample comes out as silence, and a + /// channel past the configured count is left alone. + #[test] + fn tremolo_depth_zero_non_finite_and_extra_channels() { + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + let mut t = tremolo(&[("depth", 0.0), ("shape", 2.0)], 2); + let (mut l, mut r) = (x.clone(), x.clone()); + t.process(&mut [&mut l, &mut r]); + assert!(l == x && r == x); + let mut t = tremolo(&[("depth", 100.0)], 1); + let (mut l, mut r) = (x.clone(), x.clone()); + l[99] = f32::NAN; + l[200] = f32::INFINITY; + t.process(&mut [&mut l, &mut r]); + assert!(l[99] == 0.0 && l[200] == 0.0 && l.iter().all(|v| v.is_finite())); + assert_eq!(r, x); + } + + /// A glide keeps the LFO value within 0 ..= 1, so the gain stays between 1 - depth and 1 and + /// never inverts the input, even when the new curve moves away from the glide's offset. + #[test] + fn tremolo_glide_keeps_the_gain_in_range() { + for (from, to) in [(1.0, 2.0), (2.0, 1.0), (0.0, 2.0), (2.0, 0.0)] { + for start in [240, 480, 1680, 1900] { + let mut t = tremolo(&[("rate", 20.0), ("depth", 100.0), ("shape", from)], 1); + gains(&mut t, start); + assert!(t.set_param("shape", to)); + let g = gains(&mut t, 2400); + assert!(g.iter().all(|v| (0.0..=1.0).contains(v)), "{from} to {to} at {start}: {g:?}"); + } + } + } + + /// An empty block does not take up a change of shape, so a shape changed and restored before + /// the next sample starts no glide. + #[test] + fn tremolo_empty_block_starts_no_glide() { + let p = [("rate", 5.0), ("depth", 100.0), ("shape", 0.0)]; + let (mut t, mut still) = (tremolo(&p, 1), tremolo(&p, 1)); + gains(&mut t, 1000); + gains(&mut still, 1000); + assert!(t.set_param("shape", 1.0)); + let mut empty: [f32; 0] = []; + t.process(&mut [&mut empty[..]]); + t.process(&mut []); + assert!(t.set_param("shape", 0.0)); + assert_eq!(gains(&mut t, 2000), gains(&mut still, 2000)); + } + + fn vibrato(params: &[(&str, f32)], channels: usize) -> Vibrato { + let mut v = Vibrato::new(SR, channels); + for (id, x) in params { + assert!(v.set_param(id, *x), "{id}"); + } + v.reset(); + v + } + + /// Slope of the ramp the delay tests feed in, per sample. + const RAMP: f32 = 1e-3; + /// Most the delay moves per sample during a glide at a depth of 100 cents: the curve's + /// steepest slope plus the glide's, with room for the rounding of the ramp. + const GLIDE_STEP: f32 = 0.0562 + 1.0 / 32.0 + 0.002; + + /// The delay of a vibrato over `n` samples, read from a ramp that starts at `start` samples. + fn delays(v: &mut Vibrato, start: usize, n: usize) -> Vec { + let x: Vec = (start..start + n).map(|i| i as f32 * RAMP).collect(); + let mut y = x.clone(); + v.process(&mut [&mut y]); + x.iter().zip(&y).map(|(a, b)| (a - b) / RAMP).collect() + } + + /// Largest change of the delay between neighboring samples, averaged over 2 * `k` samples to + /// smooth out the rounding of the ramp. + fn steepest(d: &[f32], k: usize) -> f32 { + (k..d.len() - k).map(|i| (d[i + k] - d[i - k]).abs() / (2 * k) as f32).fold(0.0, f32::max) + } + + /// The delay is 0 at the start of each cycle and follows the sine or the triangle, and its + /// steepest slope lowers the pitch by the depth: 100 cents at a depth of 100 for both shapes. + #[test] + fn vibrato_delay_follows_the_shape_and_the_depth() { + let d_max = 1.0 - 2f32.powf(-100.0 / 1200.0); + for (shape, rate) in [(0, 6.0f32), (1, 6.0), (0, 1.0), (1, 14.0)] { + let mut v = vibrato(&[("rate", rate), ("depth", 100.0), ("shape", shape as f32)], 1); + let period = (SR / rate) as usize; + let swing = v.swing; + let d = delays(&mut v, 0, 2 * period); + for (i, got) in d.iter().enumerate() { + let p = (i as f64 * f64::from(rate) / f64::from(SR)).fract(); + let want = swing * if shape == 1 { uni_tri(p) } else { uni_sine(p) }; + assert!((got - want).abs() < 0.05, "shape {shape} at {rate} Hz, sample {i}: {got}, want {want}"); + } + assert!(d[0].abs() < 0.05 && d[period].abs() < 0.05, "shape {shape}: {} {}", d[0], d[period]); + let slope = steepest(&d, 40); + let cents = 1200.0 * (1.0 - slope).log2(); + assert!((cents + 100.0).abs() < 2.0, "shape {shape} at {rate} Hz: the pitch falls by {cents} cents"); + assert!((slope - d_max).abs() < 0.002, "shape {shape} at {rate} Hz: slope {slope}"); + } + } + + /// A lower depth set at the middle of the cycle, where the delay is longest, glides the delay + /// down to the new curve without jumping, and afterward the output matches a vibrato that had + /// the new depth from the start. + #[test] + fn vibrato_depth_change_glides_to_the_new_curve() { + let half = 4000; + let mut v = vibrato(&[("rate", 6.0), ("depth", 100.0)], 1); + let mut w = vibrato(&[("rate", 6.0), ("depth", 10.0)], 1); + let a = delays(&mut v, 0, half); + delays(&mut w, 0, half); + assert!(v.set_param("depth", 10.0)); + let b = delays(&mut v, half, 16_000); + let want = delays(&mut w, half, 16_000); + // The new curve moves by up to 0.0058 per sample, and the glide by 1/32 more. + let step = (b[0] - a[half - 1]).abs(); + assert!(step < 0.04, "the delay jumped by {step}"); + assert!(b.windows(2).all(|p| (p[1] - p[0]).abs() < 0.04), "the glide moved too fast"); + assert!(b[100] > want[100] + 100.0, "{} {}", b[100], want[100]); + let glide = v.glide_len; + assert!(glide < b.len() / 2, "the glide has not ended: {glide}"); + assert_eq!(b[glide..], want[glide..]); + } + + /// A new rate takes effect from the next sample with the phase kept, the delay glides to the + /// new curve without jumping, and afterward follows it. + #[test] + fn vibrato_rate_change_keeps_the_phase_and_glides() { + let mut v = vibrato(&[("rate", 6.0), ("depth", 100.0)], 1); + // A quarter of a cycle at 6 Hz. + let a = delays(&mut v, 0, 2000); + assert!(v.set_param("rate", 3.0)); + let swing = v.swing_len(); + let b = delays(&mut v, 2000, 12000); + let step = (b[0] - a[1999]).abs(); + assert!(step < GLIDE_STEP, "the delay jumped by {step}"); + assert!(b.windows(2).all(|p| (p[1] - p[0]).abs() < GLIDE_STEP), "the glide moved too fast"); + let glide = v.glide_len; + assert!(glide < b.len() / 2, "the glide has not ended: {glide}"); + for (k, got) in b.iter().enumerate().skip(glide) { + let p = (0.25 + k as f64 * 3.0 / f64::from(SR)).fract(); + let want = swing * uni_sine(p); + assert!((got - want).abs() < 0.05, "sample {k}: {got}, want {want}"); + } + } + + /// A change of shape glides from the last delay to the new curve without jumping. + #[test] + fn vibrato_shape_change_glides() { + for (from, to) in [(0.0, 1.0), (1.0, 0.0)] { + for start in [600, 2000, 4000, 7000] { + let mut v = vibrato(&[("rate", 6.0), ("depth", 100.0), ("shape", from)], 1); + let a = delays(&mut v, 0, start); + assert!(v.set_param("shape", to)); + let b = delays(&mut v, start, 8000); + assert!((b[0] - a[start - 1]).abs() < GLIDE_STEP, "{from} to {to} at {start}: jumped"); + assert!(b.windows(2).all(|p| (p[1] - p[0]).abs() < GLIDE_STEP), "{from} to {to} at {start}: the glide moved too fast"); + assert!(b.iter().all(|d| *d > -0.05), "{from} to {to} at {start}: the delay went below 0"); + } + } + } + + /// An empty block does not take up a change of depth, so a depth changed and restored before + /// the next sample starts no glide. + #[test] + fn vibrato_empty_block_starts_no_glide() { + let p = [("rate", 6.0), ("depth", 100.0)]; + let (mut v, mut still) = (vibrato(&p, 1), vibrato(&p, 1)); + delays(&mut v, 0, 1000); + delays(&mut still, 0, 1000); + assert!(v.set_param("depth", 10.0)); + let mut empty: [f32; 0] = []; + v.process(&mut [&mut empty[..]]); + v.process(&mut []); + assert!(v.set_param("depth", 100.0)); + assert_eq!(delays(&mut v, 1000, 4000), delays(&mut still, 1000, 4000)); + } + + /// After the input ends, the output falls silent within the reported tail, for every shape and + /// for a depth lowered just before the end, while the delay is still gliding down. + #[test] + fn vibrato_tail_covers_the_delay() { + for (rate, depth, shape, lower) in + [(1.0f32, 100.0f32, 1.0f32, false), (14.0, 50.0, 0.0, false), (1.0, 100.0, 1.0, true), (2.0, 100.0, 0.0, true)] + { + for len in [5000usize, 12000, 24000] { + let mut v = vibrato(&[("rate", rate), ("depth", depth), ("shape", shape)], 1); + let mut x = vec![0.5f32; len]; + v.process(&mut [&mut x]); + if lower { + assert!(v.set_param("depth", 0.0)); + } + let tail = v.tail_samples(); + let mut z = vec![0.0f32; 96_000]; + v.process(&mut [&mut z]); + let last = z.iter().rposition(|s| *s != 0.0).map_or(0, |i| i + 1); + assert!(last <= tail, "{rate} Hz {depth} ct shape {shape} lower {lower} len {len}: sound until {last} after a tail of {tail}"); + } + } + } + + /// At zero depth the input passes unchanged, a non-finite sample comes out as silence, and a + /// channel past the configured count is left alone. + #[test] + fn vibrato_depth_zero_non_finite_and_extra_channels() { + let x = sine(220.0, 0.5, SR as f64, 4800, 0.0); + let mut v = vibrato(&[("depth", 0.0), ("shape", 1.0)], 2); + let (mut l, mut r) = (x.clone(), x.clone()); + v.process(&mut [&mut l, &mut r]); + assert!(l == x && r == x); + let mut v = vibrato(&[("depth", 0.0)], 1); + let (mut l, mut r) = (x.clone(), x.clone()); + l[99] = f32::NAN; + l[200] = f32::INFINITY; + v.process(&mut [&mut l, &mut r]); + assert!(l[99] == 0.0 && l[200] == 0.0 && l.iter().all(|s| s.is_finite())); + assert_eq!(r, x); + let mut v = vibrato(&[("depth", 100.0)], 1); + let mut l = x.clone(); + l[99] = f32::NAN; + v.process(&mut [&mut l]); + assert!(l.iter().all(|s| s.is_finite())); + // Neighboring samples at the f32 limit with opposite signs stay finite. + let edge: Vec = (0..4800).map(|i| if i % 2 == 0 { f32::MAX } else { -f32::MAX }).collect(); + for depth in [0.0, 100.0] { + let mut v = vibrato(&[("depth", depth)], 1); + let mut l = edge.clone(); + v.process(&mut [&mut l]); + assert!(l.iter().all(|s| s.is_finite()), "depth {depth}"); + if depth == 0.0 { + assert_eq!(l, edge); + } + } + } + + /// A block that leaves a channel out feeds it silence, so the channel holds none of its earlier + /// audio when it comes back. + #[test] + fn vibrato_feeds_channels_a_block_leaves_out_silence() { + let p = [("rate", 1.0), ("depth", 100.0), ("shape", 1.0)]; + let (mut left_out, mut silent) = (vibrato(&p, 2), vibrato(&p, 2)); + let x = sine(220.0, 0.5, SR as f64, 12_000, 0.0); + for v in [&mut left_out, &mut silent] { + let (mut l, mut r) = (x.clone(), x.clone()); + v.process(&mut [&mut l, &mut r]); + } + let mut l = x[..2000].to_vec(); + left_out.process(&mut [&mut l]); + let (mut l, mut r) = (x[..2000].to_vec(), vec![0.0f32; 2000]); + silent.process(&mut [&mut l, &mut r]); + let (mut la, mut ra) = (x[..4800].to_vec(), x[..4800].to_vec()); + left_out.process(&mut [&mut la, &mut ra]); + let (mut lb, mut rb) = (x[..4800].to_vec(), x[..4800].to_vec()); + silent.process(&mut [&mut lb, &mut rb]); + assert_eq!(ra, rb); + assert_eq!(la, lb); + } +} diff --git a/crates/audio-dsp/src/effects/stft.rs b/crates/audio-dsp/src/effects/stft.rs index c4b9ed7070..14d1003dbb 100644 --- a/crates/audio-dsp/src/effects/stft.rs +++ b/crates/audio-dsp/src/effects/stft.rs @@ -402,7 +402,7 @@ mod tests { #[test] fn paired_effects_match_mono_on_transients() { use crate::AudioEffect; - use crate::effects::{DeNoise, DeReverb, FftFilter, PitchShifter}; + use crate::effects::{DeNoise, DeReverb, FftFilter, NoiseSuppression, PitchShifter}; const SR: f32 = 48_000.0; let len = 48_000; let material = |f: f64, amp: f32, phase: f64, click_every: usize, click_at: usize, noise: f32, seed: u64| -> Vec { @@ -427,6 +427,7 @@ mod tests { "DeReverb" => Box::new(DeReverb::new(SR, ch)), "FftFilter" => Box::new(FftFilter::new(SR, ch)), "DeNoise" => Box::new(DeNoise::new(SR, ch)), + "NoiseSuppression" => Box::new(NoiseSuppression::new(SR, ch)), _ => Box::new(PitchShifter::new(SR, ch)), }; if name == "PitchShifter" { @@ -445,7 +446,7 @@ mod tests { y }; let mut failures = Vec::new(); - for name in ["PitchShifter", "DeNoise", "DeReverb", "FftFilter"] { + for name in ["PitchShifter", "DeNoise", "NoiseSuppression", "DeReverb", "FftFilter"] { for (label, src) in [("identical", &identical), ("different", &different)] { let joint = run(name, src); for (ch, chan) in src.iter().enumerate() { @@ -502,17 +503,18 @@ mod tests { #[test] fn non_finite_sample_stays_in_its_channel() { use crate::AudioEffect; - use crate::effects::{DeNoise, DeReverb, FftFilter, PitchShifter}; + use crate::effects::{DeNoise, DeReverb, FftFilter, NoiseSuppression, PitchShifter}; const SR: f32 = 48_000.0; let len = 24_000; let mut rng = Rng::new(5); let clean_a: Vec = crate::testutil::sine(440.0, 0.4, SR as f64, len, 0.0).iter().map(|v| v + 0.05 * rng.uniform()).collect(); let clean_b: Vec = crate::testutil::sine(1250.0, 0.4, SR as f64, len, 0.3).iter().map(|v| v + 0.05 * rng.uniform()).collect(); type Make = fn() -> Box; - let make: [(&str, Make, usize); 4] = [ + let make: [(&str, Make, usize); 5] = [ ("DeReverb", || Box::new(DeReverb::new(SR, 2)), 1), ("FftFilter", || Box::new(FftFilter::new(SR, 2)), 1), ("DeNoise", || Box::new(DeNoise::new(SR, 2)), 1), + ("NoiseSuppression", || Box::new(NoiseSuppression::new(SR, 2)), 1), ("PitchShifter", || Box::new(PitchShifter::new(SR, 2)), 1), ]; let mono = |name: &str, src: &[f32]| -> Vec { @@ -520,6 +522,7 @@ mod tests { "DeReverb" => Box::new(DeReverb::new(SR, 1)), "FftFilter" => Box::new(FftFilter::new(SR, 1)), "DeNoise" => Box::new(DeNoise::new(SR, 1)), + "NoiseSuppression" => Box::new(NoiseSuppression::new(SR, 1)), _ => Box::new(PitchShifter::new(SR, 1)), }; if name == "PitchShifter" { diff --git a/crates/audio-dsp/src/effects/suppress.rs b/crates/audio-dsp/src/effects/suppress.rs new file mode 100644 index 0000000000..eff764db08 --- /dev/null +++ b/crates/audio-dsp/src/effects/suppress.rs @@ -0,0 +1,1022 @@ +//! Noise suppression for a live voice (`noise_suppression`), with 256 samples (5.3 ms) of latency +//! at 48 kHz. +//! +//! The effect runs a short STFT: 256 points at up to 50 kHz (twice that for each doubling of the +//! rate above it), a hop of a quarter of the size, and square-root Hann windows. Each bin's noise +//! power is the smallest value of its smoothed power over the last 1.5 s (minimum statistics, +//! R. Martin, 2001), so the estimate follows a noise floor that changes and needs no "learn noise" +//! step. Each bin's gain is a Wiener gain on the decision-directed a priori SNR (Ephraim and Malah, +//! 1984), held at or above the floor that `reduction` sets, and averaged with its neighbors. At a +//! reduction of 0 every gain is 1 and the effect is a plain delay. +//! +//! A frame enters the noise estimate only after the next four frames have arrived. A frame of +//! digital silence (a mute or a gate) drops the frames still waiting, and the four frames after +//! it do not enter either, so no frame that shares a sample with the silence lowers the estimate +//! and lets the noise pass when the sound resumes, wherever between two hops the silence ends. +//! A mute too short to fill a frame keeps every frame that holds a sample of it out too, down to +//! a run of zeros one hop long (64 samples at 48 kHz); a shorter run of zeros counts as sound. +//! Nor does a frame more than 15 dB below the estimate, until such frames have lasted a whole +//! search window without digital silence between them (the floor has really fallen). +//! The noise power the gains are computed from falls at once and rises by at most 10 dB a +//! second, so a vowel or a note held for longer than the search window keeps its level for a few +//! seconds more, and a noise floor that rises by 12 dB is suppressed again within 3 s. +//! After a reset the gain floor moves from 0 dB toward the attenuation set by `reduction` over +//! the first search window of sound. The first noise estimate after a reset starts from the +//! median bin's power. Each bin's value is clamped between 30 dB below its own estimate and its +//! own estimate. The noise power then rises by at most 10 dB a second. A vowel held from the +//! first sample keeps its level for a few seconds, like one held after a stretch of noise, while +//! steady noise of an even spectrum is suppressed as soon as the floor allows; noise whose +//! spectrum is uneven takes up to 3 s more in the bins well above the median. Continuous voiced +//! or tonal audio present from startup can eventually enter the noise estimate and be attenuated. + +use super::stft::{Pairing, Plan, Spectral, StftChannel, stream}; +use crate::{AudioEffect, MAX_CHANNELS, ParamSpec, ParamValues, Unit, block_len, db_to_gain, flush32, param_plumbing}; + +/// Length of the minimum-statistics search, and the number of sub-windows it rotates through. +const SEARCH_S: f32 = 1.5; +const SUBWINDOWS: usize = 8; +/// Time constant of the smoothing of each bin's power. +const POWER_MS: f32 = 10.0; +/// Time constant of the decision-directed a priori SNR. +const PRIORI_MS: f32 = 80.0; +/// Ratio of the mean noise power to the minimum of its smoothed power with these windows (see +/// `the_noise_estimate_follows_white_noise`). +const BIAS: f32 = 3.25; +/// Smallest noise power a bin is divided by, so digital silence keeps its gain at the floor. +const MIN_NOISE: f32 = 1.0e-30; +/// A frame whose power is below the estimated noise power by this ratio (15 dB) is quiet. +const QUIET: f32 = 1.0 / 32.0; +/// Frames that share a sample with any one frame: the hop is a quarter of the STFT size. +const OVERLAP: usize = 4; +/// Lowest the first noise power of a bin starts against the bin's own estimate (30 dB). +const SEED_SPAN: f32 = 1.0e-3; +/// Fastest rise of the noise power a bin's gain is computed from, in dB per second. +const RISE_DB_S: f32 = 10.0; + +/// STFT size: 256 at up to 50 kHz (5.3 ms at 48 kHz), doubled for each doubling of the rate above +/// it, up to 8192. +fn suppress_size(sample_rate: f32) -> usize { + let (mut n, mut top) = (256, 50_000.0); + while sample_rate > top && n < 8192 { + n *= 2; + top *= 2.0; + } + n +} + +/// Smoothing and floor shared by every frame, from the parameters and the frame rate. +#[derive(Clone, Copy, Debug)] +struct Coefs { + /// Lowest gain a bin gets. + floor: f32, + /// Weight of the previous smoothed power. + smooth: f32, + /// Weight of the previous frame's clean power in the a priori SNR. + priori: f32, + /// Frames in one minimum-statistics sub-window. + sub_frames: usize, + /// Frames in the whole search window. + window: usize, + /// Largest ratio of one frame's noise power to the previous frame's (`RISE_DB_S`). + rise: f32, +} + +/// One channel's noise estimate and gains. Every buffer is sized at creation. +#[derive(Clone, Debug)] +struct Bins { + /// Smoothed power of each bin. + power: Vec, + /// Smallest smoothed power in the current sub-window. + min: Vec, + /// Smallest smoothed power of each of the last `SUBWINDOWS` sub-windows. + ring: Vec, + slot: usize, + frames: usize, + /// Power the previous frame kept (gain² × power). + clean: Vec, + gains: Vec, + /// Smallest smoothed power of the search window for each bin, for the frame being processed. + est: Vec, + /// Noise power of each bin that the gains are computed from: `est` times the bias, rising by + /// at most `RISE_DB_S`. + noise: Vec, + /// Power of each bin of the frames waiting to enter the estimate, `OVERLAP` frames of + /// `bins` values, the oldest at `head`. + queue: Vec, + /// Total power of each waiting frame, and whether it may enter the estimate. + queue_total: [f32; OVERLAP], + queue_ok: [bool; OVERLAP], + /// Whether a mute began between a waiting frame and the one before it. + queue_cut: [bool; OVERLAP], + /// Whether a mute began since the last frame was queued. + cut_pending: bool, + head: usize, + queued: usize, + /// Whether a frame has entered the estimate since the last reset. + started: bool, + /// Frames that entered the estimate since the last reset, up to a search window. + heard: usize, + /// Frames with sound since the last frame of digital silence, up to `OVERLAP + 1`. It starts + /// at 1: the zeros the STFT starts with end on a hop boundary, so `OVERLAP` frames clear them. + since_zero: usize, + /// Quiet frames in a row since the last frame of digital silence, up to a search window. + quiet_run: usize, + /// Whether `noise` has been set from a first estimate since the last reset. + seeded: bool, + /// Room to find the median bin of the first estimate. + scratch: Vec, + /// Zero samples in a row up to the last sample, up to a hop. + zero_run: usize, + /// Samples since the last sample of a mute (a run of at least a hop of zeros), or `usize::MAX` + /// when there has been none since the last reset. + since_mute: usize, + /// Samples since the last frame. + since_frame: usize, +} + +impl Bins { + fn new(bins: usize) -> Self { + Bins { + power: vec![0.0; bins], + min: vec![f32::INFINITY; bins], + ring: vec![f32::INFINITY; bins * SUBWINDOWS], + slot: 0, + frames: 0, + clean: vec![0.0; bins], + gains: vec![1.0; bins], + est: vec![f32::INFINITY; bins], + noise: vec![f32::INFINITY; bins], + queue: vec![0.0; bins * OVERLAP], + queue_total: [0.0; OVERLAP], + queue_ok: [false; OVERLAP], + queue_cut: [false; OVERLAP], + cut_pending: false, + head: 0, + queued: 0, + started: false, + heard: 0, + since_zero: 1, + quiet_run: 0, + seeded: false, + scratch: vec![0.0; bins], + zero_run: 0, + since_mute: usize::MAX, + since_frame: 0, + } + } + + fn reset(&mut self) { + self.power.fill(0.0); + self.min.fill(f32::INFINITY); + self.ring.fill(f32::INFINITY); + self.clean.fill(0.0); + self.gains.fill(1.0); + self.est.fill(f32::INFINITY); + self.noise.fill(f32::INFINITY); + self.slot = 0; + self.frames = 0; + self.head = 0; + self.queued = 0; + self.cut_pending = false; + self.started = false; + self.heard = 0; + self.since_zero = 1; + self.quiet_run = 0; + self.seeded = false; + self.zero_run = 0; + self.since_mute = usize::MAX; + self.since_frame = 0; + } + + /// Takes one input sample before the STFT does, to find mutes too short to give a frame of + /// digital silence. Once `hop` zeros run in a row, the frame still waiting that holds the first + /// of them leaves the queue, and so does every later frame that holds a sample of the run. + fn sample(&mut self, x: f32, hop: usize) { + self.since_frame += 1; + self.zero_run = if x == 0.0 { (self.zero_run + 1).min(hop) } else { 0 }; + if self.zero_run < hop { + self.since_mute = self.since_mute.saturating_add(1); + return; + } + if self.since_mute != 0 { + // The run has just reached a hop. It started `hop - 1` samples ago, so of the frames + // waiting only the newest can hold it: when it ended less than a hop ago. + if self.queued > 0 && self.since_frame < hop { + self.queue_ok[(self.head + self.queued - 1) % OVERLAP] = false; + } + self.cut_pending = true; + } + self.since_mute = 0; + } + + /// Noise power of bin `k` for the frame last processed: the smallest smoothed power of the + /// search window times the bias, rising by at most `RISE_DB_S`. + fn noise(&self, k: usize) -> f32 { + self.noise[k].max(MIN_NOISE) + } + + /// Moves the oldest waiting frame into the noise estimate, unless it shares a sample with + /// digital silence, or it is quiet and quiet frames have not yet lasted a search window. + fn commit(&mut self, c: &Coefs) { + let bins = self.power.len(); + let at = self.head; + self.head = (at + 1) % OVERLAP; + self.queued -= 1; + if self.queue_cut[at] { + self.quiet_run = 0; + } + if !self.queue_ok[at] { + return; + } + let noise_total = self.est.iter().map(|e| e * BIAS).sum::(); + let quiet = noise_total.is_finite() && self.queue_total[at] < noise_total * QUIET; + self.quiet_run = if quiet { (self.quiet_run + 1).min(c.window) } else { 0 }; + if quiet && self.quiet_run < c.window { + return; + } + let a = if self.started { c.smooth } else { 0.0 }; + for k in 0..bins { + let p = self.queue[at * bins + k]; + self.power[k] = flush32(a * self.power[k] + (1.0 - a) * p); + self.min[k] = self.min[k].min(self.power[k]); + self.est[k] = self.est[k].min(self.power[k]); + } + self.frames += 1; + if self.frames == c.sub_frames { + for k in 0..bins { + self.ring[self.slot * bins + k] = self.min[k]; + self.min[k] = f32::INFINITY; + } + self.slot = (self.slot + 1) % SUBWINDOWS; + self.frames = 0; + } + self.started = true; + self.heard = (self.heard + 1).min(c.window); + } + + /// Takes one frame's half spectrum, updates the noise estimate and the gains, and writes the + /// gains averaged with their neighbors to `out`. A frame with a non-finite bin leaves the + /// state as it is and repeats the last gains. + fn frame(&mut self, re: &[f32], im: &[f32], c: &Coefs, out: &mut [f32]) { + let bins = self.power.len(); + self.since_frame = 0; + let finite = re.iter().zip(im).fold(true, |ok, (a, b)| ok & (a * a + b * b).is_finite()); + if finite { + for k in 0..bins { + self.est[k] = (0..SUBWINDOWS).fold(self.min[k], |m, u| m.min(self.ring[u * bins + k])); + } + let total = (0..bins).map(|k| re[k] * re[k] + im[k] * im[k]).sum::(); + if total == 0.0 { + // Digital silence: the frames still waiting share a sample with it, and so do the + // next `OVERLAP - 1` frames, or the next `OVERLAP` when the silence ends between + // two hops. A quiet run ends here too. + self.queued = 0; + self.cut_pending = false; + self.since_zero = 0; + self.quiet_run = 0; + } else { + self.since_zero = (self.since_zero + 1).min(OVERLAP + 1); + if self.queued == OVERLAP { + self.commit(c); + } + let at = (self.head + self.queued) % OVERLAP; + for k in 0..bins { + self.queue[at * bins + k] = re[k] * re[k] + im[k] * im[k]; + } + self.queue_total[at] = total; + self.queue_cut[at] = std::mem::take(&mut self.cut_pending); + // A frame holds the last STFT size of samples, `2 * (bins - 1)`. + self.queue_ok[at] = self.since_zero > OVERLAP && self.since_mute >= 2 * (bins - 1); + self.queued += 1; + } + if self.started && !self.seeded { + // The first estimate: a bin well above the median bin, such as a harmonic of a + // vowel held from the start, starts from the median and rises from there. + self.seeded = true; + self.scratch.copy_from_slice(&self.est); + let median = *self.scratch.select_nth_unstable_by(bins / 2, f32::total_cmp).1 * BIAS; + for k in 0..bins { + let own = self.est[k] * BIAS; + self.noise[k] = own.min(median.max(own * SEED_SPAN)); + } + } + // The floor moves from 1 to `c.floor` (in dB) over the first search window of sound. + let floor = c.floor.powf(self.heard as f32 / c.window as f32); + for k in 0..bins { + let p = re[k] * re[k] + im[k] * im[k]; + // The noise power falls at once and rises by at most `c.rise` a frame, so a sound + // held longer than the search window is not taken for the noise at once. + self.noise[k] = (self.est[k] * BIAS).min(self.noise[k].max(MIN_NOISE) * c.rise); + let noise = self.noise(k); + let excess = (p / noise - 1.0).max(0.0); + let xi = c.priori * self.clean[k] / noise + (1.0 - c.priori) * excess; + // `1 - 1 / (1 + xi)` is `xi / (1 + xi)`, and stays 1 for an infinite `xi`. + let g = (1.0 - 1.0 / (1.0 + xi)).max(floor); + self.gains[k] = g; + self.clean[k] = flush32(g * g * p); + } + } + for k in 0..bins { + let lo = self.gains[k.saturating_sub(1)]; + let hi = self.gains[(k + 1).min(bins - 1)]; + out[k] = 0.25 * lo + 0.5 * self.gains[k] + 0.25 * hi; + } + } +} + +/// Noise suppression for a live voice: lowers steady background noise (fans, hiss, room tone) by +/// up to `reduction` dB, with no step that learns the noise first. Its latency is the STFT size, +/// 256 samples (5.3 ms) at 48 kHz. Continuous voiced or tonal audio present from startup can +/// enter the noise estimate and be attenuated after the initial search window. +pub struct NoiseSuppression { + pv: ParamValues, + n: usize, + hop: usize, + spec: Spectral, + stft: Vec, + bins: Vec, + /// Gains of the frame being processed, averaged with their neighbors. + smoothed: Vec, + coefs: Coefs, + sample_rate: f32, + /// Samples since the last frame, the same in every channel. + pos: usize, +} + +impl NoiseSuppression { + pub const PARAMS: &'static [ParamSpec] = &[ParamSpec::new("reduction", "Reduction", 0.0, 40.0, 24.0, Unit::Decibels)]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let n = suppress_size(sample_rate); + let bins = n / 2 + 1; + let ch = crate::sane_channels(channels); + let mut s = NoiseSuppression { + pv: ParamValues::new(Self::PARAMS), + n, + hop: n / OVERLAP, + spec: Spectral::new(n, true), + stft: vec![StftChannel::new(n); ch], + bins: vec![Bins::new(bins); ch], + smoothed: vec![1.0; bins], + coefs: Coefs { floor: 1.0, smooth: 0.0, priori: 0.0, sub_frames: 1, window: SUBWINDOWS, rise: 1.0 }, + sample_rate, + pos: 0, + }; + s.apply_params(true); + s + } + + fn apply_params(&mut self, _snap: bool) { + let frame_s = self.hop as f32 / self.sample_rate; + let sub_frames = ((SEARCH_S / frame_s / SUBWINDOWS as f32).round() as usize).max(1); + self.coefs = Coefs { + floor: db_to_gain(-self.pv.v("reduction")), + smooth: (-frame_s * 1000.0 / POWER_MS).exp(), + priori: (-frame_s * 1000.0 / PRIORI_MS).exp(), + sub_frames, + window: sub_frames * SUBWINDOWS, + // A power ratio: twice the dB of an amplitude ratio. + rise: db_to_gain(2.0 * RISE_DB_S * frame_s), + }; + } +} + +impl AudioEffect for NoiseSuppression { + param_plumbing!("noise_suppression"); + fn latency(&self) -> usize { + self.n + } + fn tail_samples(&self) -> usize { + self.n + } + fn reset(&mut self) { + self.stft.iter_mut().for_each(StftChannel::reset); + self.bins.iter_mut().for_each(Bins::reset); + self.pos = 0; + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let len = block_len(channels); + let nch = channels.len().min(self.stft.len()); + // A non-finite sample is taken as silence, so it never reaches the output. + for c in channels.iter_mut().take(nch) { + c[..len].iter_mut().for_each(|v| *v = flush32(*v)); + } + let (n, hop, coefs) = (self.n, self.hop, self.coefs); + let scale = 1.0 / (n as f32 * 2.0); + let plan = Plan { hop, scale, pairing: Pairing::SynthesisOnly }; + // The block runs in pieces that end at the next frame, so each channel's noise estimate + // takes every sample of a frame before the STFT frames it. + let mut start = 0; + while start < len { + let end = len.min(start + hop - self.pos); + for (b, c) in self.bins.iter_mut().zip(channels.iter()).take(nch) { + c[start..end].iter().for_each(|&x| b.sample(x, hop)); + } + let mut piece: [&mut [f32]; MAX_CHANNELS] = std::array::from_fn(|_| <&mut [f32]>::default()); + for (p, c) in piece.iter_mut().zip(channels.iter_mut()).take(nch) { + *p = &mut c[start..end]; + } + let (bins, smoothed) = (&mut self.bins, &mut self.smoothed); + stream(&mut self.stft, &mut self.spec, &mut piece[..nch], end - start, plan, &mut |ch, _, re, im| { + bins[ch].frame(re, im, &coefs, smoothed); + for ((r, i), g) in re.iter_mut().zip(im.iter_mut()).zip(smoothed.iter()) { + *r *= g; + *i *= g; + } + }); + self.pos = (self.pos + end - start) % hop; + start = end; + } + // A channel the block leaves out is fed silence, so it holds none of its earlier audio + // when it comes back. + let half = n / 2 + 1; + let (spec, smoothed) = (&mut self.spec, &mut self.smoothed); + for (st, b) in self.stft.iter_mut().zip(self.bins.iter_mut()).skip(nch) { + for _ in 0..len { + b.sample(0.0, hop); + st.tick(0.0, hop, &mut |input, out| { + spec.analyze(input); + b.frame(&spec.re[..half], &spec.im[..half], &coefs, smoothed); + for k in 0..half { + spec.re[k] *= smoothed[k]; + spec.im[k] *= smoothed[k]; + } + spec.synthesize_add(out, scale); + }); + } + } + // A huge finite input can overflow the inverse FFT. + for c in channels.iter_mut().take(nch) { + c[..len].iter_mut().for_each(|v| *v = flush32(*v)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + + const SR: f32 = 48000.0; + + fn suppressor(reduction: f32) -> NoiseSuppression { + let mut s = NoiseSuppression::new(SR, 1); + assert!(s.set_param("reduction", reduction)); + s.reset(); + s + } + + fn white(seed: u64, n: usize, amp: f32) -> Vec { + let mut r = Rng::new(seed); + (0..n).map(|_| r.uniform() * amp).collect() + } + + /// Voiced syllables (seven harmonics of a gliding pitch from 110 to 230 Hz under a sine + /// envelope) with pauses between them, at a peak level of about 0.5. + fn voiced(sr: f64, secs: f64, seed: u64) -> Vec { + let n = (sr * secs) as usize; + let mut rng = Rng::new(seed); + let mut out = vec![0.0f32; n]; + let mut i = 0usize; + while i < n { + let len = ((0.12 + 0.2 * (rng.uniform() * 0.5 + 0.5) as f64) * sr) as usize; + let f0 = 110.0 + 120.0 * (rng.uniform() as f64 * 0.5 + 0.5); + let glide = 1.0 + 0.3 * rng.uniform() as f64; + let amp = 0.1 + 0.1 * (rng.uniform() * 0.5 + 0.5); + for k in 0..len.min(n - i) { + let t = k as f64 / sr; + let env = (std::f64::consts::PI * k as f64 / len as f64).sin() as f32; + let f = f0 * (1.0 + (glide - 1.0) * k as f64 / len as f64); + let v: f32 = (1..8).map(|h| ((2.0 * std::f64::consts::PI * f * h as f64 * t).sin() / h as f64) as f32).sum(); + out[i + k] = v * env * amp; + } + i += len + ((rng.uniform() * 0.5 + 0.5) * 0.25 * sr as f32) as usize; + } + out + } + + /// Runs the suppressor's gains, computed from `speech + noise`, on the speech and the noise + /// apart, so the SNR before and after can be measured. Returns the processed mix, speech and + /// noise. + fn shadow(speech: &[f32], noise: &[f32], reduction: f32) -> (Vec, Vec, Vec) { + let s = suppressor(reduction); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let mut spec = Spectral::new(n, true); + let half = n / 2 + 1; + let scale = 1.0 / (n as f32 * 2.0); + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let mut lanes = [StftChannel::new(n), StftChannel::new(n), StftChannel::new(n)]; + let mut out = [vec![0.0f32; speech.len()], vec![0.0f32; speech.len()], vec![0.0f32; speech.len()]]; + for i in 0..speech.len() { + let x = [speech[i] + noise[i], speech[i], noise[i]]; + bins.sample(x[0], hop); + for (lane, (st, o)) in lanes.iter_mut().zip(out.iter_mut()).enumerate() { + o[i] = st.tick(x[lane], hop, &mut |input, frame_out| { + spec.analyze(input); + if lane == 0 { + bins.frame(&spec.re[..half], &spec.im[..half], &coefs, &mut gains); + } + for k in 0..half { + spec.re[k] *= gains[k]; + spec.im[k] *= gains[k]; + } + spec.synthesize_add(frame_out, scale); + }); + } + } + let [mix, speech, noise] = out; + (mix, speech, noise) + } + + fn energy(x: &[f32]) -> f64 { + x.iter().map(|&v| v as f64 * v as f64).sum() + } + + /// SNR before and after the suppressor at a reduction of 24 dB, and the change of the voice's + /// own level, in dB, measured from 3 s on (the noise estimate has settled by then). + fn snr_gain(speech: &[f32], noise_amp: f32) -> (f64, f64, f64) { + let len = speech.len(); + let noise = white(17, len, noise_amp); + let (mix, ys, yv) = shadow(speech, &noise, 24.0); + let mut real: Vec = speech.iter().zip(&noise).map(|(a, b)| a + b).collect(); + suppressor(24.0).process(&mut [&mut real]); + assert!(real.iter().zip(&mix).all(|(a, b)| (a - b).abs() < 1e-5), "the shadow run differs from the effect"); + let lat = 256; + let (from, to) = (SR as usize * 3, len - lat); + let after = from + lat..to + lat; + let snr_in = db((energy(&speech[from..to]) / energy(&noise[from..to])).sqrt()); + let snr_out = db((energy(&ys[after.clone()]) / energy(&yv[after.clone()])).sqrt()); + let kept = db((energy(&ys[after]) / energy(&speech[from..to])).sqrt()); + (snr_in, snr_out - snr_in, kept) + } + + /// Voiced syllables in white noise come out with an SNR at least 15 dB higher at an input SNR + /// of 7 dB (13 dB higher at 17 dB), and the voice's level changes by less than 3 dB. + #[test] + fn the_voice_gains_15_db_of_snr_and_keeps_its_level() { + let speech = voiced(SR as f64, 12.0, 4); + for (noise_amp, want) in [(0.06f32, 15.0), (0.02, 13.0)] { + let (snr_in, gain, kept) = snr_gain(&speech, noise_amp); + assert!(gain >= want, "input SNR {snr_in:.1} dB: SNR gain {gain:.1} dB"); + assert!(kept.abs() < 3.0, "input SNR {snr_in:.1} dB: voice level changed by {kept:.2} dB"); + } + } + + /// Speech with consonants (bursts of broadband noise at the level of the vowels) keeps its + /// level within 3 dB and still gains SNR. Bins where a consonant covers the noise keep both. + #[test] + fn speech_with_consonants_keeps_its_level() { + let speech = speechy(SR as f64, 12.0, 4); + for noise_amp in [0.06f32, 0.02] { + let (snr_in, gain, kept) = snr_gain(&speech, noise_amp); + assert!(gain >= 4.0, "input SNR {snr_in:.1} dB: SNR gain {gain:.1} dB"); + assert!(kept.abs() < 3.0, "input SNR {snr_in:.1} dB: speech level changed by {kept:.2} dB"); + } + } + + /// Steady noise falls by close to the reduction setting, at 44.1, 48, 96 and 192 kHz, and the + /// latency is 256 samples up to 50 kHz and doubles with each doubling of the rate above it. + #[test] + fn steady_noise_falls_by_the_reduction() { + for (sr, lat) in [(44_100.0f32, 256), (48_000.0, 256), (96_000.0, 512), (192_000.0, 1024)] { + for reduction in [6.0f32, 12.0, 24.0, 40.0] { + let mut s = NoiseSuppression::new(sr, 1); + assert!(s.set_param("reduction", reduction)); + assert_eq!(s.latency(), lat); + let n = sr as usize * 4; + let x = white(5, n, 0.05); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let tail = n - sr as usize..n; + let got = -db(rms(&y[tail.clone()]) / rms(&x[tail])); + // At 40 dB the Wiener gains of noise-only bins sit above the floor. + let limit = if reduction == 40.0 { 28.0 } else { reduction as f64 - 2.0 }; + assert!(got >= limit && got <= reduction as f64 + 1.0, "{sr} Hz, reduction {reduction}: noise fell by {got:.1} dB"); + } + } + } + + /// At a reduction of 0 the output is the input delayed by the latency. + #[test] + fn zero_reduction_is_a_delay() { + let mut s = suppressor(0.0); + let lat = s.latency(); + let x = speechy(SR as f64, 2.0, 8); + let mut y = x.clone(); + s.process(&mut [&mut y]); + for i in lat..x.len() { + assert!((y[i] - x[i - lat]).abs() < 1e-5, "{i}: {} vs {}", y[i], x[i - lat]); + } + } + + /// The noise estimate follows a noise floor that rises by 12 dB within 3 s, and one that falls + /// by 12 dB at once. + #[test] + fn the_estimate_follows_a_changing_noise_floor() { + let level = |amps: [f32; 2], at: f32| -> f64 { + let mut s = suppressor(24.0); + let n = SR as usize * 8; + let mut rng = Rng::new(31); + let x: Vec = (0..n).map(|i| rng.uniform() * if i < n / 2 { amps[0] } else { amps[1] }).collect(); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let from = n / 2 + (at * SR) as usize; + let range = from..from + SR as usize / 4; + -db(rms(&y[range.clone()]) / rms(&x[range])) + }; + let up = level([0.02, 0.08], 3.0); + assert!(up >= 20.0, "rise: noise fell by {up:.1} dB 3 s later"); + let down = level([0.08, 0.02], 0.25); + assert!(down >= 20.0, "fall: noise fell by {down:.1} dB 0.25 s later"); + } + + /// Noise that starts after digital silence is suppressed again within the search window. + #[test] + fn noise_after_silence_is_suppressed_again() { + let mut s = suppressor(24.0); + let n = SR as usize * 6; + let mut x = white(41, n, 0.05); + x[..SR as usize * 2].fill(0.0); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let tail = n - SR as usize / 2..n; + let got = -db(rms(&y[tail.clone()]) / rms(&x[tail])); + assert!(got >= 20.0, "noise fell by {got:.1} dB"); + } + + /// Noise that resumes after a pause of digital silence, or of noise 40 dB lower, is suppressed + /// from the start: the pause does not enter the noise estimate. + #[test] + fn noise_after_a_pause_is_suppressed_at_once() { + for pause_amp in [0.0f32, 0.0005] { + let mut s = suppressor(24.0); + let lat = s.latency(); + let n = SR as usize * 5; + let (pause, resume) = (SR as usize * 3, SR as usize * 4); + let mut x = white(43, n, 0.05); + x[pause..resume].iter_mut().for_each(|v| *v *= pause_amp / 0.05); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let range = resume + lat + SR as usize / 50..resume + lat + SR as usize / 2; + let got = -db(rms(&y[range.clone()]) / rms(&x[range.start - lat..range.end - lat])); + assert!(got >= 20.0, "pause level {pause_amp}: noise fell by {got:.1} dB after the pause"); + } + } + + /// No frame that shares a sample with digital silence enters the noise estimate: not the + /// frames that run into a mute, nor those that run out of it, whether or not the mute starts + /// or ends on a frame boundary. At most two frames per mute that hold no silence are dropped + /// with them. + #[test] + fn frames_that_touch_a_mute_stay_out_of_the_estimate() { + let s = suppressor(24.0); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let half = n / 2 + 1; + for offset in [0usize, 17, 40, 63] { + let mut spec = Spectral::new(n, true); + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let mut lane = StftChannel::new(n); + let len = SR as usize; + let mut x = white(29, len, 0.05); + let mutes = [(SR as usize * 3 / 10 + offset, SR as usize * 4 / 10 + offset), (SR as usize * 7 / 10 + offset, SR as usize * 8 / 10)]; + for &(a, b) in &mutes { + x[a..b].fill(0.0); + } + assert!(x.iter().enumerate().all(|(i, v)| *v != 0.0 || mutes.iter().any(|&(a, b)| (a..b).contains(&i)))); + let mut frames = 0usize; + // A frame enters the estimate when the frame `OVERLAP` after it arrives, which is when + // `heard` grows. + let mut entered = Vec::new(); + for &v in &x { + lane.tick(v, hop, &mut |input, _| { + spec.analyze(input); + let heard = bins.heard; + bins.frame(&spec.re[..half], &spec.im[..half], &coefs, &mut gains); + frames += 1; + if bins.heard > heard { + entered.push(frames - OVERLAP); + } + }); + } + // Frame `j` (from 1) holds samples `j * hop - n .. j * hop`; samples before 0 are + // the zeros the STFT starts with. + let holds_no_silence = |j: usize| j * hop >= n && x[j * hop - n..j * hop].iter().all(|v| *v != 0.0); + let clean = (1..=frames).filter(|&j| holds_no_silence(j)).count(); + assert!(frames < coefs.window, "the test needs `heard` below its cap"); + assert_eq!(entered.len(), bins.heard); + for &j in &entered { + assert!(holds_no_silence(j), "offset {offset}: frame {j} holds silence and entered the estimate"); + } + assert!(bins.heard + 2 * mutes.len() + OVERLAP >= clean, "offset {offset}: {} of {clean} frames entered", bins.heard); + } + } + + /// A mute too short to fill a frame, from one hop long up, keeps the frames that hold a sample + /// of it out of the estimate too, wherever it starts and ends between two hops. + #[test] + fn frames_that_touch_a_short_mute_stay_out_of_the_estimate() { + for offset in [0usize, 17, 40, 63] { + let mut s = suppressor(24.0); + let (n, hop) = (s.n, s.hop); + let mut x = white(31, SR as usize / 2, 0.05); + // The last mute is one STFT size long and holds no whole frame unless it starts on a hop. + let mutes = [ + (192 + offset, 256 + offset), + (6000 + offset, 6100 + offset), + (12_000 + offset, 12_200 + offset), + (17_984 + offset, 17_984 + offset + n), + ]; + for &(a, b) in &mutes { + x[a..b].fill(0.0); + } + assert!(x.iter().enumerate().all(|(i, v)| *v != 0.0 || mutes.iter().any(|&(a, b)| (a..b).contains(&i)))); + // One hop per block, so each block ends with a frame. A frame enters the estimate when + // the frame `OVERLAP` after it arrives, which is when `heard` grows. + let mut entered = Vec::new(); + for (k, chunk) in x.chunks(hop).enumerate() { + let heard = s.bins[0].heard; + let mut y = chunk.to_vec(); + s.process(&mut [&mut y]); + if s.bins[0].heard > heard { + entered.push(k + 1 - OVERLAP); + } + } + let frames = x.len() / hop; + let holds_no_silence = |j: usize| j * hop >= n && x[j * hop - n..j * hop].iter().all(|v| *v != 0.0); + let clean = (1..=frames).filter(|&j| holds_no_silence(j)).count(); + assert!(frames < s.coefs.window, "the test needs `heard` below its cap"); + assert_eq!(entered.len(), s.bins[0].heard); + for &j in &entered { + assert!(holds_no_silence(j), "offset {offset}: frame {j} holds silence and entered the estimate"); + } + assert!(s.bins[0].heard + 2 * mutes.len() + OVERLAP >= clean, "offset {offset}: {} of {clean} frames entered", s.bins[0].heard); + } + } + + /// Quiet stretches that a mute separates do not add up to a search window: the estimate stays + /// at the noise before them, and falls only after a whole search window of quiet in a row. + #[test] + fn a_mute_ends_a_quiet_run() { + let s = suppressor(24.0); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let half = n / 2 + 1; + let mut spec = Spectral::new(n, true); + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let mut lane = StftChannel::new(n); + let window = coefs.window * hop; + let amp = 0.05f32; + let (loud, quiet, mute) = (SR as usize * 2, window * 6 / 10, SR as usize / 5); + let mut x = white(47, loud + 2 * quiet + mute + window + quiet, amp); + x[loud..].iter_mut().for_each(|v| *v *= 0.01); + x[loud + quiet..loud + quiet + mute].fill(0.0); + let want = amp * amp / 3.0 * n as f32 / 2.0; + let mut feed = |part: &[f32]| -> f64 { + for &v in part { + lane.tick(v, hop, &mut |input, _| { + spec.analyze(input); + bins.frame(&spec.re[..half], &spec.im[..half], &coefs, &mut gains); + }); + } + (1..half - 1).map(|k| db((bins.est[k] as f64 * BIAS as f64 / want as f64).sqrt())).sum::() / (half - 2) as f64 + }; + let split = loud + 2 * quiet + mute; + let kept = feed(&x[..split]); + assert!(kept > -6.0, "after two quiet stretches split by a mute the estimate fell by {:.1} dB", -kept); + let fell = feed(&x[split..]); + assert!(fell < -20.0, "after a search window of quiet the estimate fell by only {:.1} dB", -fell); + } + + /// A mute of one hop, which leaves no frame of digital silence, ends the quiet run where it + /// falls in the stream: the quiet frames waiting before it still count, and only the frames + /// after the mute that may enter the estimate start the next run. + #[test] + fn a_short_mute_ends_the_quiet_run_in_queue_order() { + let s = suppressor(24.0); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let half = n / 2 + 1; + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let im = vec![0.0f32; half]; + let (loud, quiet) = (vec![1.0f32; half], vec![0.001f32; half]); + let mut step = |bins: &mut Bins, sample: f32, spectrum: &[f32]| { + for _ in 0..hop { + bins.sample(sample, hop); + } + bins.frame(spectrum, &im, &coefs, &mut gains); + }; + for _ in 0..40 { + step(&mut bins, 0.1, &loud); + } + for _ in 0..OVERLAP + 3 { + step(&mut bins, 0.001, &quiet); + } + assert!(bins.quiet_run > 0, "the quiet frames before the mute did not count"); + step(&mut bins, 0.0, &quiet); + let mut eligible = 0; + for _ in 0..2 * n / hop { + step(&mut bins, 0.001, &quiet); + let newest = (bins.head + bins.queued - 1) % OVERLAP; + eligible += usize::from(bins.queue_ok[newest]); + } + let waiting = (0..bins.queued).filter(|j| bins.queue_ok[(bins.head + j) % OVERLAP]).count(); + assert_eq!(waiting, bins.queued, "a frame waiting after the mute may not enter the estimate"); + assert!(eligible + 3 < coefs.window, "the test needs the run below its cap"); + assert_eq!(bins.quiet_run, eligible - waiting, "frames from before the mute counted in the new run"); + } + + #[test] + fn a_short_mute_ends_the_queued_quiet_run() { + for offset in [0, 17] { + let mut s = suppressor(24.0); + let (n, hop) = (s.n, s.hop); + let mut loud = white(47, SR as usize * 2, 0.05); + s.process(&mut [&mut loud]); + let mut quiet = white(51, 20 * hop + offset, 0.0005); + s.process(&mut [&mut quiet]); + assert!(s.bins[0].quiet_run > 0); + let mute_end = loud.len() + quiet.len() + hop; + let first_clean_frame = (mute_end + n).div_ceil(hop); + let commit_end = (first_clean_frame + OVERLAP) * hop; + let mut after = white(53, commit_end - loud.len() - quiet.len(), 0.0005); + after[..hop].fill(0.0); + let before_mute = s.bins[0].quiet_run; + s.process(&mut [&mut after[..hop]]); + assert_eq!(s.bins[0].quiet_run, before_mute + 1, "offset {offset}: queued pre-mute frames lost their quiet run"); + s.process(&mut [&mut after[hop..]]); + assert_eq!(s.bins[0].quiet_run, 1, "offset {offset}: pre-mute quiet frames contributed to the new run"); + } + } + + /// A voice that starts with the stream keeps its level within 3 dB over its first 0.25 s and + /// its first 1.5 s, while the suppressor has no noise estimate yet. One of the voices starts on + /// its first sample with a vowel held for 0.25 s. + #[test] + fn a_voice_at_the_start_keeps_its_level() { + let mut abrupt = voiced(SR as f64, 2.0, 7); + let vowel = SR as usize / 4; + let len = abrupt.len(); + abrupt.copy_within(..len - vowel, vowel); + for (i, v) in abrupt[..vowel].iter_mut().enumerate() { + let t = std::f64::consts::TAU * 160.0 * i as f64 / SR as f64; + *v = (1..8).map(|h| (0.15 * (h as f64 * t).sin() / h as f64) as f32).sum(); + } + for speech in [abrupt, voiced(SR as f64, 2.0, 6), speechy(SR as f64, 2.0, 6)] { + let noise = white(19, speech.len(), 0.02); + let (_, ys, _) = shadow(&speech, &noise, 24.0); + let lat = 256; + for to in [SR as usize / 4, SR as usize * 3 / 2] { + let kept = db((energy(&ys[lat..to + lat]) / energy(&speech[..to])).sqrt()); + assert!(kept.abs() < 3.0, "voice level changed by {kept:.2} dB in the first {to} samples"); + } + } + } + + /// A steady vowel held for 3 s in noise, longer than the search window, keeps its level within + /// 3 dB over its last second. + #[test] + fn a_held_vowel_keeps_its_level() { + let (lead, held) = (SR as usize * 2, SR as usize * 3); + let mut speech = vec![0.0f32; lead + held + SR as usize / 2]; + for (i, v) in speech[lead..lead + held].iter_mut().enumerate() { + let t = std::f64::consts::TAU * 160.0 * i as f64 / SR as f64; + let fade = (i as f32 / 480.0).min(1.0); + *v = fade * (1..8).map(|h| (0.15 * (h as f64 * t).sin() / h as f64) as f32).sum::(); + } + let noise = white(37, speech.len(), 0.02); + let (_, ys, _) = shadow(&speech, &noise, 24.0); + let lat = 256; + let last = lead + held - SR as usize..lead + held; + let kept = db((energy(&ys[last.start + lat..last.end + lat]) / energy(&speech[last])).sqrt()); + assert!(kept.abs() < 3.0, "the held vowel's level changed by {kept:.2} dB in its last second"); + } + + /// A steady vowel held from the first sample, with no noise before it, keeps its level within + /// 3 dB over its first 2 s, after the floor has reached the reduction. + #[test] + fn a_vowel_held_from_the_start_keeps_its_level() { + let held = SR as usize * 3; + let mut speech = vec![0.0f32; held + SR as usize / 2]; + for (i, v) in speech[..held].iter_mut().enumerate() { + let t = std::f64::consts::TAU * 160.0 * i as f64 / SR as f64; + *v = (1..8).map(|h| (0.15 * (h as f64 * t).sin() / h as f64) as f32).sum(); + } + let noise = white(53, speech.len(), 0.02); + let (_, ys, _) = shadow(&speech, &noise, 24.0); + let lat = 256; + for range in [0..SR as usize * 2, SR as usize * 3 / 2..SR as usize * 2] { + let kept = db((energy(&ys[range.start + lat..range.end + lat]) / energy(&speech[range.clone()])).sqrt()); + assert!(kept.abs() < 3.0, "the vowel's level changed by {kept:.2} dB over {range:?}"); + } + } + + #[test] + fn a_hop_periodic_startup_vowel_keeps_its_level_at_16_khz() { + let sr = 16_000.0; + let held = sr as usize * 3; + let mut speech = vec![0.0f32; held + sr as usize / 2]; + for (i, v) in speech[..held].iter_mut().enumerate() { + let t = std::f64::consts::TAU * 250.0 * i as f64 / sr as f64; + *v = (1..8).map(|h| (0.15 * (h as f64 * t).sin() / h as f64) as f32).sum(); + } + let mut s = NoiseSuppression::new(sr, 1); + assert!(s.set_param("reduction", 24.0)); + s.reset(); + assert_eq!(s.hop, sr as usize / 250); + let lat = s.latency(); + let mut y = speech.clone(); + s.process(&mut [&mut y]); + for range in [0..sr as usize * 2, sr as usize * 3 / 2..sr as usize * 2] { + let kept = db((energy(&y[range.start + lat..range.end + lat]) / energy(&speech[range.clone()])).sqrt()); + assert!(kept.abs() < 3.0, "the 250 Hz startup vowel at 16 kHz changed by {kept:.2} dB over {range:?}"); + } + } + + /// Steady noise whose spectrum falls with frequency (white noise through a one-pole low-pass + /// at 500 Hz) is suppressed by at least 20 dB from 4 s on. + #[test] + fn steady_low_passed_noise_falls_by_the_reduction() { + let mut s = suppressor(24.0); + let n = SR as usize * 5; + let a = (-std::f32::consts::TAU * 500.0 / SR).exp(); + let mut state = 0.0f32; + let x: Vec = white(59, n, 0.2) + .into_iter() + .map(|v| { + state = a * state + (1.0 - a) * v; + state + }) + .collect(); + let mut y = x.clone(); + s.process(&mut [&mut y]); + let lat = s.latency(); + let from = SR as usize * 4; + let got = -db(rms(&y[from + lat..n]) / rms(&x[from..n - lat])); + assert!(got >= 20.0, "noise fell by {got:.1} dB"); + } + + /// NaN, infinite and the largest finite samples give finite output, and the noise is still + /// suppressed afterwards. + #[test] + fn non_finite_and_huge_samples_give_finite_output() { + let mut s = suppressor(24.0); + let n = SR as usize * 4; + let x = white(13, n, 0.05); + let mut y = x.clone(); + for (i, bad) in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX, -f32::MAX].into_iter().enumerate() { + y[3000 + i * 1500] = bad; + y[3001 + i * 1500] = bad; + } + s.process(&mut [&mut y]); + assert!(y.iter().all(|v| v.is_finite())); + let tail = n - SR as usize / 2..n; + let got = -db(rms(&y[tail.clone()]) / rms(&x[tail])); + assert!(got >= 20.0, "noise fell by {got:.1} dB"); + } + + /// A block that leaves channels out feeds them silence, so when they come back without a + /// reset none of their earlier audio sounds. + #[test] + fn channels_left_out_of_a_block_come_back_silent() { + let noise = white(23, 4_000, 0.5); + let mut s = NoiseSuppression::new(SR, 3); + let (mut a, mut b, mut c) = (noise.clone(), noise.clone(), noise.clone()); + s.process(&mut [&mut a, &mut b, &mut c]); + // The first channel is silent too, so the paired inverse FFT carries none of its audio + // into the second channel. + let mut a = vec![0.0f32; 4_000]; + s.process(&mut [&mut a]); + let (mut a, mut b, mut c) = (vec![0.0f32; 4_000], vec![0.0f32; 4_000], vec![0.0f32; 4_000]); + s.process(&mut [&mut a, &mut b, &mut c]); + assert!(b.iter().chain(&c).all(|v| *v == 0.0), "earlier audio came back"); + } + + /// On steady white noise, the noise estimate, averaged over the bins, lands within 1 dB of the + /// noise's mean power once the search window has filled. + #[test] + fn the_noise_estimate_follows_white_noise() { + let s = suppressor(24.0); + let (n, hop, coefs) = (s.n, s.hop, s.coefs); + let half = n / 2 + 1; + let mut spec = Spectral::new(n, true); + let mut bins = Bins::new(half); + let mut gains = vec![1.0f32; half]; + let mut lane = StftChannel::new(n); + let amp = 0.1f32; + let x = white(3, SR as usize * 4, amp); + for &v in &x { + lane.tick(v, hop, &mut |input, _| { + spec.analyze(input); + bins.frame(&spec.re[..half], &spec.im[..half], &coefs, &mut gains); + }); + } + // uniform noise of amplitude `amp` has a variance of amp²/3; each bin of the + // square-root-Hann windowed FFT gets n/2 of that + let want = amp * amp / 3.0 * n as f32 / 2.0; + let mean = (1..half - 1).map(|k| db((bins.noise(k) as f64 / want as f64).sqrt())).sum::() / (half - 2) as f64; + assert!(mean.abs() < 1.0, "the noise estimate is {mean:.2} dB from the mean power"); + } +} diff --git a/crates/audio-dsp/src/effects/util.rs b/crates/audio-dsp/src/effects/util.rs index eb19d70d72..e16654994e 100644 --- a/crates/audio-dsp/src/effects/util.rs +++ b/crates/audio-dsp/src/effects/util.rs @@ -81,7 +81,14 @@ impl DelayLine { let i0 = self.w + len - 1 - di as usize; let i0 = if i0 >= len { i0 - len } else { i0 }; let i1 = if i0 == 0 { len - 1 } else { i0 - 1 }; - self.buf[i0] + (self.buf[i1] - self.buf[i0]) * frac + let (a, b) = (self.buf[i0], self.buf[i1]); + let y = a + (b - a) * frac; + if y.is_finite() { + y + } else { + // Two large samples of opposite sign overflow `b - a` in f32. + (a as f64 + (b as f64 - a as f64) * frac as f64) as f32 + } } /// Integer read (`d` samples ago, 0 = newest). #[inline] diff --git a/crates/audio-dsp/src/effects/voice.rs b/crates/audio-dsp/src/effects/voice.rs index af487cdbbb..4b059b67b3 100644 --- a/crates/audio-dsp/src/effects/voice.rs +++ b/crates/audio-dsp/src/effects/voice.rs @@ -1,5 +1,8 @@ -//! Voice pitch shifter for live use: two read taps sweep through a short delay line and crossfade -//! (sin² and cos² gains), so the output moves by the pitch ratio with a latency of 10 ms. +//! Effects for a live voice: a pitch shifter with 10 ms of latency and a formant shifter with +//! 10.7 ms of latency (at 48 kHz). +//! +//! The pitch shifter (`voice_pitch`) has two read taps that sweep through a short delay line and +//! crossfade (sin² and cos² gains), so the output moves by the pitch ratio with a latency of 10 ms. //! //! The taps sit half a sweep apart and are centered on the latency, so the delay of each one //! stays within `latency ± spacing`. A pitch tracker (YIN, on a copy of the input low-passed and @@ -11,8 +14,21 @@ //! hertz (5 Hz for 85 Hz shifted up 5 semitones). At a shift //! of 0 the effect crossfades over 20 ms to the input delayed by the latency, so a neutral setting //! is a plain delay. +//! +//! The formant shifter (`voice_formant`) moves the spectral envelope of the voice up or down while +//! its harmonics stay where they are. It runs a short STFT (512 points at up to 50 kHz, hop 128). +//! For each frame it fits a linear predictor (one coefficient per kHz plus 2, at most 96) to the +//! last two frame lengths of input (1,024 samples at 48 kHz), which end with the frame and add no +//! latency, and takes the +//! envelope from the predictor. It then multiplies every bin by the envelope read at +//! `bin / ratio` over the envelope at the bin, with at most 24 dB of boost. Its latency is the +//! STFT size. `voice_pitch` uses the same stage for Keep Formants: the stage moves the shifted +//! voice's envelope back by the inverse of the pitch ratio, so the pitch changes and the formants +//! stay, and the latency grows by the STFT size. +use super::stft::{Spectral, StftChannel, fft_size}; use crate::biquad::{Biquad, Coeffs, FilterType}; +use crate::fft::Fft; use crate::{AudioEffect, ParamSpec, ParamValues, Unit, block_len, flush32, param_plumbing}; use std::f64::consts::PI; @@ -33,13 +49,31 @@ const MARGIN: f64 = 2.0; const MAX_STEP: f64 = 0.45; /// Analysis input is clipped to this level, so a huge sample cannot overflow the tracker. const TRACK_CLIP: f64 = 1.0e4; +/// Fewest and most predictor coefficients of the formant envelope (one per kHz plus 2 between). +const MIN_ORDER: usize = 8; +const MAX_ORDER: usize = 96; +/// Width of the Gaussian lag window, which widens each envelope peak to about this many hertz. +const LAG_HZ: f64 = 40.0; +/// White noise added to the autocorrelation (60 dB down), so a pure tone still gives a stable +/// predictor. +const WHITE: f64 = 1.0e-6; +/// Largest boost the envelope warp gives one bin: ln 16, about 24 dB. +const MAX_BOOST: f64 = 2.772_588_722_239_781; + +/// STFT size of the formant stage: 512 at up to 50 kHz (10.7 ms at 48 kHz), 1024 up to 100 kHz, +/// 2048 above. +fn formant_size(sample_rate: f32) -> usize { + fft_size(sample_rate) / 4 +} /// Fundamental period of the recent input, from YIN (de Cheveigné and Kawahara, 2002) run on a /// low-passed, decimated copy. Every buffer is sized at creation. /// -/// It keeps two copies: the mean of the channels, and the first channel alone. A frame whose -/// mean holds less than a quarter of the first channel's energy (channels of opposite polarity -/// cancel in the mean) is analyzed on the first channel. +/// It keeps two copies: the mean of the channels, and one channel alone. A frame whose mean holds +/// less than a quarter of that channel's energy (channels of opposite polarity cancel in the +/// mean) is analyzed on that channel. The channel is the first one until another channel holds +/// over four times its energy through one hop; the tracker then moves to the loudest channel, and +/// analyzes that channel's copy only once a whole frame of it has come in. #[derive(Clone, Debug)] struct Tracker { /// Input samples per analysis sample. @@ -56,10 +90,16 @@ struct Tracker { max_tau: usize, /// Period in input samples, or `None` when the last frame was unvoiced. period: Option, + /// Channel the second copy holds. + channel: usize, + /// Energy of each channel's clipped input since the last analysis. + energy: Vec, + /// Analysis samples of `channel` in the second copy, up to the frame length. + filled: usize, } impl Tracker { - fn new(sample_rate: f32) -> Self { + fn new(sample_rate: f32, channels: usize) -> Self { let factor = (sample_rate / TRACK_RATE).round().max(1.0) as usize; let rate = sample_rate / factor as f32; let max_hz = MAX_HZ.min(rate / 4.0); @@ -82,6 +122,10 @@ impl Tracker { min_tau, max_tau, period: None, + channel: 0, + energy: vec![0.0; channels.max(1)], + // The zeros the copy starts with are the first channel's silence. + filled: len, } } @@ -91,12 +135,23 @@ impl Tracker { self.at = 0; self.since = 0; self.period = None; + self.channel = 0; + self.energy.fill(0.0); + self.filled = self.frame.len(); } - /// Takes one input sample, as the mean of the channels and the first channel; runs an - /// analysis every `hop` analysis samples. - fn push(&mut self, mean: f32, first: f32) { - let clipped = [mean, first].map(|x| (x as f64).clamp(-TRACK_CLIP, TRACK_CLIP)); + /// Adds one input sample of channel `c` to that channel's energy. + fn measure(&mut self, c: usize, x: f32) { + if let Some(e) = self.energy.get_mut(c) { + let x = (x as f64).clamp(-TRACK_CLIP, TRACK_CLIP); + *e += x * x; + } + } + + /// Takes one input sample, as the mean of the channels and the sample of the channel in + /// `self.channel`; runs an analysis every `hop` analysis samples. + fn push(&mut self, mean: f32, single: f32) { + let clipped = [mean, single].map(|x| (x as f64).clamp(-TRACK_CLIP, TRACK_CLIP)); for (feed, x) in self.feeds.iter_mut().zip(clipped) { feed.filter(&self.coeffs, x); } @@ -110,16 +165,34 @@ impl Tracker { feed.ring[self.at] = feed.last as f32; } self.at = (self.at + 1) & mask; + self.filled = (self.filled + 1).min(self.frame.len()); self.since += 1; if self.since >= self.hop { self.since = 0; self.analyze(); + self.choose_channel(); } } + /// Moves the second copy to the loudest channel when that channel held over four times the + /// energy of the one in use since the last analysis. The first of equally loud channels wins. + fn choose_channel(&mut self) { + let loudest = (0..self.energy.len()).fold(0, |b, c| if self.energy[c] > self.energy[b] { c } else { b }); + if self.energy[self.channel] < 0.25 * self.energy[loudest] { + self.channel = loudest; + self.feeds[1].reset(); + self.filled = 0; + } + self.energy.fill(0.0); + } + fn analyze(&mut self) { - let [mean, first] = [0, 1].map(|f| self.feeds[f].ring.iter().map(|v| v * v).sum::()); - let feed = if mean < 0.25 * first { &self.feeds[1] } else { &self.feeds[0] }; + let [mean, single] = [0, 1].map(|f| self.feeds[f].ring.iter().map(|v| v * v).sum::()); + if mean < 0.25 * single && self.filled < self.frame.len() { + // The channel's copy holds less than a frame since the move: keep the last period. + return; + } + let feed = if mean < 0.25 * single { &self.feeds[1] } else { &self.feeds[0] }; let mask = self.frame.len() - 1; for (i, v) in self.frame.iter_mut().enumerate() { *v = feed.ring[(self.at + i) & mask]; @@ -229,10 +302,16 @@ struct Taps { delay_b: f64, } -/// Pitch shifter for a live voice, 10 ms of latency (±24 semitones and ±100 cents). +/// Pitch shifter for a live voice, 10 ms of latency (±24 semitones and ±100 cents). Keep Formants +/// (`formant_follow`) adds the formant stage's latency, 10.7 ms at 48 kHz, and `latency` reports +/// it while the switch is on. pub struct VoicePitch { pv: ParamValues, latency: usize, + /// Formant stage of Keep Formants, and the share of its output against the shifted voice. + follow: Stage, + follow_mix: f64, + follow_on: bool, /// Widest tap spacing that keeps both taps inside the line, in samples. max_spacing: f64, lines: Vec>, @@ -252,6 +331,7 @@ impl VoicePitch { pub const PARAMS: &'static [ParamSpec] = &[ ParamSpec::new("semitones", "Pitch", -24.0, 24.0, 0.0, Unit::Semitones), ParamSpec::new("cents", "Fine Tune (cents)", -100.0, 100.0, 0.0, Unit::None), + ParamSpec::new("formant_follow", "Keep Formants", 0.0, 1.0, 0.0, Unit::Toggle), ]; pub fn new(sample_rate: f32, channels: usize) -> Self { @@ -262,11 +342,14 @@ impl VoicePitch { let mut s = VoicePitch { pv: ParamValues::new(Self::PARAMS), latency, + follow: Stage::new(sample_rate, ch), + follow_mix: 0.0, + follow_on: false, max_spacing: latency as f64 - MARGIN, lines: vec![vec![0.0; len]; ch], mask: len - 1, pos: 0, - tracker: Tracker::new(sample_rate), + tracker: Tracker::new(sample_rate, ch), ratio: 1.0, phase: 0.5, spacing: latency as f64 - MARGIN, @@ -280,11 +363,17 @@ impl VoicePitch { fn apply_params(&mut self, snap: bool) { let shift = self.pv.v("semitones") as f64 + self.pv.v("cents") as f64 / 100.0; self.ratio = 2f64.powf(shift / 12.0); + self.follow_on = self.pv.v("formant_follow") >= 0.5; if snap { self.wet = self.target_wet(); + self.follow_mix = self.follow_target(); } } + fn follow_target(&self) -> f64 { + if self.follow_on { 1.0 } else { 0.0 } + } + fn target_wet(&self) -> f64 { if self.ratio == 1.0 { 0.0 } else { 1.0 } } @@ -341,12 +430,13 @@ impl VoicePitch { impl AudioEffect for VoicePitch { param_plumbing!("voice_pitch"); fn latency(&self) -> usize { - self.latency + self.latency + if self.follow_on { self.follow.n } else { 0 } } fn tail_samples(&self) -> usize { // A tap reads up to `latency + max_spacing` samples back and the cubic read two samples - // more, which is twice the latency in all. - self.latency + // more, which is twice the latency in all. Keep Formants spreads a frame over up to the + // formant stage's size more. A render drains `latency() + tail_samples()` samples. + self.latency + if self.follow_on { self.follow.n } else { 0 } } fn reset(&mut self) { self.lines.iter_mut().for_each(|l| l.iter_mut().for_each(|v| *v = 0.0)); @@ -355,23 +445,43 @@ impl AudioEffect for VoicePitch { self.phase = 0.5; self.spacing = self.max_spacing; self.wet = self.target_wet(); + self.follow.reset(); + self.follow_mix = self.follow_target(); } fn process(&mut self, channels: &mut [&mut [f32]]) { let len = block_len(channels); - let ch = channels.len().min(self.lines.len()); + let ch = self.lines.len(); let dry_at = self.mask + 1 - self.latency; + let follow_target = self.follow_target(); + // The formant stage moves the envelope by the inverse of the pitch ratio. + let back = (1.0 / self.ratio) as f32; for i in 0..len { let mut sum = 0.0f32; - for (line, io) in self.lines.iter_mut().zip(channels.iter()) { - // A non-finite sample is stored as silence, so it never reaches the output. - let x = flush32(io[i]); + for (c, line) in self.lines.iter_mut().enumerate() { + // A non-finite sample is stored as silence, so it never reaches the output. A + // channel the block leaves out is stored as silence too while its line advances, + // so after a gap of at least `latency() + tail_samples()` samples it holds none of + // its earlier audio; after a shorter gap, audio still in the line can sound. + let x = channels.get(c).map_or(0.0, |io| flush32(io[i])); line[self.pos] = x; sum += x; + self.tracker.measure(c, x); } - let first = self.lines[0][self.pos]; - self.tracker.push(sum / ch as f32, first); + let single = self.lines[self.tracker.channel][self.pos]; + self.tracker.push(sum / ch as f32, single); let t = self.advance(); - for (line, io) in self.lines.iter().zip(channels.iter_mut()) { + let mix = if self.follow_mix < follow_target { + (self.follow_mix + self.wet_step).min(follow_target) + } else { + (self.follow_mix - self.wet_step).max(follow_target) + }; + self.follow_mix = mix; + // While Keep Formants is off and faded out, the stage's frames copy the shifted voice, + // so switching it on crossfades from a delayed copy instead of from silence. + let warp = if mix > 0.0 { back } else { 1.0 }; + // A channel the block leaves out still reads its line into the formant stage, so the + // audio its line holds reaches the stage on time; only its output is dropped. + for (c, line) in self.lines.iter().enumerate() { let dry = line[(self.pos + dry_at) & self.mask] as f64; let y = if t.wet == 0.0 { dry @@ -380,13 +490,290 @@ impl AudioEffect for VoicePitch { t.gain_a * read(line, self.mask, self.pos, t.delay_a) + (1.0 - t.gain_a) * read(line, self.mask, self.pos, t.delay_b); t.wet * shifted + (1.0 - t.wet) * dry }; - io[i] = y.clamp(-f32::MAX as f64, f32::MAX as f64) as f32; + let y = y.clamp(-f32::MAX as f64, f32::MAX as f64); + let z = self.follow.tick(c, y as f32, warp); + // The stage's output is `n` samples later than `y`, so a switch fades one out + // before the other comes in instead of mixing them. + let out = if mix < 0.5 { (1.0 - 2.0 * mix) * y } else { (2.0 * mix - 1.0) * z as f64 }; + if let Some(io) = channels.get_mut(c) { + io[i] = out.clamp(-f32::MAX as f64, f32::MAX as f64) as f32; + } } self.pos = (self.pos + 1) & self.mask; } } } +/// Spectral envelope of the recent input from linear prediction, and the warp that moves it. +/// Every buffer is sized at creation. +#[derive(Clone, Debug)] +struct Envelope { + fft: Fft, + /// Hann window over the analyzed history. + window: Vec, + /// Gaussian lag window, one value per autocorrelation lag (`order + 1`). + lags: Vec, + frame: Vec, + r: Vec, + /// Predictor coefficients, `a[0] = 1`. + a: Vec, + prev: Vec, + re: Vec, + im: Vec, + /// Natural log of the envelope's magnitude, bins 0..=n/2 of the STFT. + log: Vec, +} + +impl Envelope { + /// An envelope for STFT frames of `n` points, read from the last `2 n` samples. + fn new(n: usize, sample_rate: f32) -> Self { + let order = ((sample_rate / 1000.0).round() as usize + 2).clamp(MIN_ORDER, MAX_ORDER); + let w = 2 * n; + let window = (0..w).map(|i| 0.5 - 0.5 * (2.0 * PI * (i as f64 + 0.5) / w as f64).cos()).collect(); + let lags = (0..=order) + .map(|i| { + let x = 2.0 * PI * LAG_HZ * i as f64 / sample_rate as f64; + (-0.5 * x * x).exp() + }) + .collect(); + Envelope { + fft: Fft::new(n), + window, + lags, + frame: vec![0.0; w], + r: vec![0.0; order + 1], + a: vec![0.0; order + 1], + prev: vec![0.0; order + 1], + re: vec![0.0; n], + im: vec![0.0; n], + log: vec![0.0; n / 2 + 1], + } + } + + /// Reads the envelope of the newest `2 n` samples of `history`. Returns `false` for silence, + /// which has no envelope. + fn measure(&mut self, history: &History) -> bool { + let mask = history.ring.len() - 1; + for (i, (v, w)) in self.frame.iter_mut().zip(&self.window).enumerate() { + *v = history.ring[(history.pos + i) & mask] as f64 * w; + } + let len = self.frame.len(); + self.r[0] = dot(&self.frame, &self.frame) * self.lags[0]; + if !(self.r[0] > 0.0 && self.r[0].is_finite()) { + return false; + } + for (lag, (r, w)) in self.r.iter_mut().zip(&self.lags).enumerate().skip(1) { + *r = dot(&self.frame[..len - lag], &self.frame[lag..]) * w; + } + self.r[0] *= 1.0 + WHITE; + levinson(&self.r, &mut self.a, &mut self.prev); + // The envelope is 1 / |A| on the bins of the STFT. + self.re.fill(0.0); + self.im.fill(0.0); + for (v, a) in self.re.iter_mut().zip(&self.a) { + *v = *a as f32; + } + self.fft.forward(&mut self.re, &mut self.im); + for (l, (re, im)) in self.log.iter_mut().zip(self.re.iter().zip(&self.im)) { + *l = (-0.5 * (*re as f64 * *re as f64 + *im as f64 * *im as f64 + 1e-30).ln()) as f32; + } + true + } + + /// Multiplies the half spectrum `re`/`im` (bins 0..=n/2) by the envelope read at `bin / + /// ratio` over the envelope at the bin, so the envelope moves up by `ratio` and the + /// harmonics stay. A frame with a non-finite bin is replaced with silence. + fn warp(&self, re: &mut [f32], im: &mut [f32], ratio: f32) { + let half = self.log.len(); + let (re, im) = (&mut re[..half], &mut im[..half]); + if !re.iter().chain(im.iter()).fold(true, |ok, v| ok & v.is_finite()) { + re.fill(0.0); + im.fill(0.0); + return; + } + let last = (half - 1) as f32; + for k in 0..half { + let src = (k as f32 / ratio).min(last); + let i = src as usize; + let e = match self.log.get(i + 1) { + Some(next) => self.log[i] + (src - i as f32) * (next - self.log[i]), + None => self.log[i], + }; + let g = ((e - self.log[k]) as f64).min(MAX_BOOST).exp() as f32; + re[k] *= g; + im[k] *= g; + } + } +} + +/// Dot product of two slices of the same length, in four running sums so it vectorizes. +fn dot(a: &[f64], b: &[f64]) -> f64 { + let mut sums = [0.0f64; 4]; + let ((ca, ra), (cb, rb)) = (a.as_chunks::<4>(), b.as_chunks::<4>()); + for (x, y) in ca.iter().zip(cb) { + for ((s, x), y) in sums.iter_mut().zip(x).zip(y) { + *s += x * y; + } + } + let rest: f64 = ra.iter().zip(rb).map(|(x, y)| x * y).sum(); + (sums[0] + sums[1]) + (sums[2] + sums[3]) + rest +} + +/// Levinson-Durbin recursion: the predictor `a` (`a[0] = 1`) of the autocorrelation `r`. It +/// stops at the first reflection coefficient that would make the predictor unstable. +fn levinson(r: &[f64], a: &mut [f64], prev: &mut [f64]) { + a.fill(0.0); + a[0] = 1.0; + let mut err = r[0]; + for i in 1..a.len() { + let acc = r[i] + (1..i).map(|j| a[j] * r[i - j]).sum::(); + let k = -acc / err; + // NaN (from a zero error) also stops the recursion. + if k.is_nan() || k.abs() >= 1.0 { + return; + } + prev[..i].copy_from_slice(&a[..i]); + for j in 1..i { + a[j] = prev[j] + k * prev[i - j]; + } + a[i] = k; + err *= 1.0 - k * k; + } +} + +/// The newest samples of one channel, for the envelope. +#[derive(Clone, Debug)] +struct History { + ring: Vec, + /// Where the next sample goes, which is also the oldest sample. + pos: usize, +} + +impl History { + fn push(&mut self, x: f32) { + self.ring[self.pos] = x; + self.pos = (self.pos + 1) & (self.ring.len() - 1); + } + + fn reset(&mut self) { + self.ring.fill(0.0); + self.pos = 0; + } +} + +/// STFT stage that moves each channel's envelope, fed one sample at a time: the formant +/// shifter, and the formant stage of `voice_pitch`'s Keep Formants. +#[derive(Clone, Debug)] +struct Stage { + n: usize, + hop: usize, + scale: f32, + spec: Spectral, + stft: Vec, + history: Vec, + env: Envelope, +} + +impl Stage { + fn new(sample_rate: f32, channels: usize) -> Self { + let n = formant_size(sample_rate); + Stage { + n, + hop: n / 4, + // √Hann on both sides is Hann, which sums to 2 at a hop of n/4; the inverse FFT is + // unscaled. + scale: 1.0 / (2 * n) as f32, + spec: Spectral::new(n, true), + stft: vec![StftChannel::new(n); channels], + history: vec![History { ring: vec![0.0; 2 * n], pos: 0 }; channels], + env: Envelope::new(n, sample_rate), + } + } + + fn reset(&mut self) { + self.stft.iter_mut().for_each(StftChannel::reset); + self.history.iter_mut().for_each(History::reset); + } + + /// Pushes one sample of a channel and returns the stage's output for it, `n` samples later. + /// A frame moves the envelope by `ratio`, which can spread a sound over the frame, so the + /// output can go on for up to `n` samples more (the tail). At a ratio of 1, and for silence, a frame only + /// windows and adds its input, which needs no FFT. + fn tick(&mut self, channel: usize, x: f32, ratio: f32) -> f32 { + let Stage { n, hop, scale, spec, stft, history, env } = self; + let half = *n / 2 + 1; + history[channel].push(x); + let history = &history[channel]; + let z = stft[channel].tick(x, *hop, &mut |input, out| { + if ratio != 1.0 && env.measure(history) { + spec.analyze(input); + env.warp(&mut spec.re[..half], &mut spec.im[..half], ratio); + spec.synthesize_add(out, *scale); + } else { + for ((o, x), w) in out.iter_mut().zip(input).zip(&spec.window) { + *o += x * w * w * 0.5; + } + } + }); + // A huge finite input can overflow the inverse FFT. + flush32(z) + } +} + +/// Formant shifter for a live voice: moves the spectral envelope by -12 to +12 semitones (a ratio +/// of 0.5 to 2) and keeps the harmonics. Its latency is the STFT size, 512 samples (10.7 ms) at +/// 48 kHz. +pub struct VoiceFormant { + pv: ParamValues, + stage: Stage, + ratio: f32, +} + +impl VoiceFormant { + pub const PARAMS: &'static [ParamSpec] = &[ParamSpec::new("semitones", "Formant Shift", -12.0, 12.0, 0.0, Unit::Semitones)]; + + pub fn new(sample_rate: f32, channels: usize) -> Self { + let sample_rate = crate::sane_sample_rate(sample_rate); + let mut s = VoiceFormant { pv: ParamValues::new(Self::PARAMS), stage: Stage::new(sample_rate, crate::sane_channels(channels)), ratio: 1.0 }; + s.apply_params(true); + s + } + + fn apply_params(&mut self, _snap: bool) { + self.ratio = 2f32.powf(self.pv.v("semitones") / 12.0); + } +} + +impl AudioEffect for VoiceFormant { + param_plumbing!("voice_formant"); + fn latency(&self) -> usize { + self.stage.n + } + fn tail_samples(&self) -> usize { + self.stage.n + } + fn reset(&mut self) { + self.stage.reset(); + } + fn process(&mut self, channels: &mut [&mut [f32]]) { + let len = block_len(channels); + for i in 0..len { + for c in 0..self.stage.stft.len() { + // A non-finite sample is taken as silence, so it never reaches the output. A + // channel the block leaves out is fed silence while its state advances, so after + // a gap of at least `latency() + tail_samples()` samples it holds none of its + // earlier audio; after a shorter gap, audio still pending can sound. + match channels.get_mut(c) { + Some(io) => io[i] = self.stage.tick(c, flush32(io[i]), self.ratio), + None => { + self.stage.tick(c, 0.0, self.ratio); + } + } + } + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -455,6 +842,24 @@ mod tests { } } + /// With a silent first channel, a voice on the other two channels in opposite polarity is + /// still tracked from one of them and crossfades without beating. + #[test] + fn opposite_polarity_beside_a_silent_first_channel_is_still_tracked() { + let mut p = VoicePitch::new(SR, 3); + assert!(p.set_param("semitones", 7.0)); + p.reset(); + let n = SR as usize * 2; + let mut silent = vec![0.0f32; n]; + let mut l = sine(220.0, 0.5, SR as f64, n, 0.0); + let mut r: Vec = l.iter().map(|v| -v).collect(); + p.process(&mut [&mut silent, &mut l, &mut r]); + assert!(silent.iter().all(|v| *v == 0.0)); + assert!(l.iter().zip(&r).all(|(a, b)| *a == -*b)); + let rest = beside_tone_db(&l, 220.0 * 2f64.powf(7.0 / 12.0)); + assert!(rest < -40.0, "{rest:.1} dB beside the tone"); + } + /// A voice whose two channels have opposite polarity, which cancel in their mean, is still /// tracked and crossfades without beating. #[test] @@ -557,18 +962,357 @@ mod tests { assert!(db(rms(tail) / (0.5 / std::f64::consts::SQRT_2)).abs() < 1.0, "level {}", rms(tail)); } + /// Two-pole resonance magnitude at `f`, 1 at `center`. + fn resonance(f: f64, center: f64, bandwidth: f64) -> f64 { + center * bandwidth / ((center * center - f * f).powi(2) + (f * bandwidth).powi(2)).sqrt() + } + + /// A vowel: harmonics of `f0` up to 6 kHz shaped by two formants (`f1` with an 80 Hz + /// bandwidth, `f2` with 120 Hz and half the level) over a floor 34 dB down. + fn vowel(f0: f64, f1: f64, f2: f64, sr: f64, n: usize) -> Vec { + let harmonics: Vec<(f64, f64)> = (1..) + .map(|k| k as f64 * f0) + .take_while(|f| *f < 6000.0) + .map(|f| (f, 0.02 + resonance(f, f1, 80.0) + 0.5 * resonance(f, f2, 120.0))) + .collect(); + (0..n) + .map(|i| { + let t = i as f64 / sr; + (0.08 * harmonics.iter().map(|(f, a)| a * (2.0 * std::f64::consts::PI * f * t).sin()).sum::()) as f32 + }) + .collect() + } + + /// The envelope peak of `y` between `lo` and `hi` Hz, read from the amplitudes of the + /// harmonics of `f0` with a parabola through the strongest one and its neighbors (in dB). + fn envelope_peak(y: &[f32], f0: f64, lo: f64, hi: f64, sr: f64) -> f64 { + let amp = |k: usize| tone_amplitude(y, k as f64 * f0, sr).max(1e-12).ln(); + let ks = (lo / f0).ceil() as usize..=(hi / f0).floor() as usize; + let k = ks.max_by(|a, b| amp(*a).total_cmp(&(*b))).unwrap_or(1); + let (a, b, c) = (amp(k - 1), amp(k), amp(k + 1)); + let denom = a - 2.0 * b + c; + let shift = if denom.abs() > 1e-12 { (0.5 * (a - c) / denom).clamp(-1.0, 1.0) } else { 0.0 }; + (k as f64 + shift) * f0 + } + + /// The second of `y` after its first half second, at the rate `sr`. + fn settled_at(y: &[f32], sr: f64) -> &[f32] { + &y[sr as usize / 2..sr as usize * 3 / 2] + } + + /// The two formants of the vowel test signal (600 and 2000 Hz) in `y`, each looked for within + /// a window moved by `ratio`, with `y`'s harmonics at multiples of `f0`. + fn formants(y: &[f32], f0: f64, ratio: f64, sr: f64) -> (f64, f64) { + let tail = settled_at(y, sr); + (envelope_peak(tail, f0, 400.0 * ratio, 1000.0 * ratio, sr), envelope_peak(tail, f0, 1400.0 * ratio, 3000.0 * ratio, sr)) + } + + /// Level of everything off the harmonics of `f0` in `y`'s settled second, against the whole, + /// in dB. + fn off_harmonics_db(y: &[f32], f0: f64, sr: f64) -> f64 { + let tail = settled_at(y, sr); + let total = rms(tail).powi(2); + let on: f64 = (1..).map(|k| k as f64 * f0).take_while(|f| *f < sr / 2.0 - f0).map(|f| tone_amplitude(tail, f, sr).powi(2) / 2.0).sum(); + 10.0 * ((total - on).max(1e-30) / total).log10() + } + + /// A formant shift moves both formants of a vowel by the ratio, within a tenth of the move for + /// the first and 5% for the second, while every partial stays on the harmonics of the + /// unchanged fundamental. Checked at three voice pitches and three sample rates. + #[test] + fn a_formant_shift_moves_the_envelope_and_keeps_the_harmonics() { + for sr in [44_100.0, 48_000.0, 96_000.0] { + for f0 in [110.0, 150.0, 220.0] { + let x = vowel(f0, 600.0, 2000.0, sr, sr as usize * 2); + let (p1, p2) = formants(&x, f0, 1.0, sr); + for semis in [-4.0f32, 4.0] { + let mut f = VoiceFormant::new(sr as f32, 1); + assert!(f.set_param("semitones", semis)); + let mut y = x.clone(); + f.process(&mut [&mut y]); + let r = 2f64.powf(semis as f64 / 12.0); + let (q1, q2) = formants(&y, f0, r, sr); + let at = format!("{sr} Hz, f0 {f0}, {semis:+} st: formants {p1:.0} and {p2:.0} moved to {q1:.0} and {q2:.0}"); + assert!((q1 / (p1 * r) - 1.0).abs() < 0.12, "{at}"); + assert!((q2 / (p2 * r) - 1.0).abs() < 0.05, "{at}"); + let off = off_harmonics_db(&y, f0, sr); + assert!(off < -30.0, "{at}: {off:.1} dB off the harmonics"); + } + } + } + } + + /// Keep Formants: the pitch moves up a fourth, and the formants of the vowel stay where they + /// were (where without it they move with the pitch). + #[test] + fn keep_formants_holds_the_envelope_while_the_pitch_moves() { + let (sr, f0) = (SR as f64, 150.0); + let x = vowel(f0, 600.0, 2000.0, sr, SR as usize * 2); + let (p1, p2) = formants(&x, f0, 1.0, sr); + let r = 2f64.powf(5.0 / 12.0); + for keep in [false, true] { + let mut p = shifter(5.0, 0.0); + assert!(p.set_param("formant_follow", if keep { 1.0 } else { 0.0 })); + p.reset(); + let y = run(&mut p, &x); + let want = if keep { 1.0 } else { r }; + let (q1, q2) = formants(&y, f0 * r, want, sr); + let at = format!("keep {keep}: formants {p1:.0} and {p2:.0} read {q1:.0} and {q2:.0}"); + assert!((q1 / (p1 * want) - 1.0).abs() < 0.12, "{at}"); + assert!((q2 / (p2 * want) - 1.0).abs() < 0.05, "{at}"); + assert!(cents(peak_hz(settled(&y), f0 * r * 0.98, f0 * r * 1.02), f0 * r).abs() < 2.0, "keep {keep}: pitch"); + } + } + + /// Keep Formants adds the formant shifter's latency to the pitch shifter's while it is on, at + /// each rate. + #[test] + fn the_latency_reports_the_formant_stage() { + for sr in [44_100.0, 48_000.0, 96_000.0] { + let n = VoiceFormant::new(sr, 2).latency(); + assert!(n > 0, "{sr}"); + let mut p = VoicePitch::new(sr, 2); + let base = p.latency(); + assert!(p.set_param("formant_follow", 1.0)); + assert_eq!(p.latency(), base + n, "{sr}"); + assert!(p.set_param("formant_follow", 0.0)); + assert_eq!(p.latency(), base, "{sr}"); + } + } + + /// After a burst of noise ends, the formant shifter and the pitch shifter with Keep Formants + /// fall silent within `latency + tail_samples`, so an offline render that drains that long + /// keeps all of the output. + #[test] + fn formant_output_ends_within_the_reported_tail() { + let (n, at, len) = (12_000, 1_777, 1_000); + let mut rng = Rng::new(17); + let mut x = vec![0.0f32; n]; + x[at..at + len].iter_mut().for_each(|v| *v = 0.5 * rng.uniform()); + let mut f = VoiceFormant::new(SR, 1); + assert!(f.set_param("semitones", 7.0)); + let mut p = shifter(-5.0, 0.0); + assert!(p.set_param("formant_follow", 1.0)); + p.reset(); + let fxs: [&mut dyn AudioEffect; 2] = [&mut f, &mut p]; + for fx in fxs { + let mut y = x.clone(); + fx.process(&mut [&mut y]); + let end = at + len + fx.latency() + fx.tail_samples(); + assert!(y[end..].iter().all(|v| *v == 0.0), "{}: output after {end}", fx.id()); + } + } + + /// Switching Keep Formants on fades the shifter's own output out over 10 ms and then fades the + /// formant stage's output, 512 samples later, in over 10 ms: the two never sound together, + /// so their different delays cannot comb-filter the voice. Checked at a shift of 0, where the + /// stage passes the voice unchanged. + #[test] + fn switching_keep_formants_fades_through_silence() { + let x = vowel(170.0, 650.0, 1900.0, SR as f64, 12_000); + let at = 4_000; + let mut plain = shifter(0.0, 0.0); + let y = run(&mut plain, &x); + let mut p = shifter(0.0, 0.0); + let mut out = x.clone(); + p.process(&mut [&mut out[..at]]); + assert!(p.set_param("formant_follow", 1.0)); + p.process(&mut [&mut out[at..]]); + let n = p.follow.n; + let step = 1.0 / (SR as f64 * BYPASS_MS as f64 / 1000.0); + for i in at..x.len() { + let m = ((i - at + 1) as f64 * step).min(1.0); + let want = if m < 0.5 { (1.0 - 2.0 * m) * y[i] as f64 } else { (2.0 * m - 1.0) * y[i - n] as f64 }; + assert!((out[i] as f64 - want).abs() < 1e-4, "sample {i}: {} against {want}", out[i]); + } + } + + /// The formant shifter with a shift change part way, and the pitch shifter with Keep Formants + /// switched on and off part way, give the same output however the stream is cut into blocks. + #[test] + fn formant_output_does_not_depend_on_how_the_stream_is_cut() { + let n = 40_000; + let x = vowel(130.0, 700.0, 1800.0, SR as f64, n); + let changes: [(usize, &str, f32); 3] = [(9_001, "semitones", 3.0), (17_321, "formant_follow", 1.0), (29_999, "formant_follow", 0.0)]; + let run_cut = |make: &dyn Fn() -> Box, sizes: &mut dyn FnMut() -> usize| { + let mut fx = make(); + let mut y = x.clone(); + let mut pos = 0; + while pos < n { + for (at, id, v) in changes { + if pos == at { + fx.set_param(id, v); + } + } + let next = changes.iter().map(|c| c.0).find(|at| *at > pos).unwrap_or(n); + let len = sizes().min(next - pos); + fx.process(&mut [&mut y[pos..pos + len]]); + pos += len; + } + y + }; + let makers: [&dyn Fn() -> Box; 2] = [ + &|| { + let mut f = VoiceFormant::new(SR, 1); + f.set_param("semitones", -5.0); + Box::new(f) + }, + &|| Box::new(shifter(-3.0, 0.0)), + ]; + for make in makers { + let whole = run_cut(make, &mut || usize::MAX); + let mut rng = Rng::new(13); + let cut = run_cut(make, &mut || (rng.next_u64() % 700) as usize); + assert!(whole.iter().zip(&cut).all(|(a, b)| a.to_bits() == b.to_bits())); + assert!(whole.iter().any(|v| v.abs() > 0.05)); + } + } + + /// NaN, infinite and the largest finite samples in a vowel give finite output from the formant + /// shifter and from Keep Formants, and the formants are still moved afterwards. + #[test] + fn formant_stage_output_stays_finite() { + let (sr, f0) = (SR as f64, 150.0); + let mut x = vowel(f0, 600.0, 2000.0, sr, SR as usize * 2); + let (p1, p2) = formants(&x, f0, 1.0, sr); + for (i, bad) in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX, -f32::MAX].into_iter().enumerate() { + x[3000 + i * 1500] = bad; + x[3001 + i * 1500] = bad; + } + let mut f = VoiceFormant::new(SR, 2); + assert!(f.set_param("semitones", 4.0)); + let (mut l, mut r) = (x.clone(), x.clone()); + f.process(&mut [&mut l, &mut r]); + assert!(l.iter().chain(&r).all(|v| v.is_finite())); + let ratio = 2f64.powf(4.0 / 12.0); + let (q1, _) = formants(&l, f0, ratio, sr); + assert!((q1 / (p1 * ratio) - 1.0).abs() < 0.12, "{q1}"); + let mut p = shifter(-7.0, 0.0); + assert!(p.set_param("formant_follow", 1.0)); + let y = run(&mut p, &x); + assert!(y.iter().all(|v| v.is_finite())); + assert!(rms(settled(&y)) > 0.01); + let shifted_f0 = f0 * 2f64.powf(-7.0 / 12.0); + let (q1, q2) = formants(&y, shifted_f0, 1.0, sr); + assert!((q1 / p1 - 1.0).abs() < 0.12, "Keep Formants: {p1} read {q1}"); + assert!((q2 / p2 - 1.0).abs() < 0.05, "Keep Formants: {p2} read {q2}"); + } + + /// A block that leaves channels out feeds them silence, so when they come back without a + /// reset, after a gap at least as long as the latency and the tail, none of their earlier + /// audio sounds. Checked for the formant shifter and for the pitch shifter with and without + /// Keep Formants. + #[test] + fn channels_left_out_of_a_block_come_back_silent() { + let mut rng = Rng::new(19); + let noise: Vec = (0..4_000).map(|_| 0.5 * rng.uniform()).collect(); + let mut f = VoiceFormant::new(SR, 3); + assert!(f.set_param("semitones", 4.0)); + let mut plain = VoicePitch::new(SR, 3); + assert!(plain.set_param("semitones", 5.0)); + plain.reset(); + let mut keep = VoicePitch::new(SR, 3); + assert!(keep.set_param("semitones", 5.0) && keep.set_param("formant_follow", 1.0)); + keep.reset(); + let fxs: [&mut dyn AudioEffect; 3] = [&mut f, &mut plain, &mut keep]; + for fx in fxs { + assert!(fx.latency() + fx.tail_samples() <= noise.len(), "{}: the gap is shorter than the latency and the tail", fx.id()); + let (mut a, mut b, mut c) = (noise.clone(), noise.clone(), noise.clone()); + fx.process(&mut [&mut a, &mut b, &mut c]); + let mut a = noise.clone(); + fx.process(&mut [&mut a]); + let (mut a, mut b, mut c) = (vec![0.0f32; 4_000], vec![0.0f32; 4_000], vec![0.0f32; 4_000]); + fx.process(&mut [&mut a, &mut b, &mut c]); + assert!(b.iter().chain(&c).all(|v| *v == 0.0), "{}: earlier audio came back", fx.id()); + } + } + + /// With Keep Formants on, a channel left out of a short block while its line still holds an + /// impulse passes that impulse to the formant stage, so after it comes back its output matches + /// a channel that was never left out. + #[test] + fn a_short_gap_keeps_the_formant_stage_fed() { + for semitones in [0.0, 5.0] { + let mut p = VoicePitch::new(SR, 2); + assert!(p.set_param("semitones", semitones) && p.set_param("formant_follow", 1.0)); + p.reset(); + let (mut a, mut b) = (vec![0.0f32; 480], vec![0.0f32; 480]); + a[0] = 1.0; + b[0] = 1.0; + p.process(&mut [&mut a, &mut b]); + // The impulse leaves the delay line during samples 480 to 735, while `b` is left out. + let mut a = vec![0.0f32; 256]; + p.process(&mut [&mut a]); + let (mut a, mut b) = (vec![0.0f32; 2_000], vec![0.0f32; 2_000]); + p.process(&mut [&mut a, &mut b]); + assert!(a.iter().any(|v| v.abs() > 0.01), "{semitones}: the impulse never came out"); + assert_eq!(a, b, "{semitones}: the left-out channel lost the impulse"); + } + } + + /// A block that leaves a channel out gives the same output, once the channel is back, as a + /// block that holds silence for it: with Keep Formants on, an impulse just before the block + /// still sounds afterward. + #[test] + fn a_channel_left_out_of_a_block_runs_as_silence() { + let mut out = Vec::new(); + for omit in [false, true] { + let mut p = VoicePitch::new(SR, 2); + assert!(p.set_param("formant_follow", 1.0)); + p.reset(); + let (mut l, mut r) = (vec![0.0f32; 480], vec![0.0f32; 480]); + r[479] = 1.0; + p.process(&mut [&mut l, &mut r]); + let (mut l, mut r) = (vec![0.0f32; 480], vec![0.0f32; 480]); + if omit { + p.process(&mut [&mut l]); + } else { + p.process(&mut [&mut l, &mut r]); + } + let (mut l, mut r) = (vec![0.0f32; 4_000], vec![0.0f32; 4_000]); + p.process(&mut [&mut l, &mut r]); + assert!(r.iter().any(|v| *v != 0.0), "omit {omit}: the impulse did not sound"); + out.push((l, r)); + } + assert!(out[0] == out[1], "leaving the channel out changed the output"); + } + + /// Leaving a silent third channel out of a block does not change the pitch the tracker finds, + /// so a shifted voice comes out the same on the channels that remain. + #[test] + fn a_silent_channel_left_out_keeps_the_tracked_pitch() { + let n = SR as usize; + let (low, high) = (sine(187.5, 0.2, SR as f64, n, 0.0), sine(375.0, 0.24, SR as f64, n, 0.0)); + let left: Vec = low.iter().zip(&high).map(|(a, b)| a + b).collect(); + let right: Vec = low.iter().zip(&high).map(|(a, b)| -a + b).collect(); + let mut out = Vec::new(); + for omit in [false, true] { + let mut p = VoicePitch::new(SR, 3); + assert!(p.set_param("semitones", 5.0)); + p.reset(); + let (mut l, mut r, mut s) = (left.clone(), right.clone(), vec![0.0f32; n]); + if omit { + p.process(&mut [&mut l, &mut r]); + } else { + p.process(&mut [&mut l, &mut r, &mut s]); + } + out.push((l, r)); + } + assert!(out[0] == out[1], "leaving a silent channel out changed the tracked pitch"); + } + /// The tracker finds a voice's period down to 70 Hz and reports nothing for silence. #[test] fn the_tracker_reaches_70_hz() { for f in [72.0, 110.0, 440.0, 950.0] { - let mut t = Tracker::new(SR); + let mut t = Tracker::new(SR, 1); for v in sine(f, 0.3, SR as f64, SR as usize / 4, 0.0) { t.push(v, v); } let period = t.period.unwrap_or(0.0); assert!((SR as f64 / period / f - 1.0).abs() < 0.005, "{f} Hz read as {} Hz", SR as f64 / period); } - let mut t = Tracker::new(SR); + let mut t = Tracker::new(SR, 1); (0..SR as usize / 4).for_each(|_| t.push(0.0, 0.0)); assert!(t.period.is_none()); } diff --git a/crates/audio-dsp/src/lib.rs b/crates/audio-dsp/src/lib.rs index 59bfaa1741..42018ade17 100644 --- a/crates/audio-dsp/src/lib.rs +++ b/crates/audio-dsp/src/lib.rs @@ -171,8 +171,10 @@ pub trait AudioEffect: Send { /// Parameter descriptions (same as the registry entry's). fn params(&self) -> &'static [ParamSpec]; /// Set a parameter by id; the value is clamped to its range. Returns `false` for unknown ids. - /// Takes effect from the next processed sample. Gains, mix amounts and equalizer bands move to - /// the new value smoothly; the crate documentation lists which other parameters change at once. + /// Updates the target immediately. Sample-based effects use the target from the next processed + /// sample. Frame-based effects may apply it at the next frame callback while earlier output + /// remains queued. Gains, mix amounts and equalizer bands move to the new value smoothly; the + /// crate documentation lists which other parameters change at once. fn set_param(&mut self, id: &str, value: f32) -> bool; /// Current (target) value of a parameter. fn param(&self, id: &str) -> Option; @@ -182,7 +184,11 @@ pub trait AudioEffect: Send { /// Process one block in place. All channel slices must have the same length (the shortest /// length is used otherwise). Zero-length blocks are allowed. fn process(&mut self, channels: &mut [&mut [f32]]); - /// Processing latency in samples (look-ahead / STFT delay) for delay compensation. + /// Processing latency in samples (look-ahead / STFT delay) for delay compensation. It does + /// not change with the parameters, except for `voice_pitch`'s `formant_follow` (Keep + /// Formants), which adds the formant stage's latency while it is on. The value changes as + /// soon as the switch changes, while the output crossfades between the two delays over the + /// next 20 ms, so during that fade the output does not match the reported latency. fn latency(&self) -> usize { 0 } @@ -197,7 +203,13 @@ pub trait AudioEffect: Send { None } /// How long the output keeps sounding after the input stops, in samples (reverb and delay - /// tails), so an offline render can run past the end of its input. + /// tails), so an offline render can run past the end of its input. The count starts after + /// the latency: a render that keeps the tail runs `latency() + tail_samples()` samples past + /// the end of its input. An effect whose output decays without reaching zero (a feedback + /// delay, a resonator) reports where the decay falls below a cutoff, 60 dB under its start + /// for the feedback delays and resonators, so quieter output can still follow that point. + /// Those effects also cap the tail they report at 60 s, which is what a feedback of 1 or more + /// reports. fn tail_samples(&self) -> usize { 0 } @@ -460,6 +472,37 @@ pub(crate) mod testutil { } } + /// Speech-like test signal: voiced syllables (harmonics of a gliding pitch under an envelope), + /// noise bursts (consonants) and pauses. + pub fn speechy(sr: f64, secs: f64, seed: u64) -> Vec { + let n = (sr * secs) as usize; + let mut rng = Rng::new(seed); + let mut out = vec![0.0f32; n]; + let mut i = 0usize; + while i < n { + let len = ((0.08 + 0.25 * (rng.uniform() * 0.5 + 0.5) as f64) * sr) as usize; + let kind = rng.uniform(); + let f0 = 110.0 + 120.0 * (rng.uniform() as f64 * 0.5 + 0.5); + let glide = 1.0 + 0.3 * rng.uniform() as f64; + let amp = 0.2 + 0.3 * (rng.uniform() * 0.5 + 0.5); + for k in 0..len.min(n - i) { + let t = k as f64 / sr; + let env = (std::f64::consts::PI * k as f64 / len as f64).sin() as f32; + let v = if kind > 0.3 { + let f = f0 * (1.0 + (glide - 1.0) * k as f64 / len as f64); + (1..8).map(|h| ((2.0 * std::f64::consts::PI * f * h as f64 * t).sin() / h as f64) as f32).sum::() + } else if kind > -0.4 { + rng.uniform() + } else { + 0.0 + }; + out[i + k] = v * env * amp; + } + i += len + ((rng.uniform() * 0.5 + 0.5) * 0.15 * sr as f32) as usize; + } + out + } + pub fn sine(freq: f64, amp: f64, sr: f64, n: usize, phase: f64) -> Vec { (0..n).map(|i| (amp * (2.0 * std::f64::consts::PI * freq * i as f64 / sr + phase).sin()) as f32).collect() } diff --git a/crates/audio-dsp/src/sync.rs b/crates/audio-dsp/src/sync.rs index d117ecba3f..2ea3b75aac 100644 --- a/crates/audio-dsp/src/sync.rs +++ b/crates/audio-dsp/src/sync.rs @@ -354,38 +354,7 @@ pub fn find_offset(a: &[f32], b: &[f32], sample_rate: u32, opts: &SyncOptions) - #[cfg(test)] mod tests { use super::*; - use crate::testutil::Rng; - - /// Speech-like test signal: voiced syllables (harmonics of a gliding pitch under an envelope), - /// noise bursts (consonants) and pauses. - fn speechy(sr: f64, secs: f64, seed: u64) -> Vec { - let n = (sr * secs) as usize; - let mut rng = Rng::new(seed); - let mut out = vec![0.0f32; n]; - let mut i = 0usize; - while i < n { - let len = ((0.08 + 0.25 * (rng.uniform() * 0.5 + 0.5) as f64) * sr) as usize; - let kind = rng.uniform(); - let f0 = 110.0 + 120.0 * (rng.uniform() as f64 * 0.5 + 0.5); - let glide = 1.0 + 0.3 * rng.uniform() as f64; - let amp = 0.2 + 0.3 * (rng.uniform() * 0.5 + 0.5); - for k in 0..len.min(n - i) { - let t = k as f64 / sr; - let env = (std::f64::consts::PI * k as f64 / len as f64).sin() as f32; - let v = if kind > 0.3 { - let f = f0 * (1.0 + (glide - 1.0) * k as f64 / len as f64); - (1..8).map(|h| ((2.0 * std::f64::consts::PI * f * h as f64 * t).sin() / h as f64) as f32).sum::() - } else if kind > -0.4 { - rng.uniform() - } else { - 0.0 - }; - out[i + k] = v * env * amp; - } - i += len + ((rng.uniform() * 0.5 + 0.5) * 0.15 * sr as f32) as usize; - } - out - } + use crate::testutil::{Rng, speechy}; /// `x` delayed by `delay` samples (fractional: windowed-sinc interpolation), scaled by `gain`, /// optionally colored by a zero-phase low-pass (`[k, 1-2k, k]`, so the delay stays exact), with diff --git a/crates/audio/README.md b/crates/audio/README.md index 75f5694f66..69e9d247c0 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -31,7 +31,7 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | `symphonia` | the fallback for formats with no native decoder; turning it on is the same as `decode` | `decode-native`, symphonia | | `encode` | every encoder, and every format of `encode` and `FileEncoder` | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode`, `opus-encode`, `vorbis-encode` | | `lossless-encode` | WAV, AIFF and FLAC writing | `pcm-encode`, `flac-encode` | -| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | +| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`, `wav_float_header_with_bwf`; `repair_wav` (size fields of a WAV left unfinished by a crash); `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | | `flac-decode` | `flac::decode` (whole `.flac` files) and `flac::Decoder` (single frames, for callers that demux FLAC themselves); native, CRC-checked, 4 to 32 bits. `decode` still uses symphonia for FLAC files | none | | `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` | | `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A and `PacketEncoder` for AAC | craft-media `bitstream`; `aac-encode` also `isobmff` | @@ -218,8 +218,10 @@ target, call `reset()`, decode from there, and drop the output before the target The codec modules are also usable on their own. `aac::Decoder`, `opus::Decoder` and `vorbis::decoder::Decoder` return the codec's channel order; `aac::wav_order(channel_config)`, `opus::wav_order(channels)` and `vorbis::wav_order(channels)` map it to WAV order, and -`vorbis::layout(channels)` gives the speakers of the result. `ac3::Decoder` and `mpa::Decoder` -output WAV order. +`vorbis::layout(channels)` gives the speakers of the result. `opus::wav_order` applies only to +mapping family 1. Family 0 is mono or stereo, which is already in WAV order. For other families, +`TrackDecoder` assigns no conventional speaker mapping and leaves channels in stream order. +`ac3::Decoder` and `mpa::Decoder` output WAV order. ### Encode a file diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index d57baa6b59..f7e69692d4 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -19,9 +19,9 @@ //! - [`TrackDecoder`] (any decoder feature): one track's packets from any demuxer to planar //! `f32` in WAV channel order. //! - [`encode`], [`FileEncoder`]: WAV/BWF/RF64 and AIFF/AIFF-C (feature `pcm-encode`, which also -//! gives [`wav_float_header`]), FLAC (feature `flac-encode`), AAC-LC and ALAC in M4A -//! (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3 streams (`mp3-encode`, `ac3-encode`, -//! `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature +//! gives [`wav_float_header`], [`wav_float_header_with_bwf`] and [`repair_wav`]), FLAC (feature +//! `flac-encode`), AAC-LC and ALAC in M4A (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3 +//! streams (`mp3-encode`, `ac3-encode`, `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature //! `lossless-encode` turns on WAV, AIFF and FLAC; feature `encode` turns on every format and encoder. //! - [`PacketEncoder`] (any of `aac-encode`, `alac-encode`, `mp3-encode`, `ac3-encode`, //! `eac3-encode`, `opus-encode`): planar `f32` in WAV channel order to packets of AAC-LC, ALAC, @@ -209,8 +209,6 @@ pub use track::{LOOKAHEAD_PACKETS, TrackDecoder}; feature = "eac3-encode" ))] pub use write::FileEncoder; -#[cfg(feature = "pcm-encode")] -pub use write::wav_float_header; #[cfg(any( feature = "pcm-encode", feature = "flac-encode", @@ -223,6 +221,8 @@ pub use write::wav_float_header; ))] pub use write::{ENCODE_EXTENSIONS, encode, encode_format_for}; #[cfg(feature = "pcm-encode")] +pub use write::{WavRepair, repair_wav, wav_float_header, wav_float_header_with_bwf}; +#[cfg(feature = "pcm-encode")] pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; /// Errors from probing, decoding and encoding. diff --git a/crates/audio/src/read/wav.rs b/crates/audio/src/read/wav.rs index 2cc5202780..44b2e56423 100644 --- a/crates/audio/src/read/wav.rs +++ b/crates/audio/src/read/wav.rs @@ -3,12 +3,9 @@ use super::source::Src; use crate::pcm::{PcmKind, le_u16, le_u32, le_u64, tag}; -use crate::wav::{GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM}; +use crate::wav::{AMBISONIC_TAIL, GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM}; use crate::{AudioError, AudioInfo, BwfInfo, ChannelLayout, CodecId, Container, Result, SampleFormat}; -/// Tail of the Ambisonic subtype GUIDs {0000000x-0721-11D3-8644-C8C1CA000000}: PCM (x = 1) and float (x = 3) as well. -const AMBISONIC_TAIL: [u8; 14] = [0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00]; - /// Parsed WAV layout (no sample data decoded yet). pub(crate) struct WavLayout { pub info: AudioInfo, @@ -359,7 +356,8 @@ pub(crate) fn parse(src: &Src<'_>) -> Result { ixml_time = ixml_time_reference(&small(IXML_MAX as u64)); } } - b"ds64" => ds64_data = le_u64(&small(64), 8), + // The sizes come from the first `ds64` chunk that holds them. + b"ds64" if ds64_data.is_none() => ds64_data = le_u64(&small(64), 8), _ => {} } } diff --git a/crates/audio/src/s302m.rs b/crates/audio/src/s302m.rs index 205741c529..09f5d6a4c3 100644 --- a/crates/audio/src/s302m.rs +++ b/crates/audio/src/s302m.rs @@ -53,6 +53,9 @@ pub struct Header { impl Header { /// Bytes of one frame (one sample of every channel), or 0 if `channels` or `bits` are unsupported or overflow. pub fn frame_bytes(&self) -> usize { + if !matches!(self.channels, 2 | 4 | 6 | 8) { + return 0; + } let pair_bytes = match self.bits { 16 => 5, 20 => 6, @@ -243,6 +246,17 @@ mod tests { assert_eq!(h.frame_bytes(), 0); } + #[test] + fn header_frame_bytes_rejects_unsupported_channels() { + for bits in [16, 20, 24] { + for channels in [0, 1, 3, 5, 7, 9, 10, usize::MAX] { + let header = Header { channels, channel_id: 0, bits, alignment: 0, audio_bytes: 0 }; + assert!(Encoder::new(channels, bits).is_err()); + assert_eq!(header.frame_bytes(), 0, "{channels} channels, {bits} bits"); + } + } + } + #[test] fn header_frame_bytes_rejects_unsupported_depth() { let h_max = Header { channels: 2, channel_id: 0, bits: u32::MAX, alignment: 0, audio_bytes: 0 }; diff --git a/crates/audio/src/wav.rs b/crates/audio/src/wav.rs index 61e32593a1..2a208d68bb 100644 --- a/crates/audio/src/wav.rs +++ b/crates/audio/src/wav.rs @@ -5,3 +5,5 @@ pub(crate) const WAVE_FORMAT_IEEE_FLOAT: u16 = 3; pub(crate) const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE; /// Tail of the KSDATAFORMAT_SUBTYPE_* GUIDs (bytes 2..16); bytes 0..2 hold the format tag. pub(crate) const GUID_TAIL: [u8; 14] = [0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71]; +/// Tail of the Ambisonic subtype GUIDs {0000000x-0721-11D3-8644-C8C1CA000000}: PCM (x = 1) and float (x = 3) as well. +pub(crate) const AMBISONIC_TAIL: [u8; 14] = [0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00]; diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 18beab7872..6f24e3bd1e 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -449,8 +449,99 @@ impl EncodeOptions { /// ``` #[cfg(feature = "pcm-encode")] pub fn wav_float_header(sample_rate: u32, channels: u16, frames: u64) -> Result> { + float_header(sample_rate, channels, None, frames) +} + +/// [`wav_float_header`] with a BWF `bext` chunk holding `bwf` before the format chunk. The length +/// still doesn't depend on `frames`, so the header is rewritten in place the same way. +/// +/// ``` +/// use craft_audio::{BwfInfo, wav_float_header_with_bwf}; +/// +/// let bwf = BwfInfo::default().with_originator("Recorder").with_time_reference(48_000 * 3_600); +/// let mut file = wav_float_header_with_bwf(48_000, 2, 0, &bwf).unwrap(); +/// let samples = [0.25f32, -0.25, 0.5, -0.5]; +/// file.extend(samples.iter().flat_map(|s| s.to_le_bytes())); +/// let header = wav_float_header_with_bwf(48_000, 2, 2, &bwf).unwrap(); +/// file[..header.len()].copy_from_slice(&header); +/// assert!(header.windows(4).any(|id| id == b"bext")); +/// ``` +#[cfg(feature = "pcm-encode")] +pub fn wav_float_header_with_bwf(sample_rate: u32, channels: u16, frames: u64, bwf: &crate::BwfInfo) -> Result> { + float_header(sample_rate, channels, Some(bwf), frames) +} + +#[cfg(feature = "pcm-encode")] +fn float_header(sample_rate: u32, channels: u16, bwf: Option<&crate::BwfInfo>, frames: u64) -> Result> { if channels == 0 || sample_rate == 0 { return Err(AudioError::Encode("a WAV needs channels and a sample rate".into())); } - wav::header(usize::from(channels), sample_rate, (32, true), None, None, frames, false) + wav::header(usize::from(channels), sample_rate, (32, true), bwf, None, frames, false) +} + +/// What [`repair_wav`] wrote into a file. +#[cfg(feature = "pcm-encode")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct WavRepair { + /// The whole frames the data chunk holds. + pub frames: u64, + /// The length of the repaired file. Bytes past it are a partial last frame; truncate the + /// file to this length (`File::set_len`) to drop them. + pub len: u64, +} + +/// Rewrites the size fields of a PCM or float WAV whose writer stopped before finishing it, such +/// as a recorder's file after a crash, for the whole frames the file holds. The file must end in +/// its data chunk: everything after the data chunk's header counts as samples, whatever its size +/// field says. +/// +/// It writes these fields and leaves every other byte before the samples as it is, `fmt `, `bext` +/// and unknown chunks included: +/// +/// - the RIFF size and the data chunk's size (both `0xFFFF_FFFF` in an RF64 file); +/// - the frame count, the first field of the first `fact` chunk (`0xFFFF_FFFF` past `u32::MAX` frames); +/// - in an RF64 file, the RIFF size, data size and frame count at the start of the first `ds64` chunk; +/// - the pad byte after an odd data length. +/// +/// A RIFF file that grew past 4 GiB becomes RF64 when it starts with the 28-byte `JUNK` chunk that +/// [`FileEncoder`] and [`wav_float_header`] write: `RIFF` becomes `RF64` and that `JUNK` chunk +/// becomes a `ds64` chunk with an empty table. A RIFF file whose 28-byte chunk there already has the +/// `ds64` id, left by an earlier repair that stopped before writing `RF64`, becomes RF64 the same way. +/// +/// Errors: +/// +/// - [`AudioError::Malformed`] when `file` is not a RIFF or RF64 WAVE file, has no data chunk within +/// its first 100,000 chunks, has its data chunk before its `fmt ` chunk, has a `fmt ` chunk shorter +/// than 16 bytes or cut short by the end of the file, has 0 channels or 0 bits, has a block size +/// other than the channels times the bytes per sample, has an extensible `fmt ` chunk with a cbSize +/// below 22 or more valid bits than bits per sample, or is RF64 without a `ds64` chunk or with a +/// first `ds64` chunk of 16 to 27 bytes (the WAV reader takes the data size from that chunk). +/// - [`AudioError::Unsupported`] for a format other than PCM and IEEE float, an extensible format +/// whose subformat is neither, a sample width the WAV reader does not decode (PCM above 32 bits, +/// float other than 32 or 64 bits), and unfinished 8-bit mono data of even length (its last byte +/// may be a sample or a pad byte). +/// - [`AudioError::TooLarge`] for a RIFF file past 4 GiB that does not start with that `JUNK` or +/// `ds64` chunk. +/// - [`AudioError::Io`] when reading, writing or seeking `file` fails. +/// +/// ``` +/// use craft_audio::{repair_wav, wav_float_header}; +/// use std::io::Cursor; +/// +/// // A recorder wrote the header for 0 frames, then 2 frames and part of a third, then stopped. +/// let mut bytes = wav_float_header(48_000, 2, 0).unwrap(); +/// bytes.extend([0.25f32, -0.25, 0.5, -0.5, 0.75].iter().flat_map(|s| s.to_le_bytes())); +/// let mut file = Cursor::new(bytes); +/// let repaired = repair_wav(&mut file).unwrap(); +/// assert_eq!(repaired.frames, 2); +/// let mut bytes = file.into_inner(); +/// bytes.truncate(repaired.len as usize); +/// let header = wav_float_header(48_000, 2, 2).unwrap(); +/// assert_eq!(bytes[..header.len()], header[..]); +/// ``` +#[cfg(feature = "pcm-encode")] +pub fn repair_wav(file: &mut F) -> Result { + let (frames, len) = wav::repair(file)?; + Ok(WavRepair { frames, len }) } diff --git a/crates/audio/src/write/wav.rs b/crates/audio/src/write/wav.rs index 96ba532510..496bb95801 100644 --- a/crates/audio/src/write/wav.rs +++ b/crates/audio/src/write/wav.rs @@ -2,9 +2,9 @@ //! specification, `bext` per EBU Tech 3285, `ds64` per EBU Tech 3306). use super::pcm::{Quantizer, sample_format, validate_buffer, validate_layout, write_interleaved}; -use crate::wav::{GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM}; +use crate::wav::{AMBISONIC_TAIL, GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM}; use crate::{AudioBuffer, AudioError, BitDepth, BwfInfo, Result}; -use std::io::{Cursor, Seek, SeekFrom, Write}; +use std::io::{Cursor, ErrorKind, Read, Seek, SeekFrom, Write}; const BEXT_MIN_LEN: usize = 602; @@ -239,3 +239,175 @@ pub(crate) fn header( head.extend_from_slice(&(if rf64 { u32::MAX } else { data_len as u32 }).to_le_bytes()); Ok(head) } + +/// Where the size fields of a WAV sit, from a walk of its chunks up to `data`. +struct Layout { + rf64: bool, + /// The body of the `ds64` chunk of an RF64 file, or in a RIFF file the body of the 28-byte + /// `JUNK` or `ds64` chunk right after `WAVE` that can become one. + ds64: Option, + junk: bool, + fact: Option, + block_align: u64, + data: u64, +} + +fn read_at(file: &mut F, pos: u64, buf: &mut [u8]) -> Result { + file.seek(SeekFrom::Start(pos))?; + match file.read_exact(buf) { + Ok(()) => Ok(true), + Err(e) if e.kind() == ErrorKind::UnexpectedEof => Ok(false), + Err(e) => Err(e.into()), + } +} + +fn write_at(file: &mut F, pos: u64, bytes: &[u8]) -> Result<()> { + file.seek(SeekFrom::Start(pos))?; + file.write_all(bytes)?; + Ok(()) +} + +/// The block size of a PCM or float `fmt ` chunk body at `pos` of `size` bytes. +fn pcm_block_align(file: &mut F, pos: u64, size: u32) -> Result { + let mut fmt = [0u8; 40]; + let n = if size >= 40 { 40 } else { 16 }; + if size < 16 || !read_at(file, pos, &mut fmt[..n])? { + return Err(AudioError::Malformed("WAV fmt chunk is cut short".into())); + } + let field = |at: usize| u16::from_le_bytes([fmt[at], fmt[at + 1]]); + let mut tag = field(0); + if tag == WAVE_FORMAT_EXTENSIBLE && n == 40 { + // The extensible fields the reader checks. + if field(16) < 22 || field(18) > field(14) { + return Err(AudioError::Malformed("WAVE_FORMAT_EXTENSIBLE fmt chunk has a cbSize below 22 or too many valid bits".into())); + } + if fmt[26..] == GUID_TAIL || fmt[26..] == AMBISONIC_TAIL { + tag = field(24); + } + } + if tag != WAVE_FORMAT_PCM && tag != WAVE_FORMAT_IEEE_FLOAT { + return Err(AudioError::Unsupported(format!("repairing a WAV of format tag {tag:#06x}"))); + } + let (channels, align, bits) = (field(2), field(12), field(14)); + if channels == 0 || bits == 0 || u32::from(align) != u32::from(channels) * u32::from(bits.div_ceil(8)) { + return Err(AudioError::Malformed(format!("WAV block size {align} does not fit {channels} channels of {bits} bits"))); + } + // The widths the WAV reader decodes. + if !matches!((tag, bits), (WAVE_FORMAT_PCM, 1..=32) | (WAVE_FORMAT_IEEE_FLOAT, 32 | 64)) { + return Err(AudioError::Unsupported(format!("repairing a WAV of format tag {tag:#06x} with {bits} bits per sample"))); + } + Ok(u64::from(align)) +} + +fn layout(file: &mut F, len: u64) -> Result { + let mut riff = [0u8; 12]; + if !read_at(file, 0, &mut riff)? || !(riff.starts_with(b"RIFF") || riff.starts_with(b"RF64")) || &riff[8..] != b"WAVE" { + return Err(AudioError::Malformed("not a WAV file".into())); + } + let rf64 = riff.starts_with(b"RF64"); + let (mut ds64, mut junk, mut fact, mut block_align) = (None, false, None, None); + let mut pos = 12u64; + let mut chunk = [0u8; 8]; + // The same bound as the reader's, so a file of tiny chunks can't spin forever. + for _ in 0..100_000 { + if pos >= len || !read_at(file, pos, &mut chunk)? { + break; + } + let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]); + let body = pos + 8; + match &chunk[..4] { + b"data" => { + let block_align = block_align.ok_or_else(|| AudioError::Malformed("WAV data chunk before its fmt chunk".into()))?; + return Ok(Layout { rf64, ds64, junk, fact, block_align, data: body }); + } + // The first `ds64` and `fact` chunks take the sizes; later ones are left as they are. + // The WAV reader takes the data size from the first `ds64` chunk of 16 bytes or more. + b"ds64" if rf64 && size >= 16 && ds64.is_none() => { + if size < 28 { + return Err(AudioError::Malformed("RF64 ds64 chunk is shorter than 28 bytes".into())); + } + ds64 = Some(body); + } + // A `ds64` id here in a RIFF file is a promotion that stopped before the RF64 id. + b"JUNK" | b"ds64" if !rf64 && pos == 12 && size == 28 => (ds64, junk) = (Some(body), true), + b"fact" if size >= 4 && fact.is_none() => fact = Some(body), + b"fmt " => block_align = Some(pcm_block_align(file, body, size)?), + _ => {} + } + pos = body + u64::from(size) + u64::from(size & 1); + } + Err(AudioError::Malformed("WAV has no data chunk".into())) +} + +/// The data size the header records: the `ds64` field of an RF64 file, else the data chunk's. +fn stored_data_len(file: &mut F, l: &Layout) -> Result> { + let mut size = [0u8; 8]; + Ok(match (l.rf64, l.ds64) { + (true, Some(at)) => read_at(file, at + 8, &mut size)?.then(|| u64::from_le_bytes(size)), + (true, None) => None, + (false, _) => read_at(file, l.data - 4, &mut size[..4])? + .then(|| u32::from_le_bytes([size[0], size[1], size[2], size[3]])) + .filter(|&s| s != u32::MAX) + .map(u64::from), + }) +} + +/// Rewrites the size fields of a WAV that ends in its data chunk for the whole frames it holds. +/// Returns the frame count and the length the file should have; bytes past it are a partial frame. +pub(crate) fn repair(file: &mut F) -> Result<(u64, u64)> { + let len = file.seek(SeekFrom::End(0))?; + let l = layout(file, len)?; + let held = len.saturating_sub(l.data); + // A finished file's own size, which also tells its pad byte from a frame of one byte. + let stored = stored_data_len(file, &l)?.filter(|&s| s % l.block_align == 0 && s.checked_add(s & 1) == Some(held)); + if stored.is_none() && l.block_align == 1 && held > 0 && held % 2 == 0 { + // The last byte may be a sample or the pad byte after an odd count of them. + return Err(AudioError::Unsupported("repairing 8-bit mono WAV data of even length: a pad byte reads as a sample".into())); + } + let frames = stored.unwrap_or(held) / l.block_align; + let data_len = frames * l.block_align; + let pad = data_len & 1; + let new_len = l.data + data_len + pad; + let riff_len = new_len - 8; + let rf64 = l.rf64 || u32::try_from(riff_len).is_err(); + let ds64 = match (rf64, l.ds64) { + (false, _) => None, + (true, Some(at)) if l.rf64 || l.junk => Some(at), + (true, _) if l.rf64 => return Err(AudioError::Malformed("RF64 file has no ds64 chunk".into())), + (true, _) => return Err(AudioError::TooLarge("WAV past 4 GiB has no room for a ds64 chunk".into())), + }; + if let Some(at) = l.fact { + write_at(file, at, &u32::try_from(frames).unwrap_or(u32::MAX).to_le_bytes())?; + } + match ds64 { + Some(at) => { + let mut body = Vec::with_capacity(28); + body.extend_from_slice(&riff_len.to_le_bytes()); + body.extend_from_slice(&data_len.to_le_bytes()); + body.extend_from_slice(&frames.to_le_bytes()); + if !l.rf64 { + // The `JUNK` chunk's last 4 bytes become the table length: no table entries. + body.extend_from_slice(&0u32.to_le_bytes()); + } + write_at(file, at, &body)?; + if !l.rf64 { + write_at(file, at - 8, b"ds64")?; + write_at(file, 0, b"RF64")?; + } + write_at(file, l.data - 4, &u32::MAX.to_le_bytes())?; + write_at(file, 4, &u32::MAX.to_le_bytes())?; + } + None => { + write_at(file, l.data - 4, &(data_len as u32).to_le_bytes())?; + write_at(file, 4, &(riff_len as u32).to_le_bytes())?; + } + } + // The pad byte goes last: until it is written, 8-bit mono data keeps an odd length that a + // repeated repair can count. + if pad == 1 { + write_at(file, l.data + data_len, &[0])?; + } + file.seek(SeekFrom::Start(new_len))?; + file.flush()?; + Ok((frames, new_len)) +} diff --git a/crates/audio/tests/audio/roundtrip.rs b/crates/audio/tests/audio/roundtrip.rs index 2e58cd6332..803d85f293 100644 --- a/crates/audio/tests/audio/roundtrip.rs +++ b/crates/audio/tests/audio/roundtrip.rs @@ -1,4 +1,7 @@ -use craft_audio::{AudioBuffer, BitDepth, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe}; +use craft_audio::{ + AudioBuffer, BitDepth, BwfInfo, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe, wav_float_header, + wav_float_header_with_bwf, +}; fn sine(sr: u32, channels: usize, frames: usize) -> AudioBuffer { let mut b = AudioBuffer::new(sr, channels as u16, frames); @@ -64,3 +67,335 @@ fn wav_and_aiff_roundtrip_all_depths_and_layouts() { } } } + +/// A file that stopped growing before its header was rewritten: the header for 0 frames, the +/// samples of `buf`, then `extra` bytes of a frame that was never finished. +fn unfinished_wav(buf: &AudioBuffer, opts: &EncodeOptions, extra: usize) -> (Vec, Vec) { + let finished = encode(buf, opts).unwrap(); + let mut file = encode(&AudioBuffer::new(buf.sample_rate, buf.num_channels(), 0), opts).unwrap(); + let head = file.len(); + let sample_bytes = match opts.bit_depth { + BitDepth::Int16 => 2, + BitDepth::Int24 => 3, + _ => 4, + }; + let data_len = buf.frames() * usize::from(buf.num_channels()) * sample_bytes; + file.extend_from_slice(&finished[head..head + data_len]); + file.extend(std::iter::repeat_n(0x55, extra)); + (file, finished) +} + +#[test] +fn repair_wav_rewrites_the_sizes_of_an_unfinished_file() { + let bwf = BwfInfo::default().with_description("take 3").with_time_reference(48_000 * 3600); + let cases = [ + (sine(48_000, 2, 1_000), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Float32).with_bwf(bwf.clone()), 5), + // 3 bytes a frame and an odd frame count: the data needs a pad byte. + (sine(44_100, 1, 999), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24).with_bwf(bwf.clone()), 2), + (sine(44_100, 1, 999), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24).with_bwf(bwf), 0), + (sine(48_000, 6, 300), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16).with_force_rf64(true), 11), + (sine(48_000, 2, 0), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16), 3), + ]; + for (buf, opts, extra) in cases { + let (file, finished) = unfinished_wav(&buf, &opts, extra); + assert_ne!(file, finished); + let mut file = std::io::Cursor::new(file); + let repaired = craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!(repaired.frames, buf.frames() as u64); + let mut file = file.into_inner(); + assert!(file.len() as u64 >= repaired.len); + file.truncate(repaired.len as usize); + assert_eq!(file, finished, "{opts:?}"); + // A finished file stays as it is. + let mut again = std::io::Cursor::new(file.clone()); + assert_eq!(craft_audio::repair_wav(&mut again).unwrap(), repaired); + assert_eq!(again.into_inner(), file); + } +} + +/// A file whose data is all zeros past `head`, `len` bytes long, without holding them in memory. +struct SparseWav { + head: Vec, + len: u64, + pos: u64, +} + +impl std::io::Read for SparseWav { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let n = (self.len.saturating_sub(self.pos)).min(buf.len() as u64) as usize; + for (i, b) in buf[..n].iter_mut().enumerate() { + *b = self.head.get(self.pos as usize + i).copied().unwrap_or(0); + } + self.pos += n as u64; + Ok(n) + } +} + +impl std::io::Write for SparseWav { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + let end = self.pos as usize + buf.len(); + if end <= self.head.len() { + self.head[self.pos as usize..end].copy_from_slice(buf); + } else { + assert!(buf.iter().all(|&b| b == 0), "only padding is written past the header"); + } + self.pos += buf.len() as u64; + self.len = self.len.max(self.pos); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl std::io::Seek for SparseWav { + fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result { + self.pos = match to { + std::io::SeekFrom::Start(p) => p, + std::io::SeekFrom::End(d) => self.len.checked_add_signed(d).unwrap(), + std::io::SeekFrom::Current(d) => self.pos.checked_add_signed(d).unwrap(), + }; + Ok(self.pos) + } +} + +#[test] +fn repair_wav_turns_a_file_past_4_gib_into_rf64() { + let frames = 600_000_000u64; // 4.8 GB of stereo float + let head = wav_float_header(48_000, 2, 0).unwrap(); + let len = head.len() as u64 + frames * 8 + 3; + let mut file = SparseWav { head: head.clone(), len, pos: 0 }; + let repaired = craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!((repaired.frames, repaired.len), (frames, len - 3)); + assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap()); + + // A JUNK chunk holding other bytes becomes a ds64 chunk with an empty table. + let mut dirty = head.clone(); + assert_eq!(&dirty[12..16], b"JUNK"); + dirty[20..48].fill(0xAA); + let mut file = SparseWav { head: dirty, len, pos: 0 }; + craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap()); + + // A repair that stopped after naming the ds64 chunk but before writing RF64 finishes next time. + let mut half = head.clone(); + half[12..16].copy_from_slice(b"ds64"); + let mut file = SparseWav { head: half, len, pos: 0 }; + assert_eq!(craft_audio::repair_wav(&mut file).unwrap(), repaired); + assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap()); + + // In a RIFF file only the chunk right after WAVE becomes ds64; a later ds64 chunk is left as it is. + let at = head.windows(4).position(|w| w == b"data").unwrap(); + let later: Vec = [&b"ds64"[..], &28u32.to_le_bytes(), &[0xBB; 28]].concat(); + let mut two = head.clone(); + two.splice(at..at, later.iter().copied()); + let mut file = SparseWav { head: two, len: len + 36, pos: 0 }; + assert_eq!(craft_audio::repair_wav(&mut file).unwrap().frames, frames); + assert_eq!((&file.head[..4], &file.head[12..16]), (&b"RF64"[..], &b"ds64"[..])); + assert_eq!(file.head[at..at + 36], later[..]); + + // In an RF64 file the ds64 chunk right after WAVE takes the sizes; a later ds64 chunk is left as it is. + let finished = wav_float_header(48_000, 2, frames).unwrap(); + assert_eq!((&finished[..4], &finished[12..16]), (&b"RF64"[..], &b"ds64"[..])); + let mut stale = finished.clone(); + stale[20..44].fill(0); + stale.splice(at..at, later.iter().copied()); + let mut file = SparseWav { head: stale, len: len + 36, pos: 0 }; + let r = craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!((r.frames, r.len), (frames, len + 33)); + let field = |at: usize| u64::from_le_bytes(file.head[at..at + 8].try_into().unwrap()); + assert_eq!((field(20), field(28), field(36)), (len + 25, frames * 8, frames)); + assert_eq!(file.head[at..at + 36], later[..]); + + // A RIFF file with no JUNK chunk to turn into ds64 cannot grow past 4 GiB. + let bare = craft_audio::pcm_wav_header(0, 2, 48_000, 16); + assert_eq!(&bare[12..16], b"fmt "); + let len = bare.len() as u64 + (1u64 << 32); + let mut file = SparseWav { head: bare, len, pos: 0 }; + assert!(matches!(craft_audio::repair_wav(&mut file), Err(craft_audio::AudioError::TooLarge(_)))); +} + +#[test] +fn repair_wav_writes_the_frame_count_into_the_first_fact_chunk() { + let mut file = wav_float_header(48_000, 2, 0).unwrap(); + let fact = file.windows(4).position(|w| w == b"fact").unwrap() + 8; + let at = file.windows(4).position(|w| w == b"data").unwrap(); + let later: Vec = [&b"fact"[..], &4u32.to_le_bytes(), &[0xCC; 4]].concat(); + file.splice(at..at, later.iter().copied()); + file.extend(std::iter::repeat_n(0, 100 * 8)); + let mut file = std::io::Cursor::new(file); + assert_eq!(craft_audio::repair_wav(&mut file).unwrap().frames, 100); + let file = file.into_inner(); + assert_eq!(file[fact..fact + 4], 100u32.to_le_bytes()); + assert_eq!(file[at..at + 12], later[..]); +} + +#[test] +fn rf64_data_size_comes_from_the_ds64_chunk_after_wave() { + let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16).with_force_rf64(true); + let wav = encode(&sine(48_000, 2, 300), &opts).unwrap(); + assert_eq!(&wav[12..16], b"ds64"); + // A later ds64 chunk that gives the data 4 bytes, one frame. + let mut body = [0u8; 28]; + body[8..16].copy_from_slice(&4u64.to_le_bytes()); + let later = [&b"ds64"[..], &28u32.to_le_bytes(), &body].concat(); + let at = wav.windows(4).position(|w| w == b"data").unwrap(); + let mut two = wav.clone(); + two.splice(at..at, later); + let (info, buf) = decode(&two, Some("wav")).unwrap(); + assert_eq!((info.frames, buf.frames()), (300, 300)); + + // A 16-byte first ds64 chunk gives the reader the data size, so repair does not use the later one. + let mut short = two; + short[16..20].copy_from_slice(&16u32.to_le_bytes()); + short[28..36].copy_from_slice(&4u64.to_le_bytes()); + short[36..44].copy_from_slice(&[&b"JUNK"[..], &4u32.to_le_bytes()].concat()); + assert_eq!(decode(&short, Some("wav")).unwrap().1.frames(), 1); + let repaired = craft_audio::repair_wav(&mut std::io::Cursor::new(short)); + assert!(matches!(repaired, Err(craft_audio::AudioError::Malformed(_))), "{repaired:?}"); +} + +/// A file whose writes fail once `writes` of them have gone through. +struct FailingWrites { + file: std::io::Cursor>, + writes: usize, +} + +impl std::io::Read for FailingWrites { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + std::io::Read::read(&mut self.file, buf) + } +} + +impl std::io::Write for FailingWrites { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if self.writes == 0 { + return Err(std::io::Error::other("disk full")); + } + self.writes -= 1; + std::io::Write::write(&mut self.file, buf) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl std::io::Seek for FailingWrites { + fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result { + std::io::Seek::seek(&mut self.file, to) + } +} + +#[test] +fn repair_wav_runs_again_after_a_write_error() { + let mut u8_mono = craft_audio::pcm_wav_header(0, 1, 8_000, 8); + u8_mono.extend([0x80; 3]); + let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24); + let (int24, _) = unfinished_wav(&sine(44_100, 1, 999), &opts, 2); + for (file, frames) in [(u8_mono, 3), (int24, 999)] { + let mut whole = std::io::Cursor::new(file.clone()); + let repaired = craft_audio::repair_wav(&mut whole).unwrap(); + assert_eq!(repaired.frames, frames); + for writes in 0.. { + let mut failing = FailingWrites { file: std::io::Cursor::new(file.clone()), writes }; + if craft_audio::repair_wav(&mut failing).is_ok() { + break; + } + let mut again = failing.file; + assert_eq!(craft_audio::repair_wav(&mut again).unwrap(), repaired, "stopped after {writes} writes"); + assert_eq!(again.into_inner(), *whole.get_ref(), "stopped after {writes} writes"); + } + } +} + +#[test] +fn repair_wav_refuses_what_it_cannot_repair() { + use craft_audio::AudioError; + let repair = |bytes: Vec| craft_audio::repair_wav(&mut std::io::Cursor::new(bytes)); + let wav = encode(&sine(48_000, 1, 100), &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16)).unwrap(); + assert!(matches!(repair(b"not a wave file at all".to_vec()), Err(AudioError::Malformed(_)))); + // Every cut inside the header is an error, not a panic. + let data = wav.windows(4).position(|w| w == b"data").unwrap(); + for cut in 0..data + 8 { + assert!(repair(wav[..cut].to_vec()).is_err(), "cut at {cut}"); + } + // A compressed format (format tag 2, Microsoft ADPCM) has no fixed frame size to count by. + let fmt = wav.windows(4).position(|w| w == b"fmt ").unwrap() + 8; + let mut adpcm = wav.clone(); + adpcm[fmt..fmt + 2].copy_from_slice(&2u16.to_le_bytes()); + assert!(matches!(repair(adpcm), Err(AudioError::Unsupported(_)))); + // The chunk walk stops, as the reader's does, after 100,000 chunks. + let mut many = wav[..12].to_vec(); + many.extend(b"JUNK\0\0\0\0".repeat(100_001)); + many.extend_from_slice(&wav[12..]); + assert!(matches!(repair(many), Err(AudioError::Malformed(_)))); + // 8-bit mono: an even data length could end in a sample or in the pad after an odd count. + let u8_mono = craft_audio::pcm_wav_header(0, 1, 8_000, 8); + for (samples, ok) in [(3, true), (4, false)] { + let mut file = u8_mono.clone(); + file.extend(std::iter::repeat_n(0x80, samples)); + assert_eq!(repair(file.clone()).map(|r| r.frames).ok(), ok.then_some(3), "{samples} bytes"); + if ok { + // Once repaired, the size settles it. + let mut file = std::io::Cursor::new(file); + let r = craft_audio::repair_wav(&mut file).unwrap(); + assert_eq!(repair(file.into_inner()).unwrap(), r); + } + } + // A block size that is not channels × sample bytes would count the wrong frames. + let mut odd_align = wav.clone(); + odd_align[fmt + 12..fmt + 14].copy_from_slice(&4u16.to_le_bytes()); + assert!(matches!(repair(odd_align), Err(AudioError::Malformed(_)))); + // Widths the reader does not decode: 16-bit float and 40-bit PCM, each with a block size that fits. + let mut float16 = wav.clone(); + float16[fmt..fmt + 2].copy_from_slice(&3u16.to_le_bytes()); + let mut pcm40 = wav.clone(); + pcm40[fmt + 12..fmt + 16].copy_from_slice(&[5, 0, 40, 0]); + for bad in [float16, pcm40] { + assert!(craft_audio::decode(&bad, Some("wav")).is_err()); + assert!(matches!(repair(bad), Err(AudioError::Unsupported(_)))); + } + // An extensible file whose subformat is PCM's tag under another GUID is not PCM. + let ext = encode(&sine(48_000, 2, 100), &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24)).unwrap(); + let fmt = ext.windows(4).position(|w| w == b"fmt ").unwrap() + 8; + assert!(repair(ext.clone()).is_ok()); + let mut other_guid = ext.clone(); + other_guid[fmt + 39] ^= 0xFF; + assert!(matches!(repair(other_guid), Err(AudioError::Unsupported(_)))); + // Extensible fields the reader refuses: a cbSize below 22 and more valid bits than the sample holds. + let mut short_cb = ext.clone(); + short_cb[fmt + 16..fmt + 18].copy_from_slice(&21u16.to_le_bytes()); + let mut wide_valid = ext.clone(); + wide_valid[fmt + 18..fmt + 20].copy_from_slice(&25u16.to_le_bytes()); + for bad in [short_cb, wide_valid] { + assert!(craft_audio::decode(&bad, Some("wav")).is_err()); + assert!(matches!(repair(bad), Err(AudioError::Malformed(_)))); + } + // The Ambisonic PCM subformat {00000001-0721-11D3-8644-C8C1CA000000}, which the reader reads as PCM. + let mut ambisonic = ext; + ambisonic[fmt + 26..fmt + 40].copy_from_slice(&[0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00]); + assert_eq!(repair(ambisonic).unwrap().frames, 100); +} + +#[test] +fn float_wav_header_with_bwf_keeps_its_bext_as_the_file_grows() { + let take = sine(48_000, 2, 1_000); + let bwf = BwfInfo::default() + .with_description("take 3") + .with_originator("recorder") + .with_origination("2026-11-20", "18:30:00") + .with_time_reference(48_000 * 66_600); + let mut file = wav_float_header_with_bwf(48_000, 2, 0, &bwf).unwrap(); + let len = file.len(); + assert!(len > wav_float_header(48_000, 2, 0).unwrap().len()); + file.extend(take.interleaved().iter().flat_map(|s| s.to_le_bytes())); + file[..len].copy_from_slice(&wav_float_header_with_bwf(48_000, 2, 600, &bwf).unwrap()); + let (info, decoded) = decode(&file, None).unwrap(); + assert_eq!((info.bwf.as_ref(), decoded.frames()), (Some(&bwf), 600)); + file[..len].copy_from_slice(&wav_float_header_with_bwf(48_000, 2, 1_000, &bwf).unwrap()); + let opts = EncodeOptions::default().with_bit_depth(BitDepth::Float32).with_bwf(bwf.clone()); + assert_eq!(file, encode(&take, &opts).unwrap()); + let big = wav_float_header_with_bwf(48_000, 2, 600_000_000, &bwf).unwrap(); + assert_eq!((&big[..4], big.len()), (&b"RF64"[..], len)); + assert!(wav_float_header_with_bwf(48_000, 0, 0, &bwf).is_err()); +} diff --git a/crates/automation/src/client_tests.rs b/crates/automation/src/client_tests.rs index 46687dae3b..8a767ddd21 100644 --- a/crates/automation/src/client_tests.rs +++ b/crates/automation/src/client_tests.rs @@ -103,10 +103,8 @@ fn an_unasked_line_makes_the_connection_unusable_before_sending() { let mut client = ControlClient::connect(addr, TOKEN).unwrap(); assert!(client.is_usable(), "an idle connection with nothing pending is usable"); said.send(()).unwrap(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); - while client.is_usable() && std::time::Instant::now() < deadline { - std::thread::sleep(std::time::Duration::from_millis(5)); - } + // A blocking peek (under the client's read timeout) returns once the line has arrived. + assert!(client.stream.peek(&mut [0]).unwrap() > 0, "the unasked line arrived"); assert!(!client.is_usable(), "the unasked line makes the connection unusable"); assert_eq!(client.call("next", json!({})), Err("connection closed".to_string())); assert!(client.is_broken(), "the unusable connection is closed"); diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 8e75f07ecd..180a331752 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -487,20 +487,40 @@ pub fn configure_stream(stream: &std::net::TcpStream) -> std::io::Result<()> { stream.set_write_timeout(Some(IO_TIMEOUT)) } +/// The time an [`AuthDeadlineStream`] reads its deadline against: [`Instant::now`] in a server, or a time a test sets +/// by hand. +pub type DeadlineClock = std::sync::Arc Instant + Send + Sync>; + +/// The real clock, [`Instant::now`]. +pub fn real_clock() -> DeadlineClock { + std::sync::Arc::new(Instant::now) +} + /// A read wrapper that fails once [`AUTH_DEADLINE`] passes without [`Self::authenticated`] being /// called, whatever the client sends meanwhile; after that only [`IO_TIMEOUT`] applies. -#[derive(Debug)] pub struct AuthDeadlineStream { inner: std::net::TcpStream, deadline: Option, + clock: DeadlineClock, +} + +impl std::fmt::Debug for AuthDeadlineStream { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AuthDeadlineStream").field("inner", &self.inner).field("deadline", &self.deadline).finish_non_exhaustive() + } } impl AuthDeadlineStream { /// Wraps `inner`; reads fail once `auth_deadline` has passed unauthenticated. pub fn new(inner: std::net::TcpStream, auth_deadline: Duration) -> Self { + Self::with_clock(inner, auth_deadline, real_clock()) + } + + /// [`Self::new`] with the deadline read against `clock` instead of the real clock. + pub fn with_clock(inner: std::net::TcpStream, auth_deadline: Duration, clock: DeadlineClock) -> Self { // A limit too large to represent expires at once rather than never. - let now = Instant::now(); - Self { inner, deadline: Some(now.checked_add(auth_deadline).unwrap_or(now)) } + let now = clock(); + Self { inner, deadline: Some(now.checked_add(auth_deadline).unwrap_or(now)), clock } } /// The handshake succeeded: lift the deadline and restore the idle timeout. @@ -513,7 +533,7 @@ impl AuthDeadlineStream { impl std::io::Read for AuthDeadlineStream { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { if let Some(deadline) = self.deadline { - let left = deadline.saturating_duration_since(Instant::now()); + let left = deadline.saturating_duration_since((self.clock)()); if left.is_zero() { return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "not authenticated in time")); } diff --git a/crates/automation/src/security_tests.rs b/crates/automation/src/security_tests.rs index 2716fc24c2..2d3625c0a7 100644 --- a/crates/automation/src/security_tests.rs +++ b/crates/automation/src/security_tests.rs @@ -170,6 +170,37 @@ fn server_token_sources_and_validation() { ); } +// An unauthenticated connection's reads succeed while its deadline is ahead, however much it sends, and fail once the +// deadline has passed even with input waiting; after `authenticated` the deadline no longer applies. +#[trial] +fn the_authentication_deadline_holds_whatever_the_client_sends() { + use std::io::{Read, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let mut client = std::net::TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (server, _) = listener.accept().unwrap(); + server.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let start = Instant::now(); + let at = std::sync::Arc::new(std::sync::Mutex::new(start)); + let read_at = std::sync::Arc::clone(&at); + let clock: DeadlineClock = std::sync::Arc::new(move || *read_at.lock().unwrap()); + let mut stream = AuthDeadlineStream::with_clock(server.try_clone().unwrap(), Duration::from_secs(10), clock); + let mut byte = [0]; + // Blank lines and partial frames, each read while the deadline is ahead. + for (step, sent) in [b"\n", b" ", b"{", b"\n"].into_iter().enumerate() { + *at.lock().unwrap() = start + Duration::from_secs(3 * step as u64); + client.write_all(sent).unwrap(); + assert_eq!(stream.read(&mut byte).unwrap(), 1, "read {step} is before the deadline"); + } + *at.lock().unwrap() = start + Duration::from_secs(10); + client.write_all(b"\n").unwrap(); + let late = stream.read(&mut byte).unwrap_err(); + assert_eq!(late.kind(), std::io::ErrorKind::TimedOut, "the input sent did not move the deadline: {late}"); + + stream.authenticated().unwrap(); + *at.lock().unwrap() = start + Duration::from_secs(60); + assert_eq!(stream.read(&mut byte).unwrap(), 1, "an authenticated connection reads past the deadline"); +} + // A token file create that runs out of time fails with its own error, even when it left a file at // the path: that file is not read as another process's. A create that another process beat to the // path reads that process's token. diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index c6808156d7..e913cf3b4c 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -16,8 +16,8 @@ use serde_json::{Value, json}; use crate::control::{ControlRequest, REPLY_DEADLINE}; use crate::protocol::write_reply; use crate::security::{ - AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake, configure_stream, - read_bounded_line, repeat_auth_reply, + AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, DeadlineClock, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake, + configure_stream, read_bounded_line, real_clock, repeat_auth_reply, }; /// A running control server. Dropping it stops accepting connections and returns once the port is @@ -72,6 +72,36 @@ pub fn serve_with_deadline( host: WindowHost, auth_deadline: Duration, ) -> std::io::Result<(Receiver, Listening)> { + serve_with(listener, token, host, ServeOptions { auth_deadline, ..ServeOptions::default() }) +} + +/// What a test sets on a server [`serve_with`] starts. +#[doc(hidden)] +pub struct ServeOptions { + /// How long a connection has to authenticate ([`AUTH_DEADLINE`] in [`serve`]). + pub auth_deadline: Duration, + /// The clock the authentication deadline is read against. + pub clock: DeadlineClock, + /// Sent `()` each time a connection has ended: its request sender is dropped and its place under + /// [`MAX_CONNECTIONS`] is free again. + pub ended: Option>, +} + +impl Default for ServeOptions { + fn default() -> Self { + Self { auth_deadline: AUTH_DEADLINE, clock: real_clock(), ended: None } + } +} + +/// [`serve`] with the authentication deadline, its clock and a signal for each ended connection set by a test. +#[doc(hidden)] +pub fn serve_with( + listener: TcpListener, + token: String, + host: WindowHost, + options: ServeOptions, +) -> std::io::Result<(Receiver, Listening)> { + let ServeOptions { auth_deadline, clock, ended } = options; let (tx, rx) = channel::(); let addr = listener.local_addr()?; // `ui.inspect`, `ui.click {label}` and `ui.focus` read the kept tree of the last presented frame; it is kept @@ -95,13 +125,19 @@ pub fn serve_with_deadline( let tx = tx.clone(); let host = host.clone(); let token = Arc::clone(&token); + let clock = Arc::clone(&clock); + let ended = ended.clone(); std::thread::spawn(move || { - serve_connection(stream, &token, &tx, &host, auth_deadline); + serve_connection(stream, &token, &tx, &host, auth_deadline, clock); + drop(tx); // What the last client held down would otherwise stay held with no one left to // release it; while another connection is live, its input is left alone. if permit.release() { host.end_injection(); } + if let Some(ended) = ended { + let _ = ended.send(()); + } }); } })?; @@ -110,12 +146,12 @@ pub fn serve_with_deadline( /// Serve one connection: it must authenticate ([`ServerHandshake`]) within `auth_deadline` of /// connecting, however much it sends meanwhile; after that only the idle timeout applies. -fn serve_connection(stream: TcpStream, token: &str, tx: &Sender, host: &WindowHost, auth_deadline: Duration) { +fn serve_connection(stream: TcpStream, token: &str, tx: &Sender, host: &WindowHost, auth_deadline: Duration, clock: DeadlineClock) { if configure_stream(&stream).is_err() { return; } let Ok(read) = stream.try_clone() else { return }; - let mut reader = BufReader::new(AuthDeadlineStream::new(read, auth_deadline)); + let mut reader = BufReader::new(AuthDeadlineStream::with_clock(read, auth_deadline, clock)); let mut out = stream; let mut line = String::new(); let mut handshake = ServerHandshake::new(); diff --git a/crates/automation/tests/it/agents.rs b/crates/automation/tests/it/agents.rs index 6cca4325a2..9238151b96 100644 --- a/crates/automation/tests/it/agents.rs +++ b/crates/automation/tests/it/agents.rs @@ -3,8 +3,8 @@ use std::net::TcpListener; use std::path::PathBuf; -use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, mpsc}; use std::time::Duration; use craft_automation::agents::AgentLinkStatus; @@ -17,7 +17,6 @@ use craft_automation::ui::agents::AgentsPage; use craft_host::{AppInfo, Host, PickId, Picked, ScriptedFiles}; use craft_ui::contract::Role; use craft_ui::patterns::preferences::SettingsDraft; -use craft_ui::runtime::motion; use craft_ui::runtime::windows::WindowHost; use craft_ui::testing::Fixture; use craft_ui::testing::trial; @@ -29,16 +28,40 @@ fn temp_dir(tag: &str) -> tempfile::TempDir { tempfile::Builder::new().prefix(&format!("craft-agents-{tag}-")).tempdir().expect("a temp dir") } -/// Waits up to five seconds for `done`. -fn wait_for(mut done: impl FnMut() -> bool) -> bool { - let started = motion::now(); - while !done() { - if started.elapsed() > Duration::from_secs(5) { - return false; +/// The watch thread's poll clock, driven by the test: [`Self::poll`] lets one poll run and returns once the thread has +/// finished it and waits for the next. +struct Ticks { + tick: mpsc::SyncSender<()>, + waiting: mpsc::Receiver<()>, +} + +impl Ticks { + /// The clock and the `tick` to give [`AgentSwitch::watch_with`]. + fn new() -> (Self, impl FnMut() -> bool + Send + 'static) { + let (tick, ticks) = mpsc::sync_channel(0); + let (waits, waiting) = mpsc::channel(); + let wait = move || { + let _ = waits.send(()); + ticks.recv().is_ok() + }; + (Self { tick, waiting }, wait) + } + + /// Blocks until the watch thread waits for its next poll; `false` once the thread has ended. + fn waiting(&self) -> bool { + // A hang guard only: the thread answers at once, so the limit is never reached by a run that works. + match self.waiting.recv_timeout(Duration::from_secs(60)) { + Ok(()) => true, + Err(mpsc::RecvTimeoutError::Disconnected) => false, + Err(mpsc::RecvTimeoutError::Timeout) => panic!("the watch thread hung"), } - std::thread::sleep(Duration::from_millis(5)); + } + + /// Runs one poll; `false` when the thread ended in it instead of waiting for the next one. + fn poll(&self) -> bool { + self.tick.send(()).unwrap(); + self.waiting() } - true } /// With the `AI-MCP` flag only the launcher's switch decides; without it the app's earlier consent. @@ -52,8 +75,8 @@ fn with_the_flag_only_the_launchers_switch_lets_agents_in() { assert!(!AgentSwitch::fixed(false, true).allows(false)); } -/// The switch follows the launcher's list within a poll, wakes the app once per change rather than once per poll, and -/// its thread ends once the last clone is dropped. +/// The switch follows the launcher's list at the next poll, wakes the app once per change rather than once per poll, +/// and its thread ends at the first poll after the last clone is dropped. #[trial] fn the_switch_wakes_once_per_change() { let launcher = Arc::new(AtomicBool::new(false)); @@ -72,28 +95,35 @@ fn the_switch_wakes_once_per_change() { wakes.fetch_add(1, Ordering::Relaxed); } }; - let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake); + let (ticks, tick) = Ticks::new(); + let switch = AgentSwitch::watch_with(true, probe, tick, wake); let clone = switch.clone(); + assert!(ticks.waiting()); assert!(!switch.launcher()); + assert_eq!(probes.load(Ordering::Relaxed), 1, "asked once at the start"); launcher.store(true, Ordering::Relaxed); - assert!(wait_for(|| clone.launcher()), "the switch follows the launcher"); + assert!(ticks.poll()); + assert!(clone.launcher(), "the switch follows the launcher"); assert!(switch.allows(false)); // Many polls with nothing changed. - let polled = probes.load(Ordering::Relaxed); - assert!(wait_for(|| probes.load(Ordering::Relaxed) > polled + 10)); + for _ in 0..10 { + assert!(ticks.poll()); + } + assert_eq!(probes.load(Ordering::Relaxed), 12, "one probe per poll"); + assert_eq!(wakes.load(Ordering::Relaxed), 1, "one wake per change, not per poll"); launcher.store(false, Ordering::Relaxed); - assert!(wait_for(|| !switch.launcher())); - assert!(wait_for(|| wakes.load(Ordering::Relaxed) == 2)); + assert!(ticks.poll()); + assert!(!switch.launcher()); assert_eq!(wakes.load(Ordering::Relaxed), 2, "one wake per change, not per poll"); drop(switch); + assert!(ticks.poll(), "a clone keeps the watch"); drop(clone); - // The thread sees the switch gone at its next poll and stops probing. - std::thread::sleep(Duration::from_millis(50)); - let after_drop = probes.load(Ordering::Relaxed); - std::thread::sleep(Duration::from_millis(50)); - assert_eq!(probes.load(Ordering::Relaxed), after_drop, "the watch ended with the last switch"); + // The thread probes once more, sees the switch gone and ends, so nothing probes after it. + assert!(!ticks.poll(), "the watch ended with the last switch"); + assert_eq!(probes.load(Ordering::Relaxed), 15, "one probe per poll, the last one before the watch ended"); + assert_eq!(wakes.load(Ordering::Relaxed), 2); } /// A published connection reads back in its documented shape, and only the process that wrote it removes it. diff --git a/crates/automation/tests/it/control.rs b/crates/automation/tests/it/control.rs index 913d02d16a..6e1dc700fc 100644 --- a/crates/automation/tests/it/control.rs +++ b/crates/automation/tests/it/control.rs @@ -2,14 +2,15 @@ use std::io::{BufRead, BufReader, Write}; use std::net::{SocketAddr, TcpListener, TcpStream}; -use std::sync::mpsc::{Receiver, channel}; +use std::sync::mpsc::{Receiver, RecvTimeoutError, channel}; +use std::sync::{Arc, Mutex}; use std::time::Duration; use craft_automation::client::ControlClient; use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse, Reply, expired_error, result_reply, timeout_error}; use craft_automation::protocol::MAX_RESPONSE_BYTES; use craft_automation::security::{CHALLENGE_METHOD, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, proof_matches}; -use craft_automation::server; +use craft_automation::server::{self, ServeOptions}; use craft_ui::runtime::motion; use craft_ui::runtime::windows::WindowHost; use craft_ui::testing::trial; @@ -101,39 +102,90 @@ fn host() -> WindowHost { /// sent is dispatched. #[trial] fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() { - // A short deadline, so the test does not wait out the real one. - let deadline = Duration::from_millis(400); - let listener = TcpListener::bind("127.0.0.1:0").expect("bound"); - let (rx, server) = server::serve_with_deadline(listener, TOKEN.into(), host(), deadline).expect("started"); - // Blank lines and partial frames, one byte every 20 ms: each read succeeds long before the idle timeout. + let start = motion::now(); + let at = Arc::new(Mutex::new(start)); + let read_at = Arc::clone(&at); + let (ended, connection_ended) = channel(); + // Each read of the clock is announced, so the test moves it only after the connection has set its deadline. + let (read, clock_read) = channel(); + let clock = Arc::new(move || { + let now = *read_at.lock().expect("the clock"); + let _ = read.send(()); + now + }); + let options = ServeOptions { auth_deadline: Duration::from_secs(10), clock, ended: Some(ended) }; + let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started"); let mut stream = TcpStream::connect(server.addr).expect("connected"); - let started = motion::now(); - let mut closed = false; - for i in 0..1000 { - let byte: &[u8] = if i % 5 == 0 { b"\n" } else { b" " }; - if stream.write_all(byte).is_err() { - closed = true; - break; - } - std::thread::sleep(Duration::from_millis(20)); - } - let served = started.elapsed(); - assert!(closed, "the trickle did not keep the connection open"); - assert!(served < deadline + Duration::from_secs(3), "the trickle did not extend the deadline: {served:?}"); - assert!(rx.try_recv().is_err(), "nothing was dispatched"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let mut reader = BufReader::new(stream.try_clone().expect("cloned")); + clock_read.recv_timeout(Duration::from_secs(5)).expect("the connection set its deadline"); + // Blank lines and the start of a line, sent while the deadline is ahead: none is a frame the handshake refuses. + stream.write_all(b"\n \n ").expect("written"); + *at.lock().expect("the clock") = start + Duration::from_secs(10); + // The server may already have closed when this is written; if not, it wakes the server's read. + let _ = stream.write_all(b" "); + assert!(is_closed(&mut reader), "the input sent did not keep the connection open past the deadline"); + assert!(nothing_more_dispatched(&rx, server, &connection_ended, 1), "nothing was dispatched"); } -/// Whether the server closed the connection: the next read is the end of the stream, not a timeout or an error. +/// Whether the server closed the connection: the next read is the end of the stream, or an error other than a timeout. +/// A server that closes with input still unread makes the kernel send a reset, so the read fails with +/// `ConnectionReset` or `ConnectionAborted` instead of returning the end of the stream (mostly on Windows). fn is_closed(reader: &mut impl BufRead) -> bool { let mut line = String::new(); - matches!(reader.read_line(&mut line), Ok(0)) + match reader.read_line(&mut line) { + Ok(read) => read == 0, + Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), + } +} + +/// A reader whose every read fails with the given error kind. +struct Failing(std::io::ErrorKind); + +impl std::io::Read for Failing { + fn read(&mut self, _: &mut [u8]) -> std::io::Result { + Err(self.0.into()) + } +} + +/// A reset or aborted connection counts as closed; a read timeout does not. +#[trial] +fn a_reset_connection_counts_as_closed() { + use std::io::ErrorKind::{ConnectionAborted, ConnectionReset, TimedOut, WouldBlock}; + assert!(is_closed(&mut BufReader::new(Failing(ConnectionReset))), "a reset is a close"); + assert!(is_closed(&mut BufReader::new(Failing(ConnectionAborted))), "an abort is a close"); + assert!(!is_closed(&mut BufReader::new(Failing(TimedOut))), "a timeout is not a close"); + assert!(!is_closed(&mut BufReader::new(Failing(WouldBlock))), "a timeout is not a close"); +} + +/// A server whose `ended` receiver gets `()` each time one of its connections has ended. Its clock stands still, so no +/// connection reaches the authentication deadline: only the client or a refusal ends one. The frozen clock does not +/// stop the socket's read timeout, which runs on real time and is the time left to the deadline capped at the idle +/// timeout. The deadline is a minute, so a waiting connection's read times out after the 30-second idle timeout +/// instead of after 10 seconds. +fn serve_counting_ends() -> (Receiver, server::Listening, Receiver<()>) { + let (ended, connection_ended) = channel(); + let start = motion::now(); + let options = ServeOptions { auth_deadline: Duration::from_secs(60), clock: Arc::new(move || start), ended: Some(ended) }; + let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started"); + (rx, server, connection_ended) +} + +/// Stops `server` and waits for its `connections` connections to end, so the request receiver `rx` is disconnected +/// once every request that reached it has been taken: `rx` then answers whether anything more was dispatched. +fn nothing_more_dispatched(rx: &Receiver, server: server::Listening, ended: &Receiver<()>, connections: usize) -> bool { + drop(server); + for _ in 0..connections { + ended.recv_timeout(Duration::from_secs(5)).expect("a connection ended"); + } + rx.recv_timeout(Duration::from_secs(5)).err() == Some(RecvTimeoutError::Disconnected) } /// With `MAX_CONNECTIONS` connections open, the next one is told `connection limit reached` and closed; once one of /// the open ones ends, its place serves a new connection. #[trial] fn connections_past_the_limit_are_refused_with_the_reason() { - let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let (rx, server, ended) = serve_counting_ends(); let connect = || { let stream = TcpStream::connect(server.addr).expect("connected"); stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); @@ -150,20 +202,14 @@ fn connections_past_the_limit_are_refused_with_the_reason() { drop(open.pop()); // The server frees the place when it reads the close; a new connection is served once it has. - let started = motion::now(); - let served = loop { - let (mut stream, mut reader) = connect(); - writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written"); - let reply = read_json(&mut reader).expect("a reply"); - if reply["ok"] == true || started.elapsed() > Duration::from_secs(5) { - break reply; - } - assert_eq!(reply["error"], "connection limit reached", "{reply}"); - std::thread::sleep(Duration::from_millis(20)); - }; + ended.recv_timeout(Duration::from_secs(5)).expect("the closed connection ended"); + let (mut stream, mut reader) = connect(); + writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written"); + let served = read_json(&mut reader).expect("a reply"); assert_eq!(served["result"]["authenticated"], true, "the freed place serves: {served}"); - assert!(rx.try_recv().is_err(), "nothing was dispatched"); + drop((stream, reader)); drop(open); + assert!(nothing_more_dispatched(&rx, server, &ended, MAX_CONNECTIONS), "nothing was dispatched"); } /// A first frame that is not JSON, and one with a wrong token, each get the `authentication required` refusal and the @@ -191,9 +237,8 @@ fn a_refused_first_frame_closes_the_connection() { /// and the connection closed, so neither the body's `auth` nor a request after it reaches the app. #[trial] fn a_browser_post_never_reaches_the_app() { - // Far longer than the trial, so the close comes from the refusal, not the deadline. - let (rx, server) = server::serve_with_deadline(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), Duration::from_secs(60)) - .expect("started"); + // The server's clock stands still, so the close comes from the refusal, not the deadline. + let (rx, server, ended) = serve_counting_ends(); let mut stream = TcpStream::connect(server.addr).expect("connected"); stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); let mut reader = BufReader::new(stream.try_clone().expect("cloned")); @@ -211,7 +256,8 @@ fn a_browser_post_never_reaches_the_app() { Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), }; assert!(closed, "the connection closes after the refusal, answering nothing more: {rest:?}"); - assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "nothing reached the app"); + drop((stream, reader)); + assert!(nothing_more_dispatched(&rx, server, &ended, 1), "nothing reached the app"); } /// A request line over `MAX_REQUEST_BYTES` without a newline gets an error reply and the connection is closed. @@ -325,19 +371,19 @@ fn the_documented_capture_client_sends_setup_steps_and_capture() { let mut client = ControlClient::connect(addr, TOKEN).expect("connected"); capture_state(&mut client, &client_doc, &client_doc["states"][0], "new") }); - let mut channel = ControlChannel::new(requests); + // Each request is waited for as it arrives and then taken through the channel, as the app's frame takes it. + let (forward, forwarded) = channel(); + let mut channel = ControlChannel::new(forwarded); let mut seen: Vec = Vec::new(); - let started = motion::now(); - while seen.len() < 4 && started.elapsed() < Duration::from_secs(10) { - while let Some(req) = channel.next_request() { - seen.push(format!("{} {}", req.method, req.params)); - let reply = match req.method.as_str() { - "ui.screenshot" => Reply::from_result(Ok(json!({"path": req.params["path"], "width": 1280, "height": 800}))), - _ => Reply::from_result(Ok(Value::Null)), - }; - channel.settle(req, reply, None, 0.0); - } - std::thread::sleep(Duration::from_millis(5)); + while seen.len() < 4 { + forward.send(requests.recv_timeout(Duration::from_secs(10)).expect("a request")).expect("forwarded"); + let req = channel.next_request().expect("the forwarded request is dispatched"); + seen.push(format!("{} {}", req.method, req.params)); + let reply = match req.method.as_str() { + "ui.screenshot" => Reply::from_result(Ok(json!({"path": req.params["path"], "width": 1280, "height": 800}))), + _ => Reply::from_result(Ok(Value::Null)), + }; + channel.settle(req, reply, None, 0.0); } let reply = client.join().expect("client ran").expect("the capture replied"); assert_eq!( @@ -440,12 +486,12 @@ fn a_repeated_auth_is_answered_already_authenticated_without_dispatching() { /// and shut its end down) still reaches the app and is answered: a client cannot know it was dropped. #[trial] fn a_complete_json_request_at_eof_can_reach_the_app() { - let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let (rx, server, ended) = serve_counting_ends(); let handler = std::thread::spawn(move || { let req = rx.recv_timeout(Duration::from_secs(5)).expect("the request reached the app"); assert_eq!(req.method, "test.once"); req.reply.send(json!({"ok": true, "result": "once"})).expect("replied"); - assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "it ran exactly once"); + rx }); let (mut stream, mut reader) = authenticated(server.addr); stream.write_all(json!({"id": 3, "method": "test.once"}).to_string().as_bytes()).expect("written"); @@ -454,7 +500,8 @@ fn a_complete_json_request_at_eof_can_reach_the_app() { assert_eq!((&reply["id"], &reply["result"]), (&json!(3), &json!("once"))); let mut rest = String::new(); assert_eq!(reader.read_line(&mut rest).expect("closed, not timed out"), 0, "closed after the last request: {rest:?}"); - handler.join().expect("handler ran"); + let rx = handler.join().expect("handler ran"); + assert!(nothing_more_dispatched(&rx, server, &ended, 1), "it ran exactly once"); } /// Ported from WordCraft (#7317). Connections that never authenticate cannot fill the server: past the limit a new @@ -462,9 +509,8 @@ fn a_complete_json_request_at_eof_can_reach_the_app() { #[trial] fn idle_unauthenticated_connections_are_limited() { use craft_automation::security::MAX_CONNECTIONS; - // Far longer than the trial, so only the limit refuses. - let (rx, server) = server::serve_with_deadline(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), Duration::from_secs(60)) - .expect("started"); + // The server's clock stands still, so only the limit refuses. + let (rx, server, ended) = serve_counting_ends(); let idle: Vec = (0..MAX_CONNECTIONS).map(|_| TcpStream::connect(server.addr).expect("connected")).collect(); // Admission is counted by the accept thread: it is done once the next connection is answered. let refused = |addr| { @@ -477,18 +523,14 @@ fn idle_unauthenticated_connections_are_limited() { assert!(reply["error"].as_str().is_some_and(|e| e.contains("limit")), "{reply}"); drop(idle); // The freed slots go back as the closed connections are noticed. - let started = motion::now(); - loop { - let mut stream = TcpStream::connect(server.addr).expect("connected"); - stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); - let mut reader = BufReader::new(stream.try_clone().expect("cloned")); - // A refused connection may already be closed when the request is written (Windows resets it). - let auth = json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}}); - if writeln!(stream, "{auth}").is_ok() && read_json(&mut reader).is_some_and(|r| r["ok"] == true) { - break; - } - assert!(started.elapsed() < Duration::from_secs(10), "no slot came back"); - std::thread::sleep(Duration::from_millis(50)); + for _ in 0..MAX_CONNECTIONS { + ended.recv_timeout(Duration::from_secs(5)).expect("a closed connection ended"); } - assert!(rx.try_recv().is_err()); + let mut stream = TcpStream::connect(server.addr).expect("connected"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let mut reader = BufReader::new(stream.try_clone().expect("cloned")); + writeln!(stream, "{}", json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}})).expect("written"); + assert_eq!(read_json(&mut reader).expect("a reply")["ok"], true, "a freed slot is admitted again"); + drop((stream, reader)); + assert!(nothing_more_dispatched(&rx, server, &ended, 1)); } diff --git a/crates/behavior/src/canvas/units.rs b/crates/behavior/src/canvas/units.rs index 946e0d0aba..5bdd7b95ba 100644 --- a/crates/behavior/src/canvas/units.rs +++ b/crates/behavior/src/canvas/units.rs @@ -101,10 +101,12 @@ impl RulerUnits { (position - zero) * self.per_doc } - /// The least and most decimals a ruler writes a tick of labelled step `step` with. Whole ticks are whole numbers; - /// a step of at least 1 takes the decimals it has (none for 5, one for 2.5). Under [`TickLabels::Distance`] a - /// smaller step takes at least two (PhotoCraft's `0.50`), more when it has them (0.025), and every tick takes them - /// all; under [`TickLabels::Signed`] a tick drops the trailing zeros (`1` on a sixteenth-inch ruler). + /// The least and most decimals a ruler writes a tick of labelled step `step` with. + /// + /// Whole ticks are whole numbers; a step of at least 1 takes the decimals it has (none for 5, one for 2.5). Under + /// [`TickLabels::Distance`] a smaller step takes at least two (PhotoCraft's `0.50`), more when it has them + /// (0.025), and every tick takes them all; under [`TickLabels::Signed`] a tick drops the trailing zeros (`1` on a + /// sixteenth-inch ruler). pub fn label_decimals(&self, step: f64) -> RangeInclusive { let most = match self.ticks { Ticks::Decimal { whole: true } => 0, diff --git a/crates/behavior/src/dock/edit.rs b/crates/behavior/src/dock/edit.rs index 2184f141dd..a94b3c5554 100644 --- a/crates/behavior/src/dock/edit.rs +++ b/crates/behavior/src/dock/edit.rs @@ -449,8 +449,9 @@ impl Layout

{ return Err(DockError::MissingPanel); } let taken = column.groups.remove(group); + let part = !column.groups.is_empty(); let id = self.drop_if_empty(&place); - return Ok(Moving { id, ..Moving::taken(taken, source) }); + return Ok(Moving { id, part, ..Moving::taken(taken, source) }); }; if let Some(Node::Stack { entries }) = self.node_of_mut(&place) && entries.len() > 1 @@ -478,14 +479,14 @@ impl Layout

{ if columns.is_empty() { self.take_node(&path); } - Ok(Moving { column: taken, id: None }) + Ok(Moving { column: taken, id: None, part: false }) } Some(PanelPlace::Floating { window, .. }) => { if window >= self.floating.len() { return Err(DockError::MissingPanel); } let taken = self.floating.remove(window); - Ok(Moving { column: Column { width: Some(taken.rect.width()), ..taken.column }, id: Some(taken.id) }) + Ok(Moving { column: Column { width: Some(taken.rect.width()), ..taken.column }, id: Some(taken.id), part: false }) } Some(PanelPlace::Node(_)) | None => Err(DockError::InvalidPlacement), } @@ -500,7 +501,8 @@ impl Layout

{ } /// Insert groups taken by [`Self::take_unit`] (or a new single-panel group). A new column, docked or floating, - /// keeps the moving column's state; groups that join a column take that column's. + /// keeps the moving column's state, expanded when they are part of a collapsed column; groups that join a column + /// take that column's. /// `canvas` is the protected-panel test an outer edge drop narrows by ([`Self::edge_path`]). pub(super) fn insert_moving(&mut self, moving: Moving

, to: Target

, canvas: &dyn Fn(&P) -> bool) -> Result<(), DockError> { let mut moving = moving; @@ -517,7 +519,7 @@ impl Layout

{ Some(id) => id, None => self.fresh_window_id(), }; - let window = Floating::new(id, Column { width: None, ..moving.column }, rect); + let window = Floating::new(id, moving.into_window_column(), rect); let edge = edge.filter(|_| window.column.iconic); self.floating.push(Floating { edge, ..window }); Ok(()) diff --git a/crates/behavior/src/dock/groups.rs b/crates/behavior/src/dock/groups.rs index a05570c53e..4ff36d0f16 100644 --- a/crates/behavior/src/dock/groups.rs +++ b/crates/behavior/src/dock/groups.rs @@ -330,12 +330,14 @@ pub(super) enum Unit { } /// Groups in transit, in a column that carries the state of the column they came from: a new column, docked or -/// floating, keeps that state (an icon group taken out of a collapsed column stays icons), and a column they -/// join keeps its own. +/// floating, keeps that state, except that part of a collapsed column makes an expanded one (the last group of a +/// collapsed column stays icons); a column they join keeps its own. pub(super) struct Moving

{ pub column: Column

, /// The id of a floating window whose last group is in transit, which a new window keeps. pub id: Option, + /// Panels stay in the column the groups left, so a new column made of them is expanded. + pub part: bool, } impl

Moving

{ @@ -344,14 +346,26 @@ impl

Moving

{ Self::taken(group, Column::new(Vec::new())) } - /// `group` taken out of a column whose state is `source` ([`Column::emptied`]). + /// `group` taken out of a column whose state is `source` ([`Column::emptied`]), as all of that column. pub(super) fn taken(group: Group

, source: Column

) -> Self { - Self { column: Column { groups: vec![group], ..source }, id: None } + Self { column: Column { groups: vec![group], ..source }, id: None, part: false } } - /// The column a new dock column gets: the moving column, `width` points wide unless it brings a width. + /// `panel` alone, taken out of a column whose state is `source`, with whether other panels stay in it. + pub(super) fn panel(panel: P, source: (Column

, bool)) -> Self { + let (column, part) = source; + Self { part, ..Self::taken(Group::new(vec![panel], 0), column) } + } + + /// The column a new floating window gets: the moving column, expanded when it is part of a collapsed one. + pub(super) fn into_window_column(self) -> Column

{ + Column { width: None, iconic: self.column.iconic && !self.part, ..self.column } + } + + /// The column a new dock column gets: the moving column, `width` points wide unless it brings a width, and + /// expanded when it is part of a collapsed one. pub(super) fn into_column(self, width: Option) -> Column

{ - Column { width: self.column.width.or(width), ..self.column } + Column { width: self.column.width.or(width), iconic: self.column.iconic && !self.part, ..self.column } } } diff --git a/crates/behavior/src/dock/inner.rs b/crates/behavior/src/dock/inner.rs index b213dd3177..6d652e7e71 100644 --- a/crates/behavior/src/dock/inner.rs +++ b/crates/behavior/src/dock/inner.rs @@ -49,7 +49,7 @@ impl Layout

{ let source = self.source_of(&panel); // A panel the layout does not hold opens in the new window. let entry = self.take(&panel).unwrap_or(StackEntry { panel: panel.clone(), open: true, height: None }); - let moving = Moving { id: lone, ..Moving::taken(Group::new(vec![entry.panel], 0), source) }; + let moving = Moving { id: lone, ..Moving::panel(entry.panel, source) }; self.insert_moving(moving, Target::Float { rect, edge: None }, canvas) } Action::Close { panel } => self.take(&panel).map(|_| ()).ok_or(DockError::MissingPanel), @@ -72,7 +72,7 @@ impl Layout

{ } let entry = StackEntry { panel, open: true, height: None }; if let Some(anchor) = anchor { - self.insert(entry, Column::new(Vec::new()), &anchor, DockPlacement::Tab { before: None }, canvas) + self.insert(entry, (Column::new(Vec::new()), false), &anchor, DockPlacement::Tab { before: None }, canvas) } else if self.root.is_none() { self.root = Some(Node::Tabs { panels: vec![entry.panel], active: 0 }); Ok(()) @@ -89,7 +89,7 @@ impl Layout

{ { return Err(DockError::MissingTarget); } - self.insert(StackEntry { panel, open: true, height: None }, Column::new(Vec::new()), &anchor, placement, canvas) + self.insert(StackEntry { panel, open: true, height: None }, (Column::new(Vec::new()), false), &anchor, placement, canvas) } Action::MoveFloating { panel, rect, edge } => { if !valid_rect(rect) { @@ -142,7 +142,7 @@ impl Layout

{ to => { let source = self.source_of(&panel); let entry = self.take(&panel).ok_or(DockError::MissingPanel)?; - self.insert_moving(Moving::taken(Group::new(vec![entry.panel], 0), source), to, canvas) + self.insert_moving(Moving::panel(entry.panel, source), to, canvas) } }, Action::Restore { panel, location } => { @@ -256,9 +256,11 @@ impl Layout

{ } /// The state a new column made of `panel` keeps: its column's ([`Self::source_column`]), or none for a panel - /// outside a column or absent. - pub(super) fn source_of(&self, panel: &P) -> Column

{ - self.place(panel).map_or_else(|| Column::new(Vec::new()), |place| self.source_column(&place)) + /// outside a column or absent; and whether other panels stay in that column ([`Moving::part`]). + pub(super) fn source_of(&self, panel: &P) -> (Column

, bool) { + let Some(place) = self.place(panel) else { return (Column::new(Vec::new()), false) }; + let part = self.column(&place).is_some_and(|column| column.panels().any(|other| other != panel)); + (self.source_column(&place), part) } /// The accordion entry of `panel` in the docked tree. @@ -327,7 +329,7 @@ impl Layout

{ pub(super) fn insert( &mut self, entry: StackEntry

, - source: Column

, + source: (Column

, bool), anchor: &P, placement: DockPlacement

, canvas: &dyn Fn(&P) -> bool, @@ -338,8 +340,7 @@ impl Layout

{ .filter(|_| !matches!(placement, DockPlacement::Group { .. } | DockPlacement::Column { .. } | DockPlacement::Edge(_))) .map(<[bool]>::to_vec) else { - let moving = Moving::taken(Group::new(vec![entry.panel], 0), source); - return self.insert_moving(moving, Target::At { anchor: anchor.clone(), placement }, canvas); + return self.insert_moving(Moving::panel(entry.panel, source), Target::At { anchor: anchor.clone(), placement }, canvas); }; let root = self.root.as_mut().ok_or(DockError::MissingTarget)?; if let DockPlacement::Split(zone) = placement diff --git a/crates/behavior/src/frame_step.rs b/crates/behavior/src/frame_step.rs index a293d5a1ff..225cc70b4c 100644 --- a/crates/behavior/src/frame_step.rs +++ b/crates/behavior/src/frame_step.rs @@ -3,8 +3,9 @@ /// The longest step motion integrates, in seconds, so a stalled pass never jumps the view. pub const FRAME_STEP_MAX: f64 = 0.1; -/// The step of a pass that came `dt` seconds after the previous one, `dt` being the time between two readings of the -/// caller's pass clock: `dt` within `0..=FRAME_STEP_MAX`, and 0 where it is not a number. +/// The step of a pass that came `dt` seconds after the previous one, kept within `0..=FRAME_STEP_MAX`. +/// +/// `dt` is the time between two readings of the caller's pass clock; where it is not a number, the step is 0. pub fn frame_step(dt: f64) -> f64 { if dt.is_finite() { dt.clamp(0.0, FRAME_STEP_MAX) } else { 0.0 } } diff --git a/crates/behavior/src/geometry/crop.rs b/crates/behavior/src/geometry/crop.rs index 7fa0422777..80e6ce7fd3 100644 --- a/crates/behavior/src/geometry/crop.rs +++ b/crates/behavior/src/geometry/crop.rs @@ -148,8 +148,9 @@ impl CropBox { (w.is_finite() && h.is_finite()).then(|| (w.round().max(1.0), h.round().max(1.0))) } - /// Whether both sides are at least `min`, and never under one document unit whatever `min` says (a `min` that is - /// not a number counts as one unit). + /// Whether both sides are at least `min`, and never under one document unit whatever `min` says. + /// + /// A `min` that is not a number counts as one unit. pub fn size_ok(&self, min: f64) -> bool { let min = min.max(MIN_FRAME); self.rect.width() >= min && self.rect.height() >= min @@ -544,7 +545,7 @@ const INV_PHI: f64 = 0.618_033_988_749_894_9; const PHI: f64 = 1.0 + INV_PHI; /// The composition guide drawn inside a crop frame, in Photoshop's menu order. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum CropGuide { @@ -727,7 +728,7 @@ fn golden_spiral() -> Vec<[f64; 2]> { } /// When the guide shows. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum GuideShow { diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index be5f2b3a8b..347f7da531 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -310,7 +310,7 @@ fn a_floating_windows_edge_is_saved_set_by_collapsed_moves_and_floats_and_cleare assert_eq!(layout.floating[0].edge, None, "collapsing hangs the strip from the edge nearer the window"); let mut moved = columns(); - moved.apply(Action::move_group(3, Target::float_with_edge(window(), Some(DockEdge::End)))).unwrap(); + moved.apply(Action::move_column(3, Target::float_with_edge(window(), Some(DockEdge::End)))).unwrap(); let floated = moved.floating.iter().find(|window| window.contains(&3)).unwrap(); assert_eq!(floated.edge, Some(DockEdge::End), "a collapsed column floats at the edge its strip was dropped near"); let mut moved = columns(); @@ -356,10 +356,21 @@ fn a_group_docked_into_a_collapsed_column_keeps_its_width_as_the_flyout_width() layout.apply(Action::resize_flyout_width(3, Some(350.0))).unwrap(); layout.apply(Action::move_group(3, Target::at(7, DockPlacement::group(true, None)))).unwrap(); assert_eq!(flyout(&layout, 3), Some(350.0), "a group from another collapsed column keeps its own"); + + let source = Column::new(vec![g(&[3], 0), g(&[4], 0)]).with_width(300.0).with_iconic(true); + let target = Column::new(vec![g(&[7], 0)]).with_iconic(true); + let mut layout = Layout::new( + Some(Node::split(Axis::X, SplitSize::Ratio(0.5), Node::dock(DockEdge::Start, vec![target]), Node::dock(DockEdge::End, vec![source]))), + vec![], + ); + layout.apply(Action::resize_flyout_width(3, Some(350.0))).unwrap(); + layout.apply(Action::move_group(3, Target::at(7, DockPlacement::group(true, None)))).unwrap(); + assert_eq!(flyout(&layout, 3), Some(350.0), "a group from a collapsed column of its own width keeps its flyout width"); } -/// Collapse to icons is a state of every column: a floating window collapses and stays floating; groups leaving a -/// column float in its state; groups joining a column, docked or floating, take that column's state. +/// Collapse to icons is a state of every column: a floating window collapses and stays floating; a whole column +/// leaving floats in its state, and part of a collapsed column floats expanded; groups joining a column, docked or +/// floating, take that column's state. #[test] fn a_column_keeps_its_collapsed_state_when_it_floats_and_a_joined_column_decides() { let mut layout = columns(); @@ -369,15 +380,24 @@ fn a_column_keeps_its_collapsed_state_when_it_floats_and_a_joined_column_decides layout.apply(Action::set_iconic(6, false)).unwrap(); assert_eq!(layout.panel_state(&6), PanelState::Front); - for action in [ - Action::move_column(3, Target::float(window())), - Action::move_group(3, Target::float(window())), - Action::move_panel(3, Target::float(window())), - ] { + let mut moved = columns(); + moved.apply(Action::move_column(3, Target::float(window()))).unwrap(); + assert!(floats(&moved, 3) && column_of(&moved, 3).iconic, "the whole collapsed column floats as icons"); + for action in [Action::move_group(3, Target::float(window())), Action::move_panel(3, Target::float(window()))] { let mut moved = columns(); moved.apply(action.clone()).unwrap(); - assert!(floats(&moved, 3) && column_of(&moved, 3).iconic, "{action:?} floats as icons"); + assert!(floats(&moved, 3) && !column_of(&moved, 3).iconic, "{action:?} out of a column with another group floats expanded"); + assert!(column_of(&moved, 4).iconic, "the column it left stays collapsed"); + moved.apply(Action::move_group(4, Target::float(window()))).unwrap(); + assert!(floats(&moved, 4) && column_of(&moved, 4).iconic, "the column's last group floats as icons"); } + let mut tabbed = Layout::new(None, vec![Floating::new(102, Column::new(vec![g(&[3, 4, 5], 0)]).with_iconic(true), window())]); + tabbed.apply(Action::move_panel(3, Target::float(window()))).unwrap(); + assert!(!column_of(&tabbed, 3).iconic, "a tab out of a collapsed column's only group floats expanded"); + tabbed.apply(Action::move_panel(5, Target::new_dock(DockEdge::End))).unwrap(); + assert!(!column_of(&tabbed, 5).iconic, "a tab out of a collapsed column docks expanded"); + tabbed.apply(Action::move_panel(4, Target::new_dock(DockEdge::Start))).unwrap(); + assert!(column_of(&tabbed, 4).iconic, "the column's last panel docks as icons"); let mut moved = columns(); moved.apply(Action::move_group(2, Target::float(window()))).unwrap(); assert!(floats(&moved, 2) && !column_of(&moved, 2).iconic, "out of an expanded column it floats expanded"); diff --git a/crates/captions/src/jacosub.rs b/crates/captions/src/jacosub.rs index 30233b6f1d..73bf51c9f1 100644 --- a/crates/captions/src/jacosub.rs +++ b/crates/captions/src/jacosub.rs @@ -146,10 +146,10 @@ pub fn parse(text: &str) -> Result { Some(end_bracket) => stripped[end_bracket + 1..].trim_start(), None => trimmed_rem, } - } else if let Some(space_idx) = trimmed_rem.find(' ') { - let first_token = &trimmed_rem[..space_idx]; + } else if let Some(separator) = trimmed_rem.find(char::is_whitespace) { + let first_token = &trimmed_rem[..separator]; if first_token.starts_with('D') && first_token[1..].chars().all(|c| c.is_ascii_digit()) { - trimmed_rem[space_idx + 1..].trim_start() + trimmed_rem[separator..].trim_start() } else { trimmed_rem } @@ -218,6 +218,13 @@ mod tests { assert_eq!(written, jss); } + #[test] + fn tab_after_directive_keeps_only_the_subtitle_text() { + let doc = parse("0:00:01.00 0:00:03.00 D0\tFirst\tline\n").unwrap(); + assert_eq!(doc.cues.len(), 1); + assert_eq!(doc.cues[0].text, "First\tline"); + } + #[test] fn parse_bracketed_directive() { let jss = "#TimeRes 100\n0:00:01.00 0:00:03.00 [Style1] Bracketed style text\n"; diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rs index e83b868ce2..4251b79efb 100644 --- a/crates/captions/src/lib.rs +++ b/crates/captions/src/lib.rs @@ -351,7 +351,9 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { if ext.as_deref() != Some("srt") && !has_arrow_timing && first_lines.iter().any(|l| subviewer::parse_timing(l).is_some()) { return Some(Format::SubViewer); } - if !first_lines.is_empty() && first_lines.iter().all(|l| vplayer::split_line(l).is_some()) { + if !first_lines.is_empty() + && head.lines().map(str::trim_start).filter(|line| !line.trim().is_empty()).take(3).all(|line| vplayer::split_line(line).is_some()) + { return Some(Format::VPlayer); } if first_lines.first().is_some_and(|l| pjs::split_cue(l).is_some()) { diff --git a/crates/captions/src/ttml.rs b/crates/captions/src/ttml.rs index 78db4763b3..07c2fd9cb1 100644 --- a/crates/captions/src/ttml.rs +++ b/crates/captions/src/ttml.rs @@ -113,6 +113,57 @@ fn time_expr(t: Tick, rate: Option) -> String { } } +/// The caption text as the tag parser sees it: one byte at a time, counted in tests. +mod reader { + #[cfg(test)] + thread_local! { + /// Calls to [`Reader::byte`] on this thread (tests: the tag parser's work is linear in the text). + pub(super) static READS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + /// The bytes of a caption text, read only through [`Reader::byte`]. + #[derive(Clone, Copy)] + pub(super) struct Reader<'a> { + bytes: &'a [u8], + } + + impl<'a> Reader<'a> { + pub(super) fn new(bytes: &'a [u8]) -> Self { + Self { bytes } + } + + /// The byte at `index`, or `None` past the end. + pub(super) fn byte(self, index: usize) -> Option { + #[cfg(test)] + READS.with(|r| r.set(r.get().saturating_add(1))); + self.bytes.get(index).copied() + } + + /// The bytes from `start` to the end, each read through [`Reader::byte`]. + pub(super) fn suffix(self, start: usize) -> Suffix<'a> { + Suffix { reader: self, next: start } + } + } + + /// Iterator returned by [`Reader::suffix`]. + pub(super) struct Suffix<'a> { + reader: Reader<'a>, + next: usize, + } + + impl Iterator for Suffix<'_> { + type Item = u8; + + fn next(&mut self) -> Option { + let c = self.reader.byte(self.next)?; + self.next = self.next.saturating_add(1); + Some(c) + } + } +} + +use reader::Reader; + /// Memoised "next occurrence of a quote byte" searches, so unterminated quotes are not rescanned. #[derive(Default)] struct QuoteCache { @@ -121,7 +172,7 @@ struct QuoteCache { impl QuoteCache { /// Index of the next `quote` byte at or after `from`. - fn next(&mut self, bytes: &[u8], quote: u8, from: usize) -> Option { + fn next(&mut self, bytes: Reader<'_>, quote: u8, from: usize) -> Option { let slot = usize::from(quote == b'\''); if let Some((searched, result)) = self.found[slot] && searched <= from @@ -129,7 +180,7 @@ impl QuoteCache { { return result; } - let result = bytes.get(from..).and_then(|t| t.iter().position(|&c| c == quote)).map(|i| from + i); + let result = bytes.suffix(from).position(|c| c == quote).map(|i| from + i); self.found[slot] = Some((from, result)); result } @@ -139,42 +190,42 @@ impl QuoteCache { /// letters/digits starting with a letter immediately after, then whitespace-separated /// `name="value"` / `name='value'` attributes, optional `/` before `>`. A `>` inside a quoted /// value does not end the tag. Returns `(index after '>', closing, lowercase name)`; the name is empty for a self-closing tag. -fn parse_tag(bytes: &[u8], start: usize, cache: &mut QuoteCache) -> Option<(usize, bool, String)> { +fn parse_tag(bytes: Reader<'_>, start: usize, cache: &mut QuoteCache) -> Option<(usize, bool, String)> { let mut i = start + 1; - let closing = bytes.get(i) == Some(&b'/'); + let closing = bytes.byte(i) == Some(b'/'); if closing { i += 1; } - let name_start = i; - if !bytes.get(i)?.is_ascii_alphabetic() { + if !bytes.byte(i)?.is_ascii_alphabetic() { return None; } - while bytes.get(i).is_some_and(u8::is_ascii_alphanumeric) { + let mut name = String::new(); + while let Some(c) = bytes.byte(i).filter(u8::is_ascii_alphanumeric) { + name.push(char::from(c.to_ascii_lowercase())); i += 1; } - let name = String::from_utf8_lossy(bytes.get(name_start..i)?).to_ascii_lowercase(); loop { let ws_start = i; - while bytes.get(i).is_some_and(u8::is_ascii_whitespace) { + while bytes.byte(i).is_some_and(|c| c.is_ascii_whitespace()) { i += 1; } - match bytes.get(i)? { + match bytes.byte(i)? { b'>' => return Some((i + 1, closing, name)), // self-closing: no markup - b'/' if !closing && bytes.get(i + 1) == Some(&b'>') => return Some((i + 2, closing, String::new())), + b'/' if !closing && bytes.byte(i + 1) == Some(b'>') => return Some((i + 2, closing, String::new())), _ => {} } if i == ws_start { return None; } let key_start = i; - while bytes.get(i).is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b':' | b'_')) { + while bytes.byte(i).is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b':' | b'_')) { i += 1; } - if i == key_start || bytes.get(i) != Some(&b'=') { + if i == key_start || bytes.byte(i) != Some(b'=') { return None; } - let quote = *bytes.get(i + 1)?; + let quote = bytes.byte(i + 1)?; if quote != b'"' && quote != b'\'' { return None; } @@ -204,10 +255,11 @@ fn inline(text: &str) -> String { }; let mut rest = text; let mut cache = QuoteCache::default(); + let bytes = Reader::new(text.as_bytes()); while !rest.is_empty() { // Only a well-formed tag is markup; "1 < 2 and 3 > 2" and "ad" are text. if rest.starts_with('<') - && let Some((end, closing, name)) = parse_tag(text.as_bytes(), text.len() - rest.len(), &mut cache) + && let Some((end, closing, name)) = parse_tag(bytes, text.len() - rest.len(), &mut cache) { let attr = match name.as_str() { "i" => Some("tts:fontStyle=\"italic\""), @@ -1171,15 +1223,34 @@ mod tests { assert_eq!(out, "x"); } + /// `inline(text)` and the number of bytes the tag parser read for it. + fn inline_cost(text: &str) -> (String, usize) { + reader::READS.with(|r| r.set(0)); + let out = inline(text); + (out, reader::READS.with(std::cell::Cell::get)) + } + + /// The tag parser reads each byte of `text` a bounded number of times, and twice the text costs about twice the work. + fn assert_linear(make: impl Fn(usize) -> String, escaped: impl Fn(usize) -> String) { + let (out, small) = inline_cost(&make(50_000)); + assert_eq!(out, escaped(50_000)); + let text = make(100_000); + let (out, large) = inline_cost(&text); + assert_eq!(out, escaped(100_000)); + assert!(large <= 3 * text.len(), "{large} byte reads in a text of {}", text.len()); + assert!(large < 3 * small, "twice the text, {small} then {large} byte reads"); + } + #[test] fn unclosed_angle_brackets_are_escaped_in_one_pass() { // Every `<` used to search the rest of the text for a `>`, which made this quadratic. - let text = "<".repeat(200_000); - let started = std::time::Instant::now(); - let out = inline(&text); - assert_eq!(out, "<".repeat(200_000)); - assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed()); + assert_linear(|n| "<".repeat(n), |n| "<".repeat(n)); // A tag before the unclosed tail is still markup; the tail stays literal text. assert_eq!(inline("a 1 < 2"), "a 1 < 2"); } + + #[test] + fn many_unmatched_angle_brackets_before_one_gt_are_read_once() { + assert_linear(|n| format!("{}>", "<".repeat(n)), |n| format!("{}>", "<".repeat(n))); + } } diff --git a/crates/captions/src/vplayer.rs b/crates/captions/src/vplayer.rs index 169e4f24a0..bcc834f58a 100644 --- a/crates/captions/src/vplayer.rs +++ b/crates/captions/src/vplayer.rs @@ -49,7 +49,7 @@ pub fn parse(text: &str) -> Result { if line.trim().is_empty() { continue; } - match split_line(line.trim()) { + match split_line(line.trim_start()) { Some((t, raw)) => { let lines: Vec = raw.split('|').map(str::trim).filter(|l| !l.is_empty()).map(escape_markup).collect(); starts.push((t, lines.join("\n"))); @@ -121,6 +121,38 @@ pub fn write(doc: &Document) -> String { mod tests { use super::*; + #[test] + fn empty_clearing_lines_keep_each_separator() { + for separator in [":", "=", " "] { + for indent in ["", " \t"] { + let input = format!("{indent}00:00:01{separator} hello \n{indent}00:00:02{separator} \n"); + assert_eq!(crate::detect(input.as_bytes(), None), Some(crate::Format::VPlayer), "{input:?}"); + let doc = parse(&input).unwrap(); + assert_eq!(doc.cues.len(), 1, "{input:?}"); + assert_eq!(doc.cues[0].text, "hello", "{input:?}"); + assert_eq!(doc.cues[0].end, ms_to_tick(2000), "{input:?}"); + assert!(doc.warnings.is_empty(), "{:?}", doc.warnings); + } + } + } + + #[test] + fn detection_keeps_clearing_lines_at_each_sampled_position() { + for separator in [":", "=", " "] { + for at in 0..3 { + let mut lines = ["00:00:01=one".to_owned(), "00:00:02=two".to_owned(), "00:00:03=three".to_owned()]; + lines[at] = format!(" \t00:00:0{}{separator} \t", at + 1); + let input = format!("\u{feff}\n \t\n{}\n", lines.join("\n")); + let format = crate::detect(input.as_bytes(), None).unwrap(); + assert_eq!(format, crate::Format::VPlayer, "{input:?}"); + let document = crate::parse(input.as_bytes(), format).unwrap(); + assert_eq!(document.cues.len(), 2, "{input:?}"); + assert!(document.warnings.is_empty(), "{:?}", document.warnings); + } + } + assert_eq!(crate::detect(b"00:00:01 hello\n00:00:02\n", None), None); + } + #[test] fn short_duration_cue_preserves_positive_duration_on_write_and_read() { let mut doc = Document::default(); diff --git a/crates/captions/tests/it/ttml_literal_angle.rs b/crates/captions/tests/it/ttml_literal_angle.rs index 0e48439013..f2a98abb61 100644 --- a/crates/captions/tests/it/ttml_literal_angle.rs +++ b/crates/captions/tests/it/ttml_literal_angle.rs @@ -66,11 +66,10 @@ fn whitespace_after_lt_is_literal_text() { } } +/// The work for this text is checked in `ttml.rs`'s `many_unmatched_angle_brackets_before_one_gt_are_read_once`. #[test] -fn many_unmatched_lt_is_fast() { +fn many_unmatched_lt_stay_text() { let input = format!("{}>", "<".repeat(256_000)); - let start = std::time::Instant::now(); let text = export(&input, Format::Ttml); - assert!(start.elapsed() < std::time::Duration::from_secs(2), "took {:?}", start.elapsed()); assert!(text.contains(&format!("{}>", "<".repeat(256_000)))); } diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index 8200a763f6..e29d443fea 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -2,7 +2,7 @@ The reader relies on the record layouts below, and the writer (`src/write.rs`) lays out version 15 files by the same rows, with R64 to R73 for what only the writer needs. The `.cmx` writer -(`src/cmx_write.rs`) writes in them, with R74 for what only it needs ("Written fields" lists each +(`src/cmx_write.rs`) writes in them, with R74 and R77 for what only it needs ("Written fields" lists each field it sets). Code cites a row by its id (`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row here. @@ -56,9 +56,16 @@ Sources: https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/crates/cdr/src/cmx.rs, was read for the order of fields that the notes do not spell out (the table entries, the rendering attributes and the curve body); no code was copied from it +- **LC**: the `.cmx` reader of libcdr (MPL-2.0), `src/lib/CMXParser.cpp`, `src/lib/CMXParser.h` + and `src/lib/CMXDocumentStructure.h` at commit `b5211a57af37dac59a04f6041822a07f4a7cf7d6`, + https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXParser.cpp, + https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXParser.h + and https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXDocumentStructure.h, + read for the header's offsets, the index chunks and the fields of a color entry; no code was + copied from it Status: `public-spec` (K, KF, KR, Z, F, PR or G), `sample` (S), `public-notes` (a layout CN marks -confirmed that no CX file shows), `unconfirmed` (a point no source states and no sample file shows; +confirmed that no CX file shows), `public-reader` (a layout LC reads), `unconfirmed` (a point no source states and no sample file shows; listed so it can be checked against a file, with what the reader does when it is wrong). The "Written fields" table also uses `own` (a value the reader does not read, set as the synthetic test files of `src/synth_cmx.rs` set it) and `the writer's choice` (a value the reader does not read and @@ -129,7 +136,7 @@ file is committed. | R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list. When that chunk is one the reader passes over or a `page`, the reader may resume instead at a `page` chunk that starts 8 to 64 bytes after it, inside its body, is not empty, ends inside the list and, when the chunk found ends inside the list, reaches its end. It does so only when that page reads with objects and without damage in its instructions, and when walking on from the chunk found and from the page, each without this recovery and entering lists as the reader does, reaches the same position inside the same lists, or leaves the list (at its end, or at stray bytes with no chunk id after them), within 16 steps, with every chunk the reader uses that the first walk reads before then also read by the second, with its body cut at the same place (pages that read without objects aside). Of the chunks that only the second walk reads, or that it reads with its body cut at another place than the first walk does, the header or a table is used only when no other chunk of its id is read, and a page is kept only when it reads with objects and without damage in its instructions. Letters spelling `page` whose length runs past the list are checked the same way. In one read, the search for pages to resume at spends at most four times the length of the RIFF form (cut at the file's length), or 1,048,576 when that is more, counting 64 for each step of a walk and the length of each page body judged; past that, the reader resumes at the first chunk id found. It does the same when a limit stops the read of a page it judges. Pages kept this way are read after the other pages, so they spend only what the limits leave, and keep their place in the file; each is judged once more before it is read. One that a limit stops, or leaves without objects, is left out with the warning for limits; one the limits cut short is read as far as they allow, as other pages are. When the chunks that only these recoveries read make the read stop at a limit, the file is read again without the recoveries, with the warning for limits. Resuming at an inner page, at a chunk the reader passes over that is not followed by another chunk id or by the list's end, or after letters whose length runs past the list is reported as damage (this reader's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample | | R54 | `cont`: byte 52 is the coordinate size as an ASCII digit, `4` for 32-bit coordinates and `2` for 16-bit ones (refused); bytes 64 to 72 hold an f64, the size of a coordinate unit in meters. A value that isn't above 0 and at most 1 reads as 0.1 µm (VectorCraft's own fallback) | CN "Container"; S: the nine CX files with `4` all hold 1e-7; `abydos.cmx`, `CM33.CMX`, `LIZARDS.CMX`, `output.000.cmx` and `test.cmx` hold `2` | sample | | R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample | -| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) | +| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); LC `CMXParser.cpp` L1698-L1749 (a file with 32-bit coordinates: the model byte and a byte in tag 1, the values in tag 2, other tags passed over), L2254-L2371 (the values of each model: 2 and 3 four bytes, 5 red, green and blue, 9 one byte), `CMXDocumentStructure.h` L138-L139 (the tags); S: every color of the nine CX files is model 2 in the older fields, with the second byte of field 1 5 | sample (model 2), public-reader (the tags and the values of models 2, 5 and 9), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) | | R57 | `rpen` field 1: the width as a u32 in coordinate units (then an aspect, an angle and a matrix, not read). `rott` field 1: a flags byte (1 no outline, 2 solid, 4 dashed, 8 behind the fill, 16 scaled with the object), then the caps in the low 4 bits and the join in the high 4 bits, numbered as R12. `rdot` field 1: a u16 count, then the dash and gap lengths in outline widths (u16 each). A pattern whose lengths are all 0 draws a solid line, as R48's | CN "Tables"; S: line types 0x02 and 0x22 with caps and joins 0x00, 0x01 and 0x11 in the CX files | public-notes (the flags 4, 8 and 16 and the cap and join numbering; bit 0x20, set in `balloon.cmx`, is not read) | | R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist; in `balloon.cmx`, `PC.CMX` and `squares.cmx`, solid outlines name `rdot` entry 1, whose field 1 is a count of 0 | sample | | R59 | `rota`: a u16 count, then pairs of u16 (start and end arrowheads, 0 for none), not field lists | CN "Tables"; S: `rota` is `01 00 00 00 00 00` in every CX file | sample (pairs of 0), public-notes (other values) | @@ -148,24 +155,26 @@ file is committed. | R72 | In the version 15 samples an `mcfg` chunk starts with the tag 1300 and the length of the rest of the chunk, then 4 bytes of 0 (the 12 bytes R10 names), and each `fild` chunk sits in a `LIST filc` of its own inside `LIST filt` | S: the 15 LT `testset/15` files without text (every `mcfg` starts with 1300 and its size less 8; each of their 31 `fild` chunks is the only chunk of a `LIST filc`) | sample (the reader skips the 12 bytes and finds `fild` chunks at any depth) | | R73 | The specification reads the id in a container's argument 8005 (R46) as the stored u32 plus 1, halved, and the `spnd` id as stored. Sample files hold the same stored u32 in both places, even ids included, which the halved reading would not match. The writer numbers containers 1, 2, 3 and so on, and writes the same number in the clipped group's `spnd` | KF L799-L807 (`powerclip_id`), L2305-L2312 (`spnd`); S: the container and `spnd` of LT `powerclipsquare_blackfill_whiterectangleinside.cdr` of `testset/12` (156091928) and `powerclipsquare_blackfill_whiterectangleinside_cdr15.cdr` (1), the eight UC files `corel_powerclip_*` of versions 7 to 13 (47834832) and TDF 114901 (515235504) | sample (the halved reading: not followed) | | R74 | `rscr`: a u16 count, then one field list per screen entry, which a `rotl` entry names (R58). The reader does not read it; the `.cmx` writer writes one entry whose field 1 holds the 13 bytes `00 00 3c 00 00 00 00 00 40 a5 ae 02 00` | S: each of the nine CX files with 32-bit coordinates has an `rscr` of one entry with a 13-byte field 1, these bytes in seven of them (`bars.cmx` and `thatch.cmx` differ in bytes 2 and 8 to 11) | sample | +| R77 | The index of a file with 32-bit coordinates, which the reader does not read. `cont` bytes 84, 88 and 92 hold the u32 file offsets of the master index `ixmr`, of `LIST INFO` and of the picture of the drawing (`DISP`), 0xFFFFFFFF for one the file does not hold. Each offset here names where a chunk's id starts. `cont` bytes 96 to 112 hold four i32 edges, the same bytes as the edges in the page's begin-page record, and bytes 112 to 116 a u32, the page's instruction count as begin page holds it. `LIST indx` holds a layer table `ixlr`, then `ixtl`, `ixpg` and `ixmr`. `ixmr`: the u16 values 1 and 24, a u16 count, then a u16 id and a u32 offset for each entry: 1 `ixmr` itself, 2 `ixpg`, 3 `ixtl`, 15 `rotl`, 16 `rott`, 17 `rota`, 18 `rscr`, 19 `rpen`, 20 `rdot`, 21 `rclr`, 22 `ccmm`; a table the file does not hold has no entry. `ixpg`: a u16 count, then for each page a u16 record size of 16 and four u32: the page chunk, its layer table, its picture (0xFFFFFFFF for none) and its reference list `rlst`. `ixtl`: a u16 count, a u16 record size of 4, the u16 type 3 (layer tables), then the u32 offset of each layer table. `ixlr`: a u16 count of the page's layers and the u16 value 1, then for each layer in file order a u16 size (8 plus the name's length), the u32 offset of its begin-layer instruction, its name as a u16 count and 8-bit characters, and 0xFFFFFFFF after the size. `rlst`: a u16 count of the page's layers, then the u16 values 2 and 9 and the layer's number for each. Begin page's field 1 ends with the u32 offset of the end-page instruction, a u16 count of the page's layers and a u32 count of its instructions, begin and end page included; begin layer's field 1 holds a u32 count of the layer's instructions, begin and end layer included, at bytes 8 to 12; begin group's field 1 holds the left, top, right and bottom edges of its curves (i32), a u16 count of the groups directly inside it, a u32 count of its instructions, begin and end group included, and the u32 offset of the instruction after its end | LC `CMXParser.cpp` L260-L286 (the three offsets, 0xFFFFFFFF for none; four coordinates after them, read only for a debug message), L1011-L1019 (the four coordinates of a box), L346-L413 (`ixmr`: two u16, the count, the id and offset pairs), L545-L590 (begin group: the edges, a u16, the command count and the end address), L1974-L2019 (`ixtl`: the count, the record size, the type), L2060-L2096 (`ixpg`: the count, the record size and four offsets for each page), `CMXParser.h` L24-L41 (the ids); S: every CX file with 32-bit coordinates holds these chunks in this order, its `ixmr` entries name these chunks with these ids, the values 1 and 24 and `ixtl` type 3, its `ixpg` names its one page, the one `ixlr` and the `rlst`, its `ixlr` names its layers' begin-layer instructions with their names and the value 1, its `rlst` holds 2, 9 and the number of each of its layers, and the counts and offsets in its 9 pages, 33 layers and 12 groups match the instructions; in each of the 9 files, `cont` bytes 96 to 116 match its one page's edges and instruction count; 8 of the 12 groups hold the edges of their curves' points | sample (the order, `ixlr`, `rlst`, the values 1 and 24, the counts and offsets in the records, the header's edges and instruction count), public-reader (the header's offsets, the `ixmr` ids, `ixpg`, `ixtl` and the order of begin group's fields; the samples agree), unconfirmed (the group count counting only the groups directly inside, as no sample nests groups two deep; the value 1 in a layer table of a page after the first) | ## Written fields `src/cmx_write.rs` writes `.cmx` files in the layouts of the rows above, nothing else. The table lists every field it sets. `own` marks a value the reader does not read, which the writer sets as -the synthetic test files of `src/synth_cmx.rs` set it. The header's offsets at bytes 84 to 95, the -index chunks (`LIST indx`), the instruction counts and file offsets that the CX files also keep in -their page, layer and group records, and the bounds they keep in layer and group records are not -written: no public source describes -them, and the reader finds every chunk by its id and walks the instructions in order. +the synthetic test files of `src/synth_cmx.rs` set it. | Field written | Rows | Status | |---|---|---| | The RIFF form `CMX1`, chunk ids and sizes, a pad byte after an odd body | R53 | sample | -| Chunk order: `cont`, the `page` chunks, then `rclr`, `rpen`, `rott`, `rdot`, `rotl`, `rota` and `rscr` | R53 | own (the reader finds each chunk by its id) | +| Chunk order: `cont`, each `page` chunk followed by its `rlst`, then `rclr`, `rpen`, `rott`, `rdot`, `rotl`, `rota` and `rscr`, then `LIST indx` | R53, R77 | sample (`page`, `rlst`, the tables, `LIST indx`), own (the order of the tables; the `rlst` of a page after the first) | | `cont`: `4` at byte 52, the unit 1e-7 m as an f64 at bytes 64 to 72 | R54 | sample | +| `cont`: the offset of `ixmr` at bytes 84 to 88, 0xFFFFFFFF for the information list and the picture at bytes 88 to 96 | R77 | public-reader, sample (the picture), own (no information list) | +| `cont`: the first page's edges at bytes 96 to 112 and its instruction count at bytes 112 to 116, as its begin-page record holds them; zeros for a file with no page | R77 | sample (one page), the writer's choice (the first page of several, and zeros) | | `cont`: `2` at bytes 48 and 54, zeros elsewhere, 180 bytes | R54 | own | +| `LIST indx`: a layer table `ixlr` for each page, `ixtl` listing them, `ixpg` with each page, and `ixmr` with itself, `ixpg`, `ixtl` and the seven tables | R77 | sample (one page), own (a layer table for each page, `ixtl` listing each, and the page number after the count) | +| `rlst` for each page: its layers' numbers | R77 | sample | | Table counts and field lists | R55 | sample | +| `rclr` fields 1 and 2, before field 10: the model and 5, then four value bytes; model 2 (CMYK in percent), 5 (red, green, blue, then 0) and 9 (gray, then three zero bytes); a spot color as model 5 with its look at its tint, and the registration color as model 2 with four values of 100 | R56 | sample (the fields, model 2 and the 5), public-reader (models 5 and 9), the writer's choice (the models of spot and registration colors, the zero bytes and the order of the fields) | | `rclr` field 10: a property list with part 1, the color record (model, palette 5, 4 zero bytes, 4 values), and for a spot color part 3, its name; models 2 (CMYK in percent), 5 (blue, green, red), 9 (gray), 20 (registration) and 21 (blue, green, red at the tint, and the tint in percent) | R11, R14, R56 | public-notes (field 10), public-spec (the models) | | `rpen` field 1: the width | R57 | public-notes | | `rpen` field 1 after the width: an aspect of 100, an angle of 0, a matrix type of 1 | R57 | own | @@ -177,9 +186,11 @@ them, and the reader finds every chunk by its id and walks the instructions in o | `rscr`: one screen entry, its field 1 as the sample files write it | R74 | sample | | Instructions in the short form, and the long form past 65,534 bytes | R60 | sample (short form), public-notes (long form) | | Begin page, field 1: the page number (from 1), a u32 of 0, the left, top, right and bottom edges of the page's curves (of the page around its center when it has none; all 0 for a page without a size) | R61 | sample (page number 1, the edges), own (the later numbers, the edges of a page with no curves or no size) | +| Begin page, field 1 after the edges: the offset of the end-page instruction, the layer count and the instruction count | R77 | sample | | Begin page, field 4: the page's width and height | R61 | public-notes | -| Begin layer, field 1: the page number and the layer number (u16 each, from 1), then 8 zero bytes, then the name as a u16 byte count and 8-bit characters | R62 | sample (the numbers: `balloon.cmx` and `PC.CMX` number their four layers `01 00 01 00` to `01 00 04 00`; the name), own (the 8 bytes) | +| Begin layer, field 1: the page number and the layer number (u16 each, from 1), then 4 zero bytes, the layer's instruction count, then the name as a u16 byte count and 8-bit characters | R62, R77 | sample (the numbers: `balloon.cmx` and `PC.CMX` number their four layers `01 00 01 00` to `01 00 04 00`; the count; the name), own (the 4 bytes) | | Begin layer, field 4: the name as a u32 count of UTF-16 code units and the units | R62 | public-notes | -| Begin group with field 1 of 26 zero bytes; end layer, group and page with no fields | R60 | own (the bodies are not read) | +| Begin group, field 1: the edges of the group's curves as the page's are measured (all 0 for a group with none), the groups directly inside it, its instruction count and the offset of the instruction after its end | R77 | sample (the counts and the offset), public-reader (the order), the writer's choice (the edges where they differ from the points' edges, as for a page) | +| End layer, group and page with no fields | R60 | own (the bodies are not read) | | Curve, field 1: rendering attributes with a uniform fill (type 1, the color entry, screen entry 1) and an outline entry | R63, R74 | sample (the uniform fills of `bars.cmx`, `balloon.cmx` and `PC.CMX` name screen 1) | | Curve, field 2: the point count, the points as i32 and a type byte each, bit 2 set on every move, line and curve end node and clear on control points, bit 3 on the first and last nodes of a closed subpath that fits in one curve; a closed subpath cut into open pieces gets a line back to its start added when its last point is elsewhere; at most 7,281 points | R16, R62 | sample (the layout), own (bit 2 on the nodes the synthetic files set it on), the writer's choice (bit 2 on a closing node, which the synthetic files leave clear) | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index e4d2033ffa..0bf2c8e8f8 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -107,12 +107,17 @@ corners, not stretched ones. Hidden layers, groups and shapes, guide and grid la and master layers are left out; opacity, blend modes, fill rules and locked states are not written, desktop layers are written as drawing layers, and a spot color with no name opens as a process color; every use of a named spot color takes the look of its use at the strongest tint -among the uses whose look is known. +among the uses whose look is known. Each color entry holds the color twice: as the property list +`read_cmx` reads, and as the model and value fields that other readers, such as libcdr, read. In +those fields a spot color is written as its look at its tint, and the registration color as 100 +percent cyan, magenta, yellow and black. `write_cmx` returns an error, and writes nothing, for a coordinate, page side or outline width past the 32-bit range, a negative or NaN outline width, a page side that rounds to 0, more than 65,535 pages, layers on a page or different colors, pens, line types, dash patterns or outlines, a -dash pattern of more than 32,765 lengths, groups nested deeper than the limits allow, more chunks, +dash pattern of more than 32,765 lengths, groups nested deeper than the limits allow, a depth limit +of 0 (at which `read_cmx` leaves out the index list), more than 65,535 groups directly inside one +group, more chunks, objects, coordinates or dashes than a read within the limits takes, a file longer than their input size, and a chunk past its 32-bit size. Otherwise the returned `Written` reports paths split or cut into several curves, dashes rounded to whole outline widths, nonzero fills that may fill differently, names that open @@ -120,12 +125,14 @@ shortened, spot colors at a tint too low to keep their look, with no name or wit (written black), uses of one ink with different looks, and what was left out or written opaque, unclipped or unlocked. -The header's index offsets, the index chunks (`LIST indx`), the instruction counts and offsets -inside page, layer and group records, and the bounds inside layer and group records are not -written, so a reader must find the chunks by their ids and walk the instructions in order, as -`read_cmx` does. The record of a page with a size holds the edges of its curves, or of the page -when it has none. `PROVENANCE.md`'s "Written -fields" table lists every field the `.cmx` writer sets. +The file holds an index, so that a reader that finds the tables and pages through it, rather than +by their chunk ids, opens it: the header gives where the master index starts, the index list +(`LIST indx`) gives where each table, page, page reference list and layer starts, and the page, +layer and group records give their instruction counts. A page's record also gives where its +end-page instruction starts, and a group's record gives where the instruction after its end-group +instruction starts and the edges of its curves. The record of a page with a size holds the edges of its curves, or +of the page when it has none. The header repeats the first page's edges and instruction count. +`PROVENANCE.md`'s "Written fields" table lists every field the `.cmx` writer sets. ## Writing diff --git a/crates/cdr/src/cmx_write.rs b/crates/cdr/src/cmx_write.rs index 69de039cc1..a5c6e00058 100644 --- a/crates/cdr/src/cmx_write.rs +++ b/crates/cdr/src/cmx_write.rs @@ -2,8 +2,8 @@ //! reads: the RIFF form `CMX1` (R53), its header (R54), the color, pen, line type, dash, outline and //! arrowhead tables (R55 to R59), the screen table (R74) and one `page` chunk of instructions for //! each page (R60): pages, layers, groups and curves (R61, R62) with uniform fills and outlines -//! (R63). `PROVENANCE.md`'s "Written fields" lists every field the writer sets and where its layout -//! comes from. +//! (R63), and the index that gives where each of them starts (R77). `PROVENANCE.md`'s "Written +//! fields" lists every field the writer sets and where its layout comes from. //! //! Rectangles and ellipses are written as curves. A clipping container is written as a group of //! its fill, the objects it clips, unclipped, and its outline. Hidden layers, groups and shapes, @@ -130,28 +130,58 @@ pub fn write(drawing: &Drawing, limits: crate::Limits) -> Result children.push(c); Ok(()) }; - add(chunk(b"cont", &cont())?)?; - for (n, page) in drawing.pages.iter().enumerate() { - add(w.page(n, page.size.or(drawing.page_size), &page.layers)?)?; + // The header's index offset is set once the index is placed. + add(chunk(b"cont", &cont(0, PageHead::default()))?)?; + // Each page chunk and its reference list, with where they start in the file and the start and + // name of each of the page's layers. + let mut pages = Vec::new(); + let mut page = |w: &mut Writer, n: usize, size: Option<(f64, f64)>, layers: &[Layer]| -> Result<(), Error> { + let at = w.file_bytes; + let (c, written, head) = w.page(n, size, layers)?; + add(c)?; + let refs = w.file_bytes; + let r = chunk(b"rlst", &reference_list(written.len()))?; + w.check_bytes(r.len())?; + w.file_bytes += r.len(); + add(r)?; + pages.push(PageAt { at, refs, layers: written, head }); + Ok(()) + }; + for (n, p) in drawing.pages.iter().enumerate() { + page(&mut w, n, p.size.or(drawing.page_size), &p.layers)?; } // A drawing with no pages but a page size is written as one empty page of that size. if drawing.pages.is_empty() && drawing.page_size.is_some() { - add(w.page(0, drawing.page_size, &[])?)?; + page(&mut w, 0, drawing.page_size, &[])?; } - // The reader also counts every chunk (`cont`, the pages and the seven tables), every table entry - // and the one arrowhead pair. - let pages = if drawing.pages.is_empty() { usize::from(drawing.page_size.is_some()) } else { drawing.pages.len() }; + // The reader leaves out a list as deep as its depth limit, and the index is a list. + if w.limits.depth == 0 { + return Err(Error::Limit("nesting depth")); + } + // The reader also counts every chunk (`cont`, each page and its reference list, the seven + // tables, and the index list with its three chunks and a layer table for each page), every + // table entry and the one arrowhead pair. let t = &w.tables; let entries = t.colors.entries.len() + t.pens.entries.len() + t.line_types.entries.len() + t.dashes.entries.len() + t.outlines.entries.len() + 1; - w.read_cost.chunks = w.read_cost.chunks.saturating_add(1 + pages + 7 + entries); + let index_chunks = pages.len().saturating_add(4); + w.read_cost.chunks = w.read_cost.chunks.saturating_add(1 + 2 * pages.len() + 7 + entries + index_chunks); w.read_cost.check(&w.limits)?; + // Where each table chunk starts, by its id. + let mut tables = Vec::new(); + let mut at = w.file_bytes; for c in w.tables.chunks(w.limits.input.saturating_sub(w.file_bytes))? { + let id: [u8; 4] = c[0..4].try_into().map_err(|_| Error::Limit("chunk size"))?; + tables.push((id, at)); + at = at.saturating_add(c.len()); add(c)?; } + let (list, ixmr) = index(at, &pages, &tables)?; + add(list)?; let total = usize::try_from(size).ok().and_then(|n| n.checked_add(8)).ok_or(Error::Limit("chunk size"))?; if total > w.limits.input { return Err(Error::Limit("input size")); } + children[0] = chunk(b"cont", &cont(ixmr, pages.first().map(|p| p.head).unwrap_or_default()))?; let mut bytes = Vec::new(); bytes.try_reserve_exact(total).map_err(|_| Error::Limit("file size"))?; bytes.extend(b"RIFF"); @@ -190,16 +220,124 @@ fn chunk(id: &[u8; 4], body: &[u8]) -> Result, Error> { } /// The header (R54): the coordinate size digit `4` at byte 52 and the unit in meters at bytes 64 -/// to 72. Bytes 48 and 54 hold the digit `2`, as in the sample files; the rest are zeros. -fn cont() -> Vec { +/// to 72. Bytes 48 and 54 hold the digit `2`, as in the sample files. Bytes 84 to 96 hold the file +/// offset of the master index `ixmr`, then 0xFFFFFFFF for the information list and for the +/// picture of the drawing, which the file does not hold (R77). Bytes 96 to 116 hold the edges and +/// the instruction count of `first`, the first page's begin-page record (R77); the rest are zeros. +fn cont(ixmr: u32, first: PageHead) -> Vec { let mut c = vec![0u8; 180]; c[48] = b'2'; c[52] = b'4'; c[54] = b'2'; c[64..72].copy_from_slice(&UNIT_METERS.to_le_bytes()); + c[84..88].copy_from_slice(&ixmr.to_le_bytes()); + c[88..96].fill(0xFF); + for (i, v) in first.edges.iter().enumerate() { + c[96 + 4 * i..100 + 4 * i].copy_from_slice(&v.to_le_bytes()); + } + c[112..116].copy_from_slice(&first.instructions.to_le_bytes()); c } +/// What a page's begin-page record holds that the header repeats: its left, top, right and bottom +/// edges and its instruction count, begin and end page included. +#[derive(Clone, Copy, Default)] +struct PageHead { + edges: [i32; 4], + instructions: u32, +} + +/// Where a layer's begin-layer instruction starts in the file, and the layer's 8-bit name. +type LayerAt = (usize, Vec); + +/// Where a page's chunks start in the file, and its layers. +struct PageAt { + at: usize, + /// The page's reference list `rlst`. + refs: usize, + layers: Vec, + /// What the header repeats of its begin-page record. + head: PageHead, +} + +/// A page's reference list (R77): a u16 count of its layers, then for each layer from 1 the u16 +/// values 2 and 9 and its number. +fn reference_list(layers: usize) -> Vec { + let mut r = (layers as u16).to_le_bytes().to_vec(); + for n in 1..=layers { + r.extend([2u16, 9, n as u16].map(u16::to_le_bytes).concat()); + } + r +} + +/// A file offset as the u32 the index stores. +fn offset(at: usize) -> Result { + u32::try_from(at).map_err(|_| Error::Limit("chunk size")) +} + +/// The index list `LIST indx` starting at file offset `at` (R77): a layer table `ixlr` for each +/// page, the table of layer tables `ixtl`, the page index `ixpg` and the master index `ixmr`, with +/// the file offset of `ixmr`. `tables` gives where each table chunk starts, by its id. +fn index(at: usize, pages: &[PageAt], tables: &[([u8; 4], usize)]) -> Result<(Vec, u32), Error> { + let mut body = b"indx".to_vec(); + // Where the next chunk of the list starts. + let next = |body: &Vec| at.saturating_add(8).saturating_add(body.len()); + let mut layer_tables = Vec::with_capacity(pages.len()); + for (n, p) in pages.iter().enumerate() { + layer_tables.push(next(&body)); + // The layer count and the page number, then for each layer the size of its record before + // the 0xFFFFFFFF that ends it, its begin-layer instruction and its name. + let mut t = (p.layers.len() as u16).to_le_bytes().to_vec(); + t.extend(u16::try_from(n + 1).map_err(|_| Error::Limit("pages"))?.to_le_bytes()); + for (start, name) in &p.layers { + t.extend(((8 + name.len()) as u16).to_le_bytes()); + t.extend(offset(*start)?.to_le_bytes()); + t.extend((name.len() as u16).to_le_bytes()); + t.extend(name); + t.extend(u32::MAX.to_le_bytes()); + } + body.extend(chunk(b"ixlr", &t)?); + } + // The table of layer tables: their count, the size of each record, the type 3 and the offsets. + let ixtl = next(&body); + let mut t = (pages.len() as u16).to_le_bytes().to_vec(); + t.extend(4u16.to_le_bytes()); + t.extend(3u16.to_le_bytes()); + for l in &layer_tables { + t.extend(offset(*l)?.to_le_bytes()); + } + body.extend(chunk(b"ixtl", &t)?); + // The page index: the page count, then for each page the size of its record, its page chunk, + // its layer table, 0xFFFFFFFF for a picture of the page it does not have and its reference + // list. + let ixpg = next(&body); + let mut t = (pages.len() as u16).to_le_bytes().to_vec(); + for (p, l) in pages.iter().zip(&layer_tables) { + t.extend(16u16.to_le_bytes()); + for v in [offset(p.at)?, offset(*l)?, u32::MAX, offset(p.refs)?] { + t.extend(v.to_le_bytes()); + } + } + body.extend(chunk(b"ixpg", &t)?); + // The master index: the values 1 and 24, the entry count, then an id and an offset for itself, + // the page index, the table of layer tables and each table. + let ixmr = next(&body); + let ids: [(&[u8; 4], u16); 7] = [(b"rotl", 15), (b"rott", 16), (b"rota", 17), (b"rscr", 18), (b"rpen", 19), (b"rdot", 20), (b"rclr", 21)]; + let mut entries = vec![(1u16, ixmr), (2, ixpg), (3, ixtl)]; + for (id, n) in ids { + if let Some((_, start)) = tables.iter().find(|(t, _)| t == id) { + entries.push((n, *start)); + } + } + let mut t = [1u16, 24, entries.len() as u16].map(u16::to_le_bytes).concat(); + for (n, start) in entries { + t.extend(n.to_le_bytes()); + t.extend(offset(start)?.to_le_bytes()); + } + body.extend(chunk(b"ixmr", &t)?); + Ok((chunk(b"LIST", &body)?, offset(ixmr)?)) +} + /// A field: its tag, a u16 length counting the 3 header bytes, then `data` (R55). `None` when the /// data does not fit the length. fn field(tag: u8, data: &[u8]) -> Option> { @@ -397,9 +535,25 @@ fn color_key(c: &Color) -> ColorKey { } } -/// A color entry (R56): field 10 holds a property list, a u32 length then parts of a u8 kind, a u32 -/// length and the body (R11): part 1 the color record (model, palette 5, 4 zero bytes, the -/// values; R14), and for a named color part 3, a u32 count and UTF-16 units. +/// The color of `k` in the fields 1 and 2 of a color entry (R56): the model and the palette 5, +/// then four value bytes. A spot color is written as its look at its tint in red, green and blue, +/// and the registration color as cyan, magenta, yellow and black at 100 percent, since the +/// models of these fields hold neither. +fn older_fields(k: &ColorKey) -> (u8, [u8; 4]) { + let [v0, v1, v2, v3] = k.values; + match k.model { + 2 => (2, [v0, v1, v2, v3]), + // Red, green and blue, where the color record holds blue, green and red. + 5 | 21 => (5, [v2, v1, v0, 0]), + 9 => (9, [v0, 0, 0, 0]), + _ => (2, [100; 4]), + } +} + +/// A color entry (R56): field 1 the model and the palette, field 2 the values, as +/// [`older_fields`] gives them, then field 10, a property list: a u32 length then parts of a u8 +/// kind, a u32 length and the body (R11): part 1 the color record (model, palette 5, 4 zero bytes, +/// the values; R14), and for a named color part 3, a u32 count and UTF-16 units. fn color_entry(k: &ColorKey) -> Result, Error> { let mut list = vec![1u8]; list.extend(12u32.to_le_bytes()); @@ -416,7 +570,9 @@ fn color_entry(k: &ColorKey) -> Result, Error> { } let mut rec = (list.len() as u32).to_le_bytes().to_vec(); rec.extend(list); - Ok(fields(&[field(10, &rec).ok_or(Error::Limit("table entry size"))?])) + let (model, values) = older_fields(k); + let size = || Error::Limit("table entry size"); + Ok(fields(&[field(1, &[model, 5]).ok_or_else(size)?, field(2, &values).ok_or_else(size)?, field(10, &rec).ok_or_else(size)?])) } /// The counts [`crate::read_cmx`] holds to [`crate::Limits`] while it reads a file. @@ -462,8 +618,14 @@ struct Writer { looks: HashMap, /// The comparisons [`may_fill_differently`] may still make. crossing_budget: u64, - /// The groups open where the next instruction is written. - open_groups: usize, + /// The groups open where the next instruction is written, outermost first. + open_groups: Vec, + /// The instructions written on the current page, its begin-page instruction included. + instructions: usize, + /// For each group closed on the current page, where its end offset goes in the page's + /// instructions after the begin-page instruction, and the offset there, both counted from the + /// end of the begin-page instruction. + group_ends: Vec<(usize, usize)>, /// The smallest and largest x and y the curves written on the current page reach, in /// coordinate units. bounds: Option<[i32; 4]>, @@ -585,10 +747,17 @@ impl Writer { self.tables.colors.index(key) } - /// A `page` chunk: begin page `n` (from 0), its shown layers back to front, end the page (R60). - fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result, Error> { + /// A `page` chunk: begin page `n` (from 0), its shown layers back to front, end the page (R60), + /// with the file offset of each layer's begin-layer instruction and the layer's 8-bit name, and + /// what the header repeats of the begin-page record. The chunk starts at the file offset + /// [`Writer::file_bytes`] gives. + fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result<(Vec, Vec, PageHead), Error> { let mut out = Vec::new(); self.bounds = None; + self.instructions = 1; + self.group_ends.clear(); + // Where each layer's begin-layer instruction starts in `out`, and its 8-bit name. + let mut starts = Vec::new(); // The model holds layers and objects front to back; the file lists them back to front. let mut written = 0; for layer in layers.iter().rev() { @@ -604,19 +773,43 @@ impl Writer { // The reader also stops a layer's name at its first NUL and takes a blank name as none. let name = &layer.name; self.long_names |= shortened(name) || name.contains('\0') || (!name.is_empty() && name.trim().is_empty()); - out.extend(instr(BEGIN_LAYER, &layer_fields(n, written, &layer.name)?)); + let body = layer_fields(n, written, &layer.name)?; + let begin = instr(BEGIN_LAYER, &body); + // The layer's instruction count goes at bytes 8 to 12 of field 1, after the + // instruction's header and the field's tag and length. + let count_at = out.len() + begin.len() - body.len() + 3 + 8; + let first = self.instructions; + starts.push((out.len(), narrow_name(&layer.name))); + out.extend(begin); + self.instructions += 1; written += 1; self.objects(&layer.objects, &mut out)?; out.extend(instr(END_LAYER, &[])); + self.instructions += 1; + put_u32(&mut out, count_at, self.instructions - first)?; self.read_cost.chunks += 2; self.read_cost.check(&self.limits)?; self.check_bytes(out.len())?; } + let end = out.len(); out.extend(instr(END_PAGE, &[])); + self.instructions += 1; // The begin and end page instructions. self.read_cost.chunks += 2; self.read_cost.check(&self.limits)?; - let begin = begin_page(n, size, self.bounds.take())?; + let bounds = self.bounds.take(); + let begin_len = begin_page(n, size, bounds, PageTail::default())?.len(); + // The page's instructions after the begin-page instruction start here in the file. + let base = self.file_bytes.saturating_add(8).saturating_add(begin_len); + let tail = PageTail { + end: offset(base.saturating_add(end))?, + layers: u16::try_from(written).map_err(|_| Error::Limit("layers"))?, + instructions: u32::try_from(self.instructions).map_err(|_| Error::Limit("chunk count"))?, + }; + for (at, end) in std::mem::take(&mut self.group_ends) { + put_u32(&mut out, at, base.saturating_add(end))?; + } + let begin = begin_page(n, size, bounds, tail)?; if u32::try_from(begin.len() + out.len()).is_err() { return Err(Error::Limit("chunk size")); } @@ -624,8 +817,9 @@ impl Writer { page.extend(out); let c = chunk(b"page", &page)?; self.check_bytes(c.len())?; + let layers = starts.into_iter().map(|(at, name)| (base.saturating_add(at), name)).collect(); self.file_bytes += c.len(); - Ok(c) + Ok((c, layers, PageHead { edges: page_edges(size, bounds)?, instructions: tail.instructions })) } /// An [`Error::Limit`] when the file would be longer than the input size of the limits with @@ -657,7 +851,7 @@ impl Writer { self.shape(&s, out)?; } if ends { - self.end_group(out); + self.end_group(out)?; } } continue; @@ -699,20 +893,55 @@ impl Writer { /// Begin a group. A group inside as many groups as the reader opens (the depth of the /// [`crate::Limits`] written for) is an [`Error::Limit`]: the reader leaves out what it holds. fn begin_group(&mut self, out: &mut Vec) -> Result<(), Error> { - if self.open_groups >= self.limits.depth { + if self.open_groups.len() >= self.limits.depth { return Err(Error::Limit("nesting depth")); } - self.open_groups += 1; + if let Some(parent) = self.open_groups.last_mut() { + parent.groups = parent.groups.checked_add(1).ok_or(Error::Limit("groups"))?; + } + self.open_groups.push(OpenGroup { at: out.len(), first: self.instructions, groups: 0, bounds: None }); out.extend(group()); + self.instructions += 1; self.read_cost.chunks += 1; self.read_cost.objects += 1; self.read_cost.check(&self.limits) } - fn end_group(&mut self, out: &mut Vec) { - self.open_groups = self.open_groups.saturating_sub(1); + /// End the innermost open group, and fill in its begin-group record (R77): the edges of its + /// curves (all 0 when it has none), the groups directly inside it, its instructions from begin + /// to end, and where the instruction after its end starts, which [`Writer::page`] places in + /// the file. + fn end_group(&mut self, out: &mut Vec) -> Result<(), Error> { out.extend(instr(END_GROUP, &[])); + self.instructions += 1; self.read_cost.chunks += 1; + let Some(g) = self.open_groups.pop() else { return Ok(()) }; + if let (Some(parent), Some(b)) = (self.open_groups.last_mut(), g.bounds) { + parent.bounds = Some(match parent.bounds { + Some(p) => [p[0].min(b[0]), p[1].min(b[1]), p[2].max(b[2]), p[3].max(b[3])], + None => b, + }); + } + // Field 1's data starts after the instruction's 4-byte header and the field's tag and + // length. + let data = g.at + 4 + 3; + let [x0, y0, x1, y1] = g.bounds.unwrap_or_default(); + for (i, v) in [x0, y1, x1, y0].into_iter().enumerate() { + out[data + 4 * i..data + 4 * i + 4].copy_from_slice(&v.to_le_bytes()); + } + out[data + 16..data + 18].copy_from_slice(&g.groups.to_le_bytes()); + put_u32(out, data + 18, self.instructions - g.first)?; + self.group_ends.push((data + 22, out.len())); + Ok(()) + } + + /// Take in `[x0, y0, x1, y1]`, the edges of a written curve, in the page's and the innermost + /// open group's edges. + fn reach(&mut self, e: [i32; 4]) { + for b in [Some(&mut self.bounds), self.open_groups.last_mut().map(|g| &mut g.bounds)].into_iter().flatten() { + let b = b.get_or_insert(e); + *b = [b[0].min(e[0]), b[1].min(e[1]), b[2].max(e[2]), b[3].max(e[3])]; + } } /// A shape as one curve, or as a group of curves when its path holds more than @@ -802,9 +1031,7 @@ impl Writer { _ => [p.x, p.y, p.x, p.y], }; // Within the anchors and control points, which are i32, so the casts keep them. - let (x0, y0, x1, y1) = (x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32); - let b = self.bounds.get_or_insert([x0, y0, x1, y1]); - *b = [b[0].min(x0), b[1].min(y0), b[2].max(x1), b[3].max(y1)]; + self.reach([x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32]); } g.extend(c.iter().map(|(_, t)| *t)); bodies.push(field(2, &g).ok_or(Error::Limit("curve size"))?); @@ -815,10 +1042,11 @@ impl Writer { let i = instr(CURVE, &fields(&[f1.clone(), f2.clone()])); self.check_bytes(out.len().saturating_add(i.len()))?; out.extend(i); + self.instructions += 1; } } if curves.len() > 1 { - self.end_group(out); + self.end_group(out)?; } Ok(()) } @@ -912,41 +1140,61 @@ impl Writer { } } +/// A group open where the next instruction is written. +struct OpenGroup { + /// Where its begin-group instruction starts in the page's instructions after the begin-page + /// instruction. + at: usize, + /// The page's instructions written before it. + first: usize, + /// The groups directly inside it so far. + groups: u16, + /// The smallest and largest x and y its curves reach so far, in coordinate units. + bounds: Option<[i32; 4]>, +} + +/// What begin page keeps of the rest of the page (R77). +#[derive(Clone, Copy, Default)] +struct PageTail { + /// The file offset of the end-page instruction. + end: u32, + /// The layers on the page. + layers: u16, + /// The page's instructions, begin and end page included. + instructions: u32, +} + +/// Write `v` as a u32 at `at` of `out`. +fn put_u32(out: &mut [u8], at: usize, v: usize) -> Result<(), Error> { + let v = u32::try_from(v).map_err(|_| Error::Limit("chunk size"))?; + out.get_mut(at..at + 4).ok_or(Error::Limit("chunk size"))?.copy_from_slice(&v.to_le_bytes()); + Ok(()) +} + /// Begin page `n` (from 0; R61): field 1 the page number from 1, a u32 of flags and the left, /// top, right and bottom edges of `bounds`, the page's art (smallest x and y, largest x and y), -/// or of the page around its center when it has no art; field 4 its width and height. Without a -/// size the edges are all 0, which the reader takes as no size. -fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>) -> Result, Error> { +/// or of the page around its center when it has no art, then `tail` (R77); field 4 its width and +/// height. Without a size the edges are all 0, which the reader takes as no size. +fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>, tail: PageTail) -> Result, Error> { let number = u16::try_from(n + 1).map_err(|_| Error::Limit("pages"))?; let mut d = number.to_le_bytes().to_vec(); d.extend(0u32.to_le_bytes()); let mut list = Vec::new(); - let mut size_field = None; - let mut edges = [0i32; 4]; - if let Some((w, h)) = size { - // A negative or NaN side counts as 0. - let (wu, hu) = (width_units(w)?, width_units(h)?); - // A side that rounds to nothing would make the reader drop the page's whole size. - if wu == 0 || hu == 0 { - return Err(Error::Limit("page size")); + let edges = page_edges(size, bounds)?; + let size_field = match size { + Some((w, h)) => { + let mut s = width_units(w)?.to_le_bytes().to_vec(); + s.extend(width_units(h)?.to_le_bytes()); + Some(s) } - edges = match bounds { - Some([x0, y0, x1, y1]) => [x0, y1, x1, y0], - None => { - // The page around its center; an odd size keeps its extra unit on the left and - // bottom, where the edge reaches -2^31. - let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size")); - let (w, h) = (i64::from(wu), i64::from(hu)); - [edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?] - } - }; - let mut s = wu.to_le_bytes().to_vec(); - s.extend(hu.to_le_bytes()); - size_field = Some(s); - } + None => None, + }; for v in edges { d.extend(v.to_le_bytes()); } + d.extend(tail.end.to_le_bytes()); + d.extend(tail.layers.to_le_bytes()); + d.extend(tail.instructions.to_le_bytes()); list.push(field(1, &d).ok_or(Error::Limit("page size"))?); if let Some(s) = size_field { list.push(field(4, &s).ok_or(Error::Limit("page size"))?); @@ -954,6 +1202,28 @@ fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>) -> R Ok(instr(BEGIN_PAGE, &fields(&list))) } +/// The left, top, right and bottom edges begin page holds for a page of `size` whose art reaches +/// `bounds`, as [`begin_page`] describes. A page side that rounds to 0 is an [`Error::Limit`]. +fn page_edges(size: Option<(f64, f64)>, bounds: Option<[i32; 4]>) -> Result<[i32; 4], Error> { + let Some((w, h)) = size else { return Ok([0; 4]) }; + // A negative or NaN side counts as 0. + let (wu, hu) = (width_units(w)?, width_units(h)?); + // A side that rounds to nothing would make the reader drop the page's whole size. + if wu == 0 || hu == 0 { + return Err(Error::Limit("page size")); + } + Ok(match bounds { + Some([x0, y0, x1, y1]) => [x0, y1, x1, y0], + None => { + // The page around its center; an odd size keeps its extra unit on the left and + // bottom, where the edge reaches -2^31. + let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size")); + let (w, h) = (i64::from(wu), i64::from(hu)); + [edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?] + } + }) +} + /// `c` as a Windows-1252 byte, or `?` when the code page has no byte for it. fn windows_1252_byte(c: char) -> u8 { match u8::try_from(u32::from(c)) { @@ -962,16 +1232,26 @@ fn windows_1252_byte(c: char) -> u8 { } } -/// A layer's fields (R62): field 1 the page number and the layer number (u16 each, from 1), 8 zero -/// bytes, then the name as a u16 count and 8-bit characters (Windows-1252: characters the code -/// page has no byte for are written as `?`); field 4 the name as a u32 count and UTF-16 units. -/// `page` and `n` count the pages and the page's layers written from 0; past 65,535 layers is an -/// [`Error::Limit`]. +/// Whether a layer's `name`, up to the first NUL where the reader stops, is blank: it is written +/// empty, so it opens with no name. +fn blank_name(name: &str) -> bool { + name.split('\0').next().unwrap_or_default().trim().is_empty() +} + +/// A layer's name as written in 8-bit characters (Windows-1252: characters the code page has no +/// byte for are written as `?`). +fn narrow_name(name: &str) -> Vec { + if blank_name(name) { Vec::new() } else { name.chars().map(windows_1252_byte).take(MAX_NAME_BYTES).collect() } +} + +/// A layer's fields (R62): field 1 the page number and the layer number (u16 each, from 1), 4 zero +/// bytes, the layer's instruction count, which [`Writer::page`] fills in (R77), then the name as a +/// u16 count and 8-bit characters ([`narrow_name`]); field 4 the name as a u32 count and UTF-16 +/// units. `page` and `n` count the pages and the page's layers written from 0; past 65,535 layers +/// is an [`Error::Limit`]. fn layer_fields(page: usize, n: usize, name: &str) -> Result, Error> { - // A blank name, up to the first NUL where the reader stops, is written empty in both fields, - // so it opens with no name. - let blank = name.split('\0').next().unwrap_or_default().trim().is_empty(); - let narrow: Vec = if blank { Vec::new() } else { name.chars().map(windows_1252_byte).take(MAX_NAME_BYTES).collect() }; + let blank = blank_name(name); + let narrow = narrow_name(name); let page = u16::try_from(page + 1).map_err(|_| Error::Limit("pages"))?; let number = u16::try_from(n + 1).map_err(|_| Error::Limit("layers"))?; let mut d = page.to_le_bytes().to_vec(); @@ -987,7 +1267,7 @@ fn layer_fields(page: usize, n: usize, name: &str) -> Result, Error> { Ok(fields(&[f1, f4])) } -/// Begin a group: field 1 of 26 zero bytes, as the test files of `synth_cmx` hold. +/// Begin a group: field 1 of 26 bytes, which [`Writer::end_group`] fills in (R77). fn group() -> Vec { instr(BEGIN_GROUP, &fields(&[field(1, &[0; 26]).unwrap_or_default()])) } diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs index 523384491c..b18029fb25 100644 --- a/crates/cdr/src/lib.rs +++ b/crates/cdr/src/lib.rs @@ -133,8 +133,9 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result { /// width, or a page side that rounds to 0; /// - more than 65,535 pages, layers on a page, or different colors, pens, line types, dash /// patterns or outlines, or a dash pattern of more than 32,765 lengths; -/// - groups nested deeper than the depth of `limits`, or more chunks, objects, coordinates or -/// dashes than a read within `limits` takes; +/// - groups nested deeper than the depth of `limits`, a depth of 0, at which the reader leaves out +/// the index list, more than 65,535 groups directly inside one group, or more chunks, objects, +/// coordinates or dashes than a read within `limits` takes; /// - a file longer than the input size of `limits`, or a chunk past what its 32-bit size holds. /// /// [`Written`] reports what the file holds differently from the drawing; its fields name each @@ -142,11 +143,18 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result { /// written with round corners of its radii times the square root of the scales' product, not with /// stretched corners, and is not reported. /// -/// The header's index offsets, the index chunks (`LIST indx`), the instruction counts and offsets -/// inside page, layer and group records, and the bounds inside layer and group records are not -/// written, so a reader must find the chunks by their ids and walk the instructions in order, as -/// [`read_cmx`] does. The record of a page with a size holds the edges of its curves, or of the -/// page when it has none. +/// Each color entry holds the color twice: as the property list [`read_cmx`] reads, and as the +/// model and value fields that other readers read. In those fields a spot color is written as its +/// look at its tint, and the registration color as 100 percent cyan, magenta, yellow and black. +/// +/// The file holds an index, so that a reader that finds the tables and pages through it, rather +/// than by their chunk ids, opens it: the header gives where the master index starts, the index +/// list (`LIST indx`) gives where each table, page, page reference list and layer starts, and the +/// page, layer and group records give their instruction counts. A page's record also gives where +/// its end-page instruction starts, and a group's record gives where the instruction after its +/// end-group instruction starts and the edges of its curves. The record of a page with a size holds the edges of +/// its curves, or of the page when it has none. The header repeats the first page's edges and +/// instruction count. pub fn write_cmx(drawing: &Drawing, limits: Limits) -> Result { cmx_write::write(drawing, limits) } diff --git a/crates/cdr/tests/it/cmx_write.rs b/crates/cdr/tests/it/cmx_write.rs index d751a04c2a..989205e635 100644 --- a/crates/cdr/tests/it/cmx_write.rs +++ b/crates/cdr/tests/it/cmx_write.rs @@ -283,9 +283,15 @@ fn pages_are_numbered_in_their_order() { assert_eq!(numbers, [1, 2]); } -/// Field 1 of each entry of the table chunk `id`: a u16 count, then a field list per entry (a tag, -/// a u16 length counting the 3 header bytes, the data; 0xff after the last field). +/// Field 1 of each entry of the table chunk `id`. fn table_entries(bytes: &[u8], id: &[u8; 4]) -> Vec> { + table_fields(bytes, id).into_iter().map(|e| e.into_iter().find(|(tag, ..)| *tag == 1).map(|(.., data)| data).expect("field 1")).collect() +} + +/// The fields of each entry of the table chunk `id`, each its tag, where it starts in the file and +/// its data: a u16 count, then a field list per entry (a tag, a u16 length counting the 3 header +/// bytes, the data; 0xff after the last field). +fn table_fields(bytes: &[u8], id: &[u8; 4]) -> Vec)>> { let at = bytes.windows(4).position(|w| w == id).unwrap_or_else(|| panic!("no {id:?} chunk")) + 8; // The chunk's body runs for the size after its id. let end = at + u32::from_le_bytes(bytes[at - 4..at].try_into().unwrap()) as usize; @@ -294,7 +300,7 @@ fn table_entries(bytes: &[u8], id: &[u8; 4]) -> Vec> { let mut p = at + 2; let mut out = Vec::new(); for _ in 0..count { - let mut first = None; + let mut entry = Vec::new(); loop { assert!(p < end, "entry runs past the {id:?} chunk at {p}"); if bytes[p] == 0xff { @@ -304,13 +310,11 @@ fn table_entries(bytes: &[u8], id: &[u8; 4]) -> Vec> { let len = usize::from(u16::from_le_bytes([bytes[p + 1], bytes[p + 2]])); // A length shorter than its header, or past the chunk, would stop the walk. assert!(len >= 3 && p + len <= end, "field at {p} has length {len}"); - if bytes[p] == 1 { - first = Some(bytes[p + 3..p + len].to_vec()); - } + entry.push((bytes[p], p, bytes[p + 3..p + len].to_vec())); p += len; } p += 1; - out.push(first.expect("field 1")); + out.push(entry); } // The size counts the u16 count and the entries; the pad byte comes after it. assert_eq!(p, end, "{id:?} chunk has bytes left after its entries"); @@ -348,6 +352,61 @@ fn every_outline_names_a_screen_and_a_dash_pattern_the_file_holds() { assert_eq!(patterns, vec![(false, vec![]), (true, vec![3, 1])]); } +#[test] +fn colors_are_also_written_in_the_model_and_value_fields() { + let colors = [ + Color::Rgb([1.0, 0.2, 0.0]), + Color::Cmyk([0.6, 0.0, 0.13, 0.05]), + Color::Gray(0.75), + Color::Spot { name: "Ink 300".into(), tint: 0.4, look: Some([0.0, 0.4, 0.8]) }, + Color::Registration, + ]; + let objects = colors + .iter() + .enumerate() + .map(|(i, c)| Object::Shape(Box::new(Shape::new(square(20.0 * i as f64, 0.0, 10.0), Matrix::IDENTITY, Some(c.clone()), None)))) + .collect(); + let d = drawing(vec![Page { size: Some((200.0, 100.0)), layers: vec![layer("Art", objects)] }]); + let mut bytes = write_cmx(&d).unwrap().bytes; + let entries = table_fields(&bytes, b"rclr"); + // Each entry holds the model and the palette 5 in field 1 and four values in field 2, before + // the property list of field 10. + let mut older: Vec<(Vec, Vec)> = entries + .iter() + .map(|e| { + assert_eq!(e.iter().map(|(tag, ..)| *tag).collect::>(), [1, 2, 10]); + (e[0].2.clone(), e[1].2.clone()) + }) + .collect(); + older.sort(); + let mut want = vec![ + // Red, green and blue. + (vec![5, 5], vec![255, 51, 0, 0]), + // Cyan, magenta, yellow and black in percent. + (vec![2, 5], vec![60, 0, 13, 5]), + // Gray, 255 white. + (vec![9, 5], vec![64, 0, 0, 0]), + // The spot color's look at its tint of 40 percent. + (vec![5, 5], vec![153, 194, 235, 0]), + // The registration color as every ink at 100 percent. + (vec![2, 5], vec![100, 100, 100, 100]), + ]; + want.sort(); + assert_eq!(older, want); + // With field 10 retagged, the reader takes each color from fields 1 and 2. + for e in &entries { + bytes[e[2].1] = 11; + } + let back = read_cmx(&bytes, Limits::default()).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + let fills: Vec = back.pages[0].layers[0].objects.iter().map(|o| shape(o).fill.clone().unwrap()).collect(); + let opened = [colors[0].clone(), colors[1].clone(), colors[2].clone(), Color::Rgb([0.6, 0.76, 0.92]), Color::Cmyk([1.0; 4])]; + assert_eq!(fills.len(), opened.len()); + for (got, want) in fills.iter().zip(&opened) { + assert!(near_color(got, want), "{got:?} for {want:?}"); + } +} + #[test] fn an_outline_that_scales_with_its_shape_keeps_its_drawn_width() { let m = Matrix([3.0, 0.0, 0.0, 3.0, 0.0, 0.0]); @@ -657,7 +716,7 @@ fn a_page_without_a_size_still_writes_its_four_edges() { // The begin-page instruction: a u16 size, the code 9, then field 1: a tag and its length. assert_eq!(i16::from_le_bytes([bytes[at + 2], bytes[at + 3]]), 9); let len = usize::from(u16::from_le_bytes([bytes[at + 5], bytes[at + 6]])); - assert_eq!(len - 3, 2 + 4 + 16, "the page number, the flags and four edges"); + assert_eq!(len - 3, 2 + 4 + 16 + 4 + 2 + 4, "the page number, the flags, four edges, the end, the layers and the instructions"); } #[test] @@ -950,6 +1009,277 @@ fn layers_give_their_page_and_their_number() { assert_eq!(numbers, [(1, 1), (1, 2), (2, 1), (2, 2)]); } +fn u16_at(b: &[u8], at: usize) -> usize { + usize::from(u16::from_le_bytes([b[at], b[at + 1]])) +} + +fn u32_at(b: &[u8], at: usize) -> usize { + u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize +} + +/// The id of each chunk of a written file by where it starts, those inside lists included. +fn chunk_ids(b: &[u8]) -> std::collections::HashMap { + let mut ids = std::collections::HashMap::new(); + let mut stack = vec![(12, b.len())]; + while let Some((mut at, end)) = stack.pop() { + while at + 8 <= end { + let id: [u8; 4] = b[at..at + 4].try_into().unwrap(); + let size = u32_at(b, at + 4); + ids.insert(at, id); + if id == *b"LIST" { + stack.push((at + 12, at + 8 + size)); + } + at += 8 + size + size % 2; + } + } + ids +} + +/// The field list at `at` of `b`, in an instruction that ends at `end`: each field's tag and where +/// its data starts. A field shorter than its 3 header bytes, or past `end`, fails the test. +fn field_starts(b: &[u8], mut at: usize, end: usize) -> Vec<(u8, usize)> { + let mut out = Vec::new(); + while b[at] != 0xff { + let len = u16_at(b, at + 1); + assert!(len >= 3 && at + len <= end, "a field of length {len} at {at}, in an instruction that ends at {end}"); + out.push((b[at], at + 3)); + at += len; + } + out +} + +#[test] +#[should_panic(expected = "a field of length 0")] +fn a_field_of_length_0_fails_the_check() { + field_starts(&[1, 0, 0, 0xff], 0, 4); +} + +#[test] +#[should_panic(expected = "a field of length 9")] +fn a_field_past_its_instruction_fails_the_check() { + field_starts(&[1, 9, 0, 0, 0xff], 0, 5); +} + +#[test] +fn the_index_and_the_records_give_where_everything_is() { + let plain = |x: f64| Object::Shape(Box::new(Shape::new(square(x, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let inner = Object::Group { objects: vec![plain(20.0)], flags: Flags::default() }; + let outer = Object::Group { objects: vec![plain(0.0), inner, plain(50.0)], flags: Flags::default() }; + let pages = vec![ + Page { size: Some((200.0, 100.0)), layers: vec![layer("Front", vec![outer]), layer("Back", vec![plain(5.0)])] }, + Page { size: Some((300.0, 100.0)), layers: vec![layer("Only", vec![plain(1.0), plain(2.0)])] }, + ]; + let b = write_cmx(&drawing(pages)).unwrap().bytes; + let page_entries = page_index(&b); + let layer_starts = layer_tables(&b, &page_entries, &[&["Back", "Front"], &["Only"]]); + let (seen_layers, groups) = page_records(&b, &page_entries); + assert_eq!(seen_layers, layer_starts); + // The inner group: itself and a curve; the outer: two curves and the inner group. + assert_eq!(groups, [(0, 3), (1, 7)]); +} + +#[test] +fn the_header_repeats_the_first_pages_edges_and_instruction_count() { + let plain = |x: f64| Object::Shape(Box::new(Shape::new(square(x, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let pages = vec![ + Page { size: Some((200.0, 100.0)), layers: vec![layer("Front", vec![plain(0.0), plain(20.0)]), layer("Back", vec![plain(5.0)])] }, + Page { size: Some((300.0, 100.0)), layers: vec![layer("Only", vec![plain(1.0)])] }, + ]; + let b = write_cmx(&drawing(pages)).unwrap().bytes; + let cont = 12 + 8; + let chunk = page_index(&b)[0][0]; + let page = chunk + 8; + // Begin page's field 1: the page number, the flags, the edges, the end offset, the layer count + // and the instruction count. + let fields = field_starts(&b, page + 4, page + instruction_size(&b, page, page + u32_at(&b, chunk + 4))); + assert_eq!(fields[0].0, 1); + let f1 = fields[0].1; + assert_eq!(&b[cont + 96..cont + 112], &b[f1 + 6..f1 + 22]); + // The curves of the first page reach from 0 to 30 pt across and 0 to 10 pt down. + let edges: Vec = (0..4).map(|i| i32::from_le_bytes(b[cont + 96 + 4 * i..cont + 100 + 4 * i].try_into().unwrap())).collect(); + let unit = |pt: f64| (pt * 0.0254 / 72.0 / 1e-7).round() as i32; + assert_eq!(edges, [0, unit(10.0), unit(30.0), 0]); + // Begin and end page, two begin and end layers and three curves. + assert_eq!(u32_at(&b, cont + 112), 9); + assert_eq!(u32_at(&b, f1 + 28), 9); + // A drawing without pages leaves them 0. + let b = write_cmx(&drawing(Vec::new())).unwrap().bytes; + assert!(b[cont + 96..cont + 116].iter().all(|v| *v == 0)); +} + +/// The page index of a written file of two pages, each entry's page chunk, layer table, picture +/// and reference list, checked through the header and the master index. +fn page_index(b: &[u8]) -> Vec<[usize; 4]> { + let ids = chunk_ids(b); + let id = |at: usize| ids.get(&at).map(|i| String::from_utf8_lossy(i).into_owned()).unwrap_or_default(); + // The header names the master index, and no information list or picture. + let cont = 12 + 8; + let ixmr = u32_at(b, cont + 84); + assert_eq!(id(ixmr), "ixmr"); + assert_eq!((u32_at(b, cont + 88), u32_at(b, cont + 92)), (u32::MAX as usize, u32::MAX as usize)); + // The master index names itself, the page index, the table of layer tables and each table. + let m = ixmr + 8; + assert_eq!((u16_at(b, m), u16_at(b, m + 2)), (1, 24)); + let entries: Vec<(usize, String)> = (0..u16_at(b, m + 4)).map(|i| (u16_at(b, m + 6 + 6 * i), id(u32_at(b, m + 8 + 6 * i)))).collect(); + let want = + [(1, "ixmr"), (2, "ixpg"), (3, "ixtl"), (15, "rotl"), (16, "rott"), (17, "rota"), (18, "rscr"), (19, "rpen"), (20, "rdot"), (21, "rclr")]; + assert_eq!(entries, want.map(|(n, s)| (n, s.to_string()))); + let at_of = |n: usize| u32_at(b, m + 8 + 6 * entries.iter().position(|(k, _)| *k == n).unwrap()); + // The page index: each page chunk, its layer table, no picture and its reference list. + let pg = at_of(2) + 8; + assert_eq!(u16_at(b, pg), 2); + let page_entries: Vec<[usize; 4]> = (0..2) + .map(|i| { + let e = pg + 2 + 18 * i; + assert_eq!(u16_at(b, e), 16); + [0, 1, 2, 3].map(|k| u32_at(b, e + 2 + 4 * k)) + }) + .collect(); + for [page, layers, picture, refs] in &page_entries { + assert_eq!((id(*page), id(*layers), *picture, id(*refs)), ("page".into(), "ixlr".into(), u32::MAX as usize, "rlst".into())); + } + // The table of layer tables lists each page's. + let tl = at_of(3) + 8; + assert_eq!([u16_at(b, tl), u16_at(b, tl + 2), u16_at(b, tl + 4)], [2, 4, 3]); + assert_eq!([u32_at(b, tl + 6), u32_at(b, tl + 10)], [page_entries[0][1], page_entries[1][1]]); + page_entries +} + +/// Where each layer table of `page_entries` says the layers named `names` start, checking each +/// table and each reference list: a layer table holds its count, the page number, then each +/// layer's begin-layer instruction and name, back to front; a reference list a count, and 2, 9 and +/// the number of each layer. +fn layer_tables(b: &[u8], page_entries: &[[usize; 4]], names: &[&[&str]]) -> Vec { + let mut layer_starts = Vec::new(); + for (n, (entry, names)) in page_entries.iter().zip(names).enumerate() { + let t = entry[1] + 8; + assert_eq!((u16_at(b, t), u16_at(b, t + 2)), (names.len(), n + 1)); + let mut at = t + 4; + for name in *names { + let size = u16_at(b, at); + let start = u32_at(b, at + 2); + let len = u16_at(b, at + 6); + assert_eq!((size, &b[at + 8..at + 8 + len]), (8 + name.len(), name.as_bytes())); + assert_eq!(u32_at(b, at + 8 + len), u32::MAX as usize); + assert_eq!(u16_at(b, start + 2), 11, "a begin-layer instruction"); + layer_starts.push(start); + at += size + 4; + } + let r = entry[3] + 8; + let refs: Vec = (0..1 + 3 * names.len()).map(|i| u16_at(b, r + 2 * i)).collect(); + let want: Vec = std::iter::once(names.len()).chain((1..=names.len()).flat_map(|k| [2, 9, k])).collect(); + assert_eq!(refs, want); + } + layer_starts +} + +/// An open begin-page, begin-layer or begin-group record: its code, where its field 1 starts, the +/// instructions before it, the records found directly inside it and the edges of its curves. +type Open = (usize, usize, usize, usize, Option<[i32; 4]>); + +/// Check what the record `open` gives, now closed by the instruction of `code` and `size` at `at` +/// after `count` instructions of its page: begin page where the page ends, its layers and its +/// instructions; begin layer its instructions; begin group the edges of its curves, then its +/// groups and instructions, which are returned, and where the instruction after it starts. +fn closed_record(b: &[u8], open: Open, code: usize, at: usize, size: usize, count: usize) -> Option<(usize, usize)> { + let (opened, f1, before, inside, edges) = open; + assert_eq!(opened + 1, code); + let instructions = count - before; + match code { + 10 => { + assert_eq!(u32_at(b, f1 + 22), at, "where the page ends"); + assert_eq!(u16_at(b, f1 + 26), inside, "the page's layers"); + assert_eq!(u32_at(b, f1 + 28), instructions); + None + } + 12 => { + assert_eq!(u32_at(b, f1 + 8), instructions); + None + } + _ => { + let [x0, y0, x1, y1] = edges.unwrap(); + let stored: Vec = (0..4).map(|k| u32_at(b, f1 + 4 * k) as i32).collect(); + assert_eq!(stored, [x0, y1, x1, y0], "left, top, right and bottom"); + assert_eq!(u32_at(b, f1 + 22), at + size, "where the group ends"); + Some((u16_at(b, f1 + 16), u32_at(b, f1 + 18))) + } + } +} + +/// Walk the instructions of each page of `page_entries`, checking the begin-page, begin-layer and +/// begin-group records, and give where each begin-layer instruction starts and each group's +/// groups and instructions, in the order the groups end. +fn page_records(b: &[u8], page_entries: &[[usize; 4]]) -> (Vec, Vec<(usize, usize)>) { + let mut seen_layers = Vec::new(); + let mut groups = Vec::new(); + for entry in page_entries { + let end = entry[0] + 8 + u32_at(b, entry[0] + 4); + let mut at = entry[0] + 8; + let mut open: Vec = Vec::new(); + let mut count = 0; + while at < end { + let size = instruction_size(b, at, end); + let code = u16_at(b, at + 2); + count += 1; + match code { + 9 | 11 | 13 => { + let f1 = field_starts(b, at + 4, at + size).iter().find(|(t, _)| *t == 1).unwrap().1; + if code == 11 { + seen_layers.push(at); + } + // A page counts its layers and a group the groups directly inside it. + if code != 9 { + open.last_mut().unwrap().3 += 1; + } + open.push((code, f1, count - 1, 0, None)); + } + 67 => { + let f2 = field_starts(b, at + 4, at + size).iter().find(|(t, _)| *t == 2).unwrap().1; + for i in 0..u16_at(b, f2) { + let p = f2 + 2 + 8 * i; + let (x, y) = (u32_at(b, p) as i32, u32_at(b, p + 4) as i32); + for o in open.iter_mut().filter(|o| o.0 == 13) { + let e = o.4.get_or_insert([x, y, x, y]); + *e = [e[0].min(x), e[1].min(y), e[2].max(x), e[3].max(y)]; + } + } + } + 10 | 12 | 14 => groups.extend(closed_record(b, open.pop().unwrap(), code, at, size, count)), + _ => {} + } + at += size; + } + } + (seen_layers, groups) +} + +/// The size of the instruction at `at` of `b`, in a page that ends at `end`. These files hold +/// only short instructions, so the long form (0xFFFF), a size shorter than the 4-byte header or +/// one past `end` fails the test. +fn instruction_size(b: &[u8], at: usize, end: usize) -> usize { + let size = u16_at(b, at); + assert!(size != 0xFFFF && size >= 4 && at + size <= end, "an instruction of size {size} at {at}, in a page that ends at {end}"); + size +} + +#[test] +#[should_panic(expected = "an instruction of size 0")] +fn an_instruction_of_size_0_fails_the_check() { + instruction_size(&[0, 0, 67, 0], 0, 4); +} + +#[test] +#[should_panic(expected = "an instruction of size 65535")] +fn a_long_instruction_fails_the_check() { + instruction_size(&[0xff, 0xff, 67, 0, 8, 0, 0, 0], 0, 8); +} + +#[test] +#[should_panic(expected = "an instruction of size 8")] +fn an_instruction_past_its_page_fails_the_check() { + instruction_size(&[8, 0, 67, 0], 0, 4); +} + #[test] fn a_uniform_fill_names_the_screen_the_file_holds() { let bytes = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))).unwrap().bytes; diff --git a/crates/cms/src/black_tests.rs b/crates/cms/src/black_tests.rs index 2d4864a990..90b7bee271 100644 --- a/crates/cms/src/black_tests.rs +++ b/crates/cms/src/black_tests.rs @@ -10,9 +10,8 @@ fn opts() -> TransformOptions { TransformOptions::default() } -/// L* of a CMYK colour under `p`, measured as the transform with `o` measures it. -fn lightness(p: &Profile, o: TransformOptions, cmyk: [f32; 4]) -> f32 { - let t = Transform::with_options(p, Builtin::LabD50.profile(), o).unwrap(); +/// L* of a CMYK colour, measured by the prebuilt transform. +fn lightness(t: &Transform, cmyk: [f32; 4]) -> f32 { let mut lab = [0.0f32; 3]; t.eval(&cmyk, &mut lab).unwrap(); lab[0] * 100.0 @@ -70,18 +69,22 @@ fn the_destination_black_matches_the_source_lightness() { for intent in [Intent::RelativeColorimetric, Intent::Perceptual] { for bpc in [true, false] { let o = TransformOptions { intent, bpc, ..opts() }; + let coated_lab = Transform::with_options(coated(), Builtin::LabD50.profile(), o).unwrap(); + let fogra_lab = Transform::with_options(fogra(), Builtin::LabD50.profile(), o).unwrap(); // Both directions for one setting; the other settings in the forward one. let directions = if intent == Intent::RelativeColorimetric && bpc { 2 } else { 1 }; - for (src, dst) in [(coated(), fogra()), (fogra(), coated())].into_iter().take(directions) { + for (src, dst, src_lab, dst_lab) in + [(coated(), fogra(), &coated_lab, &fogra_lab), (fogra(), coated(), &fogra_lab, &coated_lab)].into_iter().take(directions) + { let bp = BlackPreserving::new(src, dst, o).unwrap(); - let dst_black = lightness(dst, o, [0.0, 0.0, 0.0, 1.0]); + let dst_black = lightness(dst_lab, [0.0, 0.0, 0.0, 1.0]); for k in [0.1f32, 0.5, 0.9, 1.0] { - let want = lightness(src, o, [0.0, 0.0, 0.0, k]); + let want = lightness(src_lab, [0.0, 0.0, 0.0, k]); if want <= dst_black { assert_eq!(bp.map_k(k), 1.0, "darker than the destination's black clamps to K = 1"); continue; } - let got = lightness(dst, o, [0.0, 0.0, 0.0, bp.map_k(k)]); + let got = lightness(dst_lab, [0.0, 0.0, 0.0, bp.map_k(k)]); assert!((got - want).abs() < 0.02, "{intent:?} bpc {bpc} k {k}: L* {got} for {want}"); } assert_eq!(bp.map_k(0.0), 0.0, "paper stays paper"); diff --git a/crates/cms/src/curve.rs b/crates/cms/src/curve.rs index 8494bd029a..f1df948d43 100644 --- a/crates/cms/src/curve.rs +++ b/crates/cms/src/curve.rs @@ -361,17 +361,35 @@ fn edge_index(t: &[f32], start: bool) -> f32 { if start { let v = t[0]; // The first value that differs, given they do so from there on. - let first_other = t.partition_point(|x| (*x - v).abs() <= 1e-7); + let first_other = t.partition_point(|x| { + count_edge_read(); + (*x - v).abs() <= 1e-7 + }); let i = if first_other >= n { n - 1 } else { first_other.saturating_sub(1) }; i as f32 / (n - 1) as f32 } else { let v = t[n - 1]; // The start of the trailing run equal to the last value. - let i = t.partition_point(|x| (*x - v).abs() > 1e-7); + let i = t.partition_point(|x| { + count_edge_read(); + (*x - v).abs() > 1e-7 + }); i as f32 / (n - 1) as f32 } } +// Each table entry `edge_index` reads on this thread. +#[cfg(test)] +std::thread_local! { + static EDGE_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +#[inline] +fn count_edge_read() { + #[cfg(test)] + EDGE_READS.with(|reads| reads.set(reads.get().saturating_add(1))); +} + #[cfg(test)] mod tests { use super::*; @@ -381,13 +399,18 @@ mod tests { // Four million zeros and a one: a scan per call would be 8·10¹¹ steps for these calls. let mut t = vec![0.0f32; 4_000_000]; t.push(1.0); + // Bisection reads one entry per halving of the table, and a scan reads the whole run. + let per_call = t.len().ilog2() as usize + 2; let c = Curve::Table(t); - let started = std::time::Instant::now(); - let mut last = 0.0; - for _ in 0..200_000 { + EDGE_READS.with(|reads| reads.set(0)); + let mut last = c.eval_inverse(0.0); + let one_call = EDGE_READS.with(std::cell::Cell::get); + assert!(one_call <= per_call, "one inversion read {one_call} entries"); + for _ in 1..200_000 { last = c.eval_inverse(0.0); } assert!(last > 0.99, "the flat start ends at the last zero: {last}"); - assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed()); + let total = EDGE_READS.with(std::cell::Cell::get); + assert!(total <= 200_000 * per_call, "200,000 inversions read {total} entries"); } } diff --git a/crates/cms/src/synth.rs b/crates/cms/src/synth.rs index 1705f64002..c026896980 100644 --- a/crates/cms/src/synth.rs +++ b/crates/cms/src/synth.rs @@ -901,7 +901,7 @@ mod tests { #[test] fn oklab_profile_has_three_tables() { - let p = CmykParams { grid_a2b: 5, grid_b2a: 5, mapping: GamutMapping::Oklab { knee: 0.65, saturation: 1.05 }, ..CmykParams::default() }; + let p = CmykParams { grid_a2b: 3, grid_b2a: 3, mapping: GamutMapping::Oklab { knee: 0.65, saturation: 1.05 }, ..CmykParams::default() }; let profile = cmyk_profile(&p).unwrap(); let [Some(b0), Some(b1), Some(b2)] = &profile.b2a else { panic!("missing BToA tables") }; assert!(b0 != b1 && b0 != b2, "perceptual shares a table"); diff --git a/crates/color-ui/README.md b/crates/color-ui/README.md index 9c81d3d68b..a38b1f9827 100644 --- a/crates/color-ui/README.md +++ b/crates/color-ui/README.md @@ -7,3 +7,8 @@ Stories: `patterns/color/{picker-dialog, panel, swatches, eyedropper-bar, sample Without `ui`: `CmykModel` (CMYK through a craft-cms profile), swatch files (`palette`: `.aco`, `.act`, `.ase`, `.gpl`, `.css`), the display transform and its caches (`display`), and colour harmonies (`harmony`). The colour model and conversions are in `craft-theme`; profiles and transforms in `craft-cms`. + +`ColorPanel::edited` can supply a colour's native components. Editing one channel preserves the other components, +even when the host renders the colour through a different working-space transform. Current host components take +precedence over the panel's remembered values. Canceling a channel gesture restores the host's complete opening +colour, including its display colour, alpha and native components. diff --git a/crates/color-ui/src/ui/compare.rs b/crates/color-ui/src/ui/compare.rs index d45e75509f..ccd4720c5a 100644 --- a/crates/color-ui/src/ui/compare.rs +++ b/crates/color-ui/src/ui/compare.rs @@ -4,7 +4,7 @@ use craft_behavior::{Metrics, Mixed, PartKey, Sense}; use craft_theme::Srgba; use craft_ui::contract::{Access, Common, Component, Cx, MeasureCx, Name, Outcome, PaintUi, PartsCx, Props as _, Role}; use craft_ui::display::{Shade, Text}; -use craft_ui::primitives::{PaintShape, StrokeWidth, TextRun}; +use craft_ui::primitives::{PaintShape, StrokeWidth, TextRun, WellFill}; use craft_ui::runtime::env::Label; use craft_ui::style::{ComponentStyle, FocusLook, StyleColor, StyleCx, TypeRole}; use egui::{CornerRadius, Rect, Response, Vec2, pos2}; @@ -83,6 +83,7 @@ pub struct CompareSwatch<'a> { new: Mixed, current: Mixed, warnings: &'a [ColorWarning], + no_current: bool, restore: bool, warning: Option, } @@ -90,7 +91,23 @@ pub struct CompareSwatch<'a> { impl<'a> CompareSwatch<'a> { /// A block named `label` ("New color", the new half's name) showing `new` over `current`. pub fn new(label: impl Into

+ Send + Sync + 'static) -> Self { self.recent_setup = Some(recent_setup(map)); @@ -573,7 +600,23 @@ impl<'a> ColorPanel<'a> { /// Shows the panel and returns this pass's edits and requests. pub fn show(self, ui: &mut Ui) -> ColorPanelOutput { - let ColorPanel { state, colors, cmyk, rgb, dynamic, layout, wells, buttons, edited, shown: rows, recent, recent_setup, gamut } = self; + let ColorPanel { + state, + colors, + cmyk, + rgb, + dynamic, + rgb_units, + layout, + wells, + buttons, + edited, + shown: rows, + recent, + recent_models, + recent_setup, + gamut, + } = self; let env = Env::of(ui); let (words, dialog) = (env.words::(), env.words::()); let mut held = Held::new(state); @@ -605,6 +648,7 @@ impl<'a> ColorPanel<'a> { rgb, gamut: &gamut, dynamic, + rgb_units, words: &words, dialog: &dialog, inputs: Inputs { @@ -613,6 +657,7 @@ impl<'a> ColorPanel<'a> { edited: edited.as_ref(), shown: rows.as_ref().unwrap_or(&default_rows), recent, + recent_models, recent_setup: recent_setup.as_ref(), }, now: before, @@ -904,6 +949,8 @@ struct Body<'a> { rgb: &'a dyn ColorModel, gamut: &'a Gamut<'a>, dynamic: bool, + /// The R, G and B rows have units cells ([`ColorPanel::rgb_units_cell`]). + rgb_units: bool, words: &'a ColorPanelWords, dialog: &'a ColorPickerDialogWords, /// The state as this pass leaves it. @@ -1052,12 +1099,11 @@ impl Body<'_> { /// The model's values for the edited colour, unrounded: an edit of one channel leaves the others as they are. fn values(&self, model: &dyn ColorModel) -> ModelValues { let color = self.color(); - // The host's own values of the colour (typed CMYK, a working space's numbers) stand when they give the colour. - let given = self.picked().and_then(|picked| picked.model); - let kept = self.kept.values[self.target.index()] - .iter() - .chain(given.as_ref()) - .find(|v| v.model == model.id() && model.to_srgb(&v.values).same_rgb8(color)); + // Current host values are authoritative: its working-space transform may differ from the panel's. + if let Some(values) = self.picked().and_then(|picked| picked.model).filter(|values| values.model == model.id()) { + return finite_values(values); + } + let kept = self.kept.values[self.target.index()].iter().find(|v| v.model == model.id() && model.to_srgb(&v.values).same_rgb8(color)); finite_values(kept.copied().unwrap_or_else(|| self.read(model, color))) } @@ -1096,11 +1142,39 @@ impl Body<'_> { fn model_event(&mut self, model: &dyn ColorModel, event: EditEvent) { let event = event.map(finite_values); self.kept.dragging = matches!(event.phase(), Some(GesturePhase::Begin | GesturePhase::Update)); + if let EditEvent::Begin { id, .. } = &event { + self.kept.opening = self.picked().copied().map(|picked| (*id, self.target, picked)); + } if let Some(values) = event.value() { self.remember(model, *values); } let alpha = self.color().a; - let event = event.map(|values| PickedColor { color: model.to_srgb(&values.values).with_alpha(alpha), model: Some(values) }); + let mut event = event.map(|values| PickedColor { color: model.to_srgb(&values.values).with_alpha(alpha), model: Some(values) }); + let opening = self.kept.opening.filter(|(id, target, _)| Some(*id) == event.id() && *target == self.target).map(|(_, _, picked)| picked); + match &mut event { + EditEvent::Begin { before, .. } | EditEvent::Commit { before, .. } => { + if let (Mixed::Same(value), Some(picked)) = (before, opening) { + *value = picked; + } + } + EditEvent::Cancel { before: Some(Mixed::Same(value)), .. } => { + if let Some(picked) = opening { + *value = picked; + if let Some(values) = picked.model.filter(|values| values.model == model.id()) { + self.remember(model, values); + } + } + } + EditEvent::Set { before: Mixed::Same(value), .. } => { + if let Some(picked) = self.picked() { + *value = *picked; + } + } + _ => {} + } + if matches!(event.phase(), Some(GesturePhase::Commit | GesturePhase::Cancel) | None) { + self.kept.opening = None; + } self.push(self.target, event); } @@ -1128,15 +1202,18 @@ impl Body<'_> { self.kept.tracks.retain(|(id, target, _)| (*id, *target) != slot); self.kept.tracks.push((slot.0, slot.1, current)); } + // The R, G and B rows are not Web Color's. The units are read once, so a double click on one units cell + // switches all three rows together, from the next pass. + let rgb = !web && model.id() == self.rgb.id(); + let rgb_percent = self.now.rgb_percent; for (i, ch) in model.channels().iter().enumerate() { let mut rule = ChannelRule::of(ch); if web { rule.step = WEB_STEP; } - // The R, G and B rows count percents of the channel's range; an edit goes back through `scale`. - // PLAN: a double click on the units cell flips `rgb_percent` while the rows are enabled; `ChannelRow` - // (color-w2) reports no signal for its units cell, so the panel cannot read it. - let percent = self.now.rgb_percent && model.id() == self.rgb.id(); + // With `rgb_percent` the R, G and B rows count percents of the channel's range; an edit goes back through + // `scale`. + let percent = rgb && rgb_percent; let scale = if percent { 100.0 / *rule.range.end() } else { 1.0 }; let unit = if percent { ChannelUnit::Percent } else { ChannelUnit::of(ch.unit) }; if percent { @@ -1152,8 +1229,17 @@ impl Body<'_> { // The field shows the channel's places, as Photoshop's; the edits start from the unrounded values. let places = 10f64.powi(i32::from(rule.decimals)); let shown = (f64::from(current.values[i]) * scale * places).round() / places; - let row = ChannelRow::new(channel_name(model, i, &[model]), Bind::given(shown), rule).short(ch.label).unit(unit).track(track).show(ui); - for event in row.into_iter().flat_map(|row| row.events) { + let row = ChannelRow::new(channel_name(model, i, &[model]), Bind::given(shown), rule).short(ch.label).unit(unit).track(track); + let edit = if rgb && self.rgb_units { + let row = row.show_with_units(ui); + if row.units_double_clicked { + self.now.rgb_percent = !rgb_percent; + } + row.edit + } else { + row.show(ui) + }; + for event in edit.into_iter().flat_map(|row| row.events) { self.channel_event(model, current, i, event.map(|x| x / scale)); } } diff --git a/crates/color-ui/src/ui/panel/fill_stroke.rs b/crates/color-ui/src/ui/panel/fill_stroke.rs index 183844b574..1e6dd88dd9 100644 --- a/crates/color-ui/src/ui/panel/fill_stroke.rs +++ b/crates/color-ui/src/ui/panel/fill_stroke.rs @@ -3,7 +3,7 @@ //! same `Body` as the Photoshop layout and shares its rows, wells, warnings and ramp helpers. use craft_behavior::{EditEvent, Mixed}; -use craft_theme::Srgba; +use craft_theme::{ModelValues, Srgba}; use craft_ui::choice::{Swatch, SwatchSpacing}; use craft_ui::contract::{Bind, Gap, LabelScheme, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; use craft_ui::display::{Shade, Text}; @@ -15,7 +15,7 @@ use craft_ui::text::{HexField, TextField}; use egui::Ui; use super::{Body, ColorPanelMode, ColorPanelShown, PanelTarget, TintRow}; -use crate::ui::{ChannelRow, ChannelRule, ChannelUnit, ColorRamp, PickedColor, RampKind, SwatchPalette}; +use crate::ui::{ChannelRow, ChannelRule, ChannelUnit, ColorRamp, PaletteCell, PickedColor, RampKind, SwatchPalette}; impl Body<'_> { /// The layout. The options (rows, quick wells, recent colours) go when the state hides them; the proxy and the @@ -156,8 +156,8 @@ impl Body<'_> { } } - /// The Recent Colors caption over a spaced palette; a pick sets the color. The caption shows while the host's list - /// is empty, where the first applied color will go. + /// The Recent Colors caption over a spaced palette; a pick sets the color, in the chip's model when the host gave it. + /// The caption shows while the host's list is empty, where the first applied color will go. // PLAN: Alt on a recent colour or a warning chip should set the other colour; `SwatchPaletteOutput` and // `ColorWarningChipOutput` report no modifiers (color-w1 for the palette, the owner of warning.rs for the chip). fn recent(&mut self, ui: &mut Ui) { @@ -174,13 +174,34 @@ impl Body<'_> { if let Some(setup) = self.inputs.recent_setup { palette = setup(palette); } - if let Some(event) = palette.show(ui).edit + let out = palette.show(ui); + let values = match out.cell { + Some(PaletteCell::Swatch(at)) => self.inputs.recent_models.get(at).copied().flatten(), + _ => None, + }; + if let (Some(color), Some(values)) = (out.picked, values) { + self.set_in_model(color, values); + } else if let Some(event) = out.edit && let Some(color) = event.value() { self.set_color(self.target, *color); } } + /// Sets the edited color to `color` in the model of `values`, keeping its alpha. It sets nothing when the host's + /// color already has those values and shows that color. + fn set_in_model(&mut self, color: Srgba, values: ModelValues) { + let before = self.picked().copied().unwrap_or_else(|| PickedColor::rgb(self.colors[self.target.index()])); + let after = PickedColor::in_model(color.with_alpha(before.color.a), values); + if before.model == after.model && before.color.to_rgba() == after.color.to_rgba() { + return; + } + // The rows' kept values in the chip's model would win over a host that keeps only sRGB (a grey's HSB hue). + self.kept.values[self.target.index()].retain(|v| v.model != values.model); + let name = self.words.title.as_str(); + self.push(self.target, EditEvent::set(Mixed::Same(before), after, name.into(), None)); + } + /// Sets `target`'s colour to `color`, keeping its alpha. fn set_color(&mut self, target: PanelTarget, color: Srgba) { let before = self.colors[target.index()]; diff --git a/crates/color-ui/src/ui/picker/channel.rs b/crates/color-ui/src/ui/picker/channel.rs index 34807fb607..53411dd79c 100644 --- a/crates/color-ui/src/ui/picker/channel.rs +++ b/crates/color-ui/src/ui/picker/channel.rs @@ -3,14 +3,19 @@ use std::ops::RangeInclusive; -use craft_behavior::{Axis, Sense}; +use craft_behavior::press::MULTI_CLICK_TIME; +use craft_behavior::{Axis, Metrics, PartKey, PressPhase, Sense}; use craft_theme::{Channel, ColorModel, Srgba}; use craft_ui::contract::{ - Bind, Common, Component, Cx, DisabledLook, EditResponse, GlyphLabel, LabelKind, MeasureCx, Role, Show as _, ShowContainer as _, SideLabel, Sizing, + Bind, Common, Component, Cx, DisabledLook, EditResponse, Gap, GlyphLabel, LabelKind, MeasureCx, NoValue, Outcome, PartsCx, Pointer as _, Role, + Show as _, ShowContainer as _, SideLabel, Sizing, }; -use craft_ui::form::{Field, SliderField, SliderFieldLayout}; +use craft_ui::form::{Field, FieldDecimals, SliderField, SliderFieldLayout}; +use craft_ui::layout_components::Row; use craft_ui::primitives::{PaintShape, StrokeWidth}; use craft_ui::runtime::env::{Label, UnitKind}; +use craft_ui::runtime::memory::sub; +use craft_ui::runtime::pointer; use craft_ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx}; use craft_ui::value_drag::{SliderThumb, TrackFace}; use egui::{Color32, CornerRadius, Ui, Vec2}; @@ -145,7 +150,8 @@ impl Component for TrackRamp { } } -/// The slider and number field of a channel, over `value`, with `track` colours on the groove. +/// The slider and number field of a channel, over `value`, with `track` colours on the groove. The field shows the +/// decimals the rule declares, a percent channel too ("67", not the percent look's "66.7"). pub(crate) fn channel_slider<'a>( name: Label, value: Bind<'a, f64>, @@ -153,7 +159,7 @@ pub(crate) fn channel_slider<'a>( unit: ChannelUnit, track: Option<(Vec, bool)>, ) -> SliderField<'a> { - let field = SliderField::new(name, value, rule.range.clone()).step(rule.step); + let field = SliderField::new(name, value, rule.range.clone()).step(rule.step).field_decimals(FieldDecimals::Fixed(usize::from(rule.decimals))); let field = match unit { ChannelUnit::None => field, ChannelUnit::Percent => field.unit_kind(UnitKind::Percent), @@ -168,7 +174,8 @@ pub(crate) fn channel_slider<'a>( /// One channel on one line, as Photoshop's Color panel draws it: the label at the start (the channel's short label /// where one is given, "C"), which scrubs the value, the slider over the channel's colours with the pointer under its -/// track, and the number field with its unit at the end, as wide as its widest value. +/// track, and the number field with its unit at the end, as wide as its widest value, showing the channel's declared +/// decimals. #[derive(craft_ui::contract::Pattern)] pub struct ChannelRow<'a> { label: Label, @@ -183,6 +190,15 @@ pub struct ChannelRow<'a> { marks: &'a [f64], } +/// What [`ChannelRow::show_with_units`] reports. +#[non_exhaustive] +pub struct ChannelRowOutput { + /// The edit of the slider or the field, `None` when the row did not run. + pub edit: Option>, + /// The units cell was double-clicked in this pass: the host switches the units the row counts in. + pub units_double_clicked: bool, +} + impl<'a> ChannelRow<'a> { /// A row named `label` over `value`, ruled by `rule`. pub fn new(label: impl Into

(place, move |payload: &P, at: &DropAt| accepts(payload, at)) })); @@ -270,8 +270,8 @@ impl<'a> SwatchesPanel<'a> { search, row_icons, select, + drops, report_invalid_renames, - takes_drop, payloads, row_items, document, @@ -331,7 +331,7 @@ impl<'a> SwatchesPanel<'a> { if let Some(items) = &row_items { browser = browser.row_menu(PresetRowMenu::Host).row_items(|key: &SwatchKey| items(key)); } - if let Some(make) = &takes_drop { + for make in &drops { browser = browser.takes_drop(make()); } for add in &payloads { diff --git a/crates/color-ui/tests/it/color_parts.rs b/crates/color-ui/tests/it/color_parts.rs index 8bb2598d34..0a44f04ffa 100644 --- a/crates/color-ui/tests/it/color_parts.rs +++ b/crates/color-ui/tests/it/color_parts.rs @@ -210,7 +210,7 @@ fn arena_tab_walk(inner: WheelInner, keys: &[Modifiers]) -> Vec> let limits = |_: &usize| craft_ui::contract::SizeLimits::default(); let rules = craft_ui::docking::tree::FrameRules::new(&limits); let area = Rect::from_min_size(ui.max_rect().min + vec2(0.0, 40.0), vec2(400.0, 340.0)); - let _ = craft_ui::docking::SplitArea::pair("Panels", craft_behavior::Axis::X, (0usize, 1usize), 0.99, rules).show_at(ui, area, |ui, _| { + let _ = craft_ui::docking::SplitArea::pair("Panels", craft_behavior::Axis::X, (0usize, 1usize), 0.99, rules, 0).show_at(ui, area, |ui, _| { let _ = ColorWheel::new("Color wheel", Bind::given(ModelValues::new("hsb", &[200.0, 50.0, 50.0]))).inner(inner).show(ui); }); let _ = craft_ui::buttons::Button::new("After").show(ui); diff --git a/crates/color-ui/tests/it/panels.rs b/crates/color-ui/tests/it/panels.rs index bb8d7a514d..7ebaeb89d1 100644 --- a/crates/color-ui/tests/it/panels.rs +++ b/crates/color-ui/tests/it/panels.rs @@ -8,11 +8,11 @@ use craft_behavior::{EditEvent, Mixed, Selection}; use craft_color_ui::palette::{SwatchColor, SwatchGroup}; use craft_color_ui::ui::{ ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel, - PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState, - SwatchesWords, swatch_rows, + PaletteCell, PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, + SwatchesState, SwatchesWords, swatch_rows, }; use craft_host::target::Os; -use craft_theme::{ColorModel as _, HsbModel, Srgba}; +use craft_theme::{ColorModel as _, HsbModel, ModelValues, Srgba}; use craft_ui::buttons::Button; use craft_ui::choice::SwatchTable; use craft_ui::contract::Role; @@ -38,6 +38,7 @@ type Edits = Rc)>>>; /// The Color panel on a state and two colours the test can change, collecting what it reports. struct PanelRig { fixture: Fixture, + state: Rc>, colors: Rc>, edits: Edits, } @@ -48,15 +49,19 @@ impl PanelRig { } fn in_room(mode: ColorPanelMode, room: Vec2) -> Self { - let start = ColorPanelState { mode, ..Default::default() }; + Self::with_state(ColorPanelState { mode, ..Default::default() }, room, true) + } + + /// The panel from `start`, with the RGB units cells where `units` is set. + fn with_state(start: ColorPanelState, room: Vec2, units: bool) -> Self { let state = Rc::new(RefCell::new(start)); let colors = Rc::new(Cell::new([RED, BLUE])); type Shared = (Edits, Rc>>, Rc>>); let (edits, opened, added): Shared = Default::default(); - let (s, c, e, o, a) = (state, colors.clone(), edits.clone(), opened, added); + let (s, c, e, o, a) = (state.clone(), colors.clone(), edits.clone(), opened, added); let mut fixture = Fixture::new(move |ui| { let mut current = *s.borrow(); - let shown = ColorPanel::new(Bind::bound(&mut current), c.get()).show(ui); + let shown = ColorPanel::new(Bind::bound(&mut current), c.get()).rgb_units_cell(units).show(ui); *s.borrow_mut() = current; e.borrow_mut().extend(shown.edits); o.borrow_mut().extend(shown.pick_color); @@ -64,7 +69,7 @@ impl PanelRig { }); fixture.room(room); fixture.settle(); - PanelRig { fixture, colors, edits } + PanelRig { fixture, state, colors, edits } } fn set_colors(&mut self, colors: [Srgba; 2]) { @@ -197,6 +202,237 @@ fn a_channel_step_keeps_the_other_channels_unrounded() { } } +/// A point in the units cell right of `field`, on its line. +fn right_of(field: &craft_ui::testing::Target) -> egui::Pos2 { + egui::pos2(field.rect.right() + 6.0, field.rect.center().y) +} + +/// The number fields' values, top to bottom, and the end of the first one's range. +fn field_values(fixture: &Fixture) -> (Vec, f64) { + let tree = fixture.tree(); + let fields = fixture.by_role(Role::SPIN_BUTTON); + let numbers: Vec<_> = fields.iter().map(|field| tree.numeric_of(field.node).expect("a field's value and range")).collect(); + let values = numbers.iter().map(|number| number.value.expect("a field's value")).collect(); + (values, *numbers[0].range.end()) +} + +/// A double click right of the R, G or B field switches all three rows between 0 to 255 and percent, and the next one +/// switches them back. The colour does not change. +#[trial] +fn a_double_click_right_of_an_rgb_field_switches_the_rgb_units() { + let mut rig = PanelRig::new(ColorPanelMode::RgbSliders); + rig.set_colors([Srgba::rgb(1.0, 0.5, 0.0), BLUE]); + let (bytes, end) = field_values(&rig.fixture); + assert!(!rig.state.borrow().rgb_percent && end > 100.0, "the rows start at 0 to 255 ({bytes:?}, to {end})"); + + let fields = rig.fixture.by_role(Role::SPIN_BUTTON); + let at = right_of(&fields[0]); + rig.fixture.click_at(at).click_at(at).settle(); + assert!(rig.state.borrow().rgb_percent, "a double click right of R switches to percent"); + let (percents, end) = field_values(&rig.fixture); + assert_eq!(end, 100.0, "the fields count to 100 %"); + for (percent, byte) in percents.iter().zip(&bytes) { + assert!((percent - byte / 2.55).abs() < 0.51, "every row shows its percent ({percents:?}, {bytes:?})"); + } + + rig.fixture.advance(1.0); + let fields = rig.fixture.by_role(Role::SPIN_BUTTON); + let at = right_of(&fields[2]); + rig.fixture.click_at(at).click_at(at).settle(); + assert!(!rig.state.borrow().rgb_percent, "a double click right of B switches back"); + assert_eq!(field_values(&rig.fixture).0, bytes, "the rows count 0 to 255 again"); + assert!(rig.edits.borrow().is_empty(), "switching the units changes no colour: {:?}", rig.edits.borrow()); +} + +/// A single click right of an RGB field, and a double click on the field itself, leave the units as they are. +#[trial] +fn only_a_double_click_on_the_units_cell_switches_the_rgb_units() { + let mut rig = PanelRig::new(ColorPanelMode::RgbSliders); + let fields = rig.fixture.by_role(Role::SPIN_BUTTON); + rig.fixture.click_at(right_of(&fields[1])).settle(); + assert!(!rig.state.borrow().rgb_percent, "a single click right of G switches nothing"); + rig.fixture.advance(1.0); + let field = rig.fixture.by_role(Role::SPIN_BUTTON).remove(1); + rig.fixture.click(&field).click(&field).settle(); + assert!(!rig.state.borrow().rgb_percent, "a double click on the G field switches nothing"); +} + +/// A click at the right edge of an RGB field followed at once by a click on the units cell beside it is not a double +/// click on the cell, though the two presses are close enough to count as one, nor are two clicks on the cell with a +/// click on the field between them. +#[trial] +fn a_click_on_the_field_then_one_on_the_units_cell_switches_nothing() { + let mut rig = PanelRig::new(ColorPanelMode::RgbSliders); + let field = rig.fixture.by_role(Role::SPIN_BUTTON).remove(0); + let (edge, cell) = (egui::pos2(field.rect.right() - 0.4, field.rect.center().y), egui::pos2(field.rect.right() + 2.4, field.rect.center().y)); + rig.fixture.click_at(cell).click_at(cell).settle(); + assert!(rig.state.borrow().rgb_percent, "a double click at {cell:?} is on the units cell"); + rig.fixture.advance(1.0); + rig.fixture.click_at(edge).click_at(cell).settle(); + assert!(rig.state.borrow().rgb_percent, "a click on the field's edge and one on the cell switch nothing"); + rig.fixture.advance(1.0); + rig.fixture.click_at(cell).click_at(edge).click_at(cell).settle(); + assert!(rig.state.borrow().rgb_percent, "two clicks on the cell with one on the field between them switch nothing"); +} + +/// Two clicks on the units cell with a click on the field between them switch nothing when the field click is too far +/// from the first to continue its click run, and the second cell click is close enough to the field click to count as +/// its second click. +#[trial] +fn a_field_click_that_starts_a_new_run_between_two_units_cell_clicks_switches_nothing() { + let mut rig = PanelRig::new(ColorPanelMode::RgbSliders); + let field = rig.fixture.by_role(Role::SPIN_BUTTON).remove(0); + let (top, bottom) = (field.rect.top() + 1.0, field.rect.bottom() - 1.0); + let (first, edge, second) = + (egui::pos2(field.rect.right() + 2.4, top), egui::pos2(field.rect.right() - 0.4, bottom), egui::pos2(field.rect.right() + 2.4, bottom)); + rig.fixture.click_at(second).click_at(second).settle(); + assert!(rig.state.borrow().rgb_percent, "a double click at {second:?} is on the units cell"); + rig.fixture.advance(1.0); + rig.fixture.click_at(first).click_at(edge).click_at(second).settle(); + assert!(rig.state.borrow().rgb_percent, "a field click that starts a new run between two cell clicks switches nothing"); +} + +/// Rows of other modes have no units cell, nor do the RGB rows of a panel whose host did not ask for them, and Web +/// Color keeps 0 to 255 while the RGB rows show percent. +#[trial] +fn rows_other_than_rgb_keep_their_units() { + let rgb = ColorPanelState { mode: ColorPanelMode::RgbSliders, ..Default::default() }; + let mut rigs = vec![("RGB without units cells".to_owned(), PanelRig::with_state(rgb, COLOR_ROOM, false))]; + for mode in [ColorPanelMode::CmykSliders, ColorPanelMode::HsbSliders, ColorPanelMode::WebColorSliders] { + rigs.push((format!("{mode:?}"), PanelRig::new(mode))); + } + for (case, mut rig) in rigs { + let fields = rig.fixture.by_role(Role::SPIN_BUTTON); + let at = right_of(&fields[0]); + rig.fixture.click_at(at).click_at(at).settle(); + assert!(!rig.state.borrow().rgb_percent, "{case}: a double click right of a field switches nothing"); + } + let start = ColorPanelState { mode: ColorPanelMode::WebColorSliders, rgb_percent: true, ..Default::default() }; + let rig = PanelRig::with_state(start, COLOR_ROOM, true); + let (_, end) = field_values(&rig.fixture); + assert!(end > 100.0, "Web Color counts 0 to 255 while the RGB rows show percent (to {end})"); +} + +/// The FillStroke layout's RGB rows switch their units the same way, and not while a mixed selection disables them. +#[trial] +fn a_disabled_fill_stroke_rgb_row_does_not_switch_its_units() { + let state = Rc::new(RefCell::new(ColorPanelState::default())); + let edited = Rc::new(Cell::new(Some(PickedColor::rgb(RED)))); + let (s, e) = (state.clone(), edited.clone()); + let mut fixture = Fixture::new(move |ui| { + let mut current = *s.borrow(); + let _ = ColorPanel::new(Bind::bound(&mut current), [RED, BLUE]) + .layout(ColorPanelLayout::FillStroke) + .shown(ColorPanelShown::Mode(ColorPanelMode::RgbSliders)) + .rgb_units_cell(true) + .edited(e.get()) + .show(ui); + *s.borrow_mut() = current; + }); + fixture.room(COLOR_ROOM).settle(); + let fields = fixture.by_role(Role::SPIN_BUTTON); + let at = right_of(&fields[0]); + fixture.click_at(at).click_at(at).settle(); + assert!(state.borrow().rgb_percent, "a double click right of R switches the FillStroke rows to percent"); + + edited.set(None); + fixture.settle().advance(1.0); + fixture.click_at(at).click_at(at).settle(); + assert!(state.borrow().rgb_percent, "with the rows disabled a double click switches nothing"); +} + +/// A Color panel whose host supplies authoritative native CMYK components. +fn native_cmyk_panel(picked: PickedColor) -> (Fixture, Rc>, Edits) { + let host = Rc::new(RefCell::new(picked)); + let edits: Edits = Default::default(); + let (color, output) = (host.clone(), edits.clone()); + let mut fixture = Fixture::new(move |ui| { + let picked = *color.borrow(); + let mut state = ColorPanelState { mode: ColorPanelMode::CmykSliders, ..Default::default() }; + let shown = ColorPanel::new(Bind::bound(&mut state), [picked.color; 2]) + .layout(ColorPanelLayout::FillStroke) + .edited(Some(picked)) + .shown(ColorPanelShown::Mode(ColorPanelMode::CmykSliders)) + .show(ui); + for (_, event) in &shown.edits { + if let Some(picked) = event.landed() { + *color.borrow_mut() = *picked; + } + } + output.borrow_mut().extend(shown.edits); + }); + fixture.room(COLOR_ROOM).settle(); + (fixture, host, edits) +} + +fn step_cyan(fixture: &mut Fixture) { + let cyan = fixture.by_role(Role::SLIDER).into_iter().next().expect("the Cyan slider"); + fixture.access(AccessActionKind::Focus, &cyan).settle(); + fixture.key(Key::ArrowRight, Modifiers::NONE).settle(); +} + +fn last_native_pick(edits: &Edits) -> PickedColor { + edits.borrow().iter().rev().find_map(|(_, event)| event.value().copied()).expect("the channel edit") +} + +/// A host may render its native CMYK through a different working-space transform. Editing one ink still keeps +/// the other explicit components, rather than deriving them from the rendered RGB. +#[trial] +fn a_channel_edit_keeps_native_host_components_with_a_different_transform() { + let native = craft_theme::ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]); + let picked = PickedColor::in_model(Srgba::rgb(0.2, 0.4, 0.6), native); + let (mut fixture, _, edits) = native_cmyk_panel(picked); + step_cyan(&mut fixture); + let after = last_native_pick(&edits).model.expect("native component values"); + assert!(after.values[0] > native.values[0], "Cyan changed"); + assert_eq!(&after.values[1..4], &native.values[1..4], "the other native inks stay exact"); +} + +/// Fresh host components win over remembered components even when both still give the same display pixel. +#[trial] +fn fresh_host_components_replace_the_panels_remembered_components() { + let model = craft_color_ui::CmykModel::new(craft_cms::convert::CmykConverter::coated().clone()); + let native = craft_theme::ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]); + let picked = PickedColor::in_model(model.to_srgb(&native.values), native); + let (mut fixture, host, edits) = native_cmyk_panel(picked); + step_cyan(&mut fixture); + let kept = last_native_pick(&edits); + let mut fresh = kept.model.expect("remembered native values"); + fresh.values[1] += 0.001; + assert!(model.to_srgb(&fresh.values).same_rgb8(kept.color), "the host update keeps the display pixel"); + *host.borrow_mut() = PickedColor::in_model(kept.color, fresh); + fixture.settle(); + step_cyan(&mut fixture); + let after = last_native_pick(&edits).model.expect("the next channel edit"); + assert!(after.values[0] > fresh.values[0], "Cyan changed again"); + assert_eq!(&after.values[1..4], &fresh.values[1..4], "fresh host inks replace the older cache"); +} + +/// Cancel restores both the native inks and the host's display colour, even after the host applies live updates. +#[trial] +fn a_canceled_native_channel_drag_restores_the_hosts_original_color() { + let native = craft_theme::ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]); + let picked = PickedColor::in_model(Srgba::new(0.2, 0.4, 0.6, 0.7), native); + let (mut fixture, host, edits) = native_cmyk_panel(picked); + let cyan = fixture.by_role(Role::SLIDER).into_iter().next().expect("the Cyan slider"); + fixture.drag_hold_at(cyan.center(), Vec2::new(25.0, 0.0)).settle(); + assert_ne!(*host.borrow(), picked, "the host applies the live channel preview"); + fixture.key(Key::Escape, Modifiers::NONE).settle(); + let canceled = edits + .borrow() + .iter() + .rev() + .find_map(|(_, event)| match event { + EditEvent::Cancel { before: Some(Mixed::Same(before)), .. } => Some(*before), + _ => None, + }) + .expect("the channel drag cancels"); + assert_eq!(canceled, picked, "Cancel carries the host's exact opening colour and model"); + assert_eq!(*host.borrow(), picked, "the host restores the complete opening colour"); + fixture.release_at(cyan.center() + Vec2::new(25.0, 0.0)).settle(); + assert_eq!(*host.borrow(), picked, "release after Cancel cannot reapply the preview"); +} + /// The rect of the FillStroke spectrum in Web Color for a foreground of `color`. fn spectrum_rect(color: Srgba) -> egui::Rect { let mut fixture = Fixture::new(move |ui| { @@ -275,6 +511,88 @@ fn the_fill_stroke_spectrums_tooltip_names_the_shown_mode_and_shift_click_cycles assert!(edits.borrow().is_empty(), "a Shift click picks nothing: {:?}", edits.borrow()); } +/// A Recent Colors pick in the FillStroke layout reports the chip's model values with its color, also when the chip +/// shows the edited color's sRGB in another model or without one; a chip whose values the edited color already has +/// sets nothing. +#[trial] +fn a_fill_stroke_recent_pick_keeps_the_chips_model() { + let chip = RECENT[0]; + let cmyk = ModelValues::new("cmyk", &[60.0, 90.0, 0.0, 0.0]); + let pick = |edited: PickedColor| { + let edits: Edits = Default::default(); + let seen = Rc::clone(&edits); + let mut fixture = Fixture::new(move |ui| { + let mut state = ColorPanelState::default(); + let out = ColorPanel::new(Bind::bound(&mut state), [edited.color, BLUE]) + .layout(ColorPanelLayout::FillStroke) + .edited(Some(edited)) + .recent(&RECENT) + .recent_models(&[Some(cmyk)]) + .show(ui); + seen.borrow_mut().extend(out.edits); + }); + fixture.room(COLOR_ROOM).settle(); + let recent = fixture.by_label(&chip.to_hex()).expect("the recent chip is named by its hex"); + fixture.click(&recent).settle(); + edits.take() + }; + let rgb_of = |color: Srgba| ModelValues::new("rgb", &[color.r * 255.0, color.g * 255.0, color.b * 255.0]); + for edited in [PickedColor::in_model(RED, rgb_of(RED)), PickedColor::in_model(chip, rgb_of(chip)), PickedColor::rgb(chip)] { + let edits = pick(edited); + assert!( + matches!(edits.as_slice(), [(PanelTarget::Foreground, EditEvent::Set { after, .. })] + if after.model == Some(cmyk) && after.color.to_rgba() == chip.to_rgba()), + "one Set to the chip in CMYK from {edited:?}: {edits:?}" + ); + } + let edits = pick(PickedColor::in_model(chip, cmyk)); + assert!(edits.is_empty(), "the chip's own values set nothing: {edits:?}"); +} + +/// A Recent Colors pick drops the HSB values the rows kept for a grey: after a host that keeps only sRGB applies a grey +/// chip with HSB values, the Hue row reads the grey afresh instead of the hue of the earlier row edits. +#[trial] +fn a_fill_stroke_recent_pick_drops_the_rows_kept_hue() { + let grey = Srgba::rgb(0.5, 0.5, 0.5); + let chip = [grey]; + let chip_hsb = ModelValues::new("hsb", &[0.0, 0.0, 50.0]); + let host = Rc::new(RefCell::new(grey)); + let color = Rc::clone(&host); + let mut fixture = Fixture::new(move |ui| { + let current = *color.borrow(); + let mut state = ColorPanelState { mode: ColorPanelMode::HsbSliders, ..Default::default() }; + let shown = ColorPanel::new(Bind::bound(&mut state), [current, BLUE]) + .layout(ColorPanelLayout::FillStroke) + .edited(Some(PickedColor::rgb(current))) + .shown(ColorPanelShown::Mode(ColorPanelMode::HsbSliders)) + .recent(&chip) + .recent_models(&[Some(chip_hsb)]) + .show(ui); + for (_, event) in &shown.edits { + if let Some(picked) = event.landed() { + *color.borrow_mut() = picked.color; + } + } + }); + fixture.room(COLOR_ROOM).settle(); + let hue = fixture.by_role(Role::SLIDER).into_iter().next().expect("the hue slider"); + fixture.access(AccessActionKind::Focus, &hue).settle(); + for _ in 0..20 { + fixture.key(Key::ArrowRight, Modifiers::NONE).settle(); + } + let hue_value = |fixture: &mut Fixture| { + let hue = fixture.by_role(Role::SLIDER).into_iter().next().expect("the hue slider"); + fixture.access(AccessActionKind::Focus, &hue).settle(); + let id = fixture.focused().expect("the hue slider takes the focus"); + fixture.tree().value(id).expect("the hue slider reports its value").to_owned() + }; + let stepped = hue_value(&mut fixture); + assert_ne!(stepped, "0", "the steps moved the kept hue of the grey"); + let recent = fixture.by_label(&grey.to_hex()).expect("the recent chip is named by its hex"); + fixture.click(&recent).settle(); + assert_eq!(hue_value(&mut fixture), "0", "the pick drops the kept hue {stepped}"); +} + /// In a host sized by its content (a floating Color panel) the FillStroke spectrum is as tall as its end boxes stacked, /// each at least as tall as it is wide, not a thin band; in a short group it keeps that height and the body scrolls. #[trial] @@ -379,6 +697,7 @@ struct PaletteReports { edits: Vec>, requests: Vec, picked: Vec, + cells: Vec, swatches: Vec, } @@ -390,6 +709,7 @@ fn collect(reports: &Reports, shown: craft_color_ui::ui::SwatchPaletteOutput) { reports.edits.extend(shown.edit); reports.requests.extend(shown.pick_color); reports.picked.extend(shown.picked); + reports.cells.extend(shown.cell); reports.swatches.extend(shown.picked_swatch); } @@ -447,11 +767,13 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() { taken.edits[0] ); assert_eq!(bound.get().to_rgba(), RECENT[0].to_rgba(), "the recent pick is written"); + assert_eq!(taken.cells, [PaletteCell::Recent(0)], "the pick names its cell in the recent row"); let violet = fixture.by_label("Violet").expect("violet"); fixture.click(&violet).settle(); - let _ = std::mem::take(&mut *reports.borrow_mut()); + let taken = std::mem::take(&mut *reports.borrow_mut()); assert_eq!(bound.get().to_rgba(), swatch("Violet").to_rgba()); + assert_eq!(taken.cells, [PaletteCell::Swatch(5)], "the pick names its swatch"); // Past the double-click time, so the repeat is a single click of its own. fixture.advance(1.0); let violet = fixture.by_label("Violet").expect("violet"); @@ -816,6 +1138,56 @@ fn a_dragged_swatch_carries_the_hosts_payload_beside_the_panels_own_move() { assert_eq!(edits.borrow().len(), 1, "a drop outside the panel edits nothing: {:?}", edits.borrow()); } +#[trial] +fn swatches_keep_both_host_drop_places() { + use craft_color_ui::palette::SwatchEntry; + use craft_ui::contract::{DropAt, DropPlace, ListDrag, ShowCollection as _}; + use craft_ui::list::{List, ListRow}; + use craft_ui::patterns::presets::{PresetEvent, PresetView}; + use egui::{Pos2, Rect, UiBuilder}; + + #[derive(Clone)] + struct Art; + + const SWATCHES: Rect = Rect { min: Pos2::ZERO, max: Pos2::new(300.0, 300.0) }; + const LAYERS: Rect = Rect { min: Pos2::new(320.0, 0.0), max: Pos2::new(460.0, 120.0) }; + let groups = vec![SwatchGroup { + name: String::new(), + entries: vec![SwatchEntry::new("Red", SwatchColor::Rgb([1.0, 0.0, 0.0])), SwatchEntry::new("Blue", SwatchColor::Rgb([0.0, 0.0, 1.0]))], + }]; + let received = Rc::new(RefCell::new(Vec::new())); + let seen = Rc::clone(&received); + let mut state = SwatchesState::default(); + state.browser.view = PresetView::List; + let mut fixture = Fixture::new(move |ui| { + ui.scope_builder(UiBuilder::new().max_rect(LAYERS), |ui| { + let ids = [7_u32]; + let source = craft_behavior::keyed(&ids, |id: &u32| *id); + List::::new("Layers").drag_payload(|_: &ListDrag| Some(Art)).show_items(ui, &source, &mut |_, _| ListRow::new("Art")); + }); + ui.scope_builder(UiBuilder::new().max_rect(SWATCHES), |ui| { + let out = SwatchesPanel::new(&groups, Bind::bound(&mut state), RED) + .takes_drop::(DropPlace::Between, |_, _| true) + .takes_drop::(DropPlace::Onto, |_, _| true) + .show(ui); + seen.borrow_mut().extend( + out.events + .into_iter() + .filter_map(|event| if let PresetEvent::Dropped { at, payload, .. } = event { payload.get::().map(|_| at) } else { None }), + ); + }); + }); + fixture.room(Vec2::new(480.0, 320.0)).settle(); + let blue = fixture.by_label("Blue, #0000ff").expect("the Blue swatch").rect; + let gap = Pos2::new(blue.center().x, blue.min.y + 2.0); + for to in [gap, blue.center()] { + let from = fixture.by_label("Art").expect("the layer row").center(); + fixture.drag_at(from, to - from).settle(); + } + let blue = SwatchKey::Swatch("Blue".into()); + assert_eq!(*received.borrow(), [DropAt::gap(Some(blue.clone()), 1), DropAt::Onto(blue)]); +} + /// A panel shown for one document after another keeps a rename left open with its document: the other document's /// swatch of the same name opens no field, and Enter there renames nothing. #[trial] @@ -1079,3 +1451,23 @@ fn the_color_guide_end_labels_sit_at_the_two_sides_of_the_grid() { assert!(shades.left() <= grid.left() + 1.0 && shades.right() < grid.center().x, "Shades {shades:?} starts at the left edge of {grid:?}"); assert!(tints.right() >= grid.right() - 1.0 && tints.left() > grid.center().x, "Tints {tints:?} ends at the right edge of {grid:?}"); } + +/// The Color Guide's variation cells stand apart: each cell's left edge lies right of the cell before it on its row, +/// and each row's top lies below the row above it. +#[trial] +fn the_color_guide_variation_cells_stand_apart() { + let mut fixture = Fixture::new(|ui| { + let (mut state, mut picked) = (HarmonyPanelState::default(), HarmonyPicked::default()); + let _ = HarmonyPanel::new(Bind::bound(&mut state), Bind::bound(&mut picked), RED).show(ui); + }); + fixture.room(COLOR_ROOM).settle(); + let grid = fixture.by_label("Variations").expect("the variations grid"); + let cells: Vec = + fixture.tree().children_of(grid.node).into_iter().filter_map(|key| fixture.target(key)).map(|cell| cell.rect).collect(); + assert!(cells.len() >= 4, "the grid holds its cells: {cells:?}"); + let (first, next) = (cells[0], cells[1]); + assert!((first.center().y - next.center().y).abs() < 0.5, "the first two cells share a row: {cells:?}"); + assert!(next.left() >= first.right() + 1.0, "a gap lies between two cells of a row: {first:?}, {next:?}"); + let below = cells.iter().find(|cell| cell.top() > first.center().y).expect("a second row of cells"); + assert!(below.top() >= first.bottom() + 1.0, "a gap lies between two rows: {first:?}, {below:?}"); +} diff --git a/crates/color-ui/tests/it/picker.rs b/crates/color-ui/tests/it/picker.rs index 7a00b133e8..03119e8114 100644 --- a/crates/color-ui/tests/it/picker.rs +++ b/crates/color-ui/tests/it/picker.rs @@ -5,12 +5,12 @@ use std::rc::Rc; use craft_behavior::Mixed; use craft_color_ui::ui::{ - ColorPicker, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerLayout, ColorPickerTab, ColorPopover, ColorReadout, ColorWarning, - PickedColor, PickerLibrary, PickerSwatches, + ChannelRow, ChannelRowOutput, ChannelRule, ColorPicker, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerLayout, ColorPickerTab, + ColorPopover, ColorReadout, ColorWarning, PickedColor, PickerLibrary, PickerSwatches, }; use craft_host::{AppInfo, Host}; use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, OklchModel, RgbModel, Rgba, Size, Srgba, ThemeId}; -use craft_ui::contract::{Bind, Role, ShowContainer as _}; +use craft_ui::contract::{Bind, EditResponse, Role, ShowContainer as _}; use craft_ui::dialog::{DialogHost, DialogResult, StackDialog, dialog_id}; use craft_ui::layout::RowAlign; use craft_ui::layout_components::Row; @@ -177,6 +177,45 @@ fn the_dialogs_rgb_fields_show_the_hosts_working_values() { } } +/// `ChannelRow::show` returns the row's edit, and `show_with_units` returns the same edit with the units cell's +/// double click, which typing into the field does not report. +#[trial] +fn a_channel_rows_show_returns_its_edit_and_show_with_units_adds_the_units_cell() { + let rule = ChannelRule { range: 0.0..=100.0, step: 1.0, decimals: 0 }; + /// Each edit: the row, the value and whether the units cell was double-clicked. + type Seen = Rc>>; + let got: Seen = Rc::default(); + let seen = Rc::clone(&got); + let mut fixture = Fixture::new(move |ui| { + let edit: Option> = ChannelRow::new("Plain", Bind::given(40.0), rule.clone()).show(ui); + for event in edit.into_iter().flat_map(|edit| edit.events) { + if let Some(v) = event.value() { + seen.borrow_mut().push(("Plain", *v, false)); + } + } + let row: ChannelRowOutput = ChannelRow::new("Units", Bind::given(40.0), rule.clone()).show_with_units(ui); + for event in row.edit.into_iter().flat_map(|edit| edit.events) { + if let Some(v) = event.value() { + seen.borrow_mut().push(("Units", *v, row.units_double_clicked)); + } + } + }); + fixture.room(vec2(320.0, 200.0)); + fixture.idle(2); + for (i, text) in [(0, "70"), (1, "20")] { + let field = fixture.by_role(Role::SPIN_BUTTON).into_iter().nth(i).unwrap_or_else(|| panic!("number field {i}")); + fixture.click(&field); + fixture.key(Key::A, Modifiers::COMMAND); + fixture.type_text(text); + fixture.key(Key::Enter, Modifiers::NONE); + fixture.settle(); + } + let got = got.borrow(); + assert!(got.iter().any(|&(row, v, _)| row == "Plain" && v == 70.0), "show reports the typed value: {got:?}"); + assert!(got.iter().any(|&(row, v, _)| row == "Units" && v == 20.0), "show_with_units reports the typed value: {got:?}"); + assert!(got.iter().all(|&(_, _, clicked)| !clicked), "typing is not a double click on the units cell: {got:?}"); +} + /// The densities and themes every layout trial runs in: compact and comfortable, a Pro and a Studio theme. const LOOKS: [(Size, &str); 4] = [(Size::Compact, "craft.pro"), (Size::Comfortable, "craft.pro"), (Size::Compact, "craft.studio"), (Size::Comfortable, "craft.studio")]; @@ -504,6 +543,33 @@ fn dialog_field(dialogs: &Rc>, name: &str) -> Option().and_then(|dialog| dialog.json_fields()).and_then(|fields| fields.get(name).cloned()) } +/// #7984: a dialog with no current colour shows the Colors heading and the compare block, its current half is not a +/// restore button, and the dialog still opens on the colour it was given. +#[trial] +fn the_standard_page_without_a_current_colour_offers_no_restore() { + let dialogs = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&dialogs); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.room(vec2(900.0, 700.0)); + fixture.host(std::sync::Arc::new(Host::builder(AppInfo { id: "picker-test", name: "Picker test", version: "0" }).build())); + let cells = vec![(Label::from("Standard 0"), Srgba::from_hex("#ff0000").expect("a colour"))]; + dialogs.borrow_mut().open( + ColorPickerDialog::new("fill", "Fill", Srgba::from_hex("#000000").expect("a colour")) + .layout(ColorPickerDialogLayout::Tabbed) + .standard(cells, Vec::new()) + .no_current() + .web_colors_remembered(false), + ); + fixture.idle(6); + assert!(fixture.by_label("Colors:").is_some(), "the honeycomb has its heading"); + assert!(fixture.by_label("New color").is_some(), "the compare block shows without a current colour"); + assert!(fixture.by_label("Restore current color").is_none(), "there is nothing to restore"); + assert_eq!(dialog_color(&dialogs).as_deref(), Some("#000000"), "the dialog opens on the colour it was given"); + fixture.click(&fixture.by_label("Standard 0").expect("a cell")); + fixture.idle(4); + assert_eq!(dialog_color(&dialogs).as_deref(), Some("#ff0000")); +} + /// The current colour of the open dialog as `#rrggbb`. fn dialog_color(dialogs: &Rc>) -> Option { dialogs.borrow().get::().and_then(|dialog| dialog.current()).map(|picked| picked.color.to_hex()) @@ -538,6 +604,7 @@ fn the_tabbed_colors_dialog_opens_on_its_tab_and_answers_from_either_page() { fixture.idle(6); assert_eq!(dialog_field(&dialogs, "tab"), Some(serde_json::json!("custom")), "the dialog opens on the tab it was given"); assert!(fixture.by_label("Hex color").is_some(), "the Custom page shows the compact picker"); + assert!(fixture.by_label("Colors:").is_some(), "and the Colors heading over it"); assert!(fixture.by_label("Standard 0").is_none(), "and not the honeycomb"); assert_eq!(dialog_field(&dialogs, "model"), Some(serde_json::Value::Null), "no model is picked yet"); assert!(fixture.by_label("Red").is_none(), "the first model (HSB) shows no red channel"); @@ -558,6 +625,15 @@ fn the_tabbed_colors_dialog_opens_on_its_tab_and_answers_from_either_page() { fixture.click(&cell); fixture.idle(4); assert_eq!(dialog_color(&dialogs).as_deref(), Some("#0000ff"), "a honeycomb pick is the colour"); + // #7984: the Standard page shows the compare block too, and its current half restores the opening colour. + assert!(fixture.by_label("New color").is_some(), "the Standard page shows the compare block"); + let restore = fixture.by_label("Restore current color").expect("the compare block's current half"); + fixture.click(&restore); + fixture.idle(4); + assert_eq!(dialog_color(&dialogs).as_deref(), Some("#123456"), "the current half restores the opening colour"); + let cell = fixture.by_label("Standard 2").expect("the honeycomb shows its cells"); + fixture.click(&cell); + fixture.idle(4); assert!(dialogs.borrow_mut().confirm::(&ctx), "OK answers"); let answered = dialogs.borrow_mut().take::().and_then(DialogResult::ok).map(|result| result.picked.color.to_hex()); @@ -609,3 +685,33 @@ fn a_request_for_the_swatches_opens_the_picker_on_its_swatch_view() { assert!(shows_swatches(request().on_swatches()), "the swatch view shows the library's cells"); assert!(!shows_swatches(request()), "without it the picker opens on the Color Models"); } + +/// The number a Compact picker's channel field named `channel` paints, the picker showing HSB `values`. +fn compact_field_number(values: [f32; 3], channel: &str) -> String { + let hsb = ModelValues::new(HsbModel.id(), &values); + let mut fixture = Fixture::new(move |ui| { + let mut color = PickedColor::in_model(HsbModel.to_srgb(&hsb.values), hsb); + let models: [&dyn ColorModel; 2] = [&HsbModel, &RgbModel]; + let _ = ColorPicker::new("Color", Bind::bound(&mut color)).layout(ColorPickerLayout::Compact).models(models).show(ui); + }); + fixture.room(vec2(600.0, 700.0)); + fixture.settle(); + let tree = fixture.tree(); + let field = fixture.by_role(Role::SPIN_BUTTON).into_iter().find(|t| tree.name_of(t.node) == Some(channel)); + let field = field.unwrap_or_else(|| panic!("the picker shows a {channel} field")).rect; + let texts = fixture.texts(); + let number = texts.iter().find(|run| field.contains(run.rect.center()) && run.text.starts_with(|c: char| c.is_ascii_digit())); + number + .unwrap_or_else(|| panic!("the {channel} field shows its value: {:?}", texts.iter().map(|r| r.text.to_string()).collect::>())) + .text + .to_string() +} + +/// A Compact picker's channel rows, which the Color panel and the harmony brightness row share, show the decimals their +/// channel declares, a percent channel too: HSB saturation declares none, so 66.7 % reads "67", not the percent look's +/// "66.7". +#[trial] +fn the_compact_pickers_percent_channels_show_the_decimals_they_declare() { + assert_eq!(compact_field_number([210.0, 66.7, 60.0], "Saturation"), "67"); + assert_eq!(compact_field_number([210.0, 66.7, 60.0], "Hue"), "210", "a degree channel keeps its whole degrees"); +} diff --git a/crates/control-protocol/Cargo.toml b/crates/control-protocol/Cargo.toml index f00bbc1c66..80f7d5af64 100644 --- a/crates/control-protocol/Cargo.toml +++ b/crates/control-protocol/Cargo.toml @@ -13,3 +13,7 @@ workspace = true [dependencies] serde_json = { workspace = true } subtle = "2" + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# The session token: 32 random bytes from the operating system (MIT OR Apache-2.0). +getrandom = "0.3" diff --git a/crates/control-protocol/src/lib.rs b/crates/control-protocol/src/lib.rs index 8194dc8e96..4bd0582853 100644 --- a/crates/control-protocol/src/lib.rs +++ b/crates/control-protocol/src/lib.rs @@ -1,7 +1,10 @@ //! Authenticated JSON-lines request framing and dispatch for local control services. #![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))] use serde_json::{Value, json}; +use std::cell::Cell; use std::io::{BufRead, BufReader, BufWriter, Read, Write}; +use std::net::TcpStream; +use std::time::{Duration, Instant}; use subtle::ConstantTimeEq; /// Whether a session token has the control protocol's 64 hexadecimal character form. @@ -9,6 +12,15 @@ pub fn valid_token(token: &str) -> bool { token.len() == 64 && token.bytes().all(|b| b.is_ascii_hexdigit()) } +/// A new session token that [`valid_token`] accepts: 32 bytes from the operating system's random +/// source, as lowercase hexadecimal. `None` when the system cannot supply random bytes. +#[cfg(not(target_arch = "wasm32"))] +pub fn new_token() -> Option { + let mut bytes = [0u8; 32]; + getrandom::fill(&mut bytes).ok()?; + Some(bytes.iter().map(|b| format!("{b:02x}")).collect()) +} + /// Encode one client request, including its terminating newline. pub fn request_line(id: u64, token: Option<&str>, method: &str, params: &Value) -> String { format!("{}\n", json!({"id": id, "token": token, "method": method, "params": params})) @@ -103,9 +115,112 @@ pub fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec, max: usiz /// Serve requests from `read`, answering on `out`, until the peer closes, sends something that is /// not a request, or `handle` returns `None` (app gone). `handle` gets `(method, params)` and /// returns the reply object (the request's `id` is added here). -pub fn serve_lines(read: R, mut out: W, token: &str, max_line: usize, mut handle: impl FnMut(String, Value) -> Option) { - let mut reader = BufReader::new(read); +pub fn serve_lines(read: R, out: W, token: &str, max_line: usize, handle: impl FnMut(String, Value) -> Option) { + serve(BufReader::new(read), out, token, max_line, |_| Ok(()), |_| false, handle); +} + +/// Serve one TCP connection as [`serve_lines`] does, but give the peer `first_request` from now +/// to send its first authenticated request. Until then every read shares that one deadline, so +/// blank lines or a line sent a byte at a time do not extend it; when it passes, the connection +/// closes without a reply and nothing is dispatched. After the first authenticated request, each +/// read waits at most `idle` (`None` waits without limit). A `first_request` too long for the +/// clock to represent waits without limit. The connection is closed when this returns. +/// +/// Returns an `InvalidInput` error, before reading anything, when `first_request` or `idle` is +/// zero, and any error from setting the socket's read timeout. +pub fn serve_tcp( + stream: TcpStream, + token: &str, + max_line: usize, + first_request: Duration, + idle: Option, + handle: impl FnMut(String, Value) -> Option, +) -> std::io::Result<()> { + if first_request.is_zero() || idle.is_some_and(|d| d.is_zero()) { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "control wait times must be longer than zero")); + } + let deadline = Instant::now().checked_add(first_request); + if deadline.is_none() { + // No deadline to apply on each read: clear any read timeout the stream already has. + stream.set_read_timeout(None)?; + } + let timeout_error = Cell::new(None); + let input = FirstRequestDeadline { socket: &stream, deadline, timeout_error: &timeout_error }; + serve( + BufReader::new(input), + &stream, + token, + max_line, + |input: &mut FirstRequestDeadline<'_>| input.admit(idle), + FirstRequestDeadline::expired, + handle, + ); + timeout_error.take().map_or(Ok(()), Err) +} + +/// A TCP connection's input whose reads share one deadline until the peer is admitted. +struct FirstRequestDeadline<'a> { + socket: &'a TcpStream, + deadline: Option, + /// The error from setting the socket's read timeout, which [`serve_tcp`] returns. + timeout_error: &'a Cell>, +} + +impl FirstRequestDeadline<'_> { + fn set_timeout(&self, timeout: Option) -> std::io::Result<()> { + self.socket.set_read_timeout(timeout).map_err(|e| { + let kind = e.kind(); + self.timeout_error.set(Some(e)); + kind.into() + }) + } + + /// The peer sent an authenticated request: from now on each read waits at most `idle`. A + /// request admitted after the first-request deadline returns `TimedOut` instead, and the + /// deadline stays in place. + fn admit(&mut self, idle: Option) -> std::io::Result<()> { + if self.expired() { + return Err(std::io::ErrorKind::TimedOut.into()); + } + self.deadline = None; + self.set_timeout(idle) + } + + /// Whether the first-request deadline has passed and no request was admitted before it. + fn expired(&self) -> bool { + self.deadline.is_some_and(|deadline| Instant::now() >= deadline) + } +} + +impl Read for FirstRequestDeadline<'_> { + 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.set_timeout(Some(left))?; + } + let mut socket = self.socket; + socket.read(buf) + } +} + +/// The request loop of [`serve_lines`] and [`serve_tcp`]: `admit` runs once, on the input, after +/// the first authenticated request and before it is dispatched; an error from it closes the +/// connection. Before the first request is admitted, a rejection closes the connection without a +/// reply when `expired` returns true for the input. +fn serve( + mut reader: BufReader, + mut out: W, + token: &str, + max_line: usize, + mut admit: impl FnMut(&mut R) -> std::io::Result<()>, + expired: impl Fn(&R) -> bool, + mut handle: impl FnMut(String, Value) -> Option, +) { let mut buf = Vec::new(); + let mut admitted = false; loop { let reject = match read_bounded_line(&mut reader, &mut buf, max_line) { Ok(false) => return, @@ -117,6 +232,12 @@ pub fn serve_lines(read: R, mut out: W, token: &str, max_line Line::Blank => continue, Line::Reject(e) => e, Line::Request { id, method, params } => { + if !admitted { + if admit(reader.get_mut()).is_err() { + return; + } + admitted = true; + } let Some(mut r) = handle(method, params) else { return }; if let Some(o) = r.as_object_mut() { o.insert("id".into(), id); @@ -128,6 +249,9 @@ pub fn serve_lines(read: R, mut out: W, token: &str, max_line } }, }; + if !admitted && expired(reader.get_ref()) { + return; + } let _ = write_line(&mut out, &json!({"ok": false, "error": reject})); return; } @@ -249,6 +373,19 @@ mod tests { assert!(!valid_token(&"g".repeat(64))); } #[test] + #[cfg(not(target_arch = "wasm32"))] + fn new_tokens_are_valid_and_distinct() { + let first = new_token().unwrap(); + let second = new_token().unwrap(); + assert!(valid_token(&first)); + assert!(valid_token(&second)); + assert_ne!(first, second); + let input = request_line(1, Some(&first), "status", &json!({})); + let mut output = Vec::new(); + serve_lines(input.as_bytes(), &mut output, &first, 4096, |_, _| Some(json!({"ok": true}))); + assert_eq!(serde_json::from_slice::(&output).unwrap(), json!({"ok": true, "id": 1})); + } + #[test] fn authenticates_each_request_and_closes_after_failure() { let input = b"{\"id\":1,\"method\":\"first\",\"token\":\"secret\"}\n{\"id\":2,\"method\":\"second\"}\n{\"method\":\"third\",\"token\":\"secret\"}\n"; @@ -263,6 +400,115 @@ mod tests { assert_eq!(lines[0], json!({"ok": true, "id": 1})); assert_eq!(lines[1]["error"], "control authentication failed; closing the connection"); } + /// The serving thread: what `serve_tcp` returned and the methods it dispatched. + type Server = std::thread::JoinHandle<(std::io::Result<()>, Vec)>; + /// A loopback connection whose client sent `input` before `serve_tcp` starts serving it on + /// another thread, so the server has read everything the client sends when a wait runs out. + fn tcp_session(input: &[u8], first_request: Duration, idle: Option) -> (TcpStream, Server) { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + // Guards the test against a server that never closes; the assertions do not depend on it. + client.set_read_timeout(Some(Duration::from_secs(30))).unwrap(); + client.write_all(input).unwrap(); + let (stream, _) = listener.accept().unwrap(); + let server = std::thread::spawn(move || { + let mut calls = Vec::new(); + let result = serve_tcp(stream, "secret", 1024, first_request, idle, |method, _| { + calls.push(method); + Some(json!({"ok": true})) + }); + (result, calls) + }); + (client, server) + } + #[test] + fn tcp_peer_without_a_request_loses_the_connection() { + let (mut client, server) = tcp_session(b"\n{\"method\":", Duration::from_millis(50), None); + let mut rest = Vec::new(); + client.read_to_end(&mut rest).expect("the server closes the connection"); + assert!(rest.is_empty()); + let (result, calls) = server.join().unwrap(); + assert!(result.is_ok()); + assert!(calls.is_empty()); + } + #[test] + fn tcp_input_waiting_after_the_deadline_is_not_read() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + client.write_all(b"\n\n").unwrap(); + let (stream, _) = listener.accept().unwrap(); + let timeout_error = Cell::new(None); + let mut input = FirstRequestDeadline { socket: &stream, deadline: Some(Instant::now()), timeout_error: &timeout_error }; + assert_eq!(input.read(&mut [0; 8]).unwrap_err().kind(), std::io::ErrorKind::TimedOut); + assert!(timeout_error.take().is_none()); + } + #[test] + fn tcp_request_read_after_the_deadline_is_not_admitted() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let _client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (stream, _) = listener.accept().unwrap(); + let timeout_error = Cell::new(None); + let mut input = FirstRequestDeadline { socket: &stream, deadline: Some(Instant::now()), timeout_error: &timeout_error }; + assert_eq!(input.admit(None).unwrap_err().kind(), std::io::ErrorKind::TimedOut); + assert!(input.deadline.is_some()); + assert!(timeout_error.take().is_none()); + } + #[test] + fn rejection_read_after_the_deadline_gets_no_reply() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let _client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (stream, _) = listener.accept().unwrap(); + let timeout_error = Cell::new(None); + let mut input = FirstRequestDeadline { socket: &stream, deadline: Some(Instant::now()), timeout_error: &timeout_error }; + assert!(input.expired()); + input.deadline = None; + assert!(!input.expired()); + let long = format!("{}\n", "x".repeat(100)); + for line in [&b"{broken}\n"[..], &b"{\"method\":\"x\",\"token\":\"wrong\"}\n"[..], long.as_bytes()] { + let mut out = Vec::new(); + serve(BufReader::new(line), &mut out, "secret", 64, |_| Ok(()), |_| true, |_, _| panic!("must not dispatch")); + assert!(out.is_empty()); + } + } + #[test] + fn tcp_peer_waits_idle_time_after_its_first_request() { + let input = b"{\"id\":1,\"method\":\"first\",\"token\":\"secret\"}\n"; + let (mut client, server) = tcp_session(input, Duration::from_secs(600), Some(Duration::from_millis(50))); + let mut rest = Vec::new(); + client.read_to_end(&mut rest).expect("the server closes the idle connection"); + assert_eq!(serde_json::from_slice::(&rest).unwrap(), json!({"ok": true, "id": 1})); + let (result, calls) = server.join().unwrap(); + assert!(result.is_ok()); + assert_eq!(calls, ["first"]); + } + #[test] + fn tcp_peer_sending_blank_lines_still_loses_the_connection_at_the_deadline() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (stream, _) = listener.accept().unwrap(); + let server = + std::thread::spawn(move || serve_tcp(stream, "secret", 1024, Duration::from_millis(200), None, |_, _| panic!("must not dispatch"))); + // Every read finds a new line, so a deadline that restarted on each read would never expire. + // The loop ends when the server closes the connection; the guard only stops a hung test. + client.set_write_timeout(Some(Duration::from_secs(30))).unwrap(); + let guard = Instant::now() + Duration::from_secs(30); + while client.write_all(b"\n").is_ok() { + assert!(Instant::now() < guard, "the server kept reading past the first-request deadline"); + std::thread::yield_now(); + } + assert!(Instant::now() < guard, "the server stopped reading but kept the connection open"); + assert!(server.join().unwrap().is_ok()); + } + #[test] + fn tcp_rejects_zero_wait_times() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let _client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (stream, _) = listener.accept().unwrap(); + for (first, idle) in [(Duration::ZERO, None), (Duration::from_secs(1), Some(Duration::ZERO))] { + let err = serve_tcp(stream.try_clone().unwrap(), "secret", 1024, first, idle, |_, _| panic!("must not dispatch")).unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); + } + } #[test] fn bounds_requests_and_preserves_last_unterminated_line() { let mut buf = Vec::new(); diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index e71a0e364b..4b128a370b 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -22,9 +22,8 @@ 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" -# The request-line reader and the reply's result, shared with servers built on it (MIT OR Apache-2.0, ours). +# The request-line reader, the reply's result and the per-launch token generator, shared with servers +# built on it (MIT OR Apache-2.0, ours). craft-control-protocol = { workspace = true } # The launcher's app list, read in one place for the launcher, the gateway and every app (MIT OR Apache-2.0, ours). craft-ai-agents = { workspace = true, optional = true } diff --git a/crates/control/src/agents/live.rs b/crates/control/src/agents/live.rs index fd975fd283..2818e7fad6 100644 --- a/crates/control/src/agents/live.rs +++ b/crates/control/src/agents/live.rs @@ -147,6 +147,16 @@ pub struct LiveConfig { pub launch_timeout: Duration, /// How often a starting app is looked for ([`LAUNCH_POLL`]; kept between 1 ms and 1 s). pub poll: Duration, + /// The clock the launch timeout is measured on ([`Instant::now`]). + #[doc(hidden)] + pub now: Box Instant + Send + Sync>, + /// Waits one poll while a started app is looked for ([`std::thread::sleep`]). + #[doc(hidden)] + pub sleep: Box, + /// Called by each [`Live::resolve`] once it has noted how many starts have finished, before it + /// waits for the lookup. + #[doc(hidden)] + pub on_queued: Option>, consent: ConsentFn, connect: ConnectFn, headless: HeadlessFn, @@ -173,6 +183,9 @@ impl LiveConfig { launch: None, launch_timeout: LAUNCH_TIMEOUT, poll: LAUNCH_POLL, + now: Box::new(Instant::now), + sleep: Box::new(std::thread::sleep), + on_queued: None, consent: Box::new(consent), connect: Box::new(connect), headless: Box::new(headless), @@ -246,6 +259,9 @@ impl Live { /// result. pub fn resolve(&self) -> Result, String> { let queued_at = self.finished.load(Ordering::Acquire); + if let Some(queued) = &self.cfg.on_queued { + queued(); + } let mut last_failure = self.lookup.lock().unwrap_or_else(PoisonError::into_inner); let consent = (self.cfg.consent)(&self.cfg.config_dir); // Allow Agent Control off refuses agents, as the app does: it doesn't listen then. @@ -310,15 +326,15 @@ impl Live { }; launch().map_err(|e| format!("couldn't start {app}: {e}"))?; let timeout = self.cfg.launch_timeout.min(MAX_LAUNCH_TIMEOUT); - let started = Instant::now(); + let started = (self.cfg.now)(); let deadline = started.checked_add(timeout).unwrap_or(started); let poll = self.cfg.poll.clamp(POLL_RANGE.0, POLL_RANGE.1); loop { - std::thread::sleep(poll); + (self.cfg.sleep)(poll); if let Some(window) = self.find_app()? { return self.use_window(window); } - if Instant::now() >= deadline { + if (self.cfg.now)() >= deadline { return Err(format!( "{app} didn't accept agents within {} s of starting. If it's still opening, try again in a moment; otherwise check that AI agents are on in ArtCraft Launcher › Settings › AI agents.", timeout.as_secs() diff --git a/crates/control/src/agents/switch.rs b/crates/control/src/agents/switch.rs index 9165879dc3..b5cabcc7fb 100644 --- a/crates/control/src/agents/switch.rs +++ b/crates/control/src/agents/switch.rs @@ -44,7 +44,11 @@ impl AgentSwitch { if !flag { return Self::fixed(false, false); } - Self::watch_with(flag, move || craft_ai_agents::allowed(app_id), POLL, wake) + let tick = || { + std::thread::sleep(POLL); + true + }; + Self::watch_with(flag, move || craft_ai_agents::allowed(app_id), tick, wake) } /// A switch that never changes: tests, the web, an app without agents. @@ -52,14 +56,20 @@ impl AgentSwitch { Self { mcp_flag, on: Arc::new(AtomicBool::new(launcher)) } } - /// [`Self::watch`] with the flag given, `probe` asked once now and then every `poll`. + /// [`Self::watch`] with the flag given and `probe` asked once now. The watch thread then calls + /// `tick`, which returns when the next poll is due ([`Self::watch`] sleeps [`POLL`]), and asks + /// `probe` again; the watch ends when `tick` returns `false`. #[doc(hidden)] - pub fn watch_with(mcp_flag: bool, probe: impl Fn() -> bool + Send + 'static, poll: Duration, wake: impl Fn() + Send + 'static) -> Self { + pub fn watch_with( + mcp_flag: bool, + probe: impl Fn() -> bool + Send + 'static, + mut tick: impl FnMut() -> bool + Send + 'static, + wake: impl Fn() + Send + 'static, + ) -> Self { let on = Arc::new(AtomicBool::new(probe())); let seen: Weak = Arc::downgrade(&on); let started = std::thread::Builder::new().name("launcher-agents".into()).spawn(move || { - loop { - std::thread::sleep(poll); + while tick() { let now = probe(); let Some(seen) = seen.upgrade() else { return }; if seen.swap(now, Ordering::Relaxed) != now { diff --git a/crates/control/src/client_tests.rs b/crates/control/src/client_tests.rs index e20bada163..32f757ac8e 100644 --- a/crates/control/src/client_tests.rs +++ b/crates/control/src/client_tests.rs @@ -4,11 +4,12 @@ use super::*; use crate::ControlRequest; use crate::server::{Hub, Protocol, Stop, Summary, Waits as ServerWaits}; use socket2::{Domain, Socket, Type}; +use std::cell::RefCell; use std::ffi::OsString; use std::net::TcpListener; use std::path::PathBuf; use std::sync::Arc; -use std::sync::mpsc::channel; +use std::sync::mpsc::{Receiver, Sender, channel}; const TOKEN: &str = "0123456789abcdef0123456789abcdef"; @@ -51,22 +52,17 @@ impl Protocol for Probe { } } -/// 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(); +/// The app on `listener` behind [`TOKEN`]: its window answers each request with the request's +/// method and parameters. With a `gate`, it answers each request only once the gate is opened (a +/// message, or the sender dropped), and the server says at once that the request is still running. +fn serve(listener: TcpListener, gate: Option>) -> Stop { + let wait = if gate.is_some() { Duration::ZERO } else { Duration::from_secs(10) }; let (tx, rx) = channel::(); std::thread::spawn(move || { for req in rx { - std::thread::sleep(delay); + if let Some(gate) = &gate { + let _ = gate.recv(); + } let _ = req.reply.send(json!({"ok": true, "result": {"method": req.method, "params": req.params}})); } }); @@ -75,6 +71,60 @@ fn serve(port: u16, delay: Duration, wait: Duration) -> Stop { hub.listen_stoppable(listener, TOKEN.into(), tx, false).unwrap() } +/// A listener on an ephemeral loopback port. +fn any_port() -> TcpListener { + TcpListener::bind("127.0.0.1:0").unwrap() +} + +/// `port` bound as [`TcpListener::bind`] binds it, but not listening yet: the port stays held, and +/// a connection to it is refused until [`listen`]. A listener just stopped may still hold the port +/// on a loaded machine ([`Stop::stop`] waits at most a couple of seconds), so the bind is retried +/// for up to two seconds. +fn hold(port: u16) -> Socket { + let started = Instant::now(); + hold_after(port, || { + if started.elapsed() >= Duration::from_secs(2) { + return false; + } + std::thread::sleep(Duration::from_millis(10)); + true + }) +} + +/// [`hold`], calling `busy` each time the port is still taken; the bind is tried again while +/// `busy` returns true. +fn hold_after(port: u16, mut busy: impl FnMut() -> bool) -> Socket { + let address = std::net::SocketAddr::from(([127, 0, 0, 1], port)).into(); + loop { + let socket = Socket::new(Domain::IPV4, Type::STREAM, Some(socket2::Protocol::TCP)).unwrap(); + #[cfg(not(windows))] + socket.set_reuse_address(true).unwrap(); + match socket.bind(&address) { + Ok(()) => return socket, + Err(e) if e.kind() == std::io::ErrorKind::AddrInUse && busy() => {} + Err(e) => panic!("binding 127.0.0.1:{port}: {e}"), + } + } +} + +fn listen(socket: Socket) -> TcpListener { + socket.listen(128).unwrap(); + socket.into() +} + +thread_local! { + /// Opened by [`open_gate`] when the client first reports a wait. + static GATE: RefCell>> = const { RefCell::new(None) }; +} + +/// A client's progress report: the app said its request is still running, so its window may +/// answer now. +fn open_gate(_: &str) { + if let Some(gate) = GATE.with(|g| g.borrow_mut().take()) { + let _ = gate.send(()); + } +} + fn addr(port: u16) -> String { format!("127.0.0.1:{port}") } @@ -91,7 +141,7 @@ fn reserve_non_listening_port() -> (Socket, u16) { #[test] fn a_call_is_one_round_trip_with_the_token() { - let app = serve(0, Duration::ZERO, Duration::from_secs(10)); + let app = serve(any_port(), None); 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(); @@ -109,7 +159,7 @@ fn a_call_is_one_round_trip_with_the_token() { #[test] fn a_wrong_token_or_none_is_refused() { - let app = serve(0, Duration::ZERO, Duration::from_secs(10)); + let app = serve(any_port(), None); for token in [Some("fedcba9876543210fedcba9876543210"), None] { let mut c = Connection::new(APP, &addr(app.port()), token); match c.call(Request::new("document.inspect", json!({}))) { @@ -139,20 +189,36 @@ fn the_not_running_fixture_keeps_its_port_from_another_listener() { drop(reserved); } +/// A port a listener still holds is bound once that listener closes, not refused at the first try. +#[test] +fn holding_a_port_waits_for_the_listener_on_it_to_close() { + let mut listener = Some(any_port()); + let port = listener.as_ref().unwrap().local_addr().unwrap().port(); + let mut tries = 0; + let held = hold_after(port, || { + tries += 1; + listener.take().is_some() + }); + assert_eq!(tries, 1, "the port was free while its listener was open"); + assert_eq!(held.local_addr().unwrap().as_socket().unwrap().port(), port); +} + /// 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 app = serve(any_port(), None); let port = app.port(); let mut c = Connection::new(APP, &addr(port), Some(TOKEN)); c.call(Request::new("document.inspect", json!({}))).unwrap(); app.stop(); + // Held, not listening, until the app is back, so no other listener takes the port meanwhile. + let held = hold(port); 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)); + let _back = serve(listen(held), None); assert_eq!(c.call(Request::new("ui.view", json!({}))).unwrap()["method"], json!("ui.view")); } @@ -178,10 +244,13 @@ fn a_connection_closed_without_a_reply_is_lost() { /// 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)); + let (gate, held) = channel(); + let app = serve(any_port(), Some(held)); + GATE.with(|g| *g.borrow_mut() = Some(gate)); + let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN)).with_progress(open_gate); 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!(GATE.with(|g| g.borrow().is_none()), "the app never said the request was still running"); assert_eq!(r, json!({"method": "solid.slow", "params": {"n": 2}})); assert!(!c.has_outstanding()); assert_eq!(c.pending(), json!({"pending": null})); @@ -190,15 +259,17 @@ fn a_request_still_running_is_waited_for_through_pending() { /// 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 (gate, held) = channel(); + let app = serve(any_port(), Some(held)); 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) }); + c.set_waits(Waits { pending: Duration::ZERO, 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()); + gate.send(()).unwrap(); 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/server.rs b/crates/control/src/server.rs index a276060c81..1346d68d89 100644 --- a/crates/control/src/server.rs +++ b/crates/control/src/server.rs @@ -7,7 +7,7 @@ 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::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; use std::time::{Duration, Instant}; use craft_control_protocol::ReadFailure; @@ -60,11 +60,16 @@ pub struct Hub { /// Longest request line accepted. max_line: usize, waits: Waits, + clock: Clock, watch: &'static DocumentWatch, running: Arc, open: AtomicUsize, } +/// The time a connection's token deadline is measured on: [`Instant::now`], or a clock a test +/// moves. +pub type Clock = Arc Instant + Send + Sync>; + 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 { @@ -73,6 +78,7 @@ impl Hub { wake: Box::new(wake), max_line, waits: Waits::default(), + clock: Arc::new(Instant::now), watch: &DOCUMENT_WATCH, running: Arc::new(Running::new()), open: AtomicUsize::new(0), @@ -85,6 +91,12 @@ impl Hub { self } + /// Another clock for the token deadline than [`Instant::now`] (tests). + pub fn with_clock(mut self, clock: Clock) -> Self { + self.clock = clock; + self + } + /// Another document watch than the app's [`DOCUMENT_WATCH`] (tests). pub fn with_watch(mut self, watch: &'static DocumentWatch) -> Self { self.watch = watch; @@ -187,12 +199,17 @@ impl Stop { } /// 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. + /// port is closed, so the same port can be bound again at once. When no connection can be + /// made to wake the listener, it waits at most two seconds for the port to close. 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)); + // The listener waits in `accept`: a connection of our own wakes it to see the flag. Once + // that connection is made, the listener accepts it and ends however busy the machine is. + if TcpStream::connect_timeout(&self.addr, Duration::from_secs(1)).is_ok() { + let _ = self.closed.recv(); + } else { + let _ = self.closed.recv_timeout(Duration::from_secs(2)); + } self.shared.close_all(); } } @@ -209,12 +226,9 @@ const EVENT_GAP: Duration = Duration::from_millis(100); /// [`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()) -} +/// A new random token: 32 bytes from the operating system, as hex. The generator lives in +/// [`craft_control_protocol`], so this crate and servers built on that crate make the same tokens. +pub use craft_control_protocol::new_token; /// One line without its newline (and a `\r` before it), or `None` at the end of the stream, read /// with [`craft_control_protocol::read_bounded_line`]. A line of more than `max` bytes, not @@ -283,7 +297,8 @@ 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 input = reader.get_mut(); + input.deadline = Some((input.clock)() + Duration::from_millis(500)); let _ = std::io::copy(&mut reader.by_ref().take(64 * 1024), &mut std::io::sink()); } @@ -293,6 +308,8 @@ fn refuse(out: &mut TcpStream, reader: &mut BufReader, docs: &str) struct ClientInput { socket: TcpStream, deadline: Option, + /// What the deadline is measured on. + clock: Clock, } impl ClientInput { @@ -306,7 +323,7 @@ impl ClientInput { 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()); + let left = deadline.saturating_duration_since((self.clock)()); if left.is_zero() { return Err(std::io::ErrorKind::TimedOut.into()); } @@ -402,6 +419,8 @@ fn cancel(pending: &mut Option, late: Option, id: Option<&Value> /// a running request. struct Running { list: Mutex>, + /// Notified each time a request leaves the list. + left: Condvar, connections: AtomicU64, keys: AtomicU64, } @@ -420,7 +439,7 @@ struct InFlight { impl Running { fn new() -> Self { - Running { list: Mutex::new(Vec::new()), connections: AtomicU64::new(0), keys: AtomicU64::new(0) } + Running { list: Mutex::new(Vec::new()), left: Condvar::new(), connections: AtomicU64::new(0), keys: AtomicU64::new(0) } } fn lock(&self) -> MutexGuard<'_, Vec> { @@ -482,6 +501,7 @@ impl Drop for Listing { fn drop(&mut self) { let key = self.key; self.running.lock().retain(|e| e.key != key); + self.running.left.notify_all(); } } @@ -660,7 +680,8 @@ impl Hub { 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 clock = Arc::clone(&self.clock); + let mut reader = BufReader::new(ClientInput { socket: read, deadline: Some(clock() + waits.token), clock }); let mut bad = 0usize; let mut authenticated = false; let mut pending: Option = None; @@ -844,6 +865,52 @@ mod tests { Arc::new(Hub::new(Plain, || {}, MAX_LINE).with_waits(waits).with_watch(watch)) } + /// [`Plain`], except that only `slow` and `queued` take the short wait. + struct Holding; + + impl Protocol for Holding { + fn summary(&self, method: &str, params: &Value) -> Summary { + Summary { long: !matches!(method, "slow" | "queued"), ..Plain.summary(method, params) } + } + fn document(&self) -> &'static str { + Plain.document() + } + fn change_event(&self) -> &'static str { + Plain.change_event() + } + fn revision_method(&self) -> &'static str { + Plain.revision_method() + } + fn docs(&self) -> &'static str { + Plain.docs() + } + fn capabilities(&self) -> Value { + Plain.capabilities() + } + } + + /// A server for [`Holding`] whose test window holds `slow` and `queued` back: they time out at + /// once, as neither has its reply yet, and every other request waits for its reply. The hour + /// only stops a hung test. + fn holding_hub() -> Arc { + let waits = Waits { short: Duration::ZERO, long: Duration::from_secs(3600), token: TOKEN_WAIT }; + Arc::new(Hub::new(Holding, || {}, MAX_LINE).with_waits(waits)) + } + + /// Wait until `hub` lists no request in `control.running`. A request that timed out leaves the + /// list once its connection's `control.pending` has its reply. Each wait ends when the list + /// tells the test that a request left it; one that runs out its ten seconds fails the test, + /// even if the list has emptied since without telling it. + fn wait_until_nothing_runs(hub: &Hub) { + let mut list = hub.running.lock(); + while !list.is_empty() { + let (now, waited) = hub.running.left.wait_timeout(list, Duration::from_secs(10)).unwrap_or_else(PoisonError::into_inner); + list = now; + assert!(!waited.timed_out(), "no request was reported leaving the list"); + } + assert!(list.is_empty(), "a request still runs"); + } + /// The channel never goes on the network: a listener on any address but loopback is refused, /// and nothing is served on it. #[test] @@ -863,55 +930,91 @@ mod tests { 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 limit = Duration::from_secs(3600); + // A server for one connection, whose clock stands still until the test moves it with the + // returned `at` (the time since the connection's deadline was set). It returns once that + // deadline is set: the clock's first reading. + let serve_one = |limit: Duration| { + 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 start = Instant::now(); - s.set_read_timeout(Some(Duration::from_millis(50))).unwrap(); + let now = Arc::new(Mutex::new(start)); + let (read_tx, read) = channel::<()>(); + let clock: Clock = { + let now = Arc::clone(&now); + Arc::new(move || { + let t = *now.lock().unwrap(); + // Told only once the time is read, so the test moves the clock after it. + let _ = read_tx.send(()); + t + }) + }; + let waits = Waits { short: Duration::from_secs(3600), long: Duration::from_secs(3600), token: limit }; + let hub = Arc::new(Hub::new(Plain, || {}, MAX_LINE).with_waits(waits).with_clock(clock)); + std::thread::spawn(move || { + if let Some(stream) = listener.incoming().flatten().next() { + hub.serve(stream, token, tx, false); + } + }); + let s = TcpStream::connect(addr).unwrap(); + // Only stops a hung test. + s.set_read_timeout(Some(Duration::from_secs(20))).unwrap(); + read.recv_timeout(Duration::from_secs(20)).expect("the connection's deadline is set"); + let at = move |after: Duration| *now.lock().unwrap() = start + after; + (s, at) + }; + // What the server sent until it closed the connection. + let until_closed = |s: &mut TcpStream| { 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(e) => { + assert!(!matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), "still open"); + break; } - Err(_) => break, } } - (got, start.elapsed()) + got }; - for drip in [&b""[..], b"\n", b"\r\n \n", b" ", b"{"] { - let (got, took) = closed_after(drip); + // A connection that sends nothing is closed when the limit runs out on the socket's own + // read timeout, without a word. + let (mut s, _) = serve_one(Duration::from_millis(100)); + let got = until_closed(&mut s); + assert!(got.is_empty(), "a silent connection was answered: {}", String::from_utf8_lossy(&got)); + for drip in [&b"\n"[..], b"\r\n \n", b" ", b"{"] { + // Once the limit has passed, the next thing sent closes the connection without a + // word, however the time before it was filled. + let (mut s, at) = serve_one(limit); + s.write_all(drip).unwrap(); + at(limit / 2); + s.write_all(drip).unwrap(); + at(limit); + let _ = s.write_all(drip); + let got = until_closed(&mut s); 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:?}"); + // Before the limit, the connection is still open: a request finished then is answered. + // A `{` is the request's own first byte. + let request = format!("{}\n", json!({"id": 1, "method": "ui.view", "token": token})); + let rest = request.strip_prefix(std::str::from_utf8(drip).unwrap()).unwrap_or(&request); + let (mut s, at) = serve_one(limit); + s.write_all(drip).unwrap(); + at(limit - Duration::from_secs(60)); + s.write_all(rest.as_bytes()).unwrap(); + let mut l = String::new(); + BufReader::new(&s).read_line(&mut l).unwrap(); + assert!(serde_json::from_str::(&l).is_ok_and(|r| r["ok"] == true), "{drip:?} closed before the limit: {l}"); } - let mut s = open(); + let (mut s, at) = serve_one(limit); let mut lines = BufReader::new(s.try_clone().unwrap()); let mut ask = |line: Value| -> Value { writeln!(s, "{line}").unwrap(); @@ -920,11 +1023,11 @@ mod tests { serde_json::from_str(&l).unwrap() }; assert_eq!(ask(json!({"id": 1, "method": "ui.view", "token": token}))["ok"], true); - std::thread::sleep(limit * 3); + at(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(); + let (mut wrong, _) = serve_one(limit); writeln!(wrong, "{}", json!({"id": 1, "method": "ui.view", "token": "nope"})).unwrap(); let mut l = String::new(); BufReader::new(wrong).read_line(&mut l).unwrap(); @@ -942,6 +1045,8 @@ mod tests { let addr = listener.local_addr().unwrap(); let (tx, rx) = channel::(); let (gate_tx, gate_rx) = channel::<()>(); + // `()` once the window has taken `slow` to run it. + let (started_tx, started) = 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 @@ -958,6 +1063,7 @@ mod tests { } seen.lock().unwrap().push(req.method.clone()); if req.method == "slow" { + let _ = started_tx.send(()); let _ = gate_rx.recv(); } let _ = req.reply.send(json!({"ok": true, "result": req.method})); @@ -970,11 +1076,11 @@ mod tests { } } }); - let waits = Waits { short: Duration::from_millis(100), long: Duration::from_millis(100), token: TOKEN_WAIT }; - let hub = hub(waits, &DOCUMENT_WATCH); + let hub = holding_hub(); + let server = Arc::clone(&hub); std::thread::spawn(move || { for stream in listener.incoming().flatten() { - let (tx, hub) = (tx.clone(), Arc::clone(&hub)); + let (tx, hub) = (tx.clone(), Arc::clone(&server)); std::thread::spawn(move || hub.serve(stream, token, tx, false)); } }); @@ -1007,6 +1113,8 @@ mod tests { // 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}"); + // The ten seconds only stop a hung test. + started.recv_timeout(Duration::from_secs(10)).expect("the window took `slow`"); 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}})); @@ -1015,14 +1123,8 @@ mod tests { 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)); - }; + wait_until_nothing_runs(&hub); + let r = ask(&mut a, json!({"id": 7, "method": "control.pending"})); 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}"); @@ -1052,11 +1154,11 @@ mod tests { 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); + let hub = holding_hub(); + let server = Arc::clone(&hub); std::thread::spawn(move || { if let Some(stream) = listener.incoming().flatten().next() { - hub.serve(stream, token, tx, false); + server.serve(stream, token, tx, false); } }); let s = TcpStream::connect(addr).unwrap(); @@ -1076,14 +1178,8 @@ mod tests { 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)); - }; + wait_until_nothing_runs(&hub); + let r = ask(json!({"id": 4, "method": "control.pending"})); assert_eq!( (&r["result"]["pending"], &r["result"]["done"], &r["result"]["reply"]["result"]), (&json!(1), &json!(true), &json!("slow")), @@ -1122,10 +1218,15 @@ mod tests { } }); let hub = hub(Waits::default(), &WATCH); + // `()` each time a connection's own thread is done with it. + let (ended_tx, ended) = channel::<()>(); 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 (tx, hub, ended) = (tx.clone(), Arc::clone(&hub), ended_tx.clone()); + std::thread::spawn(move || { + hub.serve(stream, token, tx, false); + let _ = ended.send(()); + }); } }); let open = || { @@ -1176,18 +1277,10 @@ mod tests { 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). + // Closed, it is no longer counted once its own thread is done with it (the quiet one is + // still open). The ten seconds only stop a hung test. 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)); - } + ended.recv_timeout(Duration::from_secs(10)).expect("the closed connection ended"); assert!(!WATCH.subscribed()); } @@ -1215,10 +1308,12 @@ mod tests { } }); let hub = hub(Waits::default(), &WATCH); + // `()` once the connection's own thread is done with it. + let (ended_tx, ended) = channel::<()>(); 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)); + if let Some(stream) = listener.incoming().flatten().next() { + hub.serve(stream, token, tx, false); + let _ = ended_tx.send(()); } }); let s = TcpStream::connect(addr).unwrap(); @@ -1231,18 +1326,47 @@ mod tests { 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. + // The client goes away without asking anything else. The design stands still, so the + // events thread has nothing to write: the seat must be gone when the connection's own + // thread is done, not when the events thread next wakes. The ten seconds only stop a hung + // test. drop((out, lines)); - let deadline = Instant::now() + Duration::from_millis(400); - while WATCH.subscribed() && Instant::now() < deadline { - std::thread::sleep(Duration::from_millis(10)); - } + ended.recv_timeout(Duration::from_secs(10)).expect("the closed connection ended"); assert!(!WATCH.subscribed(), "a closed connection is not counted on the watch"); } + /// #7226: the events thread leaves the watch at the first write its socket refuses, while the + /// connection's own thread still holds the seat and has not seen the end of the stream. + #[test] + fn the_events_thread_leaves_the_watch_when_a_write_fails() { + static WATCH: DocumentWatch = DocumentWatch::new(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (socket, _) = listener.accept().unwrap(); + // The socket takes no more writes, as one to a client that closed: the next line fails. + socket.shutdown(std::net::Shutdown::Write).unwrap(); + let lines = Arc::new(Lines { socket, turn: Mutex::new(()) }); + let stop = Arc::new(AtomicBool::new(false)); + WATCH.publish("d-1", 3); + let seat = Arc::new(Seat::new(WATCH.join())); + // The connection's own thread, which keeps its share of the seat throughout. + let held = Arc::clone(&seat); + assert!(WATCH.subscribed(), "the connection is subscribed"); + // `()` once the events thread has ended. + let (ended_tx, ended) = channel::<()>(); + let (l, s) = (Arc::clone(&lines), Arc::clone(&stop)); + std::thread::spawn(move || { + send_events(&WATCH, "design.changed", &l, &s, ("d-1".to_string(), 3), seat); + let _ = ended_tx.send(()); + }); + WATCH.publish("d-1", 4); + // The ten seconds only stop a hung test. + ended.recv_timeout(Duration::from_secs(10)).expect("the events thread ended at the failed write"); + assert!(!stop.load(Ordering::Relaxed), "nothing stopped the events thread but the write"); + assert!(!WATCH.subscribed(), "the seat left with the events thread"); + drop((held, client)); + } + /// 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. @@ -1449,19 +1573,26 @@ mod tests { #[test] fn a_stopped_listener_closes_its_port_and_its_connections() { use std::io::Read; + let token = "0123456789abcdef0123456789abcdef"; 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(); + let (tx, rx) = channel::(); + std::thread::spawn(move || { + for req in rx { + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + }); + let stop = hub(Waits::default(), &DOCUMENT_WATCH).listen_stoppable(listener, token.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(); + // Only stops a hung test. + client.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + // Once its first request is answered, the server holds the connection, so stopping has one + // to close. It has shown the token, so the token wait cannot end it: only stopping can. + writeln!(client, "{}", json!({"id": 1, "method": "ui.view", "token": token})).unwrap(); + let mut l = String::new(); + BufReader::new(&client).read_line(&mut l).unwrap(); + assert!(serde_json::from_str::(&l).is_ok_and(|r| r["ok"] == true), "{l}"); stop.stop(); let mut byte = [0u8; 1]; match client.read(&mut byte) { @@ -1470,15 +1601,8 @@ mod tests { 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)); - } + // `stop` returns once the port is closed. + let bound = TcpListener::bind(("127.0.0.1", port)); assert!(bound.is_ok(), "the port is free again: {:?}", bound.err()); } } diff --git a/crates/control/tests/agents.rs b/crates/control/tests/agents.rs index 5dfaa90c27..5895caf8df 100644 --- a/crates/control/tests/agents.rs +++ b/crates/control/tests/agents.rs @@ -6,7 +6,7 @@ use std::net::TcpListener; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, mpsc}; use std::time::{Duration, Instant}; use craft_control::agents::{ @@ -18,18 +18,6 @@ fn temp_dir(tag: &str) -> tempfile::TempDir { tempfile::Builder::new().prefix(&format!("craft-agents-{tag}-")).tempdir().expect("a temp dir") } -/// Waits up to five seconds for `done`. -fn wait_for(mut done: impl FnMut() -> bool) -> bool { - let started = Instant::now(); - while !done() { - if started.elapsed() > Duration::from_secs(5) { - return false; - } - std::thread::sleep(Duration::from_millis(5)); - } - true -} - const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; /// Writes `text` as an owner-only token file, as an app's own token writer does. @@ -65,19 +53,53 @@ fn with_the_flag_only_the_launchers_switch_lets_agents_in() { assert!(!AgentSwitch::fixed(false, true).allows(false)); } -/// The switch follows the launcher's list within a poll, wakes the app once per change rather than -/// once per poll, and its thread ends once the last clone is dropped. +/// The watch thread's poll clock, driven by the test: [`Self::poll`] lets one poll run and returns +/// once the thread has finished it and waits for the next. +struct Ticks { + tick: mpsc::SyncSender<()>, + waiting: mpsc::Receiver<()>, +} + +impl Ticks { + /// The clock and the `tick` to give [`AgentSwitch::watch_with`]. + fn new() -> (Self, impl FnMut() -> bool + Send + 'static) { + let (tick, ticks) = mpsc::sync_channel(0); + let (waits, waiting) = mpsc::channel(); + let wait = move || { + let _ = waits.send(()); + ticks.recv().is_ok() + }; + (Self { tick, waiting }, wait) + } + + /// Blocks until the watch thread waits for its next poll; `false` once the thread has ended. + fn waiting(&self) -> bool { + // A hang guard only: the thread answers at once, so the limit is never reached by a run + // that works. + match self.waiting.recv_timeout(Duration::from_secs(60)) { + Ok(()) => true, + Err(mpsc::RecvTimeoutError::Disconnected) => false, + Err(mpsc::RecvTimeoutError::Timeout) => panic!("the watch thread hung"), + } + } + + /// Runs one poll; `false` when the thread ended in it instead of waiting for the next one. + fn poll(&self) -> bool { + self.tick.send(()).unwrap(); + self.waiting() + } +} + +/// The switch follows the launcher's list at the next poll, wakes the app once per change rather +/// than once per poll, and its thread ends at the first poll after the last clone is dropped. #[test] fn the_switch_wakes_once_per_change() { let launcher = Arc::new(AtomicBool::new(false)); let probes = Arc::new(AtomicUsize::new(0)); let wakes = Arc::new(AtomicUsize::new(0)); - // Held by the watch thread through its probe: gone once the thread has ended. - let alive = Arc::new(()); let probe = { - let (launcher, probes, alive) = (launcher.clone(), probes.clone(), alive.clone()); + let (launcher, probes) = (launcher.clone(), probes.clone()); move || { - let _ = &alive; probes.fetch_add(1, Ordering::Relaxed); launcher.load(Ordering::Relaxed) } @@ -88,26 +110,35 @@ fn the_switch_wakes_once_per_change() { wakes.fetch_add(1, Ordering::Relaxed); } }; - let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake); + let (ticks, tick) = Ticks::new(); + let switch = AgentSwitch::watch_with(true, probe, tick, wake); let clone = switch.clone(); + assert!(ticks.waiting()); assert!(!switch.launcher()); + assert_eq!(probes.load(Ordering::Relaxed), 1, "asked once at the start"); launcher.store(true, Ordering::Relaxed); - assert!(wait_for(|| clone.launcher()), "the switch follows the launcher"); + assert!(ticks.poll()); + assert!(clone.launcher(), "the switch follows the launcher"); assert!(switch.allows(false)); - let polled = probes.load(Ordering::Relaxed); - assert!(wait_for(|| probes.load(Ordering::Relaxed) > polled + 10)); + // Many polls with nothing changed. + for _ in 0..10 { + assert!(ticks.poll()); + } + assert_eq!(probes.load(Ordering::Relaxed), 12, "one probe per poll"); + assert_eq!(wakes.load(Ordering::Relaxed), 1, "one wake per change, not per poll"); launcher.store(false, Ordering::Relaxed); - assert!(wait_for(|| !switch.launcher())); - assert!(wait_for(|| wakes.load(Ordering::Relaxed) == 2)); + assert!(ticks.poll()); + assert!(!switch.launcher()); assert_eq!(wakes.load(Ordering::Relaxed), 2, "one wake per change, not per poll"); drop(switch); + assert!(ticks.poll(), "a clone keeps the watch"); drop(clone); - assert!(wait_for(|| Arc::strong_count(&alive) == 1), "the watch ended with the last switch"); - let after_end = probes.load(Ordering::Relaxed); - std::thread::sleep(Duration::from_millis(20)); - assert_eq!(probes.load(Ordering::Relaxed), after_end, "nothing probes after the watch ended"); + // The thread probes once more, sees the switch gone and ends, so nothing probes after it. + assert!(!ticks.poll(), "the watch ended with the last switch"); + assert_eq!(probes.load(Ordering::Relaxed), 15, "one probe per poll, the last one before the watch ended"); + assert_eq!(wakes.load(Ordering::Relaxed), 2); } // ---- The connection file ------------------------------------------------------------------------ @@ -238,6 +269,21 @@ fn paths(p: &[&str]) -> Vec { p.iter().map(PathBuf::from).collect() } +/// Gives `cfg`'s launch wait a clock that moves only when the wait sleeps: each sleep calls +/// `gate`, then adds its length to the time and returns. Returns the lengths slept. +fn virtual_clock(cfg: &mut LiveConfig, gate: impl Fn() + Send + Sync + 'static) -> Arc>> { + let slept = Arc::new(Mutex::new(Vec::new())); + let start = Instant::now(); + let s = slept.clone(); + cfg.now = Box::new(move || start + s.lock().unwrap().iter().sum::()); + let s = slept.clone(); + cfg.sleep = Box::new(move |d| { + gate(); + s.lock().unwrap().push(d); + }); + slept +} + /// An app accepting agents takes the call; the same port, token and process keep the client, a /// restarted app (another process on the same port and token) gets a new one. #[test] @@ -444,8 +490,10 @@ fn a_launch_that_cannot_happen_or_never_finishes_says_what_to_do() { let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); cfg.launch = Some(Box::new(|| Ok(()))); cfg.launch_timeout = Duration::from_millis(40); + let slept = virtual_clock(&mut cfg, || {}); let err = TestLive::new(cfg).resolve().err().unwrap(); assert!(err.starts_with("Test didn't accept agents within 0 s of starting."), "{err}"); + assert_eq!(*slept.lock().unwrap(), [Duration::from_millis(5); 8], "the app is looked for every poll until the timeout"); } /// "Launch" starts the app once, also for calls that arrive together, and the calls go to its @@ -455,19 +503,24 @@ fn a_started_app_takes_the_call_and_concurrent_calls_start_it_once() { let dir = temp_dir("launch"); let made = Arc::new(Made::default()); let launches = Arc::new(AtomicUsize::new(0)); - let app: Arc>> = Arc::new(Mutex::new(None)); let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); - let (d, n, slot) = (dir.path().to_path_buf(), launches.clone(), app.clone()); + let (queued_tx, queued) = mpsc::channel(); + cfg.on_queued = Some(Box::new(move || { + let _ = queued_tx.send(()); + })); + let (launched_tx, launched) = mpsc::channel(); + let n = launches.clone(); cfg.launch = Some(Box::new(move || { n.fetch_add(1, Ordering::Relaxed); - let (d, slot) = (d.clone(), slot.clone()); - // The app takes a moment before it accepts agents. - std::thread::spawn(move || { - std::thread::sleep(Duration::from_millis(60)); - *slot.lock().unwrap() = Some(publish(&d).0); - }); + let _ = launched_tx.send(()); Ok(()) })); + // The started app's first poll waits until the test has published the app. + let (open, opened) = mpsc::channel::<()>(); + let opened = Mutex::new(opened); + virtual_clock(&mut cfg, move || { + let _ = opened.lock().unwrap().recv(); + }); let live = Arc::new(TestLive::new(cfg)); let calls: Vec<_> = (0..4) .map(|_| { @@ -475,6 +528,13 @@ fn a_started_app_takes_the_call_and_concurrent_calls_start_it_once() { std::thread::spawn(move || window(live.resolve())) }) .collect(); + // Every call is under way before the app is started and accepts agents. + for _ in 0..4 { + queued.recv().unwrap(); + } + launched.recv().unwrap(); + let _app = publish(dir.path()); + drop(open); let ports: Vec = calls.into_iter().map(|c| c.join().unwrap().port).collect(); assert_eq!(launches.load(Ordering::Relaxed), 1, "one start for every call"); assert!(ports.windows(2).all(|p| p[0] == p[1]), "{ports:?}"); @@ -489,26 +549,30 @@ fn calls_queued_behind_a_failed_start_share_its_error() { let made = Arc::new(Made::default()); let launches = Arc::new(AtomicUsize::new(0)); let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); - let entered = Arc::new(AtomicUsize::new(0)); - let (n, e) = (launches.clone(), entered.clone()); - // The app is started but never accepts agents within the timeout. The start waits until every - // call is under way and then a while longer, so a call that hasn't reached its lookup by the - // time the start ends is very unlikely (there is no hook between the two). + let (queued_tx, queued) = mpsc::channel(); + cfg.on_queued = Some(Box::new(move || { + let _ = queued_tx.send(()); + })); + let queued = Mutex::new(queued); + let n = launches.clone(); + // The app is started but never accepts agents within the timeout. The first start returns only + // once every call has queued behind it. cfg.launch = Some(Box::new(move || { - n.fetch_add(1, Ordering::Relaxed); - assert!(wait_for(|| e.load(Ordering::Relaxed) == 4), "every call starts"); - std::thread::sleep(Duration::from_millis(250)); + if n.fetch_add(1, Ordering::Relaxed) == 0 { + let queued = queued.lock().unwrap(); + for _ in 0..4 { + queued.recv().unwrap(); + } + } Ok(()) })); cfg.launch_timeout = Duration::from_millis(150); + virtual_clock(&mut cfg, || {}); let live = Arc::new(TestLive::new(cfg)); let calls: Vec<_> = (0..4) .map(|_| { - let (live, entered) = (live.clone(), entered.clone()); - std::thread::spawn(move || { - entered.fetch_add(1, Ordering::Relaxed); - live.resolve() - }) + let live = live.clone(); + std::thread::spawn(move || live.resolve()) }) .collect(); let answers: Vec<_> = calls.into_iter().map(|c| c.join().unwrap()).collect(); @@ -596,7 +660,19 @@ fn a_huge_launch_timeout_or_poll_neither_panics_nor_hangs() { })); cfg.launch_timeout = Duration::MAX; cfg.poll = Duration::MAX; - let started = Instant::now(); + let slept = virtual_clock(&mut cfg, || {}); window(TestLive::new(cfg).resolve()); - assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed()); + assert_eq!(*slept.lock().unwrap(), [Duration::from_secs(1)], "the poll is cut to a second"); + + // An app that never accepts agents: the wait ends after the longest launch timeout. + let dir = temp_dir("huge-never"); + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); + cfg.launch = Some(Box::new(|| Ok(()))); + cfg.launch_timeout = Duration::MAX; + cfg.poll = Duration::MAX; + let slept = virtual_clock(&mut cfg, || {}); + let err = TestLive::new(cfg).resolve().err().unwrap(); + assert!(err.starts_with("Test didn't accept agents within 600 s of starting."), "{err}"); + let slept = slept.lock().unwrap(); + assert_eq!((slept.len(), slept.iter().max()), (600, Some(&Duration::from_secs(1)))); } diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index f62cda215b..e989add35f 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -114,6 +114,7 @@ craft-material-graph = { workspace = true, optional = true } craft-materialx = { workspace = true, optional = true } craft-math = { workspace = true, optional = true } craft-mesh = { workspace = true, optional = true } +craft-mesh-ops = { workspace = true, optional = true } craft-metadata = { workspace = true, optional = true } craft-metafile = { workspace = true, optional = true } craft-midi = { workspace = true, optional = true } @@ -138,6 +139,7 @@ craft-raster-codecs = { workspace = true, optional = true } craft-raw = { workspace = true, optional = true } craft-rtf = { workspace = true, optional = true } craft-scraft-format = { workspace = true, optional = true } +craft-scopes = { workspace = true, optional = true } craft-sf2 = { workspace = true, optional = true } craft-sheet = { workspace = true, optional = true } craft-silhouette-studio = { workspace = true, optional = true } @@ -221,9 +223,11 @@ craft-geom = { workspace = true, optional = true } craft-suite-account = { workspace = true, optional = true } craft-xfa = { workspace = true, optional = true } craft-gpu = { workspace = true, optional = true } +craft-gpu-device = { workspace = true, optional = true } craft-gpu-null = { workspace = true, optional = true } craft-gpu-providers = { workspace = true, optional = true } craft-gpu-wgpu = { workspace = true, optional = true } +craft-gpu-yuv = { workspace = true, optional = true } craft-ipp = { workspace = true, optional = true } craft-ppt-binary = { workspace = true, optional = true } craft-sqlite = { workspace = true, optional = true } @@ -532,6 +536,13 @@ gif-frames = ["gif", "craft-gif/frames"] gpu = ["dep:craft-gpu"] gpu-startup = ["gpu", "craft-gpu/startup"] +gpu-device = ["dep:craft-gpu-device"] +gpu-device-native-dx12 = ["gpu-device", "craft-gpu-device/native-dx12"] +gpu-device-native-gles = ["gpu-device", "craft-gpu-device/native-gles"] +gpu-device-native-metal = ["gpu-device", "craft-gpu-device/native-metal"] +gpu-device-native-vulkan = ["gpu-device", "craft-gpu-device/native-vulkan"] +gpu-device-serde = ["gpu-device", "craft-gpu-device/serde"] + gpu-null = ["dep:craft-gpu-null"] gpu-providers = ["dep:craft-gpu-providers"] @@ -543,6 +554,8 @@ gpu-wgpu-native-gles = ["gpu-wgpu", "craft-gpu-wgpu/native-gles"] gpu-wgpu-native-metal = ["gpu-wgpu", "craft-gpu-wgpu/native-metal"] gpu-wgpu-native-vulkan = ["gpu-wgpu", "craft-gpu-wgpu/native-vulkan"] +gpu-yuv = ["dep:craft-gpu-yuv"] + gridcraft-format = ["dep:craft-gridcraft-format"] gzip = ["dep:craft-gzip"] @@ -663,6 +676,8 @@ mesh-ply = ["mesh", "craft-mesh/ply"] mesh-stl = ["mesh", "craft-mesh/stl"] mesh-threemf = ["mesh", "craft-mesh/threemf"] +mesh-ops = ["dep:craft-mesh-ops"] + metadata = ["dep:craft-metadata"] metafile = ["dep:craft-metafile"] @@ -694,6 +709,8 @@ pages = ["dep:craft-pages", "keymap", "text"] palette = ["dep:craft-palette"] pbr = ["dep:craft-pbr"] +pbr-materialx = ["pbr", "craft-pbr/materialx"] +pbr-mesh = ["pbr", "craft-pbr/mesh"] pbr-parallel = ["pbr", "craft-pbr/parallel"] pcap = ["dep:craft-pcap"] @@ -810,6 +827,8 @@ rtf-outlook = ["rtf", "craft-rtf/outlook"] sbs = ["dep:craft-sbs"] +scopes = ["dep:craft-scopes"] + score = ["dep:craft-score"] scraft-format = ["dep:craft-scraft-format"] @@ -931,7 +950,12 @@ text-ukrainian = ["text", "craft-text/ukrainian"] texture = ["dep:craft-texture"] texture-dds = ["texture", "craft-texture/dds"] +texture-decode = ["texture", "craft-texture/decode"] +texture-exr = ["texture", "craft-texture/exr"] +texture-hdr = ["texture", "craft-texture/hdr"] texture-parallel = ["texture", "craft-texture/parallel"] +texture-png = ["texture", "craft-texture/png"] +texture-tiff = ["texture", "craft-texture/tiff"] tga = ["dep:craft-tga"] diff --git a/crates/craft/README.md b/crates/craft/README.md index 7ccfce5c1a..e302076568 100644 --- a/crates/craft/README.md +++ b/crates/craft/README.md @@ -17,6 +17,7 @@ craft = { workspace = true, features = ["ui", "color-ui", "draw", "imaging", "ke ## Features - One feature per crate, named after the crate without `craft-`: `color-ui` turns on `craft-color-ui` and re-exports it as `craft::color_ui`. +- `gpu-yuv` enables the GPU YUV provider through `craft::gpu_yuv`. - `ui` turns on `craft-ui` (`craft::ui`), re-exports `egui` (`craft::egui`, the egui the library is built with) and forwards `ui` to every enabled crate. - `screen-testing` implies `ui` and forwards to every enabled crate. - Each crate feature is forwarded as `-` (`platform-appearance`, `text-hyphen`, `ui-window-frame`). diff --git a/crates/craft/src/egui_fork.rs b/crates/craft/src/egui_fork.rs index 629fcbaf0c..e10d75f9e0 100644 --- a/crates/craft/src/egui_fork.rs +++ b/crates/craft/src/egui_fork.rs @@ -3,7 +3,7 @@ /// The egui fork the library is built and tested with. Apps patch egui to exactly this. pub const GIT: &str = "https://github.com/storytold/egui.git"; /// The commit of [`GIT`]. -pub const REV: &str = "b9770908e0f304896f9658d239a7b29cf8af1564"; +pub const REV: &str = "932a73b28560acb1a695533307b2cd0d66a42081"; /// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]). pub const PACKAGES: &[&str] = &[ diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index f02a0ce022..60863cda9a 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -161,12 +161,16 @@ pub use craft_geom as geom; pub use craft_gif as gif; #[cfg(feature = "gpu")] pub use craft_gpu as gpu; +#[cfg(feature = "gpu-device")] +pub use craft_gpu_device as gpu_device; #[cfg(feature = "gpu-null")] pub use craft_gpu_null as gpu_null; #[cfg(feature = "gpu-providers")] pub use craft_gpu_providers as gpu_providers; #[cfg(feature = "gpu-wgpu")] pub use craft_gpu_wgpu as gpu_wgpu; +#[cfg(feature = "gpu-yuv")] +pub use craft_gpu_yuv as gpu_yuv; #[cfg(feature = "gridcraft-format")] pub use craft_gridcraft_format as gridcraft_format; #[cfg(feature = "gzip")] @@ -247,6 +251,8 @@ pub use craft_media_source as media_source; pub use craft_menu as menu; #[cfg(feature = "mesh")] pub use craft_mesh as mesh; +#[cfg(feature = "mesh-ops")] +pub use craft_mesh_ops as mesh_ops; #[cfg(feature = "metadata")] pub use craft_metadata as metadata; #[cfg(feature = "metafile")] @@ -331,6 +337,8 @@ pub use craft_review as review; pub use craft_rtf as rtf; #[cfg(feature = "sbs")] pub use craft_sbs as sbs; +#[cfg(feature = "scopes")] +pub use craft_scopes as scopes; #[cfg(feature = "score")] pub use craft_score as score; #[cfg(feature = "scraft-format")] diff --git a/crates/design-lint/src/contract/pointer.rs b/crates/design-lint/src/contract/pointer.rs index bc764fcec2..270e4e89e7 100644 --- a/crates/design-lint/src/contract/pointer.rs +++ b/crates/design-lint/src/contract/pointer.rs @@ -1,4 +1,4 @@ -//! `contract/pointer`: drag and click queries and press-origin reads outside `runtime::egui`. +//! `contract/pointer`: drag and click queries, press-origin reads and hover-position reads outside `runtime::egui`. use crate::report::Finding; @@ -7,6 +7,13 @@ use super::Cx; pub const ID: &str = "contract/pointer"; pub(super) fn check(cx: &Cx<'_>, out: &mut Vec) { + cx.flag_methods( + out, + ID, + ID, + "reads egui's pointer position; `Cx::hover_pos` and `pointer::hover_point_in` read it and mark what follows the pointer", + |name, args| matches!(name, "pointer_hover_pos" | "pointer_latest_pos" | "pointer_interact_pos") || (name == "hover_pos" && args.count == 0), + ); cx.flag_methods(out, ID, ID, "reads egui's pointer state; the pointer frame carries presses and drags", |name, _| { matches!( name, diff --git a/crates/design-lint/tests/fixtures/egui-rules/reject/contract-pointer.rs b/crates/design-lint/tests/fixtures/egui-rules/reject/contract-pointer.rs index 17699b16f3..a382cbd7b3 100644 --- a/crates/design-lint/tests/fixtures/egui-rules/reject/contract-pointer.rs +++ b/crates/design-lint/tests/fixtures/egui-rules/reject/contract-pointer.rs @@ -1,4 +1,6 @@ -fn f(r: &Response) { +fn f(r: &Response, ctx: &Context) { if r.drag_started() || r.clicked() {} let _ = r.drag_delta(); + let _ = r.hover_pos(); + let _ = ctx.pointer_latest_pos(); } diff --git a/crates/dialogs/src/ui/chooser/tests.rs b/crates/dialogs/src/ui/chooser/tests.rs index 0e38060c32..d6570ea5f6 100644 --- a/crates/dialogs/src/ui/chooser/tests.rs +++ b/crates/dialogs/src/ui/chooser/tests.rs @@ -228,7 +228,12 @@ fn an_unavailable_or_forced_pick_opens_the_chooser_and_settles_its_answer() { std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("report.docx"), b"x").unwrap(); - let (service, panels) = FileService::scripted(Wake::none(), [Answer::Unavailable("no portal".to_owned())]); + // The service lists the real folder on its own threads and wakes the app when each listing is in. + let (woke, wakes) = std::sync::mpsc::channel(); + let wake = Wake::new(move || { + let _ = woke.send(()); + }); + let (service, panels) = FileService::scripted(wake, [Answer::Unavailable("no portal".to_owned())]); let panels = Rc::new(RefCell::new(panels)); let host = Rc::new(RefCell::new(DialogHost::new())); let (pumped, shown) = (panels.clone(), host.clone()); @@ -236,18 +241,15 @@ fn an_unavailable_or_forced_pick_opens_the_chooser_and_settles_its_answer() { pumped.borrow_mut().pump_with(&mut shown.borrow_mut(), NONE); shown.borrow_mut().run(ui); }); - // The service lists the real folder on its own threads: wait until the chooser is listed. - let listed = |fixture: &mut Fixture| { - for _ in 0..400 { - fixture.idle(1); - if fields(&host).get("listed") == Some(&Value::Bool(true)) { - // The chooser lays out its listing in the next passes: a click reads where the controls rest. - fixture.settle(); - return; - } - std::thread::sleep(Duration::from_millis(5)); + // A pass takes in the listings that are in; until the chooser is listed, the next pass waits for the next wake. + let listed = |fixture: &mut Fixture| loop { + fixture.idle(1); + if fields(&host).get("listed") == Some(&Value::Bool(true)) { + // The chooser lays out its listing in the next passes: a click reads where the controls rest. + fixture.settle(); + return; } - panic!("the chooser listed the folder"); + wakes.recv_timeout(Duration::from_secs(10)).expect("a finished listing wakes the app"); }; let click = |fixture: &mut Fixture, label: &str| { let target = fixture.by_label(label).unwrap_or_else(|| panic!("`{label}` is shown")); @@ -284,3 +286,26 @@ fn an_unavailable_or_forced_pick_opens_the_chooser_and_settles_its_answer() { assert!(!host.borrow().is_open::(), "the chooser closed"); let _ = std::fs::remove_dir_all(&dir); } + +#[trial] +fn an_empty_folder_says_there_are_no_items() { + let fake = Arc::new(FakeDirectories::new().folder("/d/empty").folder("/d/full").file("/d/full/chapter.docx")); + let jobs = Arc::new(ManualJobs::new()); + let folders = || FolderCache::new(fake.clone(), jobs.clone(), Wake::none()); + let host = Rc::new(RefCell::new(DialogHost::new())); + host.borrow_mut().open(FileChooser::new(PickRequest::open("document").directory("/d/empty").fallback(true), None, folders())); + let shown = host.clone(); + let run_jobs = jobs.clone(); + let mut fixture = Fixture::new(move |ui| { + run_jobs.run_all(); + shown.borrow_mut().run(ui); + }); + fixture.idle(10); + assert!(fixture.by_label("No items to show.").is_some(), "empty-state hint shown"); + + let _ = host.borrow_mut().take::(); + host.borrow_mut().open(FileChooser::new(PickRequest::open("document").directory("/d/full").fallback(true), None, folders())); + fixture.idle(10); + assert!(fixture.by_label("chapter.docx").is_some(), "the file is listed"); + assert!(fixture.by_label("No items to show.").is_none(), "the hint is gone"); +} diff --git a/crates/doc-binary/src/drawing.rs b/crates/doc-binary/src/drawing.rs index 1381455ca3..017ec0be96 100644 --- a/crates/doc-binary/src/drawing.rs +++ b/crates/doc-binary/src/drawing.rs @@ -277,7 +277,7 @@ fn members_into(nodes: &[Node], t: (f32, f32, f32, f32), depth: usize, b: &Build let float = Float { rot: sp.props.rot, flip_h: sp.flip_h(), flip_v: sp.flip_v(), ..Float::default() }; let (w, h) = (fit(ew * sx).max(0.0), fit(eh * sy).max(0.0)); if let Some(obj) = leaf(sp, w, h, float, b, pics) { - out.push(GroupChild { x: fit(x0 + ox * sx), y: fit(y0 + oy * sy), obj }); + out.push(GroupChild { link: None, x: fit(x0 + ox * sx), y: fit(y0 + oy * sy), obj }); } } } diff --git a/crates/doc-binary/src/lib.rs b/crates/doc-binary/src/lib.rs index d8e3ce31a5..bab7c612da 100644 --- a/crates/doc-binary/src/lib.rs +++ b/crates/doc-binary/src/lib.rs @@ -283,7 +283,7 @@ fn read_limited(bytes: &[u8], password: Option<&str>, max_paragraphs: usize) -> let mut doc = Document::new(); // Word opens Word 97-2003 files in compatibility mode 11 (Word 2003); the model's default // 15 would apply Word 2013+ justification and line-breaking rules to them. - doc.settings.compat_mode = 11; + doc.settings.compat_mode = Some(11); if let Some(core) = metadata::read(&comp) { doc.core = core; } @@ -455,7 +455,7 @@ fn read_word6(comp: &craft_cfb::CompoundFile<'_>, word: &[u8], max_paragraphs: u let content = word6::content(word, &fib)?; let mut doc = Document::new(); // Word opens these files in compatibility mode 11 too. - doc.settings.compat_mode = 11; + doc.settings.compat_mode = Some(11); if let Some(core) = metadata::read(comp) { doc.core = core; } diff --git a/crates/doc-binary/src/tests.rs b/crates/doc-binary/src/tests.rs index 8c1025eb27..2f380ca84a 100644 --- a/crates/doc-binary/src/tests.rs +++ b/crates/doc-binary/src/tests.rs @@ -347,7 +347,7 @@ fn a_doc_opens_in_word_97_2003_compatibility_mode() { let doc = read(&f).expect("opens"); // Word 97-2003 files are mode 11 in Word 2013+; mode 15 would change justification and // line breaking. - assert_eq!(doc.settings.compat_mode, 11); + assert_eq!(doc.settings.compat_mode, Some(11)); } #[test] diff --git a/crates/doc-binary/src/tests/drawing.rs b/crates/doc-binary/src/tests/drawing.rs index 943c2a5a2f..3e94d0ad3b 100644 --- a/crates/doc-binary/src/tests/drawing.rs +++ b/crates/doc-binary/src/tests/drawing.rs @@ -462,7 +462,7 @@ fn a_floating_copy_is_charged_its_alt_text() { }; let bare = crate::object_cost(&image(String::new())); assert_eq!(crate::object_cost(&image("€".repeat(4096))), bare + 3 * 4096); - let member = |obj| craft_wordmodel::para::GroupChild { x: 0.0, y: 0.0, obj }; + let member = |obj| craft_wordmodel::para::GroupChild { link: None, x: 0.0, y: 0.0, obj }; let group = InlineObject::Group { w: 1.0, h: 1.0, diff --git a/crates/doc/tests/pixels.rs b/crates/doc/tests/pixels.rs index de2687b45e..781b7fd361 100644 --- a/crates/doc/tests/pixels.rs +++ b/crates/doc/tests/pixels.rs @@ -105,6 +105,7 @@ fn eight_bit_tiles_land_on_the_canvas_and_missing_tiles_hold_the_default_pixel() assert_eq!((p.width, p.height, p.rgba.len()), (300, 260, 300 * 260 * 4)); assert_eq!(rgba_at(&p, 0, 0), [0, 0, 7, 255]); assert_eq!(rgba_at(&p, 255, 3), [255, 3, 7, 255]); + assert_eq!(rgba_at(&p, 255, 255), [255, 255, 7, 255]); assert_eq!(rgba_at(&p, 256, 0), [10, 20, 30, 40]); assert_eq!(rgba_at(&p, 0, 256), [10, 20, 30, 40]); assert_eq!(rgba_at(&p, 299, 259), [200, 100, 50, 128]); @@ -112,6 +113,18 @@ fn eight_bit_tiles_land_on_the_canvas_and_missing_tiles_hold_the_default_pixel() assert_eq!(p.mask, None); } +#[test] +fn a_tile_one_decoded_byte_over_its_size_is_refused() { + let mut tile = solid(&[1, 2, 3, 4]); + tile.push(0); + let s = surface("Rgb", "U8", true, &[0; 4], &[(0, 0, &hash(&tile))]); + let file = bundle(256, 256, "Rgb", &[layer(&raster(&s), None)], &[&tile]); + assert!(matches!( + pcraft_layer_rgba(&file, &[0], &Limits::default()), + Err(craft_doc::Error::Malformed(message)) if message.contains("more than 262144 bytes") + )); +} + #[test] fn every_truncation_and_flipped_byte_is_an_error_not_a_panic() { let tile = solid(&[1, 2, 3, 4]); diff --git a/crates/docx/Cargo.toml b/crates/docx/Cargo.toml index 0ffedf2aac..4da7f60729 100644 --- a/crates/docx/Cargo.toml +++ b/crates/docx/Cargo.toml @@ -27,6 +27,7 @@ unicode-bidi = "0.3" zeroize = "1" [dev-dependencies] +craft-flow = { workspace = true } craft-cfb = { workspace = true } craft-testkit = { workspace = true } craft-opc = { workspace = true, features = ["test-support"] } diff --git a/crates/docx/src/flat.rs b/crates/docx/src/flat.rs index b88211805f..5fd20ecb23 100644 --- a/crates/docx/src/flat.rs +++ b/crates/docx/src/flat.rs @@ -116,6 +116,10 @@ fn room(total: u64) -> u64 { /// Unpack a Flat OPC file into its parts, with a `[Content_Types].xml` made from the parts' /// content types (unless the file carries one). pub(crate) fn unpack(bytes: &[u8]) -> Result { + unpack_within(bytes, MAX_PART_ELEMENTS) +} + +fn unpack_within(bytes: &[u8], part_elements: usize) -> Result { let text = utf8_text(bytes); let src: &[u8] = text.as_ref(); let mut r = NsReader::from_reader(src); @@ -150,7 +154,7 @@ pub(crate) fn unpack(bytes: &[u8]) -> Result { } } elements += 1; - if elements > MAX_PART_ELEMENTS { + if elements > part_elements { return Err(DocxError::Limit("too many XML elements".into())); } let local = e.local_name().as_ref().to_vec(); @@ -552,6 +556,27 @@ mod tests { assert_eq!(out.matches("xmlns:p").count(), 256); } + #[test] + fn part_element_budget_counts_parts_that_are_not_read() { + assert_eq!(MAX_PART_ELEMENTS, 8_000_002); + let cap = 100; + let inline = |children| format!("{}", "".repeat(children)); + let part = |name: &str, xml: &str| format!("{xml}"); + let package = |parts: &str| format!("{parts}"); + // The part, xmlData and r wrappers count too: 97 children make exactly 100. + let xml = inline(97); + let first = part("/word/unused.xml", &xml); + let at_cap = unpack_within(package(&first).as_bytes(), cap).unwrap(); + assert_eq!(at_cap.get("word/unused.xml"), Some(xml.as_bytes())); + let over = part("/word/unused.xml", &inline(98)); + assert!(matches!(unpack_within(package(&over).as_bytes(), cap), Err(DocxError::Limit(_)))); + // Each package child has its own allowance, even though neither part is read. + let two = format!("{first}{}", part("/word/also-unused.xml", &xml)); + let reset = unpack_within(package(&two).as_bytes(), cap).unwrap(); + assert_eq!(reset.get("word/unused.xml"), Some(xml.as_bytes())); + assert_eq!(reset.get("word/also-unused.xml"), Some(xml.as_bytes())); + } + #[test] fn nesting_is_capped_where_the_xml_tree_reader_stops() { let inline = |levels: usize| format!("{}{}", "".repeat(levels), "".repeat(levels)); diff --git a/crates/docx/src/read.rs b/crates/docx/src/read.rs index 518f3e6b47..3588e4d25e 100644 --- a/crates/docx/src/read.rs +++ b/crates/docx/src/read.rs @@ -76,6 +76,8 @@ pub(crate) struct Reader<'p> { revs: HashMap<(u8, String, String, Option, Option), u32>, /// Move ranges (`w:moveFromRangeStart` …) seen so far. pub moves: MoveCtx, + /// Bytes of drawing hyperlink targets copied into this document. + drawing_link_bytes: usize, media_by_path: HashMap, hf_by_path: HashMap, /// Header/footer parts being read right now (see [`MAX_HF_DEPTH`]). @@ -178,6 +180,7 @@ fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, pc: PropCtx::default(), revs: HashMap::new(), moves: MoveCtx::default(), + drawing_link_bytes: 0, media_by_path: HashMap::new(), hf_by_path: HashMap::new(), hf_depth: 0, @@ -254,7 +257,8 @@ fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, lenient("numbering", r.read_numbering(&p)); } // Without a stated mode (or settings at all) Word lays a document out as Word 2007 did. - r.doc.settings.compat_mode = craft_wordmodel::LEGACY_COMPAT_MODE; + // Retain `compat_mode` as `None` when omitted from the source file to preserve XML fidelity on save (#3308). + r.doc.settings.compat_mode = None; if let Some(p) = part(rt::SETTINGS) { lenient("settings", r.read_settings(&p)); } diff --git a/crates/docx/src/read/meta.rs b/crates/docx/src/read/meta.rs index 851ecae67f..5a4330bdca 100644 --- a/crates/docx/src/read/meta.rs +++ b/crates/docx/src/read/meta.rs @@ -47,7 +47,7 @@ impl Reader<'_> { }) .and_then(|c| c.attr("w:val")); if let Some(m) = mode.and_then(u32_of) { - s.compat_mode = m.clamp(11, 99); + s.compat_mode = Some(m.clamp(11, 99)); } s.sum_paragraph_spacing = k.children("w:doNotUseHTMLParagraphAutoSpacing").any(on_off); s.do_not_expand_shift_return = k.children("w:doNotExpandShiftReturn").any(on_off); diff --git a/crates/docx/src/read/story.rs b/crates/docx/src/read/story.rs index 9b5b04300a..8d97db6afb 100644 --- a/crates/docx/src/read/story.rs +++ b/crates/docx/src/read/story.rs @@ -49,6 +49,7 @@ const MAX_FORM: usize = 64 * 1024; pub struct RunCtx { link: Option, link_tooltip: Option>, + link_history: Option, ins: Option, del: Option, } @@ -212,5 +213,5 @@ fn placeholder_of(s: &str) -> String { } fn on_off_attr(e: &El, name: &str) -> bool { - e.attr(name).is_some_and(|v| !matches!(v, "0" | "false" | "off")) + e.attr(name).is_some_and(|v| !crate::units::is_off_val(v)) } diff --git a/crates/docx/src/read/story/drawing.rs b/crates/docx/src/read/story/drawing.rs index cbffa58fc8..7c4e3e29e7 100644 --- a/crates/docx/src/read/story/drawing.rs +++ b/crates/docx/src/read/story/drawing.rs @@ -115,37 +115,62 @@ impl Reader<'_> { /// Part 1 §20.4.2.5, §21.1.2.3.5) naming an external hyperlink relationship. Word stores a /// picture's link there rather than in a `w:hyperlink` around its run (#5267). Its `#name` /// part, when the address has one, stays part of the address. - pub(super) fn drawing_link(d: &El, rels: &Rels) -> Option { + pub(super) fn drawing_link(&mut self, d: &El, rels: &Rels) -> Option { let frame = d.child("wp:inline").or_else(|| d.child("wp:anchor"))?; - let id = frame.child("wp:docPr")?.child("a:hlinkClick")?.attr("r:id")?; + self.drawing_property_link(frame.child("wp:docPr"), rels) + } + + fn drawing_property_link(&mut self, nv: Option<&El>, rels: &Rels) -> Option { + let id = nv?.child("a:hlinkClick")?.attr("r:id")?; let rel = rels.by_id(id).filter(|r| r.external && crate::package::rel_is(&r.kind, rt::HYPERLINK))?; - Some(rel.target.trim().to_string()).filter(|u| !u.is_empty()) + self.keep_drawing_link(&rel.target) + } + + /// A template or relationship can be referenced many times. Charge each retained copy + /// before allocating, using the same target and string ceilings as Flow. + pub(super) fn keep_drawing_link(&mut self, target: &str) -> Option { + let target = target.trim(); + if target.is_empty() || target.len() > 8 << 10 || target.len() > (64 << 20) - self.drawing_link_bytes { + return None; + } + self.drawing_link_bytes += target.len(); + Some(target.to_string()) } /// Native ink or an Office 2016 chart kept with its fallback (`mc:AlternateContent`), and the /// [`Self::drawing_link`] of the choice it was read from, else of its fallback: another /// choice's link is not this object's. pub(super) fn read_alternate(&mut self, sc: &mut StoryCtx, ac: &El, rels: &Rels) -> Option<(InlineObject, Option)> { - let (object, choice) = match self.read_ink_alternate(sc, ac, rels) { - Some(o) => (o, children_of_choice(ac).filter(|e| e.name == "mc:Choice")), - None => (self.read_chartex_alternate(sc, ac, rels)?, chartex_choice(ac)), - }; + if let Some(linked) = self.read_ink_alternate(sc, ac, rels) { + return Some(linked); + } + let (object, choice) = (self.read_chartex_alternate(sc, ac, rels)?, chartex_choice(ac)); let link = - [choice, ac.child("mc:Fallback")].into_iter().flatten().filter_map(|e| e.child("w:drawing")).find_map(|d| Self::drawing_link(d, rels)); + [choice, ac.child("mc:Fallback")].into_iter().flatten().filter_map(|e| e.child("w:drawing")).find_map(|d| self.drawing_link(d, rels)); Some((object, link)) } /// Keep the selected native-ink branch and its picture fallback as one object. Reading only /// the fallback flattens the ink; reading only the choice loses its preview on the next save. - fn read_ink_alternate(&mut self, sc: &mut StoryCtx, ac: &El, rels: &Rels) -> Option { + fn read_ink_alternate(&mut self, sc: &mut StoryCtx, ac: &El, rels: &Rels) -> Option<(InlineObject, Option)> { let choice = children_of_choice(ac).filter(|e| e.name == "mc:Choice")?; let drawing = choice.child("w:drawing")?; if drawing.find("a:graphicData")?.attr("uri") != Some(INK_URI) { return None; } let fallback = ac.child("mc:Fallback"); - let preview = fallback.and_then(|f| f.child("w:pict")).and_then(|p| self.read_vml(sc, p, rels)); - let Some(mut object) = self.read_drawing(sc, drawing, rels) else { return preview }; + let native = self.read_drawing(sc, drawing, rels); + // A lower-priority preview must not spend the native target's budget. + let native_link = native.as_ref().and_then(|_| { + self.drawing_link(drawing, rels).or_else(|| fallback.and_then(|f| f.child("w:drawing")).and_then(|d| self.drawing_link(d, rels))) + }); + let preview = fallback + .and_then(|f| f.child("w:pict")) + .and_then(|p| if native.is_some() { self.read_vml_preview(sc, p, rels) } else { self.read_vml(sc, p, rels) }); + let Some(mut object) = native else { + return preview.map(|(object, target)| (object, target.and_then(|target| self.keep_drawing_link(target)))); + }; + let (preview, preview_link) = preview.map(|(object, link)| (Some(object), link)).unwrap_or_default(); if let InlineObject::Graphic { w, h, graphic, .. } = &mut object { let graphic = Arc::make_mut(graphic); if let Some(InlineObject::Image { media, .. }) = preview { @@ -160,7 +185,8 @@ impl Reader<'_> { // A malformed or over-budget fallback must not discard a valid native part. } } - Some(object) + let link = native_link.or_else(|| preview_link.and_then(|target| self.keep_drawing_link(target))); + Some((object, link)) } /// An Office 2016 chart (`cx:chart`: waterfall, sunburst, box & whisker…) drawn from its @@ -323,7 +349,7 @@ impl Reader<'_> { } /// A `wpg:wgp` group (`w` × `h`): its pictures, shapes and text boxes, nested groups - /// flattened into it. `None` when it has no member we can show. + /// flattened into it unless they carry their own hyperlink. `None` when it has no member we can show. fn read_group(&mut self, sc: &mut StoryCtx, g: &El, rels: &Rels, w: f32, h: f32, mut float: Float) -> Option { let x = group_xfrm(g.child("wpg:grpSpPr")); float.set_spin(xfrm_spin(g.child("wpg:grpSpPr"))); @@ -336,7 +362,8 @@ impl Reader<'_> { let mut children = Vec::new(); let outer = self.group_fill.take(); self.group_fill = own_fill(g.child("wpg:grpSpPr"), &self.doc.settings.theme_colors, None).flatten(); - self.group_members(sc, g, rels, (-cx, -cy, 1.0, 1.0), 0, &mut children); + let mut remaining = craft_wordmodel::para::MAX_GROUP_CHILDREN; + self.group_members(sc, g, rels, (-cx, -cy, 1.0, 1.0), 0, (&mut children, &mut remaining)); self.group_fill = outer; if children.is_empty() { return None; @@ -362,7 +389,8 @@ impl Reader<'_> { stroke_width: ln.and_then(|l| l.attr("w")).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.0).clamp(0.0, 100.0), }; let mut children = Vec::new(); - self.group_members(sc, c, rels, (0.0, 0.0, 1.0, 1.0), 0, &mut children); + let mut remaining = craft_wordmodel::para::MAX_GROUP_CHILDREN; + self.group_members(sc, c, rels, (0.0, 0.0, 1.0, 1.0), 0, (&mut children, &mut remaining)); InlineObject::Group { w, h, float, ch_w: w.max(1.0), ch_h: h.max(1.0), children, canvas: Some(style) } } @@ -375,11 +403,12 @@ impl Reader<'_> { rels: &Rels, t: (f32, f32, f32, f32), depth: usize, - out: &mut Vec, + output: (&mut Vec, &mut usize), ) { + let (out, remaining) = output; let (x0, y0, sx, sy) = t; for e in g.els() { - if out.len() >= craft_wordmodel::para::MAX_GROUP_CHILDREN { + if *remaining == 0 { return; } // Native ink (`w14:contentPart`), alone or with a picture fallback: kept whole, in its @@ -412,33 +441,21 @@ impl Reader<'_> { "wpg:grpSp" | "wpg:wgp" => e.child("wpg:grpSpPr"), _ => continue, }; - let x = group_xfrm(sppr); - let ((ox, oy), (ew, eh)) = (x.off, x.ext); if e.name == "wpg:grpSp" || e.name == "wpg:wgp" { - if depth >= 8 { - continue; - } - // Its members' space maps onto its own box. - let (cox, coy) = x.ch_off.unwrap_or((0.0, 0.0)); - let (cw, ch) = x.ch_ext.filter(|(cw, ch)| *cw > 0.0 && *ch > 0.0).unwrap_or((ew.max(1.0), eh.max(1.0))); - let (kx, ky) = (ew / cw, eh / ch); - let nt = (x0 + (ox - cox * kx) * sx, y0 + (oy - coy * ky) * sy, sx * kx, sy * ky); - // Its own fill, for its members' `a:grpFill` (#1500). - // One without a fill of its own passes its group's on. - let own = own_fill(sppr, &self.doc.settings.theme_colors, self.group_fill.as_ref()).unwrap_or_else(|| self.group_fill.clone()); - let outer = std::mem::replace(&mut self.group_fill, own); - self.group_members(sc, e, rels, nt, depth + 1, out); - self.group_fill = outer; + self.group_member_group(sc, e, rels, t, depth, (&mut *out, &mut *remaining)); continue; } - let max = crate::units::MAX_LEN_PT; - let fit = |v: f32, lo: f32| craft_wordmodel::geom::finite(v).clamp(lo, max); - let (w, h) = (fit(ew * sx, 0.0), fit(eh * sy, 0.0)); + let x = group_xfrm(sppr); + let ((ox, oy), (ew, eh)) = (x.off, x.ext); let nv = match e.name.as_str() { - "pic:pic" => e.find("pic:cNvPr"), + "pic:pic" => e.child("pic:nvPicPr").and_then(|p| p.child("pic:cNvPr")), "w14:contentPart" => e.child("w14:nvContentPartPr").and_then(|p| p.child("w14:cNvPr")), _ => e.child("wps:cNvPr"), }; + let link = self.drawing_property_link(nv, rels); + let max = crate::units::MAX_LEN_PT; + let fit = |v: f32, lo: f32| craft_wordmodel::geom::finite(v).clamp(lo, max); + let (w, h) = (fit(ew * sx, 0.0), fit(eh * sy, 0.0)); let (alt, meta) = nv_alt(nv); let float = Float { alt: meta, hidden: nv.is_some_and(|p| on_off_attr(p, "hidden")), ..Float::default() }; let obj = if let Some((source, preview)) = ink { @@ -460,11 +477,65 @@ impl Reader<'_> { o }); if let Some(obj) = obj { - out.push(craft_wordmodel::para::GroupChild { x: fit(x0 + ox * sx, -max), y: fit(y0 + oy * sy, -max), obj }); + *remaining -= 1; + out.push(craft_wordmodel::para::GroupChild { x: fit(x0 + ox * sx, -max), y: fit(y0 + oy * sy, -max), obj, link }); } } } + /// Retain a linked nested group without turning the per-root limit into a per-level limit. + fn group_member_group( + &mut self, + sc: &mut StoryCtx, + e: &El, + rels: &Rels, + t: (f32, f32, f32, f32), + depth: usize, + output: (&mut Vec, &mut usize), + ) { + if depth >= 8 { + return; + } + let (out, remaining) = output; + let (x0, y0, sx, sy) = t; + let sppr = e.child("wpg:grpSpPr"); + let x = group_xfrm(sppr); + let ((ox, oy), (ew, eh)) = (x.off, x.ext); + let (cox, coy) = x.ch_off.unwrap_or((0.0, 0.0)); + let (cw, ch) = x.ch_ext.filter(|(cw, ch)| *cw > 0.0 && *ch > 0.0).unwrap_or((ew.max(1.0), eh.max(1.0))); + let nv = e.child("wpg:cNvPr"); + let link = self.drawing_property_link(nv, rels); + // A group's own fill supplies its members' grpFill, otherwise its parent's does. + let own = own_fill(sppr, &self.doc.settings.theme_colors, self.group_fill.as_ref()).unwrap_or_else(|| self.group_fill.clone()); + let outer = std::mem::replace(&mut self.group_fill, own); + if link.is_none() { + let (kx, ky) = (ew / cw, eh / ch); + let nt = (x0 + (ox - cox * kx) * sx, y0 + (oy - coy * ky) * sy, sx * kx, sy * ky); + self.group_members(sc, e, rels, nt, depth + 1, (out, remaining)); + } else { + *remaining -= 1; + let mut children = Vec::new(); + let max = crate::units::MAX_LEN_PT; + let fit = |v: f32, lo: f32| craft_wordmodel::geom::finite(v).clamp(lo, max); + let (w, h) = (fit(ew * sx, 0.0), fit(eh * sy, 0.0)); + // Store members in the group's displayed space. Clipping raw child coordinates + // before scaling would move a valid member with a large rebased offset. + let (kx, ky) = (w / cw, h / ch); + self.group_members(sc, e, rels, (-cox * kx, -coy * ky, kx, ky), depth + 1, (&mut children, &mut *remaining)); + if children.is_empty() { + *remaining += 1; + } else { + let (alt, meta) = nv_alt(nv); + let mut float = Float { alt: meta, hidden: nv.is_some_and(|p| on_off_attr(p, "hidden")), ..Float::default() }; + float.set_spin(xfrm_spin(sppr)); + let mut obj = InlineObject::Group { w, h, float, ch_w: w, ch_h: h, children, canvas: None }; + obj.set_alt_text(&alt); + out.push(craft_wordmodel::para::GroupChild { x: fit(x0 + ox * sx, -max), y: fit(y0 + oy * sy, -max), obj, link }); + } + } + self.group_fill = outer; + } + /// Build a shape from `wps:wsp`, using frame dimensions `w` and `h` in points and the caller's /// placement. Reads geometry, paint, effects and connector ends, and creates a text-box story /// when present within the nesting limit. Explicit outline caps are preserved; missing or diff --git a/crates/docx/src/read/story/runs.rs b/crates/docx/src/read/story/runs.rs index 0c8b699949..3d8e32cedc 100644 --- a/crates/docx/src/read/story/runs.rs +++ b/crates/docx/src/read/story/runs.rs @@ -32,6 +32,12 @@ impl Reader<'_> { if let Some(link) = link { c.link = Some(link); c.link_tooltip = k.attr("w:tooltip").and_then(crate::bounded_link_tooltip).map(std::sync::Arc::from); + // History on stays `None`: it is what the writer writes for a link with none. + c.link_history = match k.attr("w:history") { + Some(v) if crate::units::is_off_val(v) => Some(craft_wordmodel::props::LinkHistory::Off), + Some(_) => None, + None => Some(craft_wordmodel::props::LinkHistory::Omitted), + }; } self.read_inline_children(sc, pb, k, rels, &c, depth + 1); } @@ -138,6 +144,7 @@ impl Reader<'_> { let mut p = self.pc.rpr(rpr); p.link = ctx.link.clone(); p.link_tooltip = ctx.link_tooltip.clone(); + p.link_history = ctx.link_history; p.ins = ctx.ins; p.del = ctx.del; p.fmt_change = self.rpr_change(rpr); @@ -145,7 +152,14 @@ impl Reader<'_> { } fn run_props_none(&self, ctx: &RunCtx) -> CharProps { - CharProps { link: ctx.link.clone(), link_tooltip: ctx.link_tooltip.clone(), ins: ctx.ins, del: ctx.del, ..Default::default() } + CharProps { + link: ctx.link.clone(), + link_tooltip: ctx.link_tooltip.clone(), + link_history: ctx.link_history, + ins: ctx.ins, + del: ctx.del, + ..Default::default() + } } fn read_run(&mut self, sc: &mut StoryCtx, pb: &mut PB, r: &El, rels: &Rels, ctx: &RunCtx, depth: usize) { @@ -258,21 +272,23 @@ impl Reader<'_> { }, "w:drawing" => { if let Some(o) = self.read_drawing(sc, k, rels) { - self.emit_linked_obj(sc, pb, o, props, Self::drawing_link(k, rels)); + let link = self.drawing_link(k, rels); + self.emit_linked_obj(sc, pb, o, props, link); } } "w:pict" => { - if let Some(o) = self.read_signature_line(sc, k, rels) { - self.emit_obj(sc, pb, o, props); + if let Some((o, link)) = self.read_signature_line(sc, k, rels) { + self.emit_linked_obj(sc, pb, o, props, link); } else { - for o in self.read_vml_all(sc, k, rels) { - self.emit_obj(sc, pb, o, props); + for (o, target) in self.read_vml_all(sc, k, rels) { + let link = target.and_then(|target| self.keep_drawing_link(target)); + self.emit_linked_obj(sc, pb, o, props, link); } } } "w:object" => { - if let Some(o) = self.read_object(sc, k, rels) { - self.emit_obj(sc, pb, o, props); + if let Some((o, link)) = self.read_object(sc, k, rels) { + self.emit_linked_obj(sc, pb, o, props, link); } } "w:contentPart" => { @@ -354,7 +370,7 @@ impl Reader<'_> { let (base, base_props) = part("w:rubyBase"); let (ruby, ruby_props) = part("w:rt"); let mut bp = base_props.unwrap_or_default(); - (bp.link, bp.ins, bp.del) = (props.link.clone(), props.ins, props.del); + (bp.link, bp.link_history, bp.ins, bp.del) = (props.link.clone(), props.link_history, props.ins, props.del); if base.is_empty() { return; } diff --git a/crates/docx/src/read/story/vml.rs b/crates/docx/src/read/story/vml.rs index 4fd74b2c92..44f6769bca 100644 --- a/crates/docx/src/read/story/vml.rs +++ b/crates/docx/src/read/story/vml.rs @@ -10,14 +10,80 @@ struct VmlGroupSpace { depth: usize, } +/// Borrowed templates for one picture. Build once so repeated missing IDs do not +/// rescan the picture's groups. Direct definitions keep their existing priority. +struct VmlLinks<'a> { + pict: &'a El, + templates: std::collections::HashMap<&'a str, Option<&'a str>>, + member_links: bool, +} + +impl<'a> VmlLinks<'a> { + fn new(pict: &'a El, member_links: bool) -> Self { + let mut links = Self { pict, templates: Default::default(), member_links }; + links.definitions(pict); + for group in pict.els().filter(|e| e.name == "v:group") { + links.group(group, 0); + } + links + } + + fn definitions(&mut self, parent: &'a El) { + for template in parent.els().filter(|e| e.name == "v:shapetype") { + if let Some(id) = template.attr("id") { + self.templates.entry(id).or_insert_with(|| template.attr("href")); + } + } + } + + fn group(&mut self, group: &'a El, depth: usize) { + self.definitions(group); + if depth < MAX_VML_GROUP_DEPTH { + for nested in group.els().filter(|e| e.name == "v:group") { + self.group(nested, depth + 1); + } + } + } + + fn target(&self, shape: &'a El) -> Option<&'a str> { + shape + .attr("href") + .or_else(|| { + let id = shape.attr("type")?.trim().trim_start_matches('#'); + self.templates.get(id).copied().flatten() + }) + .map(str::trim) + .filter(|target| !target.is_empty()) + } + + fn keep(&self, reader: &mut Reader<'_>, shape: &'a El) -> Option { + if !self.member_links { + return None; + } + self.target(shape).and_then(|target| reader.keep_drawing_link(target)) + } +} + impl Reader<'_> { /// Every legacy VML drawing in one `w:pict`, in document order: a `w:pict` may hold any /// number of shapes (ECMA-376 Part 4, VML), and each one is its own object. A `v:group` /// becomes an [`InlineObject::Group`]. - pub(super) fn read_vml_all(&mut self, sc: &mut StoryCtx, pict: &El, rels: &Rels) -> Vec { + pub(super) fn read_vml_all<'a>(&mut self, sc: &mut StoryCtx, pict: &'a El, rels: &Rels) -> Vec<(InlineObject, Option<&'a str>)> { + self.vml_objects(sc, pict, rels, craft_wordmodel::para::MAX_GROUP_CHILDREN, true) + } + + fn vml_objects<'a>( + &mut self, + sc: &mut StoryCtx, + pict: &'a El, + rels: &Rels, + limit: usize, + member_links: bool, + ) -> Vec<(InlineObject, Option<&'a str>)> { + let links = VmlLinks::new(pict, member_links); let mut out = Vec::new(); for e in pict.els().filter(|e| e.name.starts_with("v:") && e.local() != "shapetype") { - if out.len() >= craft_wordmodel::para::MAX_GROUP_CHILDREN { + if out.len() >= limit { break; } if sc.in_hf @@ -28,23 +94,29 @@ impl Reader<'_> { self.doc.settings.watermark.get_or_insert(wm); continue; } - let o = if e.local() == "group" { self.read_vml_group(sc, pict, e, rels) } else { self.read_vml_shape(sc, pict, e, rels, None) }; - out.extend(o); + let o = if e.local() == "group" { self.read_vml_group(sc, &links, e, rels) } else { self.read_vml_shape(sc, pict, e, rels, None) }; + out.extend(o.map(|o| (o, links.target(e)))); } out } - /// The first VML drawing in `pict`, for the places that show a single one: an OLE object's - /// picture and a `mc:Fallback` preview. - pub(super) fn read_vml(&mut self, sc: &mut StoryCtx, pict: &El, rels: &Rels) -> Option { - self.read_vml_all(sc, pict, rels).into_iter().next() + /// The first VML drawing and its own target in `pict`, for an OLE object's + /// picture and a selected `mc:Fallback` preview. + pub(super) fn read_vml<'a>(&mut self, sc: &mut StoryCtx, pict: &'a El, rels: &Rels) -> Option<(InlineObject, Option<&'a str>)> { + self.vml_objects(sc, pict, rels, 1, true).into_iter().next() + } + + /// A native ink preview needs its media and root target, not member targets + /// belonging to a group the ink renderer will not retain. + pub(super) fn read_vml_preview<'a>(&mut self, sc: &mut StoryCtx, pict: &'a El, rels: &Rels) -> Option<(InlineObject, Option<&'a str>)> { + self.vml_objects(sc, pict, rels, 1, false).into_iter().next() } /// A `v:group`: its own box from its `style`, its members in the space `coordsize` and - /// `coordorigin` give it, nested groups flattened into it as [`Self::group_members`] does for - /// DrawingML. `None` when it has no member we can show. `pict` is the picture the group sits + /// `coordorigin` give it. Unlinked nested groups are flattened; a linked group keeps its + /// own node and target, as in DrawingML. `None` when it has no member we can show. `pict` is the picture the group sits /// in, where a member's `v:shapetype` is written. - fn read_vml_group(&mut self, sc: &mut StoryCtx, pict: &El, grp: &El, rels: &Rels) -> Option { + fn read_vml_group<'a>(&mut self, sc: &mut StoryCtx, links: &VmlLinks<'a>, grp: &'a El, rels: &Rels) -> Option { let style = grp.attr("style").unwrap_or(""); let len = |k: &str| vml_style(style, k).and_then(|v| measure(v, 1.0)).unwrap_or(0.0).clamp(0.0, crate::units::MAX_LEN_PT); let (w, h) = (len("width"), len("height")); @@ -53,7 +125,15 @@ impl Reader<'_> { let (ch_w, ch_h) = vml_coordpair(grp, "coordsize").filter(|(cw, ch)| *cw > 0.0 && *ch > 0.0).unwrap_or((w.max(1.0), h.max(1.0))); let (cx, cy) = vml_coordpair(grp, "coordorigin").unwrap_or((0.0, 0.0)); let mut children = Vec::new(); - self.vml_group_members(sc, pict, grp, rels, VmlGroupSpace { origin: (-cx, -cy), scale: (1.0, 1.0), depth: 0 }, &mut children); + let mut remaining = craft_wordmodel::para::MAX_GROUP_CHILDREN; + self.vml_group_members( + sc, + links, + grp, + rels, + VmlGroupSpace { origin: (-cx, -cy), scale: (1.0, 1.0), depth: 0 }, + (&mut children, &mut remaining), + ); if children.is_empty() { return None; } @@ -63,42 +143,36 @@ impl Reader<'_> { /// The members of VML group `g` into `out`, mapped into the outermost group's space by `t` /// (x0, y0, sx, sy: outer = x0 + inner × sx). A member is placed by `left`/`top` in that /// space, except a `v:line`, which carries its own offset in `from`. - fn vml_group_members( + fn vml_group_members<'a>( &mut self, sc: &mut StoryCtx, - pict: &El, - g: &El, + links: &VmlLinks<'a>, + g: &'a El, rels: &Rels, space: VmlGroupSpace, - out: &mut Vec, + output: (&mut Vec, &mut usize), ) { + let (out, remaining) = output; let (x0, y0) = space.origin; let (sx, sy) = space.scale; let max = crate::units::MAX_LEN_PT; let fit = |v: f32, lo: f32| craft_wordmodel::geom::finite(v).clamp(lo, max); for e in g.els() { - if out.len() >= craft_wordmodel::para::MAX_GROUP_CHILDREN { + if *remaining == 0 { return; } if !e.name.starts_with("v:") || e.local() == "shapetype" { continue; } - let style = e.attr("style").unwrap_or(""); - let num = |k: &str| vml_style(style, k).and_then(|v| measure(v, 1.0)).map_or(0.0, craft_wordmodel::geom::finite); - let ((ox, oy), (ew, eh)) = ((num("left"), num("top")), (num("width"), num("height"))); if e.local() == "group" { - if space.depth >= MAX_VML_GROUP_DEPTH { - continue; - } - // Its members' space maps onto its own box. - let (cw, ch) = vml_coordpair(e, "coordsize").filter(|(cw, ch)| *cw > 0.0 && *ch > 0.0).unwrap_or((ew.max(1.0), eh.max(1.0))); - let (cox, coy) = vml_coordpair(e, "coordorigin").unwrap_or((0.0, 0.0)); - let (kx, ky) = (ew / cw, eh / ch); - let nt = (x0 + (ox - cox * kx) * sx, y0 + (oy - coy * ky) * sy, sx * kx, sy * ky); - self.vml_group_members(sc, pict, e, rels, VmlGroupSpace { origin: (nt.0, nt.1), scale: (nt.2, nt.3), depth: space.depth + 1 }, out); + self.vml_group_member(sc, links, e, rels, space, (&mut *out, &mut *remaining)); continue; } - let Some(mut obj) = self.read_vml_shape(sc, pict, e, rels, Some((sx, sy))) else { continue }; + let style = e.attr("style").unwrap_or(""); + let num = |k: &str| vml_style(style, k).and_then(|v| measure(v, 1.0)).map_or(0.0, craft_wordmodel::geom::finite); + let (ox, oy) = (num("left"), num("top")); + let link = links.keep(self, e); + let Some(mut obj) = self.read_vml_shape(sc, links.pict, e, rels, Some((sx, sy))) else { continue }; // A member is placed by `x`/`y`, so a line's own offset comes off the member itself. let (dx, dy) = match obj.float_mut() { Some(f) => { @@ -108,10 +182,71 @@ impl Reader<'_> { } None => (0.0, 0.0), }; - out.push(craft_wordmodel::para::GroupChild { x: fit(x0 + (ox + dx) * sx, -max), y: fit(y0 + (oy + dy) * sy, -max), obj }); + *remaining -= 1; + out.push(craft_wordmodel::para::GroupChild { x: fit(x0 + (ox + dx) * sx, -max), y: fit(y0 + (oy + dy) * sy, -max), obj, link }); } } + /// An inner group shares its root's retained-member budget. Only a group with its + /// own target needs a node; unlinked groups keep the established flattening path. + fn vml_group_member<'a>( + &mut self, + sc: &mut StoryCtx, + links: &VmlLinks<'a>, + e: &'a El, + rels: &Rels, + space: VmlGroupSpace, + output: (&mut Vec, &mut usize), + ) { + if space.depth >= MAX_VML_GROUP_DEPTH { + return; + } + let (out, remaining) = output; + let (x0, y0) = space.origin; + let (sx, sy) = space.scale; + let style = e.attr("style").unwrap_or(""); + let num = |k: &str| vml_style(style, k).and_then(|v| measure(v, 1.0)).map_or(0.0, craft_wordmodel::geom::finite); + let ((ox, oy), (ew, eh)) = ((num("left"), num("top")), (num("width"), num("height"))); + let (cw, ch) = vml_coordpair(e, "coordsize").filter(|(cw, ch)| *cw > 0.0 && *ch > 0.0).unwrap_or((ew.max(1.0), eh.max(1.0))); + let (cox, coy) = vml_coordpair(e, "coordorigin").unwrap_or((0.0, 0.0)); + let link = links.keep(self, e); + if link.is_none() { + let (kx, ky) = (ew / cw, eh / ch); + let nt = (x0 + (ox - cox * kx) * sx, y0 + (oy - coy * ky) * sy, sx * kx, sy * ky); + self.vml_group_members( + sc, + links, + e, + rels, + VmlGroupSpace { origin: (nt.0, nt.1), scale: (nt.2, nt.3), depth: space.depth + 1 }, + (out, remaining), + ); + return; + } + *remaining -= 1; + let mut children = Vec::new(); + let max = crate::units::MAX_LEN_PT; + let fit = |v: f32, lo: f32| craft_wordmodel::geom::finite(v).clamp(lo, max); + let (w, h) = (fit(ew * sx, 0.0), fit(eh * sy, 0.0)); + let (kx, ky) = (w / cw, h / ch); + self.vml_group_members( + sc, + links, + e, + rels, + VmlGroupSpace { origin: (-cox * kx, -coy * ky), scale: (kx, ky), depth: space.depth + 1 }, + (&mut children, &mut *remaining), + ); + if children.is_empty() { + *remaining += 1; + return; + } + let mut float = vml_float(e, style, sc.in_hf); + (float.x, float.y) = (0.0, 0.0); + let obj = InlineObject::Group { w, h, float, ch_w: w, ch_h: h, children, canvas: None }; + out.push(craft_wordmodel::para::GroupChild { x: fit(x0 + ox * sx, -max), y: fit(y0 + oy * sy, -max), obj, link }); + } + /// One legacy VML picture, text box, line, rectangle, oval or preset shape (best effort). /// `pict` is the picture it sits in, where its `v:shapetype` is written -- for a group's /// member too, since Word writes each shapetype once, beside the group rather than inside @@ -395,25 +530,25 @@ impl Reader<'_> { /// An OLE object (`w:object`, ECMA-376 §17.3.3.19): shown as its picture (VML, or a DrawingML /// picture in `w:drawing`), and kept whole so saving writes the object back. - pub(super) fn read_object(&mut self, sc: &mut StoryCtx, obj: &El, rels: &Rels) -> Option { - let mut o = match self.read_vml(sc, obj, rels) { - Some(o) => o, + pub(super) fn read_object(&mut self, sc: &mut StoryCtx, obj: &El, rels: &Rels) -> Option<(InlineObject, Option)> { + let (mut o, link) = match self.read_vml(sc, obj, rels) { + Some((object, target)) => (object, target.and_then(|target| self.keep_drawing_link(target))), None => { let d = obj.child("w:drawing")?; - self.read_drawing(sc, d, rels)? + (self.read_drawing(sc, d, rels)?, self.drawing_link(d, rels)) } }; if let InlineObject::Image { ole, .. } = &mut o { *ole = self.keep_embedded(obj, rels, &[]); } - Some(o) + Some((o, link)) } /// A Word signature line (Insert › Signature Line): a `w:pict` whose one VML picture carries /// an `o:signatureline` (the suggested signer, title, e-mail and instructions). Shown as its /// picture, and kept whole like an OLE object so saving writes the signature line back, /// still signable in Word, not a plain picture. `None` for any other `w:pict`. - pub(super) fn read_signature_line(&mut self, sc: &mut StoryCtx, pict: &El, rels: &Rels) -> Option { + pub(super) fn read_signature_line(&mut self, sc: &mut StoryCtx, pict: &El, rels: &Rels) -> Option<(InlineObject, Option)> { let mut drawings = pict.els().filter(|e| e.name.starts_with("v:") && e.local() != "shapetype"); let shape = drawings.next().filter(|s| s.name == "v:shape")?; if drawings.next().is_some() || shape.child("o:signatureline").is_none() { @@ -423,7 +558,7 @@ impl Reader<'_> { if let InlineObject::Image { ole, .. } = &mut o { *ole = self.keep_embedded(pict, rels, &[]); } - Some(o) + Some((o, VmlLinks::new(pict, true).target(shape).and_then(|target| self.keep_drawing_link(target)))) } } diff --git a/crates/docx/src/units.rs b/crates/docx/src/units.rs index 295fe76215..cefd1977c7 100644 --- a/crates/docx/src/units.rs +++ b/crates/docx/src/units.rs @@ -141,11 +141,16 @@ pub fn tw_u16(e: &El, attr: &str) -> Option { } } +/// Return whether an XML attribute value for an `ST_OnOff` represents "off" / false. +pub fn is_off_val(v: &str) -> bool { + matches!(v.trim(), "0" | "false" | "off" | "False" | "FALSE") +} + /// ST_OnOff: absent `w:val` = on; `0`, `false`, `off` = off. pub fn on_off(e: &El) -> bool { match e.attr("w:val") { None => true, - Some(v) => !matches!(v.trim(), "0" | "false" | "off" | "False" | "FALSE"), + Some(v) => !is_off_val(v), } } diff --git a/crates/docx/src/write/settings.rs b/crates/docx/src/write/settings.rs index a76ded663a..9080ce32af 100644 --- a/crates/docx/src/write/settings.rs +++ b/crates/docx/src/write/settings.rs @@ -151,6 +151,13 @@ fn write_note_settings( } fn write_compatibility_settings(w: &mut W, doc: &Document) { + let has_compat = doc.settings.do_not_expand_shift_return + || doc.settings.sum_paragraph_spacing + || doc.settings.allow_space_of_same_style_in_table + || doc.settings.compat_mode.is_some(); + if !has_compat { + return; + } w.open("w:compat", &[]); // CT_Compat: the older switches come before the `w:compatSetting`s. if doc.settings.do_not_expand_shift_return { @@ -162,8 +169,10 @@ fn write_compatibility_settings(w: &mut W, doc: &Document) { if doc.settings.allow_space_of_same_style_in_table { w.empty("w:allowSpaceOfSameStyleInTable", &[]); } - let mode = doc.settings.compat_mode.clamp(11, 15).to_string(); - w.empty("w:compatSetting", &[("w:name", "compatibilityMode"), ("w:uri", "http://schemas.microsoft.com/office/word"), ("w:val", &mode)]); + if let Some(mode) = doc.settings.compat_mode { + let mode = mode.clamp(11, 15).to_string(); + w.empty("w:compatSetting", &[("w:name", "compatibilityMode"), ("w:uri", "http://schemas.microsoft.com/office/word"), ("w:val", &mode)]); + } w.close("w:compat"); } diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index ac673c63ad..323e9b7cfa 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -8,7 +8,8 @@ //! tag (namespace declarations, `mc:Ignorable`) and every child the model doesn't own are kept //! byte for byte; owned children come from the generated part (or go, when the model turned //! them off); owned children the original lacks are inserted at their CT_Settings position; in -//! `w:compat` only the `compatibilityMode` setting is replaced. Kept children that refer to a +//! `w:compat` only the switches the model writes and the `compatibilityMode` setting come from the +//! generated part, and a block left empty goes. Kept children that refer to a //! relationship are dropped unless owned: mail merge is regenerated with remapped external //! sources by `mail_merge`. Anything unexpected returns `None`, and the generated part is written as before. @@ -232,29 +233,125 @@ fn children(xml: &str, root: &str) -> Option<(usize, usize, Vec)> { Some((open_end, close, out)) } -/// The original `w:compat` with its `compatibilityMode` taken from the generated one. +/// The `w:compat` switches the model writes (`super::settings`). +const OWNED_COMPAT_SWITCHES: &[&str] = &["w:doNotExpandShiftReturn", "w:doNotUseHTMLParagraphAutoSpacing", "w:allowSpaceOfSameStyleInTable"]; + +/// CT_Compat's sequence (ECMA-376 §17.15.3.9), for placing inserted switches. +const CT_COMPAT_ORDER: &[&str] = &[ + "useSingleBorderforContiguousCells", + "wpJustification", + "noTabHangInd", + "noLeading", + "spaceForUL", + "noColumnBalance", + "balanceSingleByteDoubleByteWidth", + "noExtraLineSpacing", + "doNotLeaveBackslashAlone", + "ulTrailSpace", + "doNotExpandShiftReturn", + "spacingInWholePoints", + "lineWrapLikeWord6", + "printBodyTextBeforeHeader", + "printColBlack", + "wpSpaceWidth", + "showBreaksInFrames", + "subFontBySize", + "suppressBottomSpacing", + "suppressTopSpacing", + "suppressSpacingAtTopOfPage", + "suppressTopSpacingWP", + "suppressSpBfAfterPgBrk", + "swapBordersFacingPages", + "convMailMergeEsc", + "truncateFontHeightsLikeWP6", + "mwSmallCaps", + "usePrinterMetrics", + "doNotSuppressParagraphBorders", + "wrapTrailSpaces", + "footnoteLayoutLikeWW8", + "shapeLayoutLikeWW8", + "alignTablesRowByRow", + "forgetLastTabAlignment", + "adjustLineHeightInTable", + "autoSpaceLikeWord95", + "noSpaceRaiseLower", + "doNotUseHTMLParagraphAutoSpacing", + "layoutRawTableWidth", + "layoutTableRowsApart", + "useWord97LineBreakRules", + "doNotBreakWrappedTables", + "doNotSnapToGridInCell", + "selectFldWithFirstOrLastChar", + "applyBreakingRules", + "doNotWrapTextWithPunct", + "doNotUseEastAsianBreakRules", + "useWord2002TableStyleRules", + "growAutofit", + "useFELayout", + "useNormalStyleForList", + "doNotUseIndentAsNumberingTabStop", + "useAltKinsokuLineBreakRules", + "allowSpaceOfSameStyleInTable", + "doNotSuppressIndentation", + "doNotAutofitConstrainedTables", + "autofitToFirstFixedWidthCell", + "underlineTabInNumList", + "displayHangulFixedWidth", + "splitPgBreakAndParaMark", + "doNotVertAlignCellWithSp", + "doNotBreakConstrainedForcedTable", + "doNotVertAlignInTxbx", + "useAnsiKerningPairs", + "cachedColBalance", + "compatSetting", +]; + +/// Position of a `w:`-prefixed `w:compat` child in [`CT_COMPAT_ORDER`]; `None` for anything else. +fn compat_rank(name: &str) -> Option { + let local = name.strip_prefix("w:")?; + CT_COMPAT_ORDER.iter().position(|n| *n == local) +} + +/// Is this `w:compat` child Word's `compatibilityMode` setting? +fn is_compat_mode(child: &str) -> bool { + let mut reader = quick_xml::Reader::from_str(child); + let Ok(quick_xml::events::Event::Start(e) | quick_xml::events::Event::Empty(e)) = reader.read_event() else { return false }; + e.name().as_ref() == b"w:compatSetting" + && e.attributes().with_checks(false).flatten().any(|a| a.key.as_ref() == b"w:name" && a.value.as_ref() == b"compatibilityMode") +} + +/// The original `w:compat` with what the model owns in it taken from the generated one (`""` +/// when the model writes none): its switches, and the `compatibilityMode` setting. A block left +/// without children goes (`""`). fn merge_compat(orig: &str, generated: &str) -> Option { - let mode = |s: &str| -> Option<(usize, usize)> { - let at = s.find("w:name=\"compatibilityMode\"")?; - let tag_start = s.get(..at)?.rfind('<')?; - let tag_end = tag_start + s.get(tag_start..)?.find('>')? + 1; - Some((tag_start, tag_end)) + let g_kids = children(generated, "w:compat").map(|(_, _, kids)| kids).unwrap_or_default(); + let g_child = |pred: &dyn Fn(&Child, &str) -> bool| g_kids.iter().find_map(|k| generated.get(k.start..k.end).filter(|text| pred(k, text))); + let mut out = match orig.strip_suffix("/>") { + Some(open) => format!("{}>", open.trim_end()), + None => orig.to_string(), }; - match (mode(orig), mode(generated)) { - (Some((a, b)), Some((c, d))) => Some(format!("{}{}{}", orig.get(..a)?, generated.get(c..d)?, orig.get(b..)?)), - (None, Some((c, d))) => { - // No mode in the original: add the generated one before ``, or expand a self-closing ``. - if let Some(close) = orig.rfind("") { - Some(format!("{}{}{}", orig.get(..close)?, generated.get(c..d)?, orig.get(close..)?)) - } else if let Some(slash) = orig.rfind("/>") { - let open = orig.get(..slash)?.trim_end(); - Some(format!("{open}>{}", generated.get(c..d)?)) - } else { - None - } + for sw in OWNED_COMPAT_SWITCHES { + let (_, _, kids) = children(&out, "w:compat")?; + for k in kids.iter().rev().filter(|k| k.name == *sw) { + out.replace_range(k.start..k.end, ""); + } + if let Some(g) = g_child(&|k, _| k.name == *sw) { + let (_, close, kids) = children(&out, "w:compat")?; + let rank = compat_rank(sw); + let at = kids.iter().find(|k| compat_rank(&k.name) > rank).map_or(close, |k| k.start); + out.insert_str(at, g); } - _ => Some(orig.to_string()), } + let (_, close, kids) = children(&out, "w:compat")?; + let o_mode = kids.iter().find(|k| out.get(k.start..k.end).is_some_and(is_compat_mode)).map(|k| k.start..k.end); + match (o_mode, g_child(&|_, text| is_compat_mode(text))) { + (Some(span), Some(g)) => out.replace_range(span, g), + (Some(span), None) => out.replace_range(span, ""), + (None, Some(g)) => out.insert_str(close, g), + (None, None) => {} + } + let (_, _, kids) = children(&out, "w:compat")?; + Some(if kids.is_empty() { String::new() } else { out }) } /// Does `original` (a settings part) hold anything the model doesn't write? Then the reader keeps @@ -358,11 +455,11 @@ pub fn merge(original: &[u8], generated: &[u8]) -> Option> { out.push((k.name.clone(), g_text(g_kids.get(gi)?)?)); } } else if k.name == "w:compat" { - let merged = match mark("w:compat", &mut used) { - Some(gi) => merge_compat(text, &g_text(g_kids.get(gi)?)?)?, - None => text.to_string(), - }; - out.push((k.name.clone(), merged)); + let g_compat = mark("w:compat", &mut used).and_then(|gi| g_text(g_kids.get(gi)?)); + let merged = merge_compat(text, g_compat.as_deref().unwrap_or(""))?; + if !merged.is_empty() { + out.push((k.name.clone(), merged)); + } } else if !text.contains("r:id=") { out.push((k.name.clone(), text.to_string())); } @@ -475,4 +572,95 @@ mod tests { // A file whose only extra setting is this one has nothing foreign to keep. assert!(!has_unowned(br#""#)); } + + #[test] + fn compatibility_mode_removal_handles_paired_tags_quotes_and_whitespace() { + let gen_no_mode = r#""#; + + // Paired tag with closing + let orig_paired = r#""#; + assert!(has_unowned(orig_paired.as_bytes())); + let out_paired = String::from_utf8(merge(orig_paired.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out_paired.contains("compatibilityMode"), "{out_paired}"); + assert!(!out_paired.contains(""), "{out_paired}"); + assert!(out_paired.contains("overrideTableStyleFontSizeAndJustification"), "{out_paired}"); + + // Single quotes + let orig_single_quotes = r#""#; + let out_sq = String::from_utf8(merge(orig_single_quotes.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out_sq.contains("compatibilityMode"), "{out_sq}"); + assert!(out_sq.contains("overrideTableStyleFontSizeAndJustification"), "{out_sq}"); + + // Whitespace around equals + let orig_spaces = r#""#; + let out_sp = String::from_utf8(merge(orig_spaces.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out_sp.contains("compatibilityMode"), "{out_sp}"); + assert!(out_sp.contains("overrideTableStyleFontSizeAndJustification"), "{out_sp}"); + + // Foreign vendor compatSetting element is preserved + let orig_foreign = r#""#; + let gen_foreign = + r#""#; + let out_foreign = String::from_utf8(merge(orig_foreign.as_bytes(), gen_foreign.as_bytes()).unwrap()).unwrap(); + assert!(out_foreign.contains("x:compatSetting"), "{out_foreign}"); + assert!(!out_foreign.contains(r#"w:name="compatibilityMode""#), "{out_foreign}"); + } + + #[test] + fn repeated_compat_switches_are_all_removed_when_disabled_and_deduplicated_when_enabled() { + let orig_two = r#""#; + // Disabled in generated: both must be removed + let gen_disabled = + r#""#; + let out_disabled = String::from_utf8(merge(orig_two.as_bytes(), gen_disabled.as_bytes()).unwrap()).unwrap(); + assert!(!out_disabled.contains("doNotExpandShiftReturn"), "{out_disabled}"); + assert!(out_disabled.contains(""), "{out_disabled}"); + + // Enabled in generated: exactly one occurrence emitted + let gen_enabled = r#""#; + let out_enabled = String::from_utf8(merge(orig_two.as_bytes(), gen_enabled.as_bytes()).unwrap()).unwrap(); + assert_eq!(out_enabled.matches("doNotExpandShiftReturn").count(), 1, "{out_enabled}"); + assert!(out_enabled.contains(""), "{out_enabled}"); + } + + #[test] + fn new_compat_switches_are_inserted_in_schema_order() { + // spacingInWholePoints is ranked after doNotExpandShiftReturn in CT_Compat + let orig = r#""#; + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + let idx_shift = merged.find("").unwrap(); + let idx_spacing = merged.find("").unwrap(); + assert!(idx_shift < idx_spacing, "doNotExpandShiftReturn must precede spacingInWholePoints: {merged}"); + } + + #[test] + fn foreign_child_is_ignored_when_finding_switch_insertion_point() { + // x:spacingInWholePoints precedes w:ulTrailSpace + let orig = r#""#; + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + let idx_custom = merged.find("").unwrap(); + let idx_trail = merged.find("").unwrap(); + let idx_shift = merged.find("").unwrap(); + let idx_spacing = merged.find("").unwrap(); + assert!(idx_custom < idx_trail, "custom before trail: {merged}"); + assert!(idx_trail < idx_shift, "trail before shift: {merged}"); + assert!(idx_shift < idx_spacing, "shift before spacing: {merged}"); + } + + #[test] + fn a_bare_self_closing_compat_block_goes_like_an_empty_paired_one() { + let gen_xml = r#""#; + let merged_with = |compat: &str| { + let orig = format!( + r#"{compat}"# + ); + String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap() + }; + let self_closing = merged_with(""); + assert!(!self_closing.contains("compat"), "{self_closing}"); + assert!(self_closing.contains(r#""#), "{self_closing}"); + assert_eq!(self_closing, merged_with("")); + } } diff --git a/crates/docx/src/write/story/drawing.rs b/crates/docx/src/write/story/drawing.rs index 507e02b7c1..8216e774f0 100644 --- a/crates/docx/src/write/story/drawing.rs +++ b/crates/docx/src/write/story/drawing.rs @@ -14,6 +14,14 @@ pub(super) struct DrawingInfo<'a> { pub link: Option<&'a str>, } +/// The non-visual identity, placement and hyperlink relationship of one group member. +/// Top-level objects keep their link on `wp:docPr` instead. +pub(super) struct MemberInfo<'a> { + pub id: Option<&'a str>, + pub off: (f32, f32), + pub link: Option<&'a str>, +} + impl Writer<'_> { /// The relationship of the hyperlink a drawing in a run with `props` carries on itself, as /// Word writes a picture's link (`wp:docPr/a:hlinkClick`, #5267): a web or file address. A @@ -24,13 +32,13 @@ impl Writer<'_> { } /// A picture's `pic:pic` (the image in `media/{file}`), at `off` in its group (or 0, 0). - pub(super) fn pic(&mut self, w: &mut W, o: &InlineObject, file: &str, off: (f32, f32), rels: &mut PartRels) { + pub(super) fn pic(&mut self, w: &mut W, o: &InlineObject, file: &str, member: MemberInfo<'_>, rels: &mut PartRels) { let InlineObject::Image { media, w: iw, h: ih, alt, crop, float, fx, .. } = o else { return }; let rid = rels.add(rt::IMAGE, &format!("media/{file}"), false); self.used_media.insert(media.clone()); w.open("pic:pic", &[]); w.open("pic:nvPicPr", &[]); - nv_props(w, "pic:cNvPr", ("0", file), alt, &float.alt, float.hidden, None); + nv_props(w, "pic:cNvPr", (member.id.unwrap_or("0"), file), alt, &float.alt, float.hidden, member.link); w.open("pic:cNvPicPr", &[]); w.empty("a:picLocks", &[("noChangeAspect", "1"), ("noChangeArrowheads", "1")]); w.close("pic:cNvPicPr"); @@ -60,7 +68,7 @@ impl Writer<'_> { w.close("a:stretch"); w.close("pic:blipFill"); w.open("pic:spPr", &[("bwMode", "auto")]); - xfrm(w, off, *iw, *ih, float.spin()); + xfrm(w, member.off, *iw, *ih, float.spin()); w.open("a:prstGeom", &[("prst", "rect")]); w.empty("a:avLst", &[]); w.close("a:prstGeom"); @@ -80,17 +88,16 @@ impl Writer<'_> { &mut self, w: &mut W, o: &InlineObject, - id: Option<&str>, - off: (f32, f32), + member: MemberInfo<'_>, 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 { + if let Some(id) = member.id { let name = shape_name(*kind, freeform.as_deref(), id); - nv_props(w, "wps:cNvPr", (id, &name), &float.alt.text, &float.alt, float.hidden, None); + nv_props(w, "wps:cNvPr", (id, &name), &float.alt.text, &float.alt, float.hidden, member.link); } if kind.is_connector() { // A connector's glued ends (ECMA-376 §20.1.2.2.8 `cNvCxnSpPr`). @@ -112,7 +119,7 @@ impl Writer<'_> { w.empty("wps:cNvSpPr", &[]); } w.open("wps:spPr", &[]); - xfrm(w, off, *sw, *sh, float.spin()); + xfrm(w, member.off, *sw, *sh, float.spin()); let prst = match kind { ShapeKind::Rectangle | ShapeKind::TextBox | ShapeKind::Freeform => "rect", ShapeKind::RoundedRectangle => "roundRect", diff --git a/crates/docx/src/write/story/object.rs b/crates/docx/src/write/story/object.rs index 3a42a8b044..17bde48e2f 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::drawing::{DrawingInfo, MemberInfo, nv_props, shape_name, spin_attrs, write_fill, xfrm_spin_only}; use super::field::{FieldData, field_run}; use super::section::comment_reference_style; -use super::{Anchor, CharProps, Fill, Float, InlineObject, NoteKind, PartRels, ShapeKind, TextColor, W, Wrap, Writer, emu, n, rpr}; +use super::{Anchor, CharProps, Fill, Float, InlineObject, MAX_DEPTH, NoteKind, PartRels, ShapeKind, TextColor, W, Wrap, Writer, emu, n, rpr, rt}; impl Writer<'_> { /// Write an inline object (`Bookmark`, `Comment`, `Equation`, `Field`, `Shape`, etc.). @@ -284,7 +284,7 @@ impl Writer<'_> { w.empty("wp:cNvGraphicFramePr", &[]); w.open("a:graphic", &[]); w.open("a:graphicData", &[("uri", "http://schemas.openxmlformats.org/drawingml/2006/picture")]); - self.pic(w, o, &file, (0.0, 0.0), rels); + self.pic(w, o, &file, MemberInfo { id: None, off: (0.0, 0.0), link: None }, rels); w.close("a:graphicData"); w.close("a:graphic"); w.close(if float.wrap == Wrap::Inline { "wp:inline" } else { "wp:anchor" }); @@ -404,7 +404,7 @@ impl Writer<'_> { w.empty("wp:cNvGraphicFramePr", &[]); w.open("a:graphic", &[]); w.open("a:graphicData", &[("uri", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape")]); - let content = self.wsp(w, o, None, (0.0, 0.0), rels, depth); + let content = self.wsp(w, o, MemberInfo { id: None, off: (0.0, 0.0), link: None }, rels, depth); w.close("a:graphicData"); w.close("a:graphic"); w.close(if float.wrap == Wrap::Inline { "wp:inline" } else { "wp:anchor" }); @@ -605,30 +605,8 @@ impl Writer<'_> { "wpg:wgp" } }; - for c in children.iter().take(craft_wordmodel::para::MAX_GROUP_CHILDREN) { - let at = (c.x, c.y); - match &c.obj { - InlineObject::Image { media, .. } => { - if let Some(file) = self.media_files.get(media).cloned() { - self.pic(w, &c.obj, &file, at, rels); - } - } - InlineObject::Shape { extra, .. } => { - let id = self.shape_docpr(extra.id); - self.wsp(w, &c.obj, Some(&id), at, rels, depth); - } - // Native ink kept from the file, with its fallback, at the member's place. - InlineObject::Graphic { w: iw, h: ih, float, graphic, .. } if graphic.kind == craft_wordmodel::graphic::GraphicKind::Ink => { - if let Some(src) = graphic.source.as_deref() - && let Some(mut root) = self.embedded_tree(src, rels, None) - { - Self::place_member(&mut root, [c.x, c.y, *iw, *ih], float, 0); - w.raw(&root.to_xml()); - } - } - _ => {} - } - } + let mut remaining = craft_wordmodel::para::MAX_GROUP_CHILDREN; + self.write_group_members(w, children, rels, depth, &mut remaining); if canvas.is_some() && float.spin() != craft_wordmodel::geom::Spin::default() { // The canvas schema has no transform of its own: keep its turn in our // extension (Word draws it unturned, as it can't turn a canvas). @@ -646,6 +624,84 @@ impl Writer<'_> { w.close("w:r"); self.rev_close(w, props); } + /// Members share one finite budget across the whole recursive group, not one per level. + fn write_group_members( + &mut self, + w: &mut W, + children: &[craft_wordmodel::para::GroupChild], + rels: &mut PartRels, + depth: usize, + remaining: &mut usize, + ) { + if depth > MAX_DEPTH { + return; + } + for c in children { + if *remaining == 0 { + break; + } + *remaining -= 1; + let at = (c.x, c.y); + match &c.obj { + InlineObject::Image { media, .. } => { + if let Some(file) = self.media_files.get(media).cloned() { + let id = self.next_docpr(); + let link = member_link(c.link.as_deref(), rels); + self.pic(w, &c.obj, &file, MemberInfo { id: Some(&id), off: at, link: link.as_deref() }, rels); + } + } + InlineObject::Shape { extra, .. } => { + let id = self.shape_docpr(extra.id); + let link = member_link(c.link.as_deref(), rels); + self.wsp(w, &c.obj, MemberInfo { id: Some(&id), off: at, link: link.as_deref() }, rels, depth); + } + InlineObject::Group { .. } if depth < MAX_DEPTH => { + let id = self.next_docpr(); + let link = member_link(c.link.as_deref(), rels); + self.write_inner_group(w, &c.obj, MemberInfo { id: Some(&id), off: at, link: link.as_deref() }, rels, depth + 1, remaining); + } + // Native ink kept from the file, with its fallback, at the member's place. + InlineObject::Graphic { w: iw, h: ih, float, graphic, .. } if graphic.kind == craft_wordmodel::graphic::GraphicKind::Ink => { + if let Some(src) = graphic.source.as_deref() + && let Some(mut root) = self.embedded_tree(src, rels, None) + { + Self::place_member(&mut root, [c.x, c.y, *iw, *ih], float, 0); + w.raw(&root.to_xml()); + } + } + _ => {} + } + } + } + + /// A nested group is an inner `wpg:grpSp`, never another run or drawing anchor. + fn write_inner_group(&mut self, w: &mut W, o: &InlineObject, member: MemberInfo<'_>, rels: &mut PartRels, depth: usize, remaining: &mut usize) { + if depth > MAX_DEPTH { + return; + } + let InlineObject::Group { w: gw, h: gh, float, ch_w, ch_h, children, .. } = o else { return }; + let id = member.id.unwrap_or("0"); + let name = format!("Group {id}"); + w.open("wpg:grpSp", &[]); + nv_props(w, "wpg:cNvPr", (id, &name), o.alt_text(), &float.alt, float.hidden, member.link); + w.empty("wpg:cNvGrpSpPr", &[]); + w.open("wpg:grpSpPr", &[]); + w.open("a:xfrm", &spin_attrs(float.spin()).iter().map(|(k, v)| (*k, v.as_str())).collect::>()); + w.empty("a:off", &[("x", &emu(member.off.0)), ("y", &emu(member.off.1))]); + w.empty("a:ext", &[("cx", &emu(gw.max(0.0))), ("cy", &emu(gh.max(0.0)))]); + w.empty("a:chOff", &[("x", "0"), ("y", "0")]); + w.empty("a:chExt", &[("cx", &emu(ch_w.max(0.0))), ("cy", &emu(ch_h.max(0.0)))]); + w.close("a:xfrm"); + w.close("wpg:grpSpPr"); + self.write_group_members(w, children, rels, depth, remaining); + w.close("wpg:grpSp"); + } +} + +/// Group members have no enclosing run, so even a literal `#name` needs its own +/// external hyperlink relationship. Top-level drawings retain `drawing_link`'s policy. +fn member_link(target: Option<&str>, rels: &mut PartRels) -> Option { + target.filter(|url| !url.is_empty()).map(|url| rels.add(rt::HYPERLINK, url, true)) } /// The VML element that draws a shape kind, for the kinds VML has one for. diff --git a/crates/docx/src/write/story/para.rs b/crates/docx/src/write/story/para.rs index 624ce32381..15c23ee9f9 100644 --- a/crates/docx/src/write/story/para.rs +++ b/crates/docx/src/write/story/para.rs @@ -210,17 +210,24 @@ impl Writer<'_> { i += 1; continue; } - // Hyperlinks with different ScreenTips stay separate even if their target is shared. - let link = props - .link - .as_deref() - .filter(|target| !target.is_empty()) - .map(|target| (target, props.link_tooltip.as_deref().and_then(crate::bounded_link_tooltip))); + // Hyperlinks with different ScreenTips or history settings stay separate even if their target is shared. + let base = link_target_and_tip; + // Text with no history of its own (typed into a link) takes the history of the link it + // is in: the open one, or else the first of the following text in the same link that has one. + let link = base(props).map(|(target, tip)| { + let history = match open_link { + Some((open_target, open_tip, open_history)) if (open_target, open_tip) == (target, tip) => props.link_history.or(open_history), + _ => props.link_history.or_else(|| { + pieces.iter().skip(i + 1).map(|(_, p)| *p).take_while(|p| base(p) == Some((target, tip))).find_map(|p| p.link_history) + }), + }; + (target, tip, history) + }); if link != open_link { if open_link.is_some() { w.close("w:hyperlink"); } - if let Some((link, tip)) = link { + if let Some((link, tip, hist)) = link { let id; let target = if let Some(anchor) = link.strip_prefix('#') { ("w:anchor", anchor) @@ -228,11 +235,19 @@ impl Writer<'_> { id = rels.add(rt::HYPERLINK, link, true); ("r:id", id.as_str()) }; - if let Some(tip) = tip { - w.open("w:hyperlink", &[target, ("w:history", "1"), ("w:tooltip", tip)]); - } else { - w.open("w:hyperlink", &[target, ("w:history", "1")]); + let mut attrs = [("", ""); 3]; + let mut n = 0; + attrs[n] = target; + n += 1; + if let Some(h) = link_history_val(hist) { + attrs[n] = ("w:history", h); + n += 1; } + if let Some(tip) = tip { + attrs[n] = ("w:tooltip", tip); + n += 1; + } + w.open("w:hyperlink", &attrs[..n]); } open_link = link; } @@ -355,3 +370,19 @@ impl Writer<'_> { } } } + +/// A run's hyperlink target and the ScreenTip it is written with, or `None` outside a link. +fn link_target_and_tip(p: &CharProps) -> Option<(&str, Option<&str>)> { + p.link.as_deref().filter(|target| !target.is_empty()).map(|target| (target, p.link_tooltip.as_deref().and_then(crate::bounded_link_tooltip))) +} + +/// The `w:history` value a hyperlink is written with: off or none when a .docx file gave that, +/// otherwise on, as Word writes it for a new link. +fn link_history_val(history: Option) -> Option<&'static str> { + use craft_wordmodel::props::LinkHistory; + match history { + None => Some("1"), + Some(LinkHistory::Off) => Some("0"), + Some(LinkHistory::Omitted) => None, + } +} diff --git a/crates/docx/tests/it/drawing_payload.rs b/crates/docx/tests/it/drawing_payload.rs index 04a317147d..4b5847efda 100644 --- a/crates/docx/tests/it/drawing_payload.rs +++ b/crates/docx/tests/it/drawing_payload.rs @@ -108,7 +108,7 @@ fn picture_group_canvas_keep_kind() { float: Default::default(), ch_w: 100.0, ch_h: 50.0, - children: vec![GroupChild { x: 3.0, y: 4.0, obj: picture() }], + children: vec![GroupChild { link: None, x: 3.0, y: 4.0, obj: picture() }], canvas, }; for original in [picture(), group(None), group(Some(CanvasStyle::default()))] { diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index e58fb3e0a7..11307c334c 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -1280,17 +1280,17 @@ fn compatibility_mode_is_read_and_defaults_to_word_2007() { let compat = |v: &str| { format!(r#""#) }; - assert_eq!(with_settings(Some(&compat("15"))).settings.compat_mode, 15); - assert_eq!(with_settings(Some(&compat("14"))).settings.compat_mode, 14); + assert_eq!(with_settings(Some(&compat("15"))).settings.compat_mode, Some(15)); + assert_eq!(with_settings(Some(&compat("14"))).settings.compat_mode, Some(14)); // Unnamed, out of range or junk values. - assert_eq!(with_settings(Some("")).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); - assert_eq!(with_settings(None).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); - assert_eq!(with_settings(Some(&compat("-3"))).settings.compat_mode, 11); - assert_eq!(with_settings(Some(&compat("99999"))).settings.compat_mode, 99); - assert_eq!(with_settings(Some(&compat("abc"))).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); + assert_eq!(with_settings(Some("")).settings.compat_mode, None); + assert_eq!(with_settings(None).settings.compat_mode, None); + assert_eq!(with_settings(Some(&compat("-3"))).settings.compat_mode, Some(11)); + assert_eq!(with_settings(Some(&compat("99999"))).settings.compat_mode, Some(99)); + assert_eq!(with_settings(Some(&compat("abc"))).settings.compat_mode, None); // Another vendor's setting of the same name is ignored. let other = r#""#; - assert_eq!(with_settings(Some(other)).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); + assert_eq!(with_settings(Some(other)).settings.compat_mode, None); } #[test] @@ -1458,7 +1458,9 @@ fn anchor_stacking_order_is_read_and_kept() { #[test] fn documents_without_a_compatibility_mode_are_laid_out_as_word_2007() { - assert_eq!(read_body("").settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); + let d = read_body(""); + assert_eq!(d.settings.compat_mode, None); + assert_eq!(d.settings.effective_compat_mode(), craft_wordmodel::LEGACY_COMPAT_MODE); } #[test] @@ -3666,7 +3668,7 @@ const INK_NS: &str = "http://schemas.microsoft.com/office/word/2010/wordprocessi const INK_XML: &str = r##"0 0, 1 1, 2 0"##; const INK_TYPES: &str = r#""#; -fn ink_docx(fallback: bool, alias: bool) -> Vec { +pub(super) fn ink_docx(fallback: bool, alias: bool) -> Vec { let content = r#""#; let drawing = format!( r#"{content}"# diff --git a/crates/docx/tests/it/malformed.rs b/crates/docx/tests/it/malformed.rs index fc65b8e2d6..030ab8433a 100644 --- a/crates/docx/tests/it/malformed.rs +++ b/crates/docx/tests/it/malformed.rs @@ -179,9 +179,14 @@ fn many_fields_and_huge_attribute_values() { /// limit error, or the extras are dropped and the text survives (#3702, WC-06). #[test] fn millions_of_attributes_on_one_paragraph_are_capped() { + use std::fmt::Write as _; + // The gate reads a fraction of the attributes; nightly all of them. - let attrs: String = (0..2_000_000 / craft_testkit::hostile::divisor()).map(|i| format!(" a{i}=\"\"")).collect(); - let x = format!("kept"); + let mut x = format!("kept"); // Only the read is timed: deflating the test input in a debug build is not what is bounded. let z = doc_zip(x.as_bytes()); let start = std::time::Instant::now(); diff --git a/crates/docx/tests/it/picture_links.rs b/crates/docx/tests/it/picture_links.rs index 34cf625e1b..ee16352fc6 100644 --- a/crates/docx/tests/it/picture_links.rs +++ b/crates/docx/tests/it/picture_links.rs @@ -213,3 +213,694 @@ fn a_vml_picture_keeps_its_crop_when_saved() { } assert!(lost.is_empty(), "VML picture crops were lost: {lost:?}"); } + +// Original Transitional DOCX/VML: ISO 29500 VML shape/group href attributes, with +// independent literal targets at each level. No reference-app file or click oracle. +#[test] +fn vml_objects_keep_their_own_hyperlinks() { + fn check_images(doc: &Document, object: &InlineObject, original_png: &[u8], out: &mut Vec<(String, f32, f32)>) { + match object { + InlineObject::Image { media, w, h, alt, crop, .. } => { + assert_eq!(doc.media.get(media).expect("the original embedded picture").as_slice(), original_png); + assert_eq!(*crop, [0.0; 4], "a hyperlink must not invent a crop"); + out.push((alt.clone(), *w, *h)); + } + InlineObject::Group { children, .. } => { + for child in children { + check_images(doc, &child.obj, original_png, out); + } + } + InlineObject::Shape { kind, w, h, .. } => { + assert_eq!(*kind, craft_wordmodel::para::ShapeKind::Rectangle); + assert!((*w - 5.0).abs() < 0.001 && (*h - 7.0).abs() < 0.001); + } + other => panic!("the original picture fixture produced another object: {other:?}"), + } + } + fn top_links(doc: &Document) -> Vec> { + let paragraph = doc.body[1].as_para().expect("the VML paragraph"); + paragraph.object_offsets().into_iter().map(|off| paragraph.props_of_char(off).link.clone()).collect() + } + + fn model_links(doc: &Document) -> Vec<(Vec, Option)> { + fn member_links(object: &InlineObject, path: &[usize], out: &mut Vec<(Vec, Option)>) { + if let InlineObject::Group { children, .. } = object { + for (i, child) in children.iter().enumerate() { + let mut path = path.to_vec(); + path.push(i); + out.push((path.clone(), child.link.clone())); + member_links(&child.obj, &path, out); + } + } + } + let paragraph = doc.body[1].as_para().unwrap(); + let mut out = Vec::new(); + for (i, off) in paragraph.object_offsets().into_iter().enumerate() { + out.push((vec![i], paragraph.props_of_char(off).link.clone())); + member_links(paragraph.object_at(off).unwrap(), &[i], &mut out); + } + out + } + fn xml_link(nv: Option<&craft_xml::El>, rels: &craft_xml::El) -> Option { + let id = nv?.child("a:hlinkClick")?.attr("r:id")?; + let rel = rels.children("Relationship").find(|r| r.attr("Id") == Some(id)).expect("every click must name a saved relationship"); + assert_eq!(rel.attr("Type"), Some("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink")); + assert_eq!(rel.attr("TargetMode"), Some("External")); + Some(rel.attr("Target").expect("the click target").to_string()) + } + fn saved_member_links(group: &craft_xml::El, path: &[usize], rels: &craft_xml::El, out: &mut Vec<(Vec, Option)>) { + for (i, child) in group.elements().filter(|e| matches!(e.name.as_str(), "pic:pic" | "wps:wsp" | "wpg:grpSp")).enumerate() { + let mut path = path.to_vec(); + path.push(i); + let nv = match child.name.as_str() { + "pic:pic" => child.child("pic:nvPicPr").and_then(|p| p.child("pic:cNvPr")), + "wps:wsp" => child.child("wps:cNvPr"), + _ => child.child("wpg:cNvPr"), + }; + out.push((path.clone(), xml_link(nv, rels))); + if child.name == "wpg:grpSp" { + saved_member_links(child, &path, rels, out); + } + } + } + + fn check_group_geometry(current: &Document) { + let InlineObject::Group { children, .. } = ¤t.body[1].as_para().unwrap().objects[3] else { panic!() }; + assert_eq!(children.len(), 3); + assert!((children[0].x - 3.0).abs() < 0.001 && (children[0].y - 4.0).abs() < 0.001); + assert!((children[2].x - 20.0).abs() < 0.001 && (children[2].y - 5.0).abs() < 0.001); + let InlineObject::Group { children, float, ch_w, ch_h, .. } = &children[2].obj else { panic!("the linked nested group must remain a group") }; + assert_eq!((*ch_w, *ch_h), (10.0, 10.0)); + assert_eq!(float.spin(), craft_wordmodel::geom::Spin::new(30.0, true, false)); + assert_eq!(children.len(), 1); + assert!((children[0].x - 1.0).abs() < 0.001 && (children[0].y - 2.0).abs() < 0.001); + } + + let vml = r##" + + + + + + + + +"##; + // A known DrawingML link is a positive control in the same package, with the + // same generated media and relationship table as the independently linked VML. + let body = format!("{}{vml}", picture_run(10, r#""#)); + let original_png = png(); + let doc = craft_docx::read(&package(&body)).expect("the original Transitional package must read"); + let saved = craft_docx::write(&doc).expect("the supported picture/group content must save"); + let reopened = craft_docx::read(&saved).expect("the normalized DOCX must reopen"); + let expected_images = [("first", 24.0, 12.0), ("unlinked", 16.0, 8.0), ("last", 12.0, 6.0), ("child", 6.0, 4.0), ("fragment", 2.0, 3.0)]; + + // All payload, ordering, geometry and positive/unlinked controls run before + // the missing-target assertion; neither a dropped object nor bad media is red proof. + for current in [&doc, &reopened] { + assert_eq!(current.body.len(), 2); + assert_eq!(picture_links(current), [Some("https://example.com/picture".to_string())]); + let paragraph = current.body[1].as_para().expect("the VML paragraph remains a paragraph"); + assert_eq!(paragraph.objects.len(), 4, "three top-level pictures and their following group"); + let InlineObject::Group { w, h, .. } = ¶graph.objects[3] else { + panic!("the last VML object must remain a group"); + }; + assert!((*w - 40.0).abs() < 0.001 && (*h - 20.0).abs() < 0.001); + let mut images = Vec::new(); + for object in ¶graph.objects { + check_images(current, object, &original_png, &mut images); + } + assert_eq!(images.len(), expected_images.len(), "every original picture must remain"); + for ((alt, w, h), (expected_alt, expected_w, expected_h)) in images.iter().zip(expected_images) { + assert_eq!(alt, expected_alt, "picture order/identity changed"); + assert!((w - expected_w).abs() < 0.001 && (h - expected_h).abs() < 0.001, "{alt}: {w} x {h}"); + } + assert_eq!(top_links(current)[1], None, "the unlinked neighbor must stay unlinked"); + } + let rels = part(&saved, "word/_rels/document.xml.rels"); + assert!(rels.contains(r#"Target="https://example.com/picture""#), "the DrawingML control's relationship must survive"); + + let expected_top = [Some("https://example.com/TopFirst"), None, Some("https://example.com/TopLast"), Some("https://example.com/Outer")]; + let mut lost = Vec::new(); + for (phase, current) in [("read", &doc), ("reopened", &reopened)] { + for (index, (actual, expected)) in top_links(current).iter().zip(expected_top).enumerate() { + if actual.as_deref() != expected { + lost.push(format!("{phase} top-level object {index}: {actual:?} instead of {expected:?}")); + } + } + } + // These are necessary persistence checks using today's APIs, not a claim that + // relationship presence proves nested path-to-target association or activation. + for (label, target) in [ + ("first", "https://example.com/TopFirst"), + ("last", "https://example.com/TopLast"), + ("outer group", "https://example.com/Outer"), + ("group child", "https://example.com/Child"), + ("group shape", "https://example.com/Shape"), + ("nested group", "https://example.com/Nested"), + ("fragment data", "#Spot"), + ] { + if !rels.contains(&format!(r#"Target="{target}""#)) { + lost.push(format!("saved {label} target: {target}")); + } + } + let expected: Vec<_> = [ + (vec![0], Some("https://example.com/TopFirst")), + (vec![1], None), + (vec![2], Some("https://example.com/TopLast")), + (vec![3], Some("https://example.com/Outer")), + (vec![3, 0], Some("https://example.com/Child")), + (vec![3, 1], Some("https://example.com/Shape")), + (vec![3, 2], Some("https://example.com/Nested")), + (vec![3, 2, 0], Some("#Spot")), + ] + .into_iter() + .map(|(path, link)| (path, link.map(str::to_string))) + .collect(); + for current in [&doc, &reopened] { + assert_eq!(model_links(current), expected, "each target must remain on its own object path"); + check_group_geometry(current); + } + let xml = craft_xml::parse(part(&saved, "word/document.xml").as_bytes()).unwrap(); + let relationships = craft_xml::parse(rels.as_bytes()).unwrap(); + let paragraph = xml.child("w:body").unwrap().children("w:p").nth(1).unwrap(); + let mut xml_links = Vec::new(); + for (i, drawing) in paragraph.find_all("w:drawing").enumerate() { + let frame = drawing.child("wp:inline").or_else(|| drawing.child("wp:anchor")).unwrap(); + xml_links.push((vec![i], xml_link(frame.child("wp:docPr"), &relationships))); + if let Some(group) = frame.child("a:graphic").and_then(|g| g.child("a:graphicData")).and_then(|d| d.child("wpg:wgp")) { + saved_member_links(group, &[i], &relationships, &mut xml_links); + } + } + assert_eq!(xml_links, expected, "saved cNvPr/docPr clicks must name the target at the same path"); + assert!(lost.is_empty(), "VML object hyperlinks were lost: {lost:?}"); +} + +#[test] +fn vml_hyperlink_templates_and_outer_runs_keep_their_scope() { + let cases = [ + (r##"type="#Linked""##, "", Some("https://example.com/Template")), + (r##"type="#Linked" href="https://example.com/Direct""##, "", Some("https://example.com/Direct")), + (r##"type="#Linked" href=" ""##, "", None), + (r#"href=" https://example.com/Trimmed ""#, "", Some("https://example.com/Trimmed")), + ("", r#"o:href="https://example.com/ImageSource" r:href="rIdWeb""#, None), + ]; + let mut shapes = String::new(); + for (attributes, image_attributes, _) in cases { + shapes + .push_str(&format!(r#""#,)); + } + let body = format!( + r#"{shapes}"#, + ); + let doc = craft_docx::read(&package(&body)).unwrap(); + let saved = craft_docx::write(&doc).unwrap(); + let reopened = craft_docx::read(&saved).unwrap(); + let expected: Vec<_> = cases.into_iter().map(|(_, _, link)| link.map(str::to_string)).collect(); + for current in [&doc, &reopened] { + assert_eq!(picture_links(current), expected, "presence-aware template/direct href precedence"); + let paragraph = current.body[1].as_para().unwrap(); + assert_eq!(paragraph.objects.len(), 1); + assert_eq!(paragraph.props_of_char(paragraph.object_offsets()[0]).link.as_deref(), Some("https://example.com/run")); + let InlineObject::Group { children, .. } = ¶graph.objects[0] else { panic!() }; + assert_eq!(children.len(), 1); + assert_eq!(children[0].link.as_deref(), Some("https://example.com/Child"), "the run overrides the group, not its child"); + } + + // A shape type may be declared inside the group rather than beside it. These + // original inputs use unique IDs and keep image-source URLs out of click lookup. + let local_cases = [(r##"type="#GroupLocal""##, Some("https://example.com/GroupTemplate")), (r##"type="#NotSelected""##, None)]; + let mut local_shapes = String::new(); + for (attributes, _) in local_cases { + local_shapes.push_str(&format!( + r#""#, + )); + } + let local_body = format!( + r##"{local_shapes}"##, + ); + let local_doc = craft_docx::read(&package(&local_body)).unwrap(); + let local_saved = craft_docx::write(&local_doc).unwrap(); + let local_reopened = craft_docx::read(&local_saved).unwrap(); + let original_png = png(); + for current in [&local_doc, &local_reopened] { + assert_eq!(current.body.len(), 1); + let paragraph = current.body[0].as_para().unwrap(); + assert_eq!(paragraph.objects.len(), 1); + assert_eq!(paragraph.props_of_char(0).link, None, "a template must not become its containing group's link"); + let InlineObject::Group { children, .. } = ¶graph.objects[0] else { panic!() }; + assert_eq!(children.len(), local_cases.len() + 1); + for (child, (_, expected)) in children.iter().zip(local_cases) { + let InlineObject::Image { media, w, h, .. } = &child.obj else { panic!() }; + assert_eq!(current.media.get(media).unwrap().as_slice(), original_png.as_slice()); + assert!((*w - 6.0).abs() < 0.001 && (*h - 5.0).abs() < 0.001); + assert_eq!(child.link.as_deref(), expected, "group-local template href"); + } + let nested = &children[local_cases.len()]; + assert_eq!(nested.link.as_deref(), Some("https://example.com/NestedTemplateGroup")); + let InlineObject::Group { children: nested_children, .. } = &nested.obj else { panic!() }; + assert_eq!(nested_children.len(), 1); + assert_eq!(nested_children[0].link.as_deref(), Some("https://example.com/DeepTemplate"), "nested group-local template href"); + } +} + +fn replacing_picture_part(bytes: &[u8], name: &str, replacement: &str) -> Vec { + let mut input = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut output = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for i in 0..input.len() { + let mut file = input.by_index(i).unwrap(); + let entry = file.name().unwrap().to_string(); + let mut data = Vec::new(); + file.read_to_end(&mut data).unwrap(); + if entry == name { + data = replacement.as_bytes().to_vec(); + } + output.start_file(entry, zip::write::SimpleFileOptions::default()).unwrap(); + output.write_all(&data).unwrap(); + } + output.finish().unwrap().into_inner() +} + +#[test] +fn group_picture_links_require_their_own_external_hyperlink_relationship() { + let body = r#""#; + let doc = craft_docx::read(&package(body)).unwrap(); + let saved = craft_docx::write(&doc).unwrap(); + let xml = part(&saved, "word/document.xml"); + let rels = part(&saved, "word/_rels/document.xml.rels"); + let tree = craft_xml::parse(xml.as_bytes()).unwrap(); + let nv = tree.find("pic:pic").unwrap().child("pic:nvPicPr").unwrap().child("pic:cNvPr").unwrap(); + let click = nv.child("a:hlinkClick").expect("the valid child's click must be on its cNvPr"); + let id = click.attr("r:id").unwrap(); + let original_png = png(); + let check = |bytes: &[u8], expected: Option<&str>| { + let doc = craft_docx::read(bytes).unwrap(); + let paragraph = doc.body[0].as_para().unwrap(); + assert_eq!(paragraph.objects.len(), 1); + assert_eq!(paragraph.props_of_char(0).link, None, "an unlinked group must not borrow its child's link"); + let InlineObject::Group { children, .. } = ¶graph.objects[0] else { panic!() }; + assert_eq!(children.len(), 1); + let InlineObject::Image { media, w, h, .. } = &children[0].obj else { panic!() }; + assert_eq!(doc.media.get(media).unwrap().as_slice(), original_png.as_slice()); + assert!((*w - 24.0).abs() < 0.001 && (*h - 12.0).abs() < 0.001); + assert_eq!(children[0].link.as_deref(), expected); + }; + check(&saved, Some("https://example.com/Child")); + let type_name = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"; + for modified in [ + rels.replace(type_name, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"), + rels.replace(" TargetMode=\"External\"", ""), + rels.replace("Target=\"https://example.com/Child\"", "Target=\" \""), + rels.replace("https://example.com/Child", &format!("https://example.com/{}", "x".repeat(8 << 10))), + ] { + assert_ne!(modified, rels); + check(&replacing_picture_part(&saved, "word/_rels/document.xml.rels", &modified), None); + } + let missing = xml.replace(&format!(r#"r:id="{id}""#), r#"r:id="rIdAbsent""#); + assert_ne!(missing, xml); + check(&replacing_picture_part(&saved, "word/document.xml", &missing), None); + // A click in an unrelated extension is not the picture's nonvisual properties. + let mut unrelated = tree.clone(); + let picture = unrelated + .child_mut("w:body") + .unwrap() + .child_mut("w:p") + .unwrap() + .child_mut("w:r") + .unwrap() + .child_mut("w:drawing") + .unwrap() + .child_mut("wp:inline") + .unwrap() + .child_mut("a:graphic") + .unwrap() + .child_mut("a:graphicData") + .unwrap() + .child_mut("wpg:wgp") + .unwrap() + .child_mut("pic:pic") + .unwrap(); + picture.child_mut("pic:nvPicPr").unwrap().child_mut("pic:cNvPr").unwrap().children.clear(); + let extension = craft_xml::parse(format!(r#""#).as_bytes()).unwrap(); + picture.child_mut("pic:spPr").unwrap().push(extension); + check(&replacing_picture_part(&saved, "word/document.xml", &unrelated.to_xml()), None); +} + +#[test] +fn linked_groups_share_one_retained_member_budget() { + fn count(object: &InlineObject) -> usize { + match object { + InlineObject::Group { children, .. } => children.iter().map(|c| 1 + count(&c.obj)).sum(), + _ => 0, + } + } + fn input(per_group: usize) -> Vec { + let leaf = r#""#.repeat(per_group); + package(&format!( + r#"{leaf}{leaf}"#, + )) + } + let small = craft_docx::read(&input(1)).unwrap(); + assert_eq!(count(&small.body[0].as_para().unwrap().objects[0]), 4, "two linked groups and two picture leaves"); + let saved_small = craft_docx::write(&small).unwrap(); + let reopened_small = craft_docx::read(&saved_small).unwrap(); + assert_eq!(count(&reopened_small.body[0].as_para().unwrap().objects[0]), 4); + let max = craft_wordmodel::para::MAX_GROUP_CHILDREN; + assert_eq!(max, 1000, "this original fixture is bounded to the existing limit plus two nodes"); + let large = craft_docx::read(&input(500)).unwrap(); + assert_eq!(count(&large.body[0].as_para().unwrap().objects[0]), max, "VML must count linked nodes and leaves together"); + // Independently construct the same 1002-node DrawingML input from our small + // original save, so the VML reader's own bound cannot hide a DML budget regression. + let mut xml = craft_xml::parse(part(&saved_small, "word/document.xml").as_bytes()).unwrap(); + let group = xml + .child_mut("w:body") + .unwrap() + .child_mut("w:p") + .unwrap() + .child_mut("w:r") + .unwrap() + .child_mut("w:drawing") + .unwrap() + .child_mut("wp:inline") + .unwrap() + .child_mut("a:graphic") + .unwrap() + .child_mut("a:graphicData") + .unwrap() + .child_mut("wpg:wgp") + .unwrap(); + for child in group.elements_mut().filter(|e| e.name == "wpg:grpSp") { + let picture = child.child("pic:pic").unwrap().clone(); + child.children.retain(|n| !matches!(n, craft_xml::Node::El(e) if e.name == "pic:pic")); + for _ in 0..500 { + child.push(picture.clone()); + } + } + let dml = replacing_picture_part(&saved_small, "word/document.xml", &xml.to_xml()); + let doc = craft_docx::read(&dml).unwrap(); + assert_eq!(count(&doc.body[0].as_para().unwrap().objects[0]), max, "DrawingML must share the same root-wide bound"); +} + +/// An omitted linked group returns its reserved slot before the following drawable is read. +#[test] +fn empty_linked_groups_release_the_last_member_slot() { + let max = craft_wordmodel::para::MAX_GROUP_CHILDREN; + let before = r#""#; + let after = r#""#; + let empty = r#""#; + let input = |members: &str| { + package(&format!( + r#"{members}"#, + )) + }; + let check = |doc: &Document| { + let InlineObject::Group { children, .. } = &doc.body[0].as_para().unwrap().objects[0] else { + panic!("the original root group must remain"); + }; + assert_eq!(children.len(), max, "the empty linked group must return the last member slot"); + assert!(children.iter().all(|child| matches!(&child.obj, InlineObject::Image { .. }) && child.link.is_none())); + assert!( + matches!(&children.last().unwrap().obj, InlineObject::Image { alt, .. } if alt == "after-empty"), + "the drawable after the omitted group must survive" + ); + }; + let vml = input(&format!("{}{empty}{after}", before.repeat(max - 1))); + check(&craft_docx::read(&vml).unwrap()); + + // Save a small, nonempty linked group to obtain normalized DrawingML with its relationship. + // Then remove its drawable and fill the root independently of the VML boundary input. + let seed = + input(&format!(r#"{before}{after}"#,)); + let saved = craft_docx::write(&craft_docx::read(&seed).unwrap()).unwrap(); + let mut xml = craft_xml::parse(part(&saved, "word/document.xml").as_bytes()).unwrap(); + let group = xml + .child_mut("w:body") + .unwrap() + .child_mut("w:p") + .unwrap() + .child_mut("w:r") + .unwrap() + .child_mut("w:drawing") + .unwrap() + .child_mut("wp:inline") + .unwrap() + .child_mut("a:graphic") + .unwrap() + .child_mut("a:graphicData") + .unwrap() + .child_mut("wpg:wgp") + .unwrap(); + let mut empty = group.child("wpg:grpSp").unwrap().clone(); + let filler = empty.child("pic:pic").unwrap().clone(); + let last = group.child("pic:pic").unwrap().clone(); + assert!(empty.child("wpg:cNvPr").unwrap().child("a:hlinkClick").is_some(), "exercise the linked-group reservation path"); + empty.children.retain(|n| !matches!(n, craft_xml::Node::El(e) if e.name == "pic:pic")); + group.children.retain(|n| !matches!(n, craft_xml::Node::El(e) if matches!(e.name.as_str(), "wpg:grpSp" | "pic:pic"))); + for _ in 0..max - 1 { + group.push(filler.clone()); + } + group.push(empty); + group.push(last); + let dml = replacing_picture_part(&saved, "word/document.xml", &xml.to_xml()); + check(&craft_docx::read(&dml).unwrap()); +} + +#[test] +fn linked_group_coordinates_keep_their_scale() { + fn image_rect(object: &InlineObject, x: f32, scale: f32) -> (f32, f32) { + match object { + InlineObject::Image { w, .. } => (x, w * scale), + InlineObject::Group { w, ch_w, children, .. } => { + assert_eq!(children.len(), 1); + let inner = scale * w / ch_w; + image_rect(&children[0].obj, x + children[0].x * inner, inner) + } + _ => panic!("expected a picture or its group"), + } + } + let picture = picture_run(1, ""); + let picture = &picture[picture.find("").unwrap()..picture.find("").unwrap() + "".len()]; + let picture = picture + .replace(r#""#, r#""#); + for linked in [false, true] { + let vml_link = if linked { r#"href="https://example.com/subgroup""# } else { "" }; + let dml_link = if linked { r#""# } else { "" }; + let vml = format!( + r#""#, + ); + let dml = format!( + r#"{dml_link}{picture}"#, + ); + for body in [vml, dml] { + let doc = craft_docx::read(&package(&body)).unwrap(); + let reopened = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + for current in [&doc, &reopened] { + let (x, w) = image_rect(¤t.body[0].as_para().unwrap().objects[0], 0.0, 1.0); + assert!((x - 160.0).abs() < 0.01, "the rebased offset must be scaled before clipping: {x}"); + assert!((w - 10.0).abs() < 0.01, "the picture keeps its size in the same coordinate system: {w}"); + } + } + } +} + +#[test] +fn inherited_drawing_targets_share_a_document_byte_budget() { + let target = format!("https://example.com/{}", "x".repeat((8 << 10) - "https://example.com/".len())); + let leaf = r##""##.repeat(1000); + let paragraph = format!( + r#"{leaf}"#, + ); + let doc = craft_docx::read(&package(¶graph.repeat(9))).unwrap(); + let mut bytes = 0; + let mut retained = 0; + let mut dropped = 0; + for block in &doc.body { + let InlineObject::Group { children, .. } = &block.as_para().unwrap().objects[0] else { panic!() }; + assert_eq!(children.len(), 1000, "a target budget must not discard the drawing"); + for child in children { + assert!(matches!(child.obj, InlineObject::Image { .. })); + if let Some(link) = &child.link { + assert_eq!(link, &target); + bytes += link.len(); + retained += 1; + } else { + dropped += 1; + } + } + } + assert!(retained > 0 && dropped > 0, "the same budget must span every group in the document"); + assert!(bytes <= 64 << 20); +} + +#[test] +fn native_ink_keeps_its_vml_preview_target_without_overriding_its_own() { + for own_target in [false, true] { + let input = super::fixtures::ink_docx(true, false); + let mut xml = part(&input, "word/document.xml"); + xml = xml.replace(r#""##.repeat(1000); + let later = format!(r#"{leaf}"#).repeat(9); + xml = xml.replace("", &format!(r#"{later}"#)); + let mut input = replacing_picture_part(&input, "word/document.xml", &xml); + if own_target { + let xml = xml.replace( + r#""#, + r#""#, + ); + let rels = part(&input, "word/_rels/document.xml.rels").replace( + "", + r#""#, + ); + input = replacing_picture_part(&input, "word/document.xml", &xml); + input = replacing_picture_part(&input, "word/_rels/document.xml.rels", &rels); + } + let mut doc = craft_docx::read(&input).unwrap(); + for _ in 0..2 { + let paragraph = doc.body[1].as_para().unwrap(); + let InlineObject::Graphic { graphic, .. } = ¶graph.objects[0] else { panic!() }; + assert_eq!(graphic.kind.noun(), "ink"); + assert!(graphic.source.is_some() && !graphic.items.is_empty()); + let expected = if own_target { "https://example.com/native" } else { "https://example.com/preview" }; + assert_eq!(paragraph.props_of_char(0).link.as_deref(), Some(expected)); + doc = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + } + } +} + +#[test] +fn deepest_linked_vml_tree_survives_flow_and_docx() { + fn check(doc: &Document) { + let paragraph = doc.body[0].as_para().unwrap(); + assert_eq!(paragraph.objects.len(), 1); + assert_eq!(paragraph.props_of_char(0).link.as_deref(), Some("https://example.com/root")); + let mut object = ¶graph.objects[0]; + for level in 0..=8 { + let InlineObject::Group { children, .. } = object else { panic!("group at level {level}") }; + assert_eq!(children.len(), 1); + let expected = if level == 8 { "#last-picture".to_string() } else { format!("https://example.com/level{}", level + 1) }; + assert_eq!(children[0].link.as_deref(), Some(expected.as_str())); + object = &children[0].obj; + } + let InlineObject::Image { media, w, h, .. } = object else { panic!("deepest picture") }; + assert_eq!(doc.media.get(media).unwrap().as_slice(), png().as_slice()); + assert!((*w - 6.0).abs() < 0.001 && (*h - 5.0).abs() < 0.001); + } + let mut members = r##""##.to_string(); + for level in (1..=8).rev() { + members = format!(r#"{members}"#,); + } + let body = format!( + r#"{members}"#, + ); + let imported = craft_docx::read(&package(&body)).unwrap(); + check(&imported); + let flow = craft_flow::from_doc_with(&imported, craft_flow::FlowOpts { boxes: true, paras: true, ..Default::default() }); + let rebuilt = craft_flow::to_doc(&flow); + check(&rebuilt); + let reopened = craft_docx::read(&craft_docx::write(&rebuilt).unwrap()).unwrap(); + check(&reopened); +} + +/// Original Flow callers used the mark for a textless paragraph's single drawing. +#[test] +fn a_single_flow_picture_keeps_its_paragraph_mark_link() { + const MARK: &str = "https://example.com/paragraph"; + const OWN: &str = "https://example.com/object"; + let bytes = Arc::new(png()); + for (links, text, expected) in [ + (vec![None], false, vec![Some(MARK)]), + (vec![Some(OWN)], false, vec![Some(OWN)]), + (vec![Some("")], false, vec![None]), + (vec![None, None], false, vec![None, None]), + (vec![Some(OWN), None], false, vec![Some(OWN), None]), + (vec![None, Some(OWN)], false, vec![None, Some(OWN)]), + (vec![None], true, vec![None]), + ] { + let inlines = links + .into_iter() + .map(|link| { + let mut picture = craft_flow::make_img(bytes.clone(), Some(12.0), Some(6.0), "original picture").unwrap(); + picture.link = link.map(str::to_string); + craft_flow::Inline::Image(picture) + }) + .collect(); + let mut paragraph = + craft_flow::Para { inlines, mark: Some(Box::new(CharProps { link: Some(MARK.into()), ..Default::default() })), ..Default::default() }; + if text { + paragraph.push_text("beside the picture", &Default::default()); + } + let flow = craft_flow::Flow { blocks: vec![craft_flow::FBlock::Para(paragraph)], ..Default::default() }; + let model = craft_flow::to_doc(&flow); + let reopened = craft_docx::read(&craft_docx::write(&model).unwrap()).unwrap(); + let expected: Vec<_> = expected.into_iter().map(|target| target.map(str::to_string)).collect(); + for current in [&model, &reopened] { + assert_eq!( + picture_links(current), + expected, + "only the legacy single drawing inherits the mark; explicit targets and neighbors keep their own scope" + ); + let paragraph = current.body[0].as_para().unwrap(); + assert_eq!(paragraph.objects.len(), expected.len()); + for object in ¶graph.objects { + let InlineObject::Image { media, w, h, .. } = object else { panic!("the picture remains a picture") }; + assert_eq!(current.media.get(media).unwrap().as_slice(), bytes.as_slice()); + assert!((*w - 12.0).abs() < 0.001 && (*h - 6.0).abs() < 0.001, "the original picture size is retained"); + } + } + } +} + +/// The legacy paragraph target has the same byte limit as an object's own target. +#[test] +fn a_single_flow_picture_bounds_its_inherited_mark_target() { + const OWN: &str = "https://example.com/object"; + let prefix = "https://example.com/"; + let remaining = craft_flow::MAX_LINK - prefix.len(); + let ascii = format!("{prefix}{}", "a".repeat(remaining)); + let utf8 = format!("{prefix}{}{}", "é".repeat(remaining / 2), "a".repeat(remaining % 2)); + let ascii_over = format!("{ascii}a"); + let utf8_over = format!("{utf8}a"); + let bytes = Arc::new(png()); + for (mark, links, expected) in [ + (ascii.as_str(), vec![None], vec![Some(ascii.as_str())]), + (ascii_over.as_str(), vec![None], vec![None]), + (utf8.as_str(), vec![None], vec![Some(utf8.as_str())]), + (utf8_over.as_str(), vec![None], vec![None]), + (ascii_over.as_str(), vec![Some(OWN)], vec![Some(OWN)]), + (ascii_over.as_str(), vec![Some("")], vec![None]), + (ascii_over.as_str(), vec![Some(" \t ")], vec![None]), + (ascii_over.as_str(), vec![Some(ascii_over.as_str())], vec![None]), + (OWN, vec![Some(utf8_over.as_str())], vec![None]), + (ascii_over.as_str(), vec![None, None], vec![None, None]), + (ascii_over.as_str(), vec![Some(OWN), None], vec![Some(OWN), None]), + (ascii_over.as_str(), vec![None, Some(OWN)], vec![None, Some(OWN)]), + ] { + let inlines = links + .into_iter() + .map(|link| { + let mut picture = craft_flow::make_img(bytes.clone(), Some(12.0), Some(6.0), "original picture").unwrap(); + picture.link = link.map(str::to_string); + craft_flow::Inline::Image(picture) + }) + .collect(); + let paragraph = + craft_flow::Para { inlines, mark: Some(Box::new(CharProps { link: Some(mark.into()), ..Default::default() })), ..Default::default() }; + let flow = craft_flow::Flow { blocks: vec![craft_flow::FBlock::Para(paragraph)], ..Default::default() }; + let expected: Vec<_> = expected.into_iter().map(|target| target.map(str::to_string)).collect(); + let check = |current: &Document| { + assert_eq!(picture_links(current), expected, "each drawing keeps only its own or eligible inherited target"); + let paragraph = current.body[0].as_para().unwrap(); + assert_eq!(paragraph.objects.len(), expected.len()); + for object in ¶graph.objects { + let InlineObject::Image { media, w, h, .. } = object else { panic!("the picture remains a picture") }; + assert_eq!(current.media.get(media).unwrap().as_slice(), bytes.as_slice()); + assert!((*w - 12.0).abs() < 0.001 && (*h - 6.0).abs() < 0.001, "the original picture size is retained"); + } + }; + let model = craft_flow::to_doc(&flow); + check(&model); + let reopened = craft_docx::read(&craft_docx::write(&model).unwrap()).unwrap(); + check(&reopened); + } +} diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index f826bdf57e..945bb2fbbe 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -143,6 +143,7 @@ fn every_char_prop_round_trips() { }), link: None, link_tooltip: None, + link_history: None, ins: None, del: None, fmt_change: None, @@ -1411,9 +1412,9 @@ fn groups_round_trip() { ch_w: 200.0, ch_h: 100.0, children: vec![ - GroupChild { x: 0.0, y: 0.0, obj: pic }, - GroupChild { x: 150.0, y: 10.0, obj: oval.clone() }, - GroupChild { x: 50.0, y: 60.0, obj: tb }, + GroupChild { link: None, x: 0.0, y: 0.0, obj: pic }, + GroupChild { link: None, x: 150.0, y: 10.0, obj: oval.clone() }, + GroupChild { link: None, x: 50.0, y: 60.0, obj: tb }, ], canvas: None, }; @@ -1485,7 +1486,7 @@ fn drawing_canvas_round_trips() { float: Float::default(), ch_w: 432.0, ch_h: 216.0, - children: vec![GroupChild { x: 12.0, y: 18.0, obj: pic }, GroupChild { x: 300.0, y: 100.0, obj: star.clone() }], + children: vec![GroupChild { link: None, x: 12.0, y: 18.0, obj: pic }, GroupChild { link: None, x: 300.0, y: 100.0, obj: star.clone() }], canvas: Some(style.clone()), }; let mut p = Paragraph::with_text("drawn ", CharProps::default()); @@ -1532,7 +1533,7 @@ fn rotated_drawing_canvas_round_trips() { float, ch_w: 200.0, ch_h: 100.0, - children: vec![GroupChild { x: 10.0, y: 20.0, obj: member.clone() }], + children: vec![GroupChild { link: None, x: 10.0, y: 20.0, obj: member.clone() }], canvas: Some(CanvasStyle { fill: Some(Fill::solid(Rgb(0xF0, 0xF4, 0xFF))), stroke: None, stroke_width: 0.0 }), }; let square = Float { wrap: Wrap::Square, ..Default::default() }; @@ -1564,11 +1565,11 @@ fn table_contextual_spacing_compatibility_flag_round_trips() { for mode in [11, 12, 14, 15] { for allow in [false, true] { let mut d = Document::new(); - d.settings.compat_mode = mode; + d.settings.compat_mode = Some(mode); d.settings.allow_space_of_same_style_in_table = allow; let r = rt(&d); assert_eq!(r.settings.allow_space_of_same_style_in_table, allow); - assert_eq!(r.settings.compat_mode, mode); + assert_eq!(r.settings.compat_mode, Some(mode)); if allow { let bytes = craft_docx::write(&d).unwrap(); let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); @@ -1585,14 +1586,165 @@ fn table_contextual_spacing_compatibility_flag_round_trips() { fn compatibility_mode_round_trips() { // New documents are Word 2013+ documents; an older file keeps its mode, so saving it doesn't // change how Word lays it out. - assert_eq!(rt(&Document::new()).settings.compat_mode, craft_wordmodel::COMPAT_MODE_CURRENT); + assert_eq!(rt(&Document::new()).settings.compat_mode, Some(craft_wordmodel::COMPAT_MODE_CURRENT)); for mode in [11, 12, 14, 15] { let mut d = Document::new(); - d.settings.compat_mode = mode; - assert_eq!(rt(&d).settings.compat_mode, mode); + d.settings.compat_mode = Some(mode); + assert_eq!(rt(&d).settings.compat_mode, Some(mode)); } } +/// #3308: A document without `` or without `` +/// round-trips without synthesizing the tag on save. +#[test] +fn compatibility_mode_omitted_round_trips_without_synthesizing() { + let settings_xml_of = |bytes: &[u8]| { + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut xml = String::new(); + match zip.by_name("word/settings.xml") { + Ok(mut file) => { + std::io::Read::read_to_string(&mut file, &mut xml).unwrap(); + Some(xml) + } + Err(zip::result::ZipError::FileNotFound) => None, + Err(e) => panic!("zip error: {e:?}"), + } + }; + + // Case 1: settings.xml without `` at all. + let base_docx = craft_docx::write(&Document::new()).unwrap(); + let original_settings = settings_xml_of(&base_docx).unwrap(); + let without_compat = original_settings.replace( + "", + "", + ); + assert_ne!(original_settings, without_compat); + let docx_without_compat = replace_part(&base_docx, "word/settings.xml", without_compat.as_bytes()); + + let doc = craft_docx::read(&docx_without_compat).unwrap(); + assert_eq!(doc.settings.compat_mode, None); + assert_eq!(doc.settings.effective_compat_mode(), craft_wordmodel::LEGACY_COMPAT_MODE); + + let saved_bytes = craft_docx::write(&doc).unwrap(); + let saved_settings = settings_xml_of(&saved_bytes).unwrap(); + assert!(!saved_settings.contains(", got: {saved_settings}"); + assert!(!saved_settings.contains("compatibilityMode"), "expected no compatibilityMode, got: {saved_settings}"); + + let read_back = craft_docx::read(&saved_bytes).unwrap(); + assert_eq!(read_back.settings.compat_mode, None); + + // Case 2: settings.xml with `` but without `` + // (e.g. only legacy compatibility flags like ``). + let with_other_compat = original_settings.replace( + "", + "", + ); + assert_ne!(original_settings, with_other_compat); + let docx_with_other = replace_part(&base_docx, "word/settings.xml", with_other_compat.as_bytes()); + + let doc2 = craft_docx::read(&docx_with_other).unwrap(); + assert_eq!(doc2.settings.compat_mode, None); + assert!(doc2.settings.do_not_expand_shift_return); + + let saved_bytes2 = craft_docx::write(&doc2).unwrap(); + let saved_settings2 = settings_xml_of(&saved_bytes2).unwrap(); + assert!(saved_settings2.contains(""), "expected , got: {saved_settings2}"); + assert!(saved_settings2.contains(""), "expected doNotExpandShiftReturn, got: {saved_settings2}"); + assert!(!saved_settings2.contains("compatibilityMode"), "expected no compatibilityMode, got: {saved_settings2}"); + + let read_back2 = craft_docx::read(&saved_bytes2).unwrap(); + assert_eq!(read_back2.settings.compat_mode, None); + assert!(read_back2.settings.do_not_expand_shift_return); +} + +/// #3305: a hyperlink keeps the `w:history` a .docx file gave it (on, off or none), and a link +/// with no value, as one made in the app has, is written with history on and reads back the same. +#[test] +fn hyperlink_history_attribute_preservation_round_trips() { + use craft_wordmodel::props::LinkHistory; + let doc_xml_of = |bytes: &[u8]| { + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut xml = String::new(); + std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap(); + xml + }; + + // 1. Each model value is written as the matching attribute and read back as it. + for (history, written) in [(None, Some("1")), (Some(LinkHistory::Off), Some("0")), (Some(LinkHistory::Omitted), None)] { + let mut p = Paragraph::new(); + p.insert_text(0, "link", &CharProps { link: Some("https://example.com/".into()), link_history: history, ..Default::default() }).unwrap(); + let bytes = craft_docx::write(&doc_with(vec![p])).unwrap(); + let xml = doc_xml_of(&bytes); + assert!(xml.contains(" assert!(xml.contains(&format!(r#"w:history="{v}""#)), "{history:?}: {xml}"), + None => assert!(!xml.contains("w:history"), "{history:?}: {xml}"), + } + let read = craft_docx::read(&bytes).unwrap(); + assert_eq!(paras(&read)[0].props_of_char(0).link_history, history); + } + let mut p_one = Paragraph::new(); + p_one + .insert_text( + 0, + "link with history 1", + &CharProps { link: Some("https://example.com/hist-one".into()), link_history: None, ..Default::default() }, + ) + .unwrap(); + let d_one = doc_with(vec![p_one]); + + // 2. Original XML fixture round-trip: + // Verify that reading raw XML with omitted w:history and w:history="0" saves back identically. + let base = craft_docx::write(&d_one).unwrap(); + // Replace the hyperlink in document.xml to have NO w:history attribute + let orig_doc_xml = doc_xml_of(&base); + let xml_omitted_hist = orig_doc_xml.replace(r#" w:history="1""#, ""); + assert_ne!(orig_doc_xml, xml_omitted_hist); + let file_omitted = replace_part(&base, "word/document.xml", xml_omitted_hist.as_bytes()); + + let read_omitted = craft_docx::read(&file_omitted).unwrap(); + assert_eq!(paras(&read_omitted)[0].props_of_char(0).link_history, Some(LinkHistory::Omitted)); + let saved_omitted = craft_docx::write(&read_omitted).unwrap(); + let resaved_xml = doc_xml_of(&saved_omitted); + assert!(!resaved_xml.contains("w:history"), "expected no w:history on save, got: {resaved_xml}"); + + // Replace the hyperlink in document.xml to have w:history="0" + let xml_zero_hist = orig_doc_xml.replace(r#"w:history="1""#, r#"w:history="0""#); + assert_ne!(orig_doc_xml, xml_zero_hist); + let file_zero = replace_part(&base, "word/document.xml", xml_zero_hist.as_bytes()); + + let read_zero = craft_docx::read(&file_zero).unwrap(); + assert_eq!(paras(&read_zero)[0].props_of_char(0).link_history, Some(LinkHistory::Off)); + let saved_zero = craft_docx::write(&read_zero).unwrap(); + let resaved_zero_xml = doc_xml_of(&saved_zero); + assert!(resaved_zero_xml.contains(r#"w:history="0""#), "expected w:history=\"0\" on save, got: {resaved_zero_xml}"); + + // Replace the hyperlink in document.xml to have w:history=" 0 " (whitespace-padded false) + let xml_padded_zero = orig_doc_xml.replace(r#"w:history="1""#, r#"w:history=" 0 ""#); + assert_ne!(orig_doc_xml, xml_padded_zero); + let file_padded = replace_part(&base, "word/document.xml", xml_padded_zero.as_bytes()); + + let read_padded = craft_docx::read(&file_padded).unwrap(); + assert_eq!(paras(&read_padded)[0].props_of_char(0).link_history, Some(LinkHistory::Off)); + let saved_padded = craft_docx::write(&read_padded).unwrap(); + let resaved_padded_xml = doc_xml_of(&saved_padded); + assert!(resaved_padded_xml.contains(r#"w:history="0""#), "expected w:history=\"0\" on save, got: {resaved_padded_xml}"); +} + +/// #3305: a link the app makes, by laying a `CharProps` patch with a target over text, saves with +/// history on, as it did before `w:history` was kept from .docx files. +#[test] +fn a_link_made_with_a_char_props_patch_saves_with_history_on() { + let mut p = Paragraph::with_text("see the site", CharProps::default()); + let patch = CharProps { link: Some("https://example.com/".into()), ..Default::default() }; + p.format(4, 12, &|c| c.overlay(&patch)).unwrap(); + let bytes = craft_docx::write(&doc_with(vec![p])).unwrap(); + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut xml = String::new(); + std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap(); + assert!(xml.contains(""), "expected w:compat preserved for unowned settings: {s}"); + assert!(s.contains("overrideTableStyleFontSizeAndJustification"), "{s}"); + assert!(s.contains("enableOpenTypeFeatures"), "{s}"); + + let reopened = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + assert_eq!(reopened.settings.compat_mode, None); + + // Case 2: compat_mode is set to None, but another switch is enabled. + doc.settings.do_not_expand_shift_return = true; + let files2 = save(&doc); + let s2 = text(&files2, "word/settings.xml"); + assert!(!s2.contains("compatibilityMode"), "expected mode removed: {s2}"); + assert!(s2.contains(""), "{s2}"); + assert!(s2.contains(""), "expected switch preserved: {s2}"); + assert!(s2.contains("overrideTableStyleFontSizeAndJustification"), "{s2}"); + assert!(s2.contains("enableOpenTypeFeatures"), "{s2}"); + + let reopened2 = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + assert_eq!(reopened2.settings.compat_mode, None); + assert!(reopened2.settings.do_not_expand_shift_return); +} + /// Hide spelling errors and Hide grammar errors in this document only (`w:hideSpellingErrors`, /// `w:hideGrammaticalErrors`) are read, written once each (before `w:proofState` in a merged /// part), written in a generated part, and left out when they are turned off. diff --git a/crates/draw/src/geometry/shape.rs b/crates/draw/src/geometry/shape.rs index 3a8ce7a585..f1e3cdbd9b 100644 --- a/crates/draw/src/geometry/shape.rs +++ b/crates/draw/src/geometry/shape.rs @@ -41,10 +41,13 @@ pub enum ShapeGeometry { rect: Rect, }, /// A triangle filling `rect`: the apex at the top centre, the base on the bottom edge (PhotoCraft's Triangle - /// tool and Create Triangle). + /// tool and Create Triangle), each corner rounded by `corner_radius`. Triangle { /// The triangle's bounds. rect: Rect, + /// One radius for every corner, in document units; 0 for sharp corners. A radius larger than the + /// triangle allows is capped by the shape ([`ShapeGeometry::to_path`]). + corner_radius: f64, }, /// A regular polygon or star inscribed in the ellipse of `rect` (the Box frame: PhotoCraft's Polygon). /// `sides` in [`SIDES`]; `star_ratio` in [`STAR_RATIO`], 1 for a plain polygon. @@ -98,7 +101,9 @@ impl ShapeGeometry { /// to half the shorter side, as kurbo's `RoundedRect` does); all radii 0 is the plain /// rectangle. /// - `Ellipse`: kurbo's `Ellipse::from_rect`. - /// - `Triangle`: the top centre, the bottom right and the bottom left of `rect`. + /// - `Triangle`: the top centre, the bottom right and the bottom left of `rect`. A `corner_radius` over 0 + /// rounds each corner with a circular arc tangent to both its edges; the arc's ends lie no farther from + /// the corner than half its shorter edge, which caps a radius the triangle cannot hold. /// - `Polygon`: the outline of [`RadialPolygon`](Self::RadialPolygon) with the first point /// straight up, its outer points on the ellipse inscribed in `rect` (PhotoCraft's engine: /// a 3-sided polygon's base lies a quarter of the height below the centre, not on the bottom @@ -125,10 +130,10 @@ impl ShapeGeometry { } } Self::Ellipse { rect } => Ellipse::from_rect(rect.abs()).to_path(tolerance), - Self::Triangle { rect } => { - // pc: #13350 (the triangle fills its box, apex on top). + Self::Triangle { rect, corner_radius } => { + // pc: #13350 (the triangle fills its box, apex on top); #13355 (the Triangle tool's radius). let rect = rect.abs(); - closed(&[Point::new(rect.center().x, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1)]) + rounded_closed(&[Point::new(rect.center().x, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1)], corner_radius) } Self::Polygon { rect, sides, star_ratio } => { let rect = rect.abs(); @@ -156,9 +161,11 @@ impl ShapeGeometry { pub fn bounds(&self) -> Rect { // pc: crates/ui-egui/src/tools/vector_ui/shapes.rs:85-96 `shape_bounds` (a line's ends' box). match *self { - Self::Rect { rect, .. } | Self::Ellipse { rect } | Self::Triangle { rect } | Self::Polygon { rect, .. } | Self::Custom { rect, .. } => { - rect.abs() - } + Self::Rect { rect, .. } + | Self::Ellipse { rect } + | Self::Triangle { rect, .. } + | Self::Polygon { rect, .. } + | Self::Custom { rect, .. } => rect.abs(), Self::RadialPolygon { center, radius, .. } => Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius), Self::Line { from, to, .. } => Rect::from_points(from, to), } @@ -312,6 +319,50 @@ fn polygon_points(center: Point, radius: f64, rotation: f64, sides: u32, star_ra points } +/// The closed outline through `points` with every corner rounded by `radius`: a circular arc (a cubic) tangent to +/// both edges, whose ends lie no farther from the corner than half the shorter of its two edges. A radius that is +/// 0, negative or not finite, and a corner too flat or too sharp to round, keep the sharp corner. +fn rounded_closed(points: &[Point], radius: f64) -> BezPath { + let n = points.len(); + if !(radius.is_finite() && radius > 0.0) || n < 3 { + return closed(points); + } + // Per corner: where the arc meets the incoming edge, the cubic's two control points and where it leaves. + let corners: Vec<(Point, Point, Point, Point)> = (0..n) + .map(|i| { + let (prev, at, next) = (points[(i + n - 1) % n], points[i], points[(i + 1) % n]); + let (to_prev, to_next) = (prev - at, next - at); + let (len_prev, len_next) = (to_prev.hypot(), to_next.hypot()); + let angle = if len_prev > 0.0 && len_next > 0.0 { (to_prev.dot(to_next) / (len_prev * len_next)).clamp(-1.0, 1.0).acos() } else { 0.0 }; + if !(angle > f64::EPSILON && angle < PI - f64::EPSILON) { + return (at, at, at, at); + } + let half = angle / 2.0; + // The tangent points' distance from the corner, capped at half the shorter edge. + let reach = (radius / half.tan()).min(len_prev.min(len_next) / 2.0); + let (u_prev, u_next) = (to_prev / len_prev, to_next / len_next); + let (enter, leave) = (at + u_prev * reach, at + u_next * reach); + // The arc turns by π − angle; a cubic's handles for a circular arc of turn φ are 4/3·tan(φ/4)·r long. + let arc_radius = reach * half.tan(); + let handle = 4.0 / 3.0 * ((PI - angle) / 4.0).tan() * arc_radius; + (enter, enter - u_prev * handle, leave - u_next * handle, leave) + }) + .collect(); + let mut path = BezPath::new(); + for (i, (enter, c1, c2, leave)) in corners.iter().enumerate() { + if i == 0 { + path.move_to(*enter); + } else { + path.line_to(*enter); + } + if enter != leave { + path.curve_to(*c1, *c2, *leave); + } + } + path.close_path(); + path +} + fn closed(points: &[Point]) -> BezPath { let mut path = BezPath::new(); for (i, p) in points.iter().enumerate() { diff --git a/crates/draw/src/ui/corner/style.rs b/crates/draw/src/ui/corner/style.rs index 1517afb33d..1401ec4ed1 100644 --- a/crates/draw/src/ui/corner/style.rs +++ b/crates/draw/src/ui/corner/style.rs @@ -19,7 +19,7 @@ pub struct CornerStyle { pub(super) dot: f32, /// The pointer's reach. pub(super) reach: f32, - /// The least distance inside a corner. + /// The least distance inside a corner: [`CornerWidgets::INSET`](super::CornerWidgets::INSET). pub(super) inset: f32, /// The shortest side, on the screen, whose corners show widgets. pub(super) min_side: f32, @@ -38,7 +38,7 @@ impl CornerStyle { widget: tokens.size.handle.md, dot: tokens.size.handle.sm, reach: tokens.size.hit.target, - inset: tokens.space.gap.stack, + inset: super::CornerWidgets::INSET, min_side: MIN_SIDE, fill: cx.color(tokens.color.overlay.handle_fill), color: cx.color(tokens.color.overlay.line), diff --git a/crates/draw/src/ui/corner/widgets.rs b/crates/draw/src/ui/corner/widgets.rs index b2ebaff95f..d2a4ce6f6b 100644 --- a/crates/draw/src/ui/corner/widgets.rs +++ b/crates/draw/src/ui/corner/widgets.rs @@ -101,6 +101,10 @@ impl<'a> CornerWidgets<'a> { /// The widest inner angle, in degrees, a widget shows at unless [`hide_above`](Self::hide_above) says otherwise. pub const HIDE_ABOVE: f64 = 180.0; + + /// The least distance, in screen points along each side of a right angle, a widget sits inside its corner, at every + /// density. A host that hit-tests the widgets itself reads it from here. + pub const INSET: f32 = 10.0; } /// What the widgets report: the edit of the targets and what the widgets ask the host to do. diff --git a/crates/draw/src/ui/crop/options.rs b/crates/draw/src/ui/crop/options.rs index 003ba54801..8e5cc3388c 100644 --- a/crates/draw/src/ui/crop/options.rs +++ b/crates/draw/src/ui/crop/options.rs @@ -24,7 +24,7 @@ pub const FIELD_MAX: f64 = 1e9; pub const LENGTH_MIN: f64 = 0.01; /// What the frame's proportions follow. -#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum CropRatio { @@ -55,7 +55,7 @@ impl CropRatio { } /// The resolution field's unit. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ResolutionUnit { @@ -68,7 +68,7 @@ pub enum ResolutionUnit { /// A length with the unit it was entered in: the W and H of W × H × Resolution mode keep what the user typed ("2 in" /// stays in inches when the document resizes). -#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct CropLength { @@ -97,7 +97,7 @@ impl CropLength { /// The W, H and Resolution fields of W × H × Resolution mode. Unset W and H are `None`; the resolution is typed text /// ("300"), empty when unset. Perspective Crop's options bar uses the same fields. -#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct CropSizeFields { @@ -112,7 +112,7 @@ pub struct CropSizeFields { } /// What the area a turned or extending crop uncovers is filled with. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum CropFill { @@ -229,7 +229,7 @@ pub const CROP_SIZES: [CropSizePreset; 8] = [ /// options bar edits it in place, the tool reads it each pass and reports key changes (O, ⇧O, H, /// P, I, X) as [`CropEvent::Settings`](super::CropEvent::Settings). Every field defaults on its /// own, so older settings load. -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct CropSettings { diff --git a/crates/draw/src/ui/paint_bar.rs b/crates/draw/src/ui/paint_bar.rs index 870b80016d..cd1cfee7f3 100644 --- a/crates/draw/src/ui/paint_bar.rs +++ b/crates/draw/src/ui/paint_bar.rs @@ -1,6 +1,7 @@ //! [`PaintBar`]: the options bar members of the Brush, Pencil, Eraser and Mixer Brush tools after the preset picker. use std::cell::RefCell; +use std::ops::RangeInclusive; use std::sync::Arc; use craft_behavior::{EditEvent, EditEvents, IconId, Mixed, Value}; @@ -201,6 +202,25 @@ pub const MIXER_COMBINATIONS: [Option<(f64, f64, f64)>; 13] = [ /// The index of the first combination of each group (Dry, Moist, Wet, Very Wet); a separator goes above each. pub const MIXER_GROUP_STARTS: [usize; 4] = [1, 4, 7, 10]; +/// The percents a field of the bar holds, and whether it takes input. +struct Percents { + range: RangeInclusive, + enabled: bool, +} + +impl Percents { + /// 0 to 100 %. + fn any(enabled: bool) -> Self { + Percents { range: 0.0..=100.0, enabled } + } + + /// 1 to 100 %, for Opacity and Flow: a stroke at 0 % paints nothing, so a typed 0 is out of range like 150, and + /// the range alert names 1 %. + fn from_one(enabled: bool) -> Self { + Percents { range: 1.0..=100.0, enabled } + } +} + /// Whether the smoothing options popover is open. #[derive(Clone, Default)] struct SmoothingOpen(bool); @@ -208,7 +228,8 @@ struct SmoothingOpen(bool); /// The bar's members for one painting tool, after the preset picker that carries the size and the hardness: a rule, /// Mode, Opacity and the pressure-for-opacity toggle, Flow and the build-up toggle (not the Pencil), Smoothing and its /// options (the Pencil's Auto Erase in their place), Erase to History for the Eraser, a rule and the -/// pressure-for-size toggle. The Mixer Brush shows its load, combinations and mix values instead. +/// pressure-for-size toggle. Opacity and Flow hold 1 to 100 %, Smoothing 0 to 100 %. The Mixer Brush shows its load, +/// combinations and mix values instead. #[must_use = "show the bar with `show`"] #[derive(craft_ui::contract::Pattern)] #[pattern(probe(PaintBar<'static, u32>))] @@ -269,10 +290,10 @@ impl<'a, M: Value> PaintBar<'a, M> { pass.check(ui, &words.load_after_stroke, true, None, pass.values.mixer.load_after_stroke, |v, x| v.mixer.load_after_stroke = x); pass.check(ui, &words.clean_after_stroke, true, None, pass.values.mixer.clean_after_stroke, |v, x| v.mixer.clean_after_stroke = x); pass.combination(ui, &words); - pass.percent(ui, "mixer-wet", &words.wet, true, pass.values.mixer.wet, |v, x| v.mixer.wet = x); - pass.percent(ui, "mixer-load", &words.load, true, pass.values.mixer.load, |v, x| v.mixer.load = x); - pass.percent(ui, "mixer-mix", &words.mix, true, pass.values.mixer.mix, |v, x| v.mixer.mix = x); - pass.percent(ui, "mixer-flow", &words.flow, true, pass.values.mixer.flow, |v, x| v.mixer.flow = x); + pass.percent(ui, "mixer-wet", &words.wet, Percents::any(true), pass.values.mixer.wet, |v, x| v.mixer.wet = x); + pass.percent(ui, "mixer-load", &words.load, Percents::any(true), pass.values.mixer.load, |v, x| v.mixer.load = x); + pass.percent(ui, "mixer-mix", &words.mix, Percents::any(true), pass.values.mixer.mix, |v, x| v.mixer.mix = x); + pass.percent(ui, "mixer-flow", &words.flow, Percents::any(true), pass.values.mixer.flow, |v, x| v.mixer.flow = x); pass.check(ui, &words.sample_all_layers, true, None, pass.values.mixer.sample_all_layers, |v, x| v.mixer.sample_all_layers = x); return; } @@ -283,13 +304,13 @@ impl<'a, M: Value> PaintBar<'a, M> { } else { pass.mode(ui, &words.mode, modes); } - pass.percent(ui, "opacity", &words.opacity, sized, pass.values.opacity, |v, x| v.opacity = x); + pass.percent(ui, "opacity", &words.opacity, Percents::from_one(sized), pass.values.opacity, |v, x| v.opacity = x); pass.toggle(ui, PRESSURE, &words.pressure_opacity, sized, pass.values.pressure_opacity, |v, x| v.pressure_opacity = x); if tool != PaintTool::Pencil { - pass.percent(ui, "flow", &words.flow, sized && soft, pass.values.flow, |v, x| v.flow = x); + pass.percent(ui, "flow", &words.flow, Percents::from_one(sized && soft), pass.values.flow, |v, x| v.flow = x); pass.toggle(ui, "sparkles", &words.build_up, sized && soft, pass.values.build_up, |v, x| v.build_up = x); } - pass.percent(ui, "smoothing", &words.smoothing, true, pass.values.smoothing.amount, |v, x| v.smoothing.amount = x); + pass.percent(ui, "smoothing", &words.smoothing, Percents::any(true), pass.values.smoothing.amount, |v, x| v.smoothing.amount = x); if tool == PaintTool::Pencil { Divider::vertical().show(ui); pass.check(ui, &words.auto_erase, true, Some(&words.auto_erase_tip), pass.values.auto_erase, |v, x| v.auto_erase = x); @@ -361,15 +382,16 @@ impl Pass<'_, M> { } } - /// A percent field over a fraction 0..1. - fn percent(&mut self, ui: &mut Ui, salt: &'static str, caption: &Label, enabled: bool, current: f64, set: fn(&mut PaintValues, f64)) { + /// A percent field over a fraction 0..1, holding `percents`. + fn percent(&mut self, ui: &mut Ui, salt: &'static str, caption: &Label, percents: Percents, current: f64, set: fn(&mut PaintValues, f64)) { + let Percents { range, enabled } = percents; // The body may run more than once in a pass and only the run that reads the input reports its events, so every // run's events and alert are collected. let collected: RefCell<(EditEvents>, Option)> = RefCell::new((EditEvents::new(), None)); let _ = Field::new(caption.clone()).side(SideLabel::new().scrub(true)).id_salt(salt).enabled(enabled).show(ui, |ui, _| { let field = NumberField::new(caption.clone(), Bind::given(Some(current * 100.0))) .unit_kind(UnitKind::Percent) - .range(0.0..=100.0) + .range(range.clone()) .commit_decimals(0) .scrub_by_label() .show(ui); diff --git a/crates/draw/src/ui/pen/bezier/mod.rs b/crates/draw/src/ui/pen/bezier/mod.rs index 5c08d39e94..84decd8143 100644 --- a/crates/draw/src/ui/pen/bezier/mod.rs +++ b/crates/draw/src/ui/pen/bezier/mod.rs @@ -77,7 +77,8 @@ pub enum BezierTool { /// Add Anchor Point: a click on a segment, within 5 screen points of it, inserts an anchor at the hit's `t` /// ([`PathEdit::InsertAnchor`]); a drag inserts it and pulls out its handles as the Pen does /// ([`PathEdit::PullAnchor`]: ⇧ turns them to the nearest 45°, ⌥ during the drag breaks the pair); the new anchor is - /// selected. A press on an anchor or a shown handle selects and drags it as [`BezierTool::Direct`] does (⇧ adds to + /// selected. Holding Space during that drag moves the anchor and both handles; releasing it resumes pulling. + /// A press on an anchor or a shown handle selects and drags it as [`BezierTool::Direct`] does (⇧ adds to /// the selection, ⌥ on a handle moves it alone), and a click on empty canvas deselects the anchors and keeps the /// path. With ⌥ held at the press a click on a segment selects its whole subpath and a drag moves a copy of it /// ([`PathEdit::DuplicateSubpath`]; the subpath itself on a path that takes no copies), and a press on an anchor does @@ -250,16 +251,20 @@ enum Target { t: f64, from: Point, }, - /// Add Anchor's drag from a segment: an insert into `segment` at `t`, whose anchor stays at `from`, the point of - /// the curve at `t`, and whose handles follow the pointer. `out` is the out handle of the last pass, and - /// `in_ctrl` the in handle ⌥ left once it broke the pair. + /// Add Anchor's drag from a segment: `from` stays the original curve point, while Space moves the anchor by + /// `by` with both handles. `last` tracks pointer travel; `out` is the last out handle, and `in_ctrl` the in + /// handle ⌥ left once it broke the pair. Pull { path: u64, segment: KnotRef, t: f64, from: Point, + by: Vec2, out: Point, in_ctrl: Option, + last: Pos2, + /// A translated handle stays put until the pointer or its constraints change. + translated_mods: Option, }, /// Direct Selection's ⌥ drag on a segment: a copy of `subpath` dragged from `from`, the grabbed point. Duplicate { @@ -305,6 +310,7 @@ struct Pointing<'a> { start: PressStart, pos: Pos2, mods: Mods, + space: bool, } /// The kind of a part of the overlay. @@ -623,7 +629,7 @@ impl<'a> BezierOverlay<'a> { // Anchor's with ⌥, moves it. BezierHit::Segment { path, segment, t } if self.tool == BezierTool::AddAnchor && self.tool.adds(mods) => { let from = Self::segment_point(paths, path, segment, t); - Target::Pull { path, segment, t, from, out: from, in_ctrl: None } + Target::Pull { path, segment, t, from, by: Vec2::ZERO, out: from, in_ctrl: None, last: start.origin, translated_mods: None } } BezierHit::Segment { path, segment, t } if self.tool.adds(mods) => { Target::Insert { path, segment, t, from: Self::segment_point(paths, path, segment, t) } @@ -752,34 +758,46 @@ impl<'a> BezierOverlay<'a> { PathEdit::InsertCurvature { path, segment, t, by: snapped(from + locked(delta)) - from } } &Target::Insert { path, segment, t, from } => PathEdit::InsertAnchor { path, segment, t, by: snapped(from + locked(delta)) - from }, - &Target::Pull { path, segment, t, from, in_ctrl, .. } => { + &Target::Pull { path, segment, t, from, by, in_ctrl, .. } => { let to = from + delta; - let out = if mods.shift { handle_45(from, to) } else { snapped(to) }; - PathEdit::PullAnchor { path, segment, t, out, in_ctrl } + let out = if mods.shift { handle_45(from + by, to) } else { snapped(to) }; + PathEdit::PullAnchor { path, segment, t, by, out, in_ctrl } } &Target::Duplicate { path, subpath, from } => PathEdit::DuplicateSubpath { path, subpath, by: snapped(from + locked(delta)) - from }, Target::Nothing | Target::Toggle { .. } | Target::Pick { .. } | Target::Marquee => return None, }) } - /// [`edit`](Self::edit), keeping what a [`Target::Pull`] carries from pass to pass: ⌥ pressed during the drag - /// leaves the in handle where the last pass had it, and the out handle is remembered for the next pass. - fn edit_pulled( - view: &CanvasView, - snap: Option<&Snap>, - tool: BezierTool, - target: &mut Target, - origin: Pos2, - pointer: Pos2, - mods: Mods, - ) -> Option { - if let Target::Pull { from, out, in_ctrl, .. } = target - && mods.alt - && in_ctrl.is_none() - { - *in_ctrl = Some(*from - (*out - *from)); + /// Keeps Add Anchor's anchor and handles together while Space is held; otherwise pulls the handles. + /// ⌥ leaves the previous in handle in place until Space moves the whole knot again. + fn edit_pulled(tool: BezierTool, target: &mut Target, at: Pointing<'_>) -> Option { + let Pointing { view, snap, start, pos, mods, space } = at; + if let Target::Pull { path, segment, t, from, by, out, in_ctrl, last, translated_mods } = target { + if space { + let delta = view.to_doc(pos) - view.to_doc(*last); + *by += delta; + *out += delta; + if let Some(incoming) = in_ctrl { + *incoming += delta; + } + *last = pos; + *translated_mods = Some(mods); + return Some(PathEdit::PullAnchor { path: *path, segment: *segment, t: *t, by: *by, out: *out, in_ctrl: *in_ctrl }); + } + // Space keeps translation priority; on release, Alt can break the pair without moving its geometry. + if mods.alt && in_ctrl.is_none() { + let anchor = *from + *by; + *in_ctrl = Some(anchor - (*out - anchor)); + } + // Space moves by raw travel, including off the snap targets. Releasing it is not a pointer move: + // keep that geometry on every stationary pass, but still read modifier-only constraint changes. + if *last == pos && *translated_mods == Some(mods) { + return Some(PathEdit::PullAnchor { path: *path, segment: *segment, t: *t, by: *by, out: *out, in_ctrl: *in_ctrl }); + } + *translated_mods = None; + *last = pos; } - let edit = Self::edit(view, snap, tool, target, origin, pointer, mods); + let edit = Self::edit(view, snap, tool, target, start.origin, pos, mods); if let (Target::Pull { out, .. }, Some(PathEdit::PullAnchor { out: pulled, .. })) = (target, &edit) { *out = *pulled; } @@ -846,6 +864,7 @@ impl<'a> BezierOverlay<'a> { fn run_pointer(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, scene: &Scene, paths: &[EditPath]) { let snap = canvas_snap(&cx.env); let view = &space.view; + let space_held = space.space_held(); let mut hovered: Option<(u8, BezierHit, Mods)> = None; let mut pressed = false; for item in &scene.items { @@ -853,7 +872,7 @@ impl<'a> BezierOverlay<'a> { continue; } let Some(result) = cx.part_if_declared(item.part()) else { continue }; - let (press, hover) = (result.press, result.hover_pos); + let (press, hover) = (result.press, cx.hover_pos(item.part())); pressed |= press.phase.is_press(); if let Some(at) = hover { let rank = match item.kind { @@ -882,10 +901,10 @@ impl<'a> BezierOverlay<'a> { } PressPhase::DragStart { start, pos, .. } | PressPhase::Drag { start, pos, .. } if start.button == PointerButton::Primary => { let first = matches!(press.phase, PressPhase::DragStart { .. }); - self.drag(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, Some(item), paths, first); + self.drag(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods, space: space_held }, Some(item), paths, first); } PressPhase::Release { start, pos, click, .. } if start.button == PointerButton::Primary => { - self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, click, paths); + self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods, space: space_held }, click, paths); } PressPhase::Cancel { .. } => *cx.press_slot::() = None, _ => {} @@ -904,10 +923,10 @@ impl<'a> BezierOverlay<'a> { } PressPhase::DragStart { start, pos, .. } | PressPhase::Drag { start, pos, .. } if start.button == PointerButton::Primary => { let first = matches!(press.phase, PressPhase::DragStart { .. }); - self.drag(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, None, paths, first); + self.drag(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods, space: space_held }, None, paths, first); } PressPhase::Release { start, pos, click, .. } if start.button == PointerButton::Primary => { - self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, click, paths); + self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods, space: space_held }, click, paths); } PressPhase::Cancel { .. } => *cx.press_slot::() = None, _ => {} @@ -916,7 +935,7 @@ impl<'a> BezierOverlay<'a> { if matches!(self.tool, BezierTool::AddAnchor | BezierTool::DeleteAnchor) && let Some(result) = cx.part_if_declared(EMPTY) { - let (press, hover) = (result.press, result.hover_pos); + let (press, hover) = (result.press, cx.hover_pos(EMPTY)); // The part covers the canvas background, so it owns the cursor the host tool shows off the paths too. if hover.is_some() { let tool = if self.tool == BezierTool::AddAnchor { PathTool::AddAnchor } else { PathTool::DeleteAnchor }; @@ -945,7 +964,7 @@ impl<'a> BezierOverlay<'a> { /// One pass of a press dragged to `pos`; `first` on the pass the drag begins. fn drag(&mut self, cx: &mut Cx<'_, Self>, at: Pointing<'_>, item: Option<&Item>, paths: &[EditPath], first: bool) { - let Pointing { view, snap, start, pos, mods } = at; + let Pointing { view, start, pos, mods, .. } = at; let kept = cx.press_slot::().take().filter(|held| held.origin == start.origin); let mut held = match (kept, item) { (Some(held), _) => held, @@ -974,7 +993,7 @@ impl<'a> BezierOverlay<'a> { } } _ => { - if let Some(edit) = Self::edit_pulled(view, snap, self.tool, &mut held.target, start.origin, pos, mods) { + if let Some(edit) = Self::edit_pulled(self.tool, &mut held.target, at) { self.propose(cx, &held.start, edit); } } @@ -985,7 +1004,7 @@ impl<'a> BezierOverlay<'a> { /// The release of a press at `pos`: a drag commits, a click does what its tool's click does. fn release(&mut self, cx: &mut Cx<'_, Self>, at: Pointing<'_>, click: bool, paths: &[EditPath]) { - let Pointing { view, snap, start, pos, mods } = at; + let Pointing { view, start, pos, mods, .. } = at; // A press reports its Down, and its drag start, before its release, and the overlay holds the press from // either: a release with nothing held is of a press the overlay let go (a cancelled one), and does nothing. let Some(held) = cx.press_slot::().take().filter(|held| held.origin == start.origin) else { return }; @@ -1003,7 +1022,7 @@ impl<'a> BezierOverlay<'a> { } if held.began { let mut target = held.target.clone(); - if let Some(edit) = Self::edit_pulled(view, snap, self.tool, &mut target, start.origin, pos, mods) { + if let Some(edit) = Self::edit_pulled(self.tool, &mut target, at) { self.propose(cx, &held.start, edit); } // The copy is what was dragged: it ends up selected, not the source. diff --git a/crates/draw/src/ui/pen/bezier/model.rs b/crates/draw/src/ui/pen/bezier/model.rs index d95f1d0532..b3ece745a8 100644 --- a/crates/draw/src/ui/pen/bezier/model.rs +++ b/crates/draw/src/ui/pen/bezier/model.rs @@ -452,7 +452,8 @@ pub enum PathEdit { }, /// Add Anchor's drag from a segment: add an anchor to the segment leaving `segment` at `t` and pull out its /// handles, as the Pen does: the out handle at `out` and the in handle opposite it through the anchor, a smooth - /// knot; once Alt broke the pair, the in handle at `in_ctrl` and a corner knot. + /// knot; once Alt broke the pair, the in handle at `in_ctrl` and a corner knot. `by` moves the new anchor from + /// the original segment point; both handles are absolute document positions, including that move. #[non_exhaustive] PullAnchor { /// The path's host key. @@ -461,7 +462,9 @@ pub enum PathEdit { segment: KnotRef, /// Position along the segment, 0..=1. t: f64, - /// The new anchor's out handle. + /// The move of the new anchor from the original segment point, in document units. + by: Vec2, + /// The new anchor's out handle, in document coordinates. out: Point, /// The new anchor's in handle once Alt broke the pair; `None` mirrors `out`. in_ctrl: Option, @@ -546,7 +549,14 @@ impl PathEdit { /// Add Anchor's insert into the segment leaving `segment` at `t` with the new anchor's handles pulled out to `out` /// and mirrored, or with the in handle at `in_ctrl`. pub fn pull_anchor(path: u64, segment: KnotRef, t: f64, out: Point, in_ctrl: Option) -> Self { - PathEdit::PullAnchor { path, segment, t, out, in_ctrl } + Self::pull_anchor_moved(path, segment, t, Vec2::ZERO, out, in_ctrl) + } + + /// Add Anchor's insert with its anchor moved by `by` from the original segment point. + /// `out` and `in_ctrl` are absolute document positions; `None` mirrors `out` through the moved anchor. + /// Hosts applying edits themselves must apply `by` to the inserted anchor before setting the handles. + pub fn pull_anchor_moved(path: u64, segment: KnotRef, t: f64, by: Vec2, out: Point, in_ctrl: Option) -> Self { + PathEdit::PullAnchor { path, segment, t, by, out, in_ctrl } } /// The Curvature tool's toggle of `knot` between smooth and corner. diff --git a/crates/draw/src/ui/pen/bezier/ops.rs b/crates/draw/src/ui/pen/bezier/ops.rs index 889e4f5767..1befd5fbf2 100644 --- a/crates/draw/src/ui/pen/bezier/ops.rs +++ b/crates/draw/src/ui/pen/bezier/ops.rs @@ -137,9 +137,9 @@ impl PathEdit { /// `by`, then the subpath reflowed. /// - `InsertAnchor`: [`EditSubpath::insert_at`], the new knot with its handles moved by `by`; no /// reflow and no smoothing, so a straight segment gets a corner knot. - /// - `PullAnchor`: [`EditSubpath::insert_at`], then the new knot's out handle at `out` and its in - /// handle at `in_ctrl` (a corner), or mirrored through the anchor (smooth). Nothing changes when - /// a handle is not finite. + /// - `PullAnchor`: [`EditSubpath::insert_at`], then the new anchor moved by `by`, its out handle at + /// `out` and its in handle at `in_ctrl` (a corner), or mirrored through the moved anchor (smooth). + /// Nothing changes when the offset, moved anchor or a resulting handle is not finite. /// - `ToggleCurvature`: a smooth knot becomes a corner with retracted handles, a corner /// becomes smooth, then the subpath reflows. /// - `DuplicateSubpath`: a copy of the subpath goes last and moves, with its handles, by `by`; @@ -206,16 +206,23 @@ impl PathEdit { k.in_ctrl += *by; k.out_ctrl += *by; } - PathEdit::PullAnchor { segment, t, out, in_ctrl, .. } => { + PathEdit::PullAnchor { segment, t, by, out, in_ctrl, .. } => { let finite = |p: &Point| p.x.is_finite() && p.y.is_finite(); - if !finite(out) || !in_ctrl.as_ref().is_none_or(finite) { + if !by.x.is_finite() || !by.y.is_finite() || !finite(out) || !in_ctrl.as_ref().is_none_or(finite) { return false; } let Some(sp) = path.subpaths.get_mut(segment.subpath) else { return false }; let Some(at) = sp.insert_at(segment.knot, *t) else { return false }; let k = &mut sp.knots[at]; + let anchor = k.anchor + *by; + let incoming = in_ctrl.unwrap_or(anchor - (*out - anchor)); + if !finite(&anchor) || !finite(&incoming) { + *path = before; + return false; + } + k.anchor = anchor; k.out_ctrl = *out; - k.in_ctrl = in_ctrl.unwrap_or(k.anchor - (*out - k.anchor)); + k.in_ctrl = incoming; k.smooth = in_ctrl.is_none(); } PathEdit::Convert { knot, out, .. } => { diff --git a/crates/draw/src/ui/pen/options.rs b/crates/draw/src/ui/pen/options.rs index a616018e1a..ff745df7bf 100644 --- a/crates/draw/src/ui/pen/options.rs +++ b/crates/draw/src/ui/pen/options.rs @@ -38,7 +38,7 @@ pub const PATH_OPTIONS_COLOR_KEY: &str = "pathOptions.color"; /// The pen's Path Options, persisted by the app with its preferences (Photoshop's Pen gear popover). Serialised in /// camelCase; unknown fields are ignored and missing ones take their defaults. -#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct PathOptionsSettings { @@ -58,7 +58,7 @@ pub struct PathOptionsSettings { } /// How the direction handles' ends are drawn. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum HandleStyle { diff --git a/crates/draw/src/ui/shape/bar.rs b/crates/draw/src/ui/shape/bar.rs index cbe183040a..1f08eafe2f 100644 --- a/crates/draw/src/ui/shape/bar.rs +++ b/crates/draw/src/ui/shape/bar.rs @@ -35,8 +35,9 @@ pub struct ShapeBarOutput { /// The cells a Shape tool adds to the options bar, in PhotoCraft's order: the "Fill" check box and chip, the /// "Stroke" chip, the stroke width (0 to 288 px), the Stroke style button; then the kind's cell: Rectangle and -/// Rounded Rectangle "Radius" (0 to 150,000), Polygon and Star "Sides" (3 to 100), Line "Weight" (1 to 10,000). A -/// pattern shown as children of a `Bar`. +/// Rounded Rectangle "Radius" (0 to 150,000), Triangle "Radius" (0 to 150,000, its own +/// [`triangle_corner_radius`](ShapeToolSettings::triangle_corner_radius)), Polygon and Star "Sides" (3 to 100), Line +/// "Weight" (1 to 10,000). A pattern shown as children of a `Bar`. /// /// - The values are the selected shape layer's when one is selected, else the tool settings' (the app passes the /// right [`ShapeAppearance`]). @@ -143,6 +144,10 @@ impl<'a> ShapeBar<'a> { NumberCell::pixels(&units, pixels_per_inch, "radius", &words.radius, settings.corner_radius, RADIUS_RANGE), ShapeChange::CornerRadius as fn(f64) -> ShapeChange, )), + ShapeKind::Triangle => Some(( + NumberCell::pixels(&units, pixels_per_inch, "radius", &words.radius, settings.triangle_corner_radius, RADIUS_RANGE), + ShapeChange::CornerRadius as fn(f64) -> ShapeChange, + )), ShapeKind::Polygon | ShapeKind::Star => Some(( NumberCell::count(&units, "sides", &words.sides, f64::from(settings.sides), SIDES_RANGE), sides_change as fn(f64) -> ShapeChange, diff --git a/crates/draw/src/ui/shape/mod.rs b/crates/draw/src/ui/shape/mod.rs index 02995f04d8..8be6c93dfc 100644 --- a/crates/draw/src/ui/shape/mod.rs +++ b/crates/draw/src/ui/shape/mod.rs @@ -29,7 +29,7 @@ pub use stroke_cells::{StrokeCells, StrokeCellsOutput}; pub use words::ShapeWords; /// The drawing mode of the vector tools. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum VectorMode { @@ -252,7 +252,8 @@ pub enum ShapeChange { }, /// A rectangle's four radii (the "Corner radius" field sets all four). Radii([f64; 4]), - /// A polygon's corner radius, or the options bar's Radius. + /// A polygon's or triangle's corner radius, or the options bar's Radius (the Rectangle's, or the Triangle + /// tool's own). CornerRadius(f64), /// A polygon's number of sides. Sides(u32), @@ -270,8 +271,8 @@ impl ShapeChange { pub const ENABLED_STROKE_WIDTH: f64 = 3.0; } -/// The Shape tools' persisted options-bar values (Fill on, radius, sides, star ratio, weight, -/// stroke width, the Rectangle's gear); the paints are the app's foreground and background. +/// The Shape tools' persisted options-bar values (Fill on, the Rectangle's and the Triangle's radius, sides, star +/// ratio, weight, stroke width, the Rectangle's gear); the paints are the app's foreground and background. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] @@ -280,6 +281,9 @@ pub struct ShapeToolSettings { pub fill_on: bool, /// The Rectangle's corner radius. pub corner_radius: f64, + /// The Triangle's corner radius, one for its three corners: the Triangle tool keeps its own, apart from the + /// Rectangle's (storytold/photocraft#13355). + pub triangle_corner_radius: f64, /// A polygon's sides or a star's points. pub sides: u32, /// A star's inner over outer radius. @@ -295,12 +299,13 @@ pub struct ShapeToolSettings { } impl Default for ShapeToolSettings { - /// Fill on, square corners, 5 sides, a star ratio of 0.5 (production's Star), weight 3, no stroke, no + /// Fill on, square corners (Rectangle and Triangle), 5 sides, a star ratio of 0.5 (production's Star), weight 3, no stroke, no /// arrowheads, an unconstrained Rectangle. fn default() -> Self { ShapeToolSettings { fill_on: true, corner_radius: 0.0, + triangle_corner_radius: 0.0, sides: 5, star_ratio: 0.5, line_weight: 3.0, @@ -312,10 +317,11 @@ impl Default for ShapeToolSettings { } impl ShapeToolSettings { - /// The drag options of `kind` with these values; the gear's constraints apply to the Rectangle only. + /// The drag options of `kind` with these values; the gear's constraints apply to the Rectangle only, and a + /// Triangle takes its own corner radius. pub fn drag_options(&self, kind: ShapeKind) -> ShapeDragOptions { - let options = - ShapeDragOptions::new(kind).corner_radius(self.corner_radius).sides(self.sides).star_ratio(self.star_ratio).line_weight(self.line_weight); + let radius = if kind == ShapeKind::Triangle { self.triangle_corner_radius } else { self.corner_radius }; + let options = ShapeDragOptions::new(kind).corner_radius(radius).sides(self.sides).star_ratio(self.star_ratio).line_weight(self.line_weight); match kind { ShapeKind::Rectangle => options.constraints(self.rect_box), _ => options, diff --git a/crates/draw/src/ui/shape_drag/dialog.rs b/crates/draw/src/ui/shape_drag/dialog.rs index ad6b6e35ab..02f6ef61dd 100644 --- a/crates/draw/src/ui/shape_drag/dialog.rs +++ b/crates/draw/src/ui/shape_drag/dialog.rs @@ -26,6 +26,7 @@ use serde_json::{Value, json}; use super::ShapeKind; use super::words::CreateShapeWords; use crate::geometry::shape::{SIDES, ShapeGeometry}; +use crate::ui::shape::RADIUS_RANGE; /// The farthest the click may lie from the origin on either axis, in pixels: the same bound as /// a side (PhotoCraft's `MAX_PX`, `shape_dialog.rs:19`, checked at `:111`). @@ -52,7 +53,7 @@ pub struct CreateShapeOptions { /// Width and height in document pixels (100 × 100 by default). pub size: (f64, f64), /// A rectangle's radii, top-left, top-right, bottom-right, bottom-left (from the tool's corner - /// radius). + /// radius). A triangle's one corner radius is all four. pub radii: [f64; 4], /// "Link radii": one radius for all four corners; on by default. pub link_radii: bool, @@ -102,7 +103,7 @@ impl CreateShapeOptions { self } - /// The tool's corner radius (all four corners), sides and star ratio. + /// The tool's corner radius (all four corners; a triangle's three), sides and star ratio. #[must_use] pub fn tool(mut self, corner_radius: f64, sides: u32, star_ratio: f64) -> Self { self.radii = [corner_radius; 4]; @@ -149,8 +150,9 @@ struct Memory { /// picked for a field is not remembered, storytold/photocraft#7786). Rectangle and Rounded /// Rectangle: four radii Top Left, Top Right, Bottom Left, Bottom Right in two columns under one /// "Radius" label, with the "Link radii" toggle between the columns (`LinkMode::Equal`, on by -/// default). Polygon and Star: Sides (3–100) and Star Ratio (1–100 %, default 100); the Polygon drag -/// keeps ratio 1. Then "From Center". +/// default). Triangle: one "Radius" for its three corners (0 to 150,000 px, from the Triangle tool's own radius; +/// storytold/photocraft#13355). Polygon and Star: Sides (3–100) and Star Ratio (1–100 %, default 100); the Polygon +/// drag keeps ratio 1. Then "From Center". /// - A width or height typed past [`CreateShapeOptions::SIZE`] keeps the nearest end and raises the range alert, /// which the app opens from [`take_range_alert`](Self::take_range_alert) (#13358). A size set out of range /// through automation shows [`CreateShapeWords::bad_size`] under the fields and disables OK; so does a click @@ -214,7 +216,11 @@ fn answer(o: &CreateShapeOptions, words: &CreateShapeWords, units: &Units) -> Re ShapeGeometry::Rect { rect, radii } } ShapeKind::Ellipse => ShapeGeometry::Ellipse { rect }, - ShapeKind::Triangle => ShapeGeometry::Triangle { rect }, + ShapeKind::Triangle => { + let radius = o.radii[0]; + let corner_radius = if radius.is_finite() { radius.clamp(*RADIUS_RANGE.start(), *RADIUS_RANGE.end()) } else { 0.0 }; + ShapeGeometry::Triangle { rect, corner_radius } + } ShapeKind::Polygon | ShapeKind::Star => { let ratio = if o.star_ratio.is_finite() { o.star_ratio.clamp(0.01, 1.0) } else { 1.0 }; ShapeGeometry::Polygon { rect, sides, star_ratio: ratio } @@ -441,6 +447,20 @@ fn body( } }); } + if kind == ShapeKind::Triangle { + Field::new(Label::from(words.radius.as_str().to_owned())).show(ui, |ui, _| { + let radius = values.radii[0]; + let field = NumberField::new(words.radius.as_str().to_owned(), Bind::given(Some(radius))) + .range(RADIUS_RANGE) + .unit(numbers.symbol(UnitKind::Pixels)) + .commit_decimals(2); + if let Some(value) = field.show(ui).value().copied().flatten() + && value != radius + { + values.radii = [value.clamp(*RADIUS_RANGE.start(), *RADIUS_RANGE.end()); 4]; + } + }); + } if matches!(kind, ShapeKind::Polygon | ShapeKind::Star) { Field::new(Label::from(words.sides.as_str().to_owned())).show(ui, |ui, _| { let field = NumberField::new(words.sides.as_str().to_owned(), Bind::given(Some(f64::from(values.sides)))) @@ -487,7 +507,7 @@ impl StackDialog for CreateShapeDialog { type Result = CreatedShape; /// `width` and `height` in the unit their field shows, `widthUnit` and `heightUnit`, `radii` (top-left, - /// top-right, bottom-right, bottom-left, in pixels), `linkRadii`, `sides`, `starRatio` (in percent, as its + /// top-right, bottom-right, bottom-left, in pixels), `linkRadii`, a triangle's `cornerRadius` (pixels), `sides`, `starRatio` (in percent, as its /// field shows it) and `fromCenter`. fn json_fields(&self) -> Option { let o = &self.options; @@ -499,15 +519,16 @@ impl StackDialog for CreateShapeDialog { "heightUnit": self.units[1], "radii": o.radii, "linkRadii": o.link_radii, + "cornerRadius": o.radii[0], "sides": o.sides, "starRatio": (o.star_ratio * 100.0).clamp(1.0, 100.0), "fromCenter": o.from_center, })) } - /// Sets a field as its row does, from the remembered values on. The radius rows answer only for a rectangle, and - /// Sides and Star Ratio only for a polygon or star; elsewhere they refuse as inactive. Linked radii take four - /// equal values. + /// Sets a field as its row does, from the remembered values on. The radius rows answer only for a rectangle, + /// `cornerRadius` only for a triangle, and Sides and Star Ratio only for a polygon or star; elsewhere they refuse + /// as inactive. Linked radii take four equal values. fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: Value) -> Result<(), String> { self.recall(ctx); let rejects = || FieldRefusal::Rejects(&value).message(field); @@ -516,6 +537,7 @@ impl StackDialog for CreateShapeDialog { let polygon = matches!(kind, ShapeKind::Polygon | ShapeKind::Star); let shown = match field { "radii" | "linkRadii" => rect, + "cornerRadius" => kind == ShapeKind::Triangle, "sides" | "starRatio" => polygon, _ => true, }; @@ -545,6 +567,10 @@ impl StackDialog for CreateShapeDialog { o.radii = radii.map(|radius| radius.clamp(0.0, MAX_RADIUS)); } "linkRadii" => o.link_radii = value.as_bool().ok_or_else(rejects)?, + "cornerRadius" => { + let radius = value.as_f64().filter(|radius| radius.is_finite()).ok_or_else(rejects)?; + o.radii = [radius.clamp(*RADIUS_RANGE.start(), *RADIUS_RANGE.end()); 4]; + } "sides" => { let sides = value.as_f64().ok_or_else(rejects)?; o.sides = sides.round().clamp(f64::from(*SIDES.start()), f64::from(*SIDES.end())) as u32; diff --git a/crates/draw/src/ui/shape_drag/mod.rs b/crates/draw/src/ui/shape_drag/mod.rs index 9d24fe9690..c065ede2a5 100644 --- a/crates/draw/src/ui/shape_drag/mod.rs +++ b/crates/draw/src/ui/shape_drag/mod.rs @@ -115,7 +115,8 @@ impl Default for BoxConstraints { pub struct ShapeDragOptions { /// Which shape the drag draws. pub kind: ShapeKind, - /// The Rectangle's corner radius; over 0 draws four equal radii. + /// The Rectangle's corner radius, over 0 drawing four equal radii; for a Triangle, the radius of its three + /// corners. pub corner_radius: f64, /// The polygon's sides or the star's points, in [`SIDES`](crate::geometry::shape::SIDES). pub sides: u32, @@ -136,7 +137,7 @@ impl ShapeDragOptions { ShapeDragOptions { kind, ..ShapeDragOptions::default() } } - /// The Rectangle's corner radius. + /// The Rectangle's or the Triangle's corner radius. #[must_use] pub fn corner_radius(mut self, radius: f64) -> Self { self.corner_radius = radius; diff --git a/crates/draw/src/ui/shape_drag/tool.rs b/crates/draw/src/ui/shape_drag/tool.rs index d21a7a8182..0660c2bc5c 100644 --- a/crates/draw/src/ui/shape_drag/tool.rs +++ b/crates/draw/src/ui/shape_drag/tool.rs @@ -150,7 +150,7 @@ impl ShapeDragTool { /// when a side is under 1 px: [`box_drag`] for the box kinds under the options' constraints, ⇧ /// toggling Square and ⌥ From Center (Rectangle with four equal radii when /// `corner_radius` > 0, Rounded Rectangle always with them, Triangle filling the box (⇧: the equilateral - /// triangle in the square's circle), Polygon and + /// triangle in the square's circle) with its corners rounded by `corner_radius`, Polygon and /// Star with the options' sides and ratio, Custom a `Custom` box keeping proportions with ⇧), /// [`line_drag`] for a Line (weight at least 1, ⇧ snapping the end by [`line_shift`]), and /// [`RadialFrame::drag`] in the radial frame. @@ -194,7 +194,7 @@ impl ShapeDragTool { ShapeKind::Rectangle => ShapeGeometry::Rect { rect, radii: [0.0; 4] }, ShapeKind::RoundedRectangle => ShapeGeometry::Rect { rect, radii }, ShapeKind::Ellipse => ShapeGeometry::Ellipse { rect }, - ShapeKind::Triangle => ShapeGeometry::Triangle { rect: if rule.square { equilateral_in(rect) } else { rect } }, + ShapeKind::Triangle => ShapeGeometry::Triangle { rect: if rule.square { equilateral_in(rect) } else { rect }, corner_radius: radii[0] }, ShapeKind::Polygon => ShapeGeometry::Polygon { rect, sides: drag.sides, star_ratio: 1.0 }, ShapeKind::Star => ShapeGeometry::Polygon { rect, sides: drag.sides, star_ratio: o.star_ratio }, ShapeKind::Custom | ShapeKind::Line => ShapeGeometry::Custom { rect, keep_proportions: mods.shift }, diff --git a/crates/draw/src/ui/transform/session/settings.rs b/crates/draw/src/ui/transform/session/settings.rs index 72601b2bc3..3a779f3ba8 100644 --- a/crates/draw/src/ui/transform/session/settings.rs +++ b/crates/draw/src/ui/transform/session/settings.rs @@ -49,7 +49,7 @@ impl TransformPreset { /// How the transform resamples the moving pixels: PhotoCraft's three choices (LC11). The app maps /// them to its engine; [`id`](Self::id) gives PhotoCraft's ids. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum Interpolation { @@ -100,7 +100,7 @@ pub enum TransformChoice { /// Free Transform's persisted section: the app keeps it with its preferences. Unknown fields are /// ignored, missing ones take their defaults. -#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct TransformSettings { diff --git a/crates/draw/src/ui/transform/transform_box.rs b/crates/draw/src/ui/transform/transform_box.rs index 6b6594715b..2169a87453 100644 --- a/crates/draw/src/ui/transform/transform_box.rs +++ b/crates/draw/src/ui/transform/transform_box.rs @@ -493,8 +493,9 @@ pub struct TransformBox<'a> { #[prop] round_handles: bool, /// The side of the corner and side handles in points, for a host with a handle size preference; `None` uses the - /// theme's (`size.handle.md`). A handle's reach grows with a larger side and stays at least the theme's. - #[prop] + /// theme's (`size.handle.md`), as does a side that is zero, negative or not finite. A handle's reach grows with a + /// larger side and stays at least the theme's. + #[prop(quantity = "points, from the host's handle size preference")] handle_side: Option, /// Draws the box as a live line's controls (the Line tool's live line as the whole selection). Only the two ends /// take a press and the keys, each as the box handle it points to ([`LineLook`]), so an end drag scales the box as @@ -585,14 +586,19 @@ impl<'a> TransformBox<'a> { self.color.map_or(StrokeColor::from(theme), StrokeColor::from) } + /// The host's handle side when it is a finite side above zero; `None` for none or any other value. + fn host_handle_side(&self) -> Option { + self.handle_side.filter(|side| side.is_finite() && *side > 0.0) + } + /// The side of a corner or side handle: the host's, else the theme's. fn side_of_handles(&self, style: &TransformBoxStyle) -> f32 { - self.handle_side.unwrap_or(style.handle.side) + self.host_handle_side().unwrap_or(style.handle.side) } /// The hit radius of a corner or side handle: the theme's, or more for a host's larger handle. fn reach_of_handles(&self, style: &TransformBoxStyle) -> f32 { - self.handle_side.map_or(style.handle_reach, |side| style.handle_reach.max(side * HANDLE_REACH_IN_HANDLES)) + self.host_handle_side().map_or(style.handle_reach, |side| style.handle_reach.max(side * HANDLE_REACH_IN_HANDLES)) } /// Whether the middle of the box is a move part: the reference point is hidden, so it does not take that place. @@ -842,7 +848,7 @@ impl<'a> TransformBox<'a> { let suspend = suspend_key(snap.as_ref()); for (reference, part) in self.pointer_parts() { let Some(result) = cx.part_if_declared(reference) else { continue }; - let (press, hover) = (result.press, result.hover_pos.filter(|_| result.hovered)); + let (press, hover) = (result.press, cx.hover_pos(reference)); let mods = self.mods.unwrap_or(press.mods); let acting = drag_mods(mods, suspend); if let Some(pos) = hover diff --git a/crates/draw/tests/it/bezier.rs b/crates/draw/tests/it/bezier.rs index 7db3cbe69a..82a6612dc5 100644 --- a/crates/draw/tests/it/bezier.rs +++ b/crates/draw/tests/it/bezier.rs @@ -1,12 +1,13 @@ //! `BezierOverlay`: the pure path operations, and the overlay's pointer, keyboard and tools through the public API. +use craft_behavior::geometry::{SnapKind, SnapOptions, SnapTarget, SnapTargets}; use craft_behavior::kurbo::{ParamCurve as _, Point, Size, Vec2}; use craft_behavior::{CanvasView, EditEvent}; use craft_draw::ui::{ AnchorDelete, AnchorTool, AnchorsShown, BezierHit, BezierOverlay, BezierTool, EditPath, EditSubpath, HandleSide, HandlesShown, Knot, KnotRef, PathEdit, PathSelection, PathTool, SegmentMark, }; -use craft_ui::canvas::{Canvas, Guide, ToolHost, tool_pass}; +use craft_ui::canvas::{Canvas, Guide, Momentary, NavigationOptions, Snap, ToolHost, tool_pass}; use craft_ui::canvas_controls::Guides; use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; use craft_ui::primitives::cancel_press_of; @@ -176,6 +177,7 @@ struct State { paths: Vec, selection: PathSelection, guides: Vec, + snap: Option, tool: BezierTool, handles: HandlesShown, anchors: AnchorsShown, @@ -199,6 +201,8 @@ struct State { tool_clicks: usize, /// The anchor tool the canvas runs under the overlay, if any. canvas_tool: Option, + /// The app-owned momentary navigation set, enabled by tests that exercise Space-to-Hand routing. + momentary: Option, /// Passes in which that tool ran a gesture. tool_gestures: usize, } @@ -246,6 +250,7 @@ fn harness_with(paths: Vec, pans: bool) -> Harness { paths, selection: PathSelection::default(), guides: Vec::new(), + snap: None, tool: BezierTool::Direct, handles: HandlesShown::Selected, anchors: AnchorsShown::All, @@ -264,6 +269,7 @@ fn harness_with(paths: Vec, pans: bool) -> Harness { lone_selects: 0, tool_clicks: 0, canvas_tool: None, + momentary: None, tool_gestures: 0, })); let shown = Rc::clone(&state); @@ -285,6 +291,10 @@ fn harness_with(paths: Vec, pans: bool) -> Harness { let canvas_id = ui.scope_id().with("document canvas"); let canvas = Canvas::new("Document").id(canvas_id).view(view).precise_cursors(st.precise); let canvas = if st.pans { canvas.document(Size::new(4000.0, 4000.0)) } else { canvas }; + let canvas = match &st.snap { + Some(snap) => canvas.snap(snap.clone()), + None => canvas, + }; let mut reply = None; let canvas = canvas.show(ui, |ui, body| { // The guides lie under the paths: a stack position hides the levels of the ones below it. @@ -298,18 +308,25 @@ fn harness_with(paths: Vec, pans: bool) -> Harness { .segment_mark(st.segment_mark) .show_at(ui, body.rect); if let (Some(tool), Some(pass)) = (st.canvas_tool, tool_pass(&body.env)) { - reply = Some(ToolHost::new().run(ui, &pass, &mut AnchorTool::new(tool))); + let mut host = ToolHost::new(); + if let Some(momentary) = st.momentary.as_mut() { + host = host.momentary(momentary); + } + reply = Some(host.run(ui, &pass, &mut AnchorTool::new(tool))); } output }); if canvas.output.click_at().is_some() { st.tool_clicks += 1; } - if let Some(reply) = reply { + let tool_view = if let Some(reply) = reply { st.tool_gestures += usize::from(reply.gesture.is_some()); - } + reply.view + } else { + None + }; if st.pans { - st.view = canvas.output.view.or(st.view); + st.view = tool_view.or(canvas.output.view).or(st.view); } let Some(output) = canvas.inner else { return }; st.id = output.edit.response.id; @@ -1416,3 +1433,282 @@ fn a_cancelled_press_reports_nothing_on_release() { assert_eq!(st.changes.len(), changes, "{:?}", st.changes); assert_eq!(st.paths, before); } + +// Add Anchor owns one drag while Space temporarily translates the new anchor and its handles. Letting Space go +// resumes pulling the handles from that translated anchor; the canvas never takes this owned drag to pan. +#[trial] +fn space_moves_the_pulled_anchor_then_release_resumes_its_handles() { + let space_key = |pressed| egui::Event::Key { + key: egui::Key::Space, + physical_key: Some(egui::Key::Space), + pressed, + repeat: false, + modifiers: egui::Modifiers::NONE, + }; + let close = |a: Vec2, b: Vec2| (a - b).hypot() < 1e-6; + let mut h = harness_with(vec![path_a(), path_b()], true); + h.update(|st| { + st.tool = BezierTool::AddAnchor; + st.canvas_tool = Some(PathTool::AddAnchor); + st.momentary = Some(Momentary::new(NavigationOptions::default())); + }); + let at = h.screen(p(110.0, 60.0)); + let pulled_at = at + vec2(0.0, 60.0); + h.press_at(at); + h.move_to(at + vec2(0.0, 30.0)); + h.move_to(pulled_at); + let (pulled, view) = { + let st = h.state.borrow(); + assert_eq!(st.paths[0].subpaths[0].knots.len(), 5); + assert_eq!(st.selection, sel(1, &[(0, 1)])); + let knot = st.paths[0].subpaths[0].knots[1]; + assert!(knot.anchor.distance(p(110.0, 60.0)) < 1e-3); + assert!(close(knot.out_ctrl - knot.anchor, Vec2::new(0.0, 60.0)) && knot.smooth); + (knot, st.view.expect("the canvas showed")) + }; + + h.fixture.frame(vec![space_key(true)]); + { + let st = h.state.borrow(); + assert_eq!(st.paths[0].subpaths[0].knots[1], pulled, "Space down alone must not jump the anchor or handles"); + } + let moved_at = pulled_at + vec2(30.0, 20.0); + h.move_to(pulled_at + vec2(15.0, 10.0)); + h.move_to(moved_at); + let moved = { + let st = h.state.borrow(); + let knot = st.paths[0].subpaths[0].knots[1]; + let by = Vec2::new(30.0, 20.0); + assert!(close(knot.anchor - pulled.anchor, by), "the held key moves the new anchor with the pointer: {knot:?}"); + assert!( + close(knot.out_ctrl - pulled.out_ctrl, by) && close(knot.in_ctrl - pulled.in_ctrl, by), + "both handles travel with the anchor: {knot:?}" + ); + assert!(knot.smooth); + assert_eq!(st.view.expect("the canvas showed").center, view.center, "an overlay-owned drag must not turn into a pan"); + assert_eq!(st.paths[0].subpaths[0].knots.len(), 5, "Space adds no second knot"); + assert_eq!(st.selection, sel(1, &[(0, 1)])); + assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1); + assert!(!st.seen.contains(&Seen::Commit) && !st.seen.contains(&Seen::Cancel)); + knot + }; + + h.fixture.frame(vec![space_key(false)]); + assert_eq!(h.state.borrow().paths[0].subpaths[0].knots[1], moved, "Space up alone preserves the current geometry"); + let end = moved_at + vec2(20.0, 10.0); + h.move_to(moved_at + vec2(10.0, 5.0)); + h.move_to(end); + { + let st = h.state.borrow(); + let knot = st.paths[0].subpaths[0].knots[1]; + assert!(knot.anchor.distance(moved.anchor) < 1e-6, "released Space leaves the translated anchor in place"); + assert!(knot.out_ctrl.distance(view.to_doc(end)) < 1e-6, "the handle follows the pointer again"); + assert!(close(knot.in_ctrl - knot.anchor, -(knot.out_ctrl - knot.anchor)) && knot.smooth); + assert!(!close(knot.out_ctrl - knot.anchor, moved.out_ctrl - moved.anchor), "pulling resumes rather than freezing the handles"); + assert_eq!(st.view.expect("the canvas showed").center, view.center); + } + h.release_at(end); + let st = h.state.borrow(); + assert_eq!(st.paths[0].subpaths[0].knots.len(), 5); + assert_eq!(st.selection, sel(1, &[(0, 1)])); + assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1); + assert_eq!(st.seen.iter().filter(|s| **s == Seen::Commit).count(), 1); + assert_eq!((st.seen.first(), st.seen.last()), (Some(&Seen::Begin), Some(&Seen::Commit))); + assert!(!st.seen.contains(&Seen::Cancel) && !st.seen.contains(&Seen::Set)); + assert!(st.inserts.is_empty(), "this drag is not an Insert-key report"); + drop(st); + + space_before_the_first_movement_translates_from_the_press(space_key); + space_release_preserves_raw_geometry_until_constraints_change(space_key); + space_release_applies_only_an_alt_modifier_still_held(space_key); +} + +fn space_before_the_first_movement_translates_from_the_press(space_key: fn(bool) -> egui::Event) { + // Space after the press but before the first movement translates from the press, not from a first pulled handle. + let mut h = harness_with(vec![path_a(), path_b()], true); + h.update(|st| { + st.tool = BezierTool::AddAnchor; + st.canvas_tool = Some(PathTool::AddAnchor); + st.momentary = Some(Momentary::new(NavigationOptions::default())); + }); + let at = h.screen(p(110.0, 60.0)); + let to = at + vec2(30.0, 20.0); + h.press_at(at); + h.fixture.frame(vec![space_key(true)]); + h.move_to(to); + let translated = h.state.borrow().paths[0].subpaths[0].knots[1]; + assert!(translated.anchor.distance(p(140.0, 80.0)) < 1e-3, "the first Space move includes all travel from the press: {translated:?}"); + assert!(near(translated.in_ctrl, translated.anchor) && near(translated.out_ctrl, translated.anchor)); + h.fixture.frame(vec![space_key(false)]).frame(Vec::new()); + assert_eq!(h.state.borrow().paths[0].subpaths[0].knots[1], translated); + let end = to + vec2(20.0, 10.0); + h.move_to(end); + let resumed = h.state.borrow().paths[0].subpaths[0].knots[1]; + assert!(near(resumed.anchor, translated.anchor) && resumed.out_ctrl.distance(h.state.borrow().view.unwrap().to_doc(end)) < 1e-6); + h.release_at(end); + assert_eq!(h.state.borrow().seen.iter().filter(|s| **s == Seen::Begin).count(), 1); + assert_eq!(h.state.borrow().seen.iter().filter(|s| **s == Seen::Commit).count(), 1); +} + +fn space_release_preserves_raw_geometry_until_constraints_change(space_key: fn(bool) -> egui::Event) { + // A real canvas Snap would pull x=160 to the guide at x=165. Space keeps raw translation; release alone must + // not apply that snap, including later stationary passes. Moving or changing Shift/Alt still reads constraints. + let mut targets = SnapTargets::new(); + targets.add(SnapTarget::new(craft_behavior::Axis::Y, 165.0, SnapKind::Guide)); + let mut h = harness_with(vec![path_a(), path_b()], true); + h.update(|st| { + st.tool = BezierTool::AddAnchor; + st.canvas_tool = Some(PathTool::AddAnchor); + st.momentary = Some(Momentary::new(NavigationOptions::default())); + st.snap = Some(Snap::new(std::sync::Arc::new(targets), SnapOptions::default())); + }); + let at = h.screen(p(110.0, 60.0)); + let pulled_at = at + vec2(20.0, 60.0); + h.press_at(at); + h.move_to(at + vec2(10.0, 30.0)); + h.move_to(pulled_at); + let pulled = h.state.borrow().paths[0].subpaths[0].knots[1]; + h.fixture.frame(vec![space_key(true)]); + let moved_at = pulled_at + vec2(30.0, 20.0); + h.move_to(moved_at); + let moved = h.state.borrow().paths[0].subpaths[0].knots[1]; + assert!(near(moved.anchor, pulled.anchor + Vec2::new(30.0, 20.0))); + assert!(moved.out_ctrl.distance(p(160.0, 140.0)) < 1e-3 && near(moved.in_ctrl, pulled.in_ctrl + Vec2::new(30.0, 20.0))); + h.fixture.frame(vec![space_key(false)]).frame(Vec::new()).frame(Vec::new()); + h.move_to(moved_at); + assert_eq!(h.state.borrow().paths[0].subpaths[0].knots[1], moved, "no delayed stationary snap after Space release"); + // Modifier-only frames travel through the real input/press route: no synthetic PathEdit calls. + h.fixture.hold(egui::Modifiers::SHIFT).frame(Vec::new()); + let locked = h.state.borrow().paths[0].subpaths[0].knots[1]; + assert!( + near(locked.anchor, moved.anchor) && locked.out_ctrl.distance(p(140.0, 140.0)) < 1e-3, + "stationary Shift still locks the handle: {locked:?}" + ); + h.fixture.hold(egui::Modifiers::NONE).frame(Vec::new()); + let snapped = h.state.borrow().paths[0].subpaths[0].knots[1]; + assert!(snapped.out_ctrl.distance(p(165.0, 140.0)) < 1e-3, "releasing Shift reevaluates the actual enabled guide snap: {snapped:?}"); + h.fixture.hold(egui::Modifiers::ALT).frame(Vec::new()); + let alone = h.state.borrow().paths[0].subpaths[0].knots[1]; + assert!(near(alone.in_ctrl, snapped.in_ctrl) && !alone.smooth, "stationary Alt still breaks the handle pair: {alone:?}"); + let end = moved_at + vec2(20.0, 10.0); + h.move_to(end); + let resumed = h.state.borrow().paths[0].subpaths[0].knots[1]; + assert!(near(resumed.anchor, moved.anchor) && resumed.out_ctrl.distance(p(180.0, 150.0)) < 1e-3 && near(resumed.in_ctrl, alone.in_ctrl)); + h.fixture.hold(egui::Modifiers::NONE); + h.release_at(end); + let st = h.state.borrow(); + assert_eq!(st.paths[0].subpaths[0].knots.len(), 5); + assert_eq!(st.selection, sel(1, &[(0, 1)])); + assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1); + assert_eq!(st.seen.iter().filter(|s| **s == Seen::Commit).count(), 1); + assert!(!st.seen.contains(&Seen::Cancel) && !st.seen.contains(&Seen::Set)); +} + +fn space_release_applies_only_an_alt_modifier_still_held(space_key: fn(bool) -> egui::Event) { + // Alt held at Space-up breaks the pair, but an Alt tap released entirely during Space must not latch. + for keep_alt in [true, false] { + let mut h = harness_with(vec![path_a(), path_b()], true); + h.update(|st| { + st.tool = BezierTool::AddAnchor; + st.canvas_tool = Some(PathTool::AddAnchor); + st.momentary = Some(Momentary::new(NavigationOptions::default())); + }); + let at = h.screen(p(110.0, 60.0)); + let pulled_at = at + vec2(0.0, 60.0); + h.press_at(at); + h.move_to(at + vec2(0.0, 30.0)); + h.move_to(pulled_at); + h.fixture.frame(vec![space_key(true)]); + let moved_at = pulled_at + vec2(30.0, 20.0); + h.move_to(moved_at); + let moved = h.state.borrow().paths[0].subpaths[0].knots[1]; + assert!(moved.smooth, "the translated pair starts smooth"); + h.fixture.hold(egui::Modifiers::ALT).frame(Vec::new()); + assert_eq!(h.state.borrow().paths[0].subpaths[0].knots[1], moved, "Space keeps translation priority over Alt"); + if !keep_alt { + h.fixture.hold(egui::Modifiers::NONE).frame(Vec::new()); + } + let modifiers = if keep_alt { egui::Modifiers::ALT } else { egui::Modifiers::NONE }; + let space_up = egui::Event::Key { key: egui::Key::Space, physical_key: Some(egui::Key::Space), pressed: false, repeat: false, modifiers }; + h.fixture.frame(vec![space_up]).frame(Vec::new()); + let released = h.state.borrow().paths[0].subpaths[0].knots[1]; + assert_eq!((released.anchor, released.in_ctrl, released.out_ctrl), (moved.anchor, moved.in_ctrl, moved.out_ctrl)); + assert_eq!(released.smooth, !keep_alt, "only Alt still held at Space-up breaks the pair"); + h.release_at(moved_at); + let st = h.state.borrow(); + assert_eq!(st.paths[0].subpaths[0].knots[1], released, "mouse-up without travel commits the same geometry and smooth state"); + assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1); + assert_eq!(st.seen.iter().filter(|s| **s == Seen::Commit).count(), 1); + assert!(!st.seen.contains(&Seen::Cancel) && !st.seen.contains(&Seen::Set)); + } +} + +// Without an overlay-owned press, the same held key still gives the canvas its ordinary hand drag. +#[trial] +fn space_still_pans_when_add_anchor_has_no_drag() { + let space_key = |pressed| egui::Event::Key { + key: egui::Key::Space, + physical_key: Some(egui::Key::Space), + pressed, + repeat: false, + modifiers: egui::Modifiers::NONE, + }; + let mut h = harness_with(vec![path_a(), path_b()], true); + h.update(|st| { + st.tool = BezierTool::AddAnchor; + st.canvas_tool = Some(PathTool::AddAnchor); + st.momentary = Some(Momentary::new(NavigationOptions::default())); + }); + let (before, paths, selection) = { + let st = h.state.borrow(); + (st.view.expect("the canvas showed"), st.paths.clone(), st.selection.clone()) + }; + // This empty corner is clear of both paths. Drag toward the document interior, away from the origin clamp. + let at = before.rect.right_bottom() - vec2(24.0, 24.0); + h.move_to(at); + h.fixture.frame(vec![space_key(true)]); + h.drag(at, vec2(-60.0, -40.0)); + h.fixture.frame(vec![space_key(false)]).settle(); + let st = h.state.borrow(); + let after = st.view.expect("the canvas showed"); + assert!( + after.center.x > before.center.x && after.center.y > before.center.y && (after.center - before.center).hypot() > 1.0, + "ordinary Space still pans: {:?} -> {:?}", + before.center, + after.center + ); + assert_eq!(st.paths, paths, "panning does not edit the paths"); + assert_eq!(st.selection, selection); + assert!(st.changes.is_empty() && st.inserts.is_empty() && st.deletes.is_empty()); + assert!(!st.seen.contains(&Seen::Begin) && !st.seen.contains(&Seen::Commit)); +} + +// The translated public edit mirrors around the translated anchor and refuses nonfinite resulting geometry +// without partially inserting a knot. The original zero-translation constructor remains covered above. +#[trial] +fn a_translated_pull_mirrors_around_its_anchor_and_refuses_nonfinite_geometry() { + let straight = || ops_path(EditSubpath::new(vec![Knot::corner(p(0.0, 0.0)), Knot::corner(p(100.0, 0.0))], false)); + let mut path = straight(); + let by = Vec2::new(12.0, 7.0); + let out = p(80.0, 40.0); + assert!(PathEdit::pull_anchor_moved(7, kr(0), 0.5, by, out, None).apply(&mut path)); + let knot = path.subpaths[0].knots[1]; + assert!(near(knot.anchor, p(50.0, 0.0) + by) && near(knot.out_ctrl, out) && knot.smooth); + assert!((knot.in_ctrl - knot.anchor + (knot.out_ctrl - knot.anchor)).hypot() < 1e-6, "the mirror is about the moved anchor: {knot:?}"); + + let huge = f64::MAX * 0.75; + let far_x = f64::MAX * 0.25; + let far = ops_path(EditSubpath::new(vec![Knot::corner(p(far_x, 0.0)), Knot::corner(p(far_x, 100.0))], false)); + let at = far.subpaths[0].segment(0).unwrap().eval(0.5); + assert!(at.x.is_finite() && at.y.is_finite(), "the input curve is finite before translation"); + for (why, mut path, by, out) in [ + ("NaN offset", straight(), Vec2::new(f64::NAN, 0.0), p(50.0, 30.0)), + ("infinite offset", straight(), Vec2::new(0.0, f64::INFINITY), p(50.0, 30.0)), + ("overflowing anchor", far, Vec2::new(f64::MAX, 0.0), p(0.0, 0.0)), + ("overflowing mirrored handle", straight(), Vec2::new(huge, 0.0), p(-huge, 0.0)), + ] { + let before = path.clone(); + assert!(!PathEdit::pull_anchor_moved(7, kr(0), 0.5, by, out, None).apply(&mut path), "{why}"); + assert_eq!(path, before, "{why}: a refused edit changes nothing"); + } +} diff --git a/crates/draw/tests/it/corner.rs b/crates/draw/tests/it/corner.rs index 966d6b0650..37654cf4f0 100644 --- a/crates/draw/tests/it/corner.rs +++ b/crates/draw/tests/it/corner.rs @@ -118,3 +118,30 @@ fn a_triangle_apex_rounds_with_the_pointer_travel() { assert!(small > START_RADIUS, "a short pull rounds the apex: {small}"); assert!(large > small, "a longer pull rounds it more: {small} then {large}"); } + +/// A slightly rounded right-angle corner's widget sits `CornerWidgets::INSET` points inside the corner along each side, +/// at every density, so a host that hit-tests the widgets with that constant presses where the widget is drawn. +#[trial] +fn a_widget_sits_the_published_inset_inside_its_corner_at_every_density() { + for density in [craft_theme::Size::Compact, craft_theme::Size::Comfortable] { + let vertex = Rc::new(Cell::new(egui::Pos2::ZERO)); + let seen = Rc::clone(&vertex); + let mut targets = vec![square()]; + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_rect_before_wrap(); + let view = CanvasView::new(room, Point::new(210.0, 200.0), 1.0); + seen.set(view.to_screen(targets[0].corners[0].vertex)); + Canvas::new("Document") + .view(view) + .show(ui, |ui, body| CornerWidgets::new("Corner radius", Bind::bound(&mut targets)).show_at(ui, body.rect)); + }); + fixture.density(density).settle(); + let widget = fixture.by_label("Corner 1 of 4").expect("the first corner has a widget"); + let offset = widget.center() - vertex.get(); + let inset = CornerWidgets::INSET; + assert!( + (offset.x - inset).abs() < 0.5 && (offset.y - inset).abs() < 0.5, + "{density:?}: the widget sits {offset:?} from its corner, not {inset} along each side" + ); + } +} diff --git a/crates/draw/tests/it/paint_bar.rs b/crates/draw/tests/it/paint_bar.rs index 1ec55b56c5..39cb008986 100644 --- a/crates/draw/tests/it/paint_bar.rs +++ b/crates/draw/tests/it/paint_bar.rs @@ -1,5 +1,5 @@ //! `PaintBar`: which members each tool disables, the smoothing options, the gestures, the combinations list, what the -//! load swatch shows and a click on its menu. +//! load swatch shows, a click on its menu and the percents each field holds. use std::cell::RefCell; use std::rc::Rc; @@ -13,6 +13,7 @@ use craft_ui::contract::{Entry, ShowContainer as _}; use craft_ui::testing::focus::AccessActionKind; use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::{Fixture, Room, trial}; +use craft_ui::text::RangeAlert; use egui::{Color32, ColorImage, Key, Modifiers, Pos2, Shape, TextureId}; struct Host { @@ -21,16 +22,18 @@ struct Host { edits: Vec>>, /// How many passes reported Clean Brush. cleans: u32, + /// The range alerts the passes reported. + alerts: Vec, } fn harness(tool: PaintTool, eraser: EraserMode, prepare: impl FnOnce(&mut PaintValues)) -> (Fixture, Rc>) { let mut values = PaintValues::new(0u32); prepare(&mut values); - let host = Rc::new(RefCell::new(Host { values, eraser, edits: Vec::new(), cleans: 0 })); + let host = Rc::new(RefCell::new(Host { values, eraser, edits: Vec::new(), cleans: 0, alerts: Vec::new() })); let shown = Rc::clone(&host); let mut fixture = Fixture::new(move |ui| { let mut host = shown.borrow_mut(); - let Host { values, eraser, edits, cleans } = &mut *host; + let Host { values, eraser, edits, cleans, alerts } = &mut *host; let modes = [Entry::new(0u32, "Normal"), Entry::new(1u32, "Multiply")]; Bar::new("Options", BarKind::Options).show(ui, |ui, _| { let mut bar = PaintBar::new(tool, &mut *values).modes(&modes); @@ -40,6 +43,7 @@ fn harness(tool: PaintTool, eraser: EraserMode, prepare: impl FnOnce(&mut PaintV let out = bar.show(ui); edits.extend(out.edits); *cleans += u32::from(out.mixer_clean); + alerts.extend(out.out_of_range); }); }); // The options bar spans an application window; its members still run past it, and the bar scrolls. @@ -188,3 +192,46 @@ fn the_load_swatch_shows_each_mixer_load() { assert_eq!(load_swatch(&mut fixture), (value, pictures), "{load:?}"); } } + +fn type_into(fixture: &mut Fixture, label: &str, text: &str) { + let field = fixture.by_label(label).unwrap_or_else(|| panic!("the bar shows {label}")); + fixture.click(&field); + fixture.key(Key::A, Modifiers::COMMAND); + fixture.type_text(text); + fixture.key(Key::Enter, Modifiers::NONE); + fixture.settle(); +} + +/// Opacity and Flow hold 1 to 100 % on every tool that shows them (photocraft#16809): a typed 0 or -5 keeps 1 % and +/// 150 keeps 100 %, each reported once with a range that starts at 1 %. Smoothing still takes 0 with no alert. +#[trial] +fn opacity_and_flow_hold_one_to_a_hundred_percent_and_smoothing_still_takes_zero() { + let fields = [ + (PaintTool::Brush, "Opacity"), + (PaintTool::Brush, "Flow"), + (PaintTool::Eraser, "Opacity"), + (PaintTool::Eraser, "Flow"), + (PaintTool::Pencil, "Opacity"), + ]; + for (tool, label) in fields { + for (typed, kept) in [("0", 0.01), ("-5", 0.01), ("150", 1.0)] { + let (mut fixture, host) = harness(tool, EraserMode::Brush, |v| { + v.opacity = 0.5; + v.flow = 0.5; + }); + type_into(&mut fixture, label, typed); + let host = host.borrow(); + let value = if label == "Opacity" { host.values.opacity } else { host.values.flow }; + assert_eq!(value, kept, "{tool:?} {label}: {typed} keeps {kept}"); + assert_eq!(host.alerts.len(), 1, "{tool:?} {label}: {typed} is reported once: {:?}", host.alerts); + assert_eq!(host.alerts[0].range, 1.0..=100.0, "{tool:?} {label}: the alert names 1 to 100 %"); + } + } + + let (mut fixture, host) = harness(PaintTool::Brush, EraserMode::Brush, |v| v.smoothing.amount = 0.5); + page_to_end(&mut fixture); + type_into(&mut fixture, "Smoothing", "0"); + let host = host.borrow(); + assert_eq!(host.values.smoothing.amount, 0.0, "Smoothing takes 0"); + assert!(host.alerts.is_empty(), "and reports nothing: {:?}", host.alerts); +} diff --git a/crates/draw/tests/it/shape_cells.rs b/crates/draw/tests/it/shape_cells.rs index 5f58967853..e29ad711a4 100644 --- a/crates/draw/tests/it/shape_cells.rs +++ b/crates/draw/tests/it/shape_cells.rs @@ -285,3 +285,63 @@ fn a_fixed_size_typed_past_its_range_keeps_the_end_and_reports_it_once_and_an_em assert_eq!(host.borrow().value.fixed, (None, Some(50.0)), "an emptied field is empty"); assert_eq!(host.borrow().alerts.len(), 1, "an emptied field reports nothing"); } + +struct BarHost { + settings: ShapeToolSettings, + look: ShapeAppearance, + alerts: Vec, +} + +/// The Triangle tool's bar shows a Radius of its own (storytold/photocraft#13355): it starts from +/// `triangle_corner_radius`, not the Rectangle's radius, reports a typed value as `CornerRadius`, and keeps a value +/// past 0–150,000 px at the end with one range alert. The Ellipse's bar has no Radius. +#[trial] +#[allow(clippy::field_reassign_with_default, reason = "ShapeToolSettings is non_exhaustive: no struct literal outside its crate")] +fn the_triangle_bar_shows_its_own_radius() { + let kind = Rc::new(RefCell::new(ShapeKind::Triangle)); + let mut settings = ShapeToolSettings::default(); + settings.corner_radius = 7.0; + settings.triangle_corner_radius = 15.0; + let host = Rc::new(RefCell::new(BarHost { settings, look: ShapeAppearance::new(Paint::None, Paint::None, 0.0), alerts: Vec::new() })); + let (shown, shown_kind) = (Rc::clone(&host), Rc::clone(&kind)); + let mut fixture = Fixture::new(move |ui| { + let mut held = shown.borrow_mut(); + let BarHost { settings, look, alerts } = &mut *held; + let kind = *shown_kind.borrow(); + let out = Bar::new("Shape options", BarKind::Options).show(ui, |ui, _| ShapeBar::new(kind, settings, look, 72.0).show(ui)).inner; + let Some(out) = out else { return }; + if let Some(ShapeChange::CornerRadius(radius)) = out.events.iter().rev().find_map(|event| event.value()) { + settings.triangle_corner_radius = *radius; + } + alerts.extend(out.out_of_range); + }); + fixture.settle(); + let field = fixture.by_label("Radius").expect("the Triangle's Radius"); + let value = fixture.tree().value_of(field.node).map(str::to_owned); + assert!(value.as_deref().is_some_and(|v| v.starts_with("15")), "the Triangle's own radius, not the Rectangle's 7: {value:?}"); + type_into(&mut fixture, "Radius", "12"); + assert_eq!(host.borrow().settings.triangle_corner_radius, 12.0); + assert_eq!(host.borrow().settings.corner_radius, 7.0, "the Rectangle's radius is not touched"); + assert!(host.borrow().alerts.is_empty(), "12 is in range"); + type_into(&mut fixture, "Radius", "200000"); + assert_eq!(host.borrow().settings.triangle_corner_radius, 150_000.0, "a radius past the range keeps its end"); + assert_eq!(host.borrow().alerts.len(), 1, "the clamp is reported once"); + + *kind.borrow_mut() = ShapeKind::Ellipse; + fixture.settle(); + assert!(fixture.by_label("Radius").is_none(), "an Ellipse has no Radius"); +} + +/// The tool settings keep the Triangle's radius apart and read it from settings saved before it existed as 0. +#[trial] +fn the_triangle_radius_is_saved_with_the_tool_settings() { + let mut settings = ShapeToolSettings::default(); + assert_eq!(settings.triangle_corner_radius, 0.0, "sharp corners by default"); + settings.triangle_corner_radius = 25.0; + let saved = serde_json::to_value(settings).expect("settings serialize"); + assert_eq!(saved["triangleCornerRadius"], serde_json::json!(25.0)); + let back: ShapeToolSettings = serde_json::from_value(saved).expect("settings read back"); + assert_eq!(back.triangle_corner_radius, 25.0); + let old: ShapeToolSettings = serde_json::from_value(serde_json::json!({"cornerRadius": 4.0})).expect("older settings read"); + assert_eq!((old.corner_radius, old.triangle_corner_radius), (4.0, 0.0)); +} diff --git a/crates/draw/tests/it/shape_drag.rs b/crates/draw/tests/it/shape_drag.rs index 3eb3fd5027..53a366425e 100644 --- a/crates/draw/tests/it/shape_drag.rs +++ b/crates/draw/tests/it/shape_drag.rs @@ -1,6 +1,6 @@ //! The Shape tools and the Create Shape dialog. The view maps one document unit to one screen point. -use craft_behavior::kurbo::{Point, Rect, Vec2}; +use craft_behavior::kurbo::{ParamCurve as _, Point, Rect, Vec2}; use craft_behavior::{CanvasView, EditEvent}; use craft_draw::geometry::shape::ShapeGeometry; use craft_draw::ui::shape::VectorMode; @@ -373,3 +373,123 @@ fn create_shape_alerts_once_for_a_size_typed_past_its_range() { assert!(take(&host).is_none(), "{kind:?}: a width in range raises no alert"); } } + +/// The ends of each piece of `shape`'s outline, in order: for a rounded triangle, where each arc meets an edge. +fn anchors(shape: &ShapeGeometry) -> Vec { + shape.to_path(0.1).elements().iter().filter_map(|el| el.end_point()).collect() +} + +fn near(a: Point, b: Point) -> bool { + (a - b).hypot() < 1e-3 +} + +/// A triangle's corner radius rounds each corner with an arc tangent to both edges (storytold/photocraft#13355): radius +/// 20 in the box 400,300 to 600,400 meets the edges at the six points PhotoCraft's engine draws, and the arc at the +/// right-angled apex has its middle 20 px from its centre. +#[trial] +fn a_triangle_corner_radius_rounds_each_corner_tangent_to_its_edges() { + let shape = ShapeGeometry::Triangle { rect: Rect::new(400.0, 300.0, 600.0, 400.0), corner_radius: 20.0 }; + let want = [(485.858, 314.142), (514.142, 314.142), (565.858, 365.858), (551.716, 400.0), (448.284, 400.0), (434.142, 365.858)]; + let got = anchors(&shape); + assert_eq!(got.len(), want.len(), "two points per rounded corner: {got:?}"); + for (g, w) in got.iter().zip(want) { + assert!(near(*g, Point::new(w.0, w.1)), "{got:?}"); + } + let apex = shape.to_path(0.1).segments().next().expect("the apex arc"); + let middle = apex.eval(0.5); + // The apex's edges meet at 90°: the arc's centre lies 20·√2 below the apex, its middle 20 px above that. + let centre = Point::new(500.0, 300.0 + 20.0 * 2f64.sqrt()); + assert!(((middle - centre).hypot() - 20.0).abs() < 0.01, "the arc is circular: its middle is {middle:?}"); + assert_eq!(shape.bounds(), Rect::new(400.0, 300.0, 600.0, 400.0), "the bounds stay the box"); +} + +/// A radius larger than the triangle allows is capped by the shape: each arc ends at most halfway along an edge, the +/// outline stays inside the box, and no number is lost. Radius 0 keeps the sharp corners. +#[trial] +fn a_triangle_radius_past_what_the_shape_holds_is_capped_and_zero_is_sharp() { + let rect = Rect::new(0.0, 0.0, 200.0, 100.0); + for radius in [1.0e6, f64::INFINITY, f64::NAN, -5.0, 0.0] { + let got = anchors(&ShapeGeometry::Triangle { rect, corner_radius: radius }); + assert!(got.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{radius}: {got:?}"); + assert!(got.iter().all(|p| rect.inflate(1e-9, 1e-9).contains(*p)), "{radius}: the outline stays in the box: {got:?}"); + if radius.is_finite() && radius > 0.0 { + assert_eq!(got.len(), 6, "{radius}: still two points per corner"); + // The slanted edges (about 141 px) are shorter than the 200 px base: the arcs at their two ends meet + // halfway along each of them. + for middle in [Point::new(50.0, 50.0), Point::new(150.0, 50.0)] { + assert_eq!(got.iter().filter(|p| near(**p, middle)).count(), 2, "{radius}: capped at half a slanted edge: {got:?}"); + } + } else { + assert_eq!(got, vec![Point::new(100.0, 0.0), Point::new(200.0, 100.0), Point::new(0.0, 100.0)], "{radius}: sharp corners"); + } + } +} + +/// A Triangle drag takes the Triangle's own corner radius from the tool settings, not the Rectangle's, and a +/// Rectangle drag keeps the Rectangle's. +#[trial] +#[allow(clippy::field_reassign_with_default, reason = "ShapeToolSettings is non_exhaustive: no struct literal outside its crate")] +fn a_triangle_drag_takes_the_triangle_radius_from_the_settings() { + let mut settings = craft_draw::ui::shape::ShapeToolSettings::default(); + settings.corner_radius = 7.0; + settings.triangle_corner_radius = 20.0; + let mut shapes = Shapes::new(settings.drag_options(ShapeKind::Triangle)); + shapes.drag(PRESS, PRESS + Vec2::new(60.0, 40.0), Modifiers::NONE); + match shapes.committed() { + Some(ShapeGeometry::Triangle { corner_radius, .. }) => assert_eq!(corner_radius, 20.0), + other => panic!("a triangle: {other:?}"), + } + let mut shapes = Shapes::new(settings.drag_options(ShapeKind::Rectangle)); + shapes.drag(PRESS, PRESS + Vec2::new(60.0, 40.0), Modifiers::NONE); + match shapes.committed() { + Some(ShapeGeometry::Rect { radii, .. }) => assert_eq!(radii, [7.0; 4], "the Rectangle keeps its own radius"), + other => panic!("a rectangle: {other:?}"), + } +} + +/// Create Triangle starts from the tool's radius, shows it in one Radius field and answers it on OK; automation sets +/// it as `cornerRadius`, kept to 0–150,000 px, and the field is inactive for another kind. +#[trial] +fn create_triangle_takes_one_corner_radius() { + let ctx = egui::Context::default(); + let mut host = DialogHost::new(); + let options = CreateShapeOptions::initial(ShapeKind::Triangle, Point::new(10.0, 20.0)).tool(15.0, 5, 1.0).recalled(); + let id = host.open(CreateShapeDialog::new(options)); + assert_eq!(fields(&host, id)["cornerRadius"], json!(15.0), "the dialog starts from the tool's radius"); + let shape = confirm(&mut host, &ctx).expect("OK answers the triangle"); + assert_eq!(shape.geometry, ShapeGeometry::Triangle { rect: Rect::new(10.0, 20.0, 110.0, 120.0), corner_radius: 15.0 }); + + let id = open_create(&mut host, ShapeKind::Triangle); + assert_eq!(host.set_json_field(&ctx, id, "cornerRadius", json!(200000)), Ok(())); + assert_eq!(fields(&host, id)["cornerRadius"], json!(150000.0), "a radius past the range keeps its end"); + assert!(host.set_json_field(&ctx, id, "cornerRadius", json!("abc")).is_err(), "text that is not a number is refused"); + assert_eq!(host.set_json_field(&ctx, id, "cornerRadius", json!(8)), Ok(())); + match confirm(&mut host, &ctx).map(|shape| shape.geometry) { + Some(ShapeGeometry::Triangle { corner_radius, .. }) => assert_eq!(corner_radius, 8.0), + other => panic!("a triangle: {other:?}"), + } + + let id = open_create(&mut host, ShapeKind::Rectangle); + assert!(host.set_json_field(&ctx, id, "cornerRadius", json!(8)).is_err(), "a rectangle has no single corner radius"); + assert!(host.cancel::(&ctx)); + + // The field itself: one Radius field for the triangle, typed values taken. + let host = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&host); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.room(egui::Vec2::new(1200.0, 900.0)); + let options = CreateShapeOptions::initial(ShapeKind::Triangle, Point::new(10.0, 20.0)).tool(15.0, 5, 1.0).recalled(); + host.borrow_mut().open(CreateShapeDialog::new(options)); + fixture.settle(); + let names: Vec = + fixture.by_role(Role::SPIN_BUTTON).into_iter().filter_map(|field| fixture.tree().name_of(field.node).map(str::to_owned)).collect(); + assert_eq!(names.iter().filter(|name| name.as_str() == "Radius").count(), 1, "one Radius field: {names:?}"); + assert!(!names.iter().any(|name| name == "Top Left" || name == "Sides"), "no rectangle radii or sides: {names:?}"); + let radius = + fixture.by_role(Role::SPIN_BUTTON).into_iter().find(|field| fixture.tree().name_of(field.node) == Some("Radius")).expect("the Radius field"); + fixture.click(&radius).settle(); + fixture.key(Key::A, Modifiers::COMMAND).type_text("30"); + fixture.key(Key::Tab, Modifiers::NONE).settle(); + let radii = host.borrow().get::().map(|dialog| dialog.options().radii); + assert_eq!(radii, Some([30.0; 4]), "the typed radius is the triangle's"); +} diff --git a/crates/draw/tests/it/transform_box.rs b/crates/draw/tests/it/transform_box.rs index 90c8f0568e..9448dbb9f3 100644 --- a/crates/draw/tests/it/transform_box.rs +++ b/crates/draw/tests/it/transform_box.rs @@ -1678,6 +1678,43 @@ fn a_host_handle_side_sets_the_drawn_handle_square() { assert!(large > small, "a larger side draws a larger square: {large} against {small}"); } +/// A host handle side that is zero, negative or not finite draws the theme's handle and keeps the theme's reach. +#[trial] +fn an_unusable_host_handle_side_uses_the_themes() { + let corner_side = |side: Option| { + let mut h = harness(BoxState::from_rect(RECT), |config| config.handle_side = side); + let corner = h.screen(Point::new(RECT.x1, RECT.y1)); + h.fixture + .frame_shapes() + .iter() + .filter_map(|shape| match shape { + Shape::Rect(square) if (square.rect.center() - corner).length() < 0.5 => Some(square.rect.width()), + _ => None, + }) + .collect::>() + }; + let theme = corner_side(None); + assert!(!theme.is_empty(), "the theme's corner handle is drawn"); + // 3 points in from the bottom right corner on both axes: inside the theme's handle reach. + let near = Point::new(RECT.x1 - 3.0, RECT.y1 - 3.0); + for side in [0.0, -6.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + assert_eq!(corner_side(Some(side)), theme, "a side of {side} draws the theme's corner handle"); + let mut h = harness(BoxState::from_rect(RECT), |config| { + config.rules = free_rules(); + config.handle_side = Some(side); + }); + hover(&mut h, near); + assert_eq!(h.host.borrow().hovered, Some(BoxPart::Corner(2)), "a side of {side} keeps the theme's reach"); + // Far outside the theme's reach: an infinite side must not widen the reach to the whole canvas. + let mut far = harness(BoxState::from_rect(RECT), |config| { + config.rules = free_rules(); + config.handle_side = Some(side); + }); + hover(&mut far, Point::new(RECT.x1 + 60.0, RECT.y1 + 60.0)); + assert_ne!(far.host.borrow().hovered, Some(BoxPart::Corner(2)), "a side of {side} does not widen the reach"); + } +} + /// A large host handle takes a press anywhere on its square, also past the theme's reach, and the press drags it. #[trial] fn a_press_just_inside_a_large_handles_edge_grabs_it() { diff --git a/crates/drawingml/src/chart.rs b/crates/drawingml/src/chart.rs index 91321e351f..6e3f14e6f7 100644 --- a/crates/drawingml/src/chart.rs +++ b/crates/drawingml/src/chart.rs @@ -1773,6 +1773,8 @@ mod chartex_tests { assert!(stats[0].iter().all(Option::is_some)); // Enough series to cap the groups so the result stays within MAX_BOX_CELLS. let series = MAX_BOX_CELLS / n * 2; + // Keep 100 values beyond the group cap without cloning the unused tail. + c.series[0].values.truncate(MAX_BOX_CELLS / series + 100); c.series = vec![c.series[0].clone(); series]; let (groups, stats) = c.box_groups(); assert_eq!(groups.len(), MAX_BOX_CELLS / series); diff --git a/crates/exr/src/decode.rs b/crates/exr/src/decode.rs index 94efc864de..9bfdf541ad 100644 --- a/crates/exr/src/decode.rs +++ b/crates/exr/src/decode.rs @@ -1,7 +1,7 @@ //! Bounded OpenEXR reading and writing on top of the `exr` crate (feature `decode`). //! //! - [`parts`] lists every part from the headers alone (size, windows, channels, compression, -//! text attributes), after checking the declared sizes against [`Limits`] and the file's size. +//! views, text attributes), after checking the declared sizes against [`Limits`] and the file's size. //! - [`pick_part`] chooses the part a plain picture decode shows: the best colour channel group //! ([`crate::channels::color_channels`]), the earliest part on a tie. //! - [`decode_part`] decodes the channels of one flat part that a filter keeps, in their stored @@ -161,6 +161,11 @@ pub struct PartInfo { pub name: Option, /// The `view` attribute of a stereo part. pub view: Option, + /// The `multiView` attribute of a single-part stereo file: its view names, the default view + /// first. A channel without a period is the default view's; another view's channels carry + /// the view name before the channel's own (`right.R`, `diffuse.right.R`). Empty without the + /// attribute. + pub multi_view: Vec, pub data_window: Window, pub display_window: Window, pub deep: bool, @@ -317,6 +322,7 @@ pub(crate) fn part_info(index: usize, header: &Header) -> PartInfo { index, name: header.own_attributes.layer_name.as_ref().map(|n| n.to_string()), view: header.own_attributes.view_name.as_ref().map(|v| v.to_string()), + multi_view: header.own_attributes.multi_view_names.iter().flatten().map(|v| v.to_string()).collect(), data_window: Window { x: header.own_attributes.layer_position.0, y: header.own_attributes.layer_position.1, width: w, height: h }, display_window: Window { x: display.position.0, y: display.position.1, width: dw, height: dh }, deep: header.deep, diff --git a/crates/exr/src/decode_tests.rs b/crates/exr/src/decode_tests.rs index 59d2c08ff7..fd279580b6 100644 --- a/crates/exr/src/decode_tests.rs +++ b/crates/exr/src/decode_tests.rs @@ -86,6 +86,32 @@ fn multi_part_files_list_and_decode_one_part() { assert_eq!(pick_part(&[]), None); } +#[test] +fn a_multi_view_part_lists_its_views_default_first() { + let mut stereo = layer(None, 3, 2, &["B", "G", "R", "right.B", "right.G", "right.R"], false, exr::prelude::Compression::ZIP1); + stereo.attributes.multi_view_names = Some(vec![Text::from("left"), Text::from("right")]); + let bytes = file(vec![stereo], (3, 2)); + let listed = parts(&bytes, &Limits::default()).unwrap(); + assert_eq!(listed[0].multi_view, ["left", "right"]); + assert_eq!(listed[0].view, None); + // The decoded part carries the same header facts. + assert_eq!(decode_part(&bytes, 0, &all, &Limits::default()).unwrap().info.multi_view, ["left", "right"]); + // The declared order, not a sorted one: the right view may be the default. + let mut right_first = layer(None, 3, 2, &["B", "G", "R", "left.B", "left.G", "left.R"], false, exr::prelude::Compression::ZIP1); + right_first.attributes.multi_view_names = Some(vec![Text::from("right"), Text::from("left")]); + assert_eq!(parts(&file(vec![right_first], (3, 2)), &Limits::default()).unwrap()[0].multi_view, ["right", "left"]); + + // Parts that each name their own view, and a plain file, have no `multiView`. + let mut left = layer(Some("beauty.left"), 3, 2, &["R"], false, exr::prelude::Compression::ZIP1); + left.attributes.view_name = Some(Text::from("left")); + let mut right = layer(Some("beauty.right"), 3, 2, &["R"], false, exr::prelude::Compression::ZIP1); + right.attributes.view_name = Some(Text::from("right")); + let listed = parts(&file(vec![left, right], (3, 2)), &Limits::default()).unwrap(); + assert_eq!(listed.iter().map(|p| (p.view.as_deref(), p.multi_view.len())).collect::>(), [(Some("left"), 0), (Some("right"), 0)]); + let plain = file(vec![layer(None, 3, 2, &["R"], false, exr::prelude::Compression::ZIP1)], (3, 2)); + assert!(parts(&plain, &Limits::default()).unwrap()[0].multi_view.is_empty()); +} + #[test] fn written_files_read_back() { let h: Vec = (0..6).map(|i| f16::from_f32(i as f32 / 4.0)).collect(); diff --git a/crates/exr/src/seek_tests.rs b/crates/exr/src/seek_tests.rs index 2bb2ddb071..f262de09d5 100644 --- a/crates/exr/src/seek_tests.rs +++ b/crates/exr/src/seek_tests.rs @@ -1456,7 +1456,8 @@ fn groups_must_be_slots_of_one_part_each_in_one_group() { #[test] fn the_estimate_covers_what_the_read_does() { // A flat colour in ZIP16 (decodes to far more than it reads), lines of a ramp, and tiles. - let (w, h) = (256usize, 160usize); + // 136 rows retain ZIP16's eight-row final block while reducing the 160-row upstream fixture. + let (w, h) = (256usize, 136usize); let list = vec![AnyChannel::new("R", FlatSamples::F32(vec![0.25; w * h])), AnyChannel::new("G", FlatSamples::F32(vec![0.5; w * h]))]; let encoding = Encoding { compression: Compression::ZIP16, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing }; let flat = file(vec![Layer::new((w, h), LayerAttributes::default(), encoding, AnyChannels::sort(list.into()))], (w, h)); diff --git a/crates/fcproj-format/src/lib.rs b/crates/fcproj-format/src/lib.rs index 11f7e5013f..73ce858f68 100644 --- a/crates/fcproj-format/src/lib.rs +++ b/crates/fcproj-format/src/lib.rs @@ -15,7 +15,7 @@ pub type Migration = fn(Value) -> Result; /// edit a shipped one. pub const MIGRATIONS: &[Migration] = &[ v1_to_v2, v2_to_v3, v3_to_v4, v4_to_v5, v5_to_v6, v6_to_v7, v7_to_v8, v8_to_v9, v9_to_v10, v10_to_v11, v11_to_v12, v12_to_v13, v13_to_v14, - v14_to_v15, v15_to_v16, v16_to_v17, v17_to_v18, + v14_to_v15, v15_to_v16, v16_to_v17, v17_to_v18, v18_to_v19, v19_to_v20, ]; /// The schema version this build writes (and the newest it reads). @@ -262,6 +262,19 @@ fn v17_to_v18(doc: Value) -> Result { Ok(doc) } +/// v18 → v19: Script Project items (`ItemKind::Script`: script lines, slates with linked takes, +/// marks and independently positioned thumbnails). Existing data needs no change; older builds +/// must refuse such projects instead of failing on or dropping the Script items when saving. +fn v18_to_v19(doc: Value) -> Result { + Ok(doc) +} + +/// v19 → v20: effect masks may carry a colour range. Existing masks have none; older builds must +/// refuse such projects instead of silently dropping saved colour ranges. +fn v19_to_v20(doc: Value) -> Result { + Ok(doc) +} + #[cfg(test)] mod tests { use super::*; @@ -272,10 +285,10 @@ mod tests { let bare = json!({"version": 2, "items": {}, "root": {}, "extra": [1, 2]}); assert_eq!(detect_version(&bare).unwrap(), 1); let migrated = migrate_with(MIGRATIONS, bare, 1).unwrap(); - assert_eq!(migrated["schema_version"], 18); + assert_eq!(migrated["schema_version"], SCHEMA_VERSION); assert_eq!(migrated["project"]["extra"], json!([1, 2])); assert_eq!(migrated["generator"], "FilmCraft (schema v1)"); - assert_eq!(detect_bytes(serde_json::to_string(&migrated).unwrap().as_bytes()).unwrap(), 18); + assert_eq!(detect_bytes(serde_json::to_string(&migrated).unwrap().as_bytes()).unwrap(), SCHEMA_VERSION); let parsed: EnvelopeIn = serde_json::from_value(migrated).unwrap(); assert!(parsed.view.is_none()); assert_eq!(parsed.project["extra"], json!([1, 2])); @@ -303,20 +316,58 @@ mod tests { let item = json!({"Media": {"interpret": {"par": [1, 1]}}}); let v17 = json!({"format": FORMAT_ID, "schema_version": 17, "project": {"items": {"1": {"kind": item}}, "root": {}}}); let up = migrate_with(MIGRATIONS, v17.clone(), 17).unwrap(); - assert_eq!(up["schema_version"], 18); + assert_eq!(up["schema_version"], SCHEMA_VERSION); assert_eq!(up["project"], v17["project"]); let raw = json!({"white_balance": {"Custom": {"temperature": 3200.0, "tint": 12.5}}, "exposure": -0.75}); let mut v18 = up; + v18["schema_version"] = json!(18); v18["project"]["items"]["1"]["kind"]["Media"]["interpret"]["raw"] = raw.clone(); let bytes = serde_json::to_vec(&v18).unwrap(); let (file, version): (EnvelopeIn, _) = decode(&bytes).unwrap(); assert_eq!(version, 18); assert_eq!(file.project["items"]["1"]["kind"]["Media"]["interpret"]["raw"], raw); } + /// Schema 19 (Script items): a v18 project upgrades with its data untouched, and a v19 project + /// with a Script item is read rather than refused as too new. + #[test] + fn v18_upgrades_and_v19_script_items_are_read() { + let media = json!({"Media": {"interpret": {"par": [1, 1]}}}); + let v18 = json!({"format": FORMAT_ID, "schema_version": 18, "project": {"items": {"1": {"kind": media}}, "root": {}}}); + let up = migrate_with(MIGRATIONS, v18.clone(), 18).unwrap(); + assert!(up["schema_version"].as_u64().unwrap() > 18); + assert_eq!(up["project"], v18["project"]); + let script = json!({"Script": {"lines": [{"id": 1, "text": "one"}], "slates": [{"id": 2, "takes": [{"id": 3, "source": 1}]}], "next_id": 4}}); + let mut v19 = up; + v19["schema_version"] = json!(19); + v19["project"]["items"]["2"] = json!({"kind": script.clone()}); + let bytes = serde_json::to_vec(&v19).unwrap(); + let (file, version): (EnvelopeIn, _) = decode(&bytes).unwrap(); + assert_eq!(version, 19); + assert_eq!(file.project["items"]["2"]["kind"], script); + assert_eq!(file.project["items"]["1"]["kind"], media); + } + /// Schema 20 (mask colour ranges): a v19 project upgrades with its data untouched, and a v20 + /// project with a colour range on a mask is read rather than refused as too new. + #[test] + fn v19_upgrades_and_v20_mask_colour_ranges_are_read() { + let mask = json!({"mode": "add"}); + let v19 = json!({"format": FORMAT_ID, "schema_version": 19, "project": {"items": {}, "root": {}, "effects": [{"masks": [mask]}]}}); + let up = migrate_with(MIGRATIONS, v19.clone(), 19).unwrap(); + assert!(up["schema_version"].as_u64().unwrap() > 19); + assert_eq!(up["project"], v19["project"]); + let range = json!({"hue": [0.1, 0.2], "luma": [0.0, 0.2]}); + let mut v20 = up; + v20["schema_version"] = json!(20); + v20["project"]["effects"][0]["masks"][0]["color"] = range.clone(); + let bytes = serde_json::to_vec(&v20).unwrap(); + let (file, version): (EnvelopeIn, _) = decode(&bytes).unwrap(); + assert_eq!(version, 20); + assert_eq!(file.project["effects"][0]["masks"][0]["color"], range); + } #[test] fn rejects_wrong_future_and_damaged_envelopes() { assert!(matches!(detect_bytes(br#"{"format":"other","schema_version":1}"#), Err(FormatError::NotAProject(_)))); - assert!(matches!(detect_bytes(br#"{"schema_version":19}"#), Err(FormatError::TooNew { found: 19, supported: 18 }))); + assert!(matches!(detect_bytes(br#"{"schema_version":21}"#), Err(FormatError::TooNew { found: 21, supported: 20 }))); assert!(matches!(detect_bytes(br#"{"schema_version":0}"#), Err(FormatError::TooOld { found: 0, oldest: 1 }))); assert!(matches!(detect_bytes(b"{"), Err(FormatError::Corrupt(_)))); assert!(matches!(migrate_with(MIGRATIONS, json!([]), 1), Err(FormatError::Migration { from: 1, .. }))); diff --git a/crates/fig/src/rest/tests.rs b/crates/fig/src/rest/tests.rs index e277814a5b..a8a207803f 100644 --- a/crates/fig/src/rest/tests.rs +++ b/crates/fig/src/rest/tests.rs @@ -748,9 +748,10 @@ fn nested(instances: bool) -> Kv<'static> { let mut nodes = vec![node(0, None, "DOCUMENT", "D", vec![]), node(1, Some((0, "!")), "CANVAS", "P", vec![])]; let levels = 270; if instances { + // Index every main, but map only a long and a short chain plus the top instance. for i in 0..levels { let id = 10 + 2 * i; - nodes.push(node(id, Some((1, "!")), "SYMBOL", "M", vec![("size", xy(1.0, 1.0))])); + nodes.push(node(id, (i == 0 || i + 2 == levels).then_some((1, "!")), "SYMBOL", "M", vec![("size", xy(1.0, 1.0))])); if i + 1 < levels { nodes.push(node( id + 1, diff --git a/crates/flow/README.md b/crates/flow/README.md index bb0a21de17..858ee31503 100644 --- a/crates/flow/README.md +++ b/crates/flow/README.md @@ -29,3 +29,12 @@ report of what an importer leaves out to stay within a limit (`Dropped`, `begin_ WordCraft's `crates/formats/src/model` (at `07f97737`), moved as it is onto craft-wordmodel. Image decoding for re-encoding (`decode_bounded`) stays with the RTF writer that needs it. + +## Grouped drawing hyperlinks + +Pictures, shapes and groups can retain their own target in `Img::link` or the corresponding +`Inline::Shape`/`Inline::Group` field. Each `Member::link` and `craft_wordmodel::para::GroupChild::link` +keeps that member's separate target through the document/flow conversions. Add `link: None` to +older Rust struct/variant literals that do not carry a target. Older JSON group children without +`link` deserialize as unlinked, and unlinked children omit that key when serialized. This does +not promise compatibility for every binary serde format or hyperlink activation in every exporter. diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index 4911e2f2b1..4162d89d04 100644 --- a/crates/flow/src/from_doc.rs +++ b/crates/flow/src/from_doc.rs @@ -1,12 +1,35 @@ use super::types::{ - BoxLook, Cell, FBlock, FComment, FTable, Flow, FlowOpts, Fmt, FmtChange, Img, Inline, Kind, ListInfo, MAX_DEPTH, MAX_GROUP_DEPTH, Member, Meta, - Para, RevMark, Spacing, + BoxLook, Cell, Dropped, FBlock, FComment, FTable, Flow, FlowOpts, Fmt, FmtChange, Img, Inline, Kind, ListInfo, MAX_DEPTH, MAX_GROUP_DEPTH, + MAX_LINK, MAX_RUN_STRINGS, Member, Meta, Para, RevMark, Spacing, dropped, }; use super::{ Arc, Block, Blocks, CharProps, Document, InlineObject, NumFormat, OBJ, PAGE_BREAK, ParaProps, Paragraph, StyleKind, Table, TextColor, Underline, VMerge, VertAlign, }; +/// One conversion's retained drawing targets, across roots, members and nested stories. +#[derive(Default)] +struct DrawingLinks { + bytes: usize, +} + +impl DrawingLinks { + fn keep(&mut self, target: Option<&str>) -> Option { + let target = target?; + if target.len() > MAX_LINK { + let _ = super::kept_link(target); + return None; + } + let Some(bytes) = self.bytes.checked_add(target.len()).filter(|&n| n <= MAX_RUN_STRINGS) else { + dropped(Dropped::RunStrings); + return None; + }; + let target = super::kept_link(target)?; + self.bytes = bytes; + Some(target.to_string()) + } +} + pub(super) fn uses_kind(blocks: &[FBlock], k: Kind, depth: usize) -> bool { depth <= MAX_DEPTH && blocks.iter().any(|b| match b { @@ -281,12 +304,12 @@ fn media_ext(key: &str, data: &[u8]) -> String { /// The flow inlines for a note reference, comment mark or field `o` of `doc`, when `opts` asks /// for them; `None` for other objects. `f` is the formatting of the run `o` is in. -fn rich_inlines(doc: &Document, o: &InlineObject, f: &Fmt, opts: FlowOpts) -> Option> { +fn rich_inlines(doc: &Document, o: &InlineObject, f: &Fmt, opts: FlowOpts, links: &mut DrawingLinks) -> Option> { Some(match o { InlineObject::NoteRef { kind, id, custom } if opts.notes => { // The note's content without its own mark (a note holds no notes). let story = doc.parts.get(id).map(|part| &part.blocks); - let mut blocks = story.map(|b| flow_blocks(doc, b, 0, FlowOpts { notes: false, ..opts })).unwrap_or_default(); + let mut blocks = story.map(|b| flow_blocks(doc, b, 0, FlowOpts { notes: false, ..opts }, links)).unwrap_or_default(); // The space after the mark is the mark's (see `to_doc`'s `note`); a tab or more // spaces there are the note's own. if let Some(FBlock::Para(first)) = blocks.first_mut() { @@ -305,7 +328,7 @@ fn rich_inlines(doc: &Document, o: &InlineObject, f: &Fmt, opts: FlowOpts) -> Op // comment that starts the thread), which have no place of their own. InlineObject::CommentStart { id } if opts.comments => { let Some(c) = doc.comments.get(id) else { return Some(Vec::new()) }; - let mut out = vec![Inline::Comment { id: *id, comment: Box::new(flow_comment(doc, c, None, opts)) }]; + let mut out = vec![Inline::Comment { id: *id, comment: Box::new(flow_comment(doc, c, None, opts, links)) }]; let mut thread = std::collections::BTreeSet::from([*id]); let mut k = 0; while let Some(Inline::Comment { id: at, .. }) = out.get(k) { @@ -313,7 +336,7 @@ fn rich_inlines(doc: &Document, o: &InlineObject, f: &Fmt, opts: FlowOpts) -> Op k += 1; for (rid, r) in doc.comments.iter().filter(|(_, r)| r.parent == Some(at)) { if thread.insert(*rid) { - out.push(Inline::Comment { id: *rid, comment: Box::new(flow_comment(doc, r, Some(*id), opts)) }); + out.push(Inline::Comment { id: *rid, comment: Box::new(flow_comment(doc, r, Some(*id), opts, links)) }); } } } @@ -328,7 +351,13 @@ fn rich_inlines(doc: &Document, o: &InlineObject, f: &Fmt, opts: FlowOpts) -> Op } // A text box's content, without notes, comments or boxes of its own. // A drawing shape, text box or group (pictures have their own place below). - InlineObject::Shape { .. } | InlineObject::Group { .. } if opts.boxes => vec![drawing_inline(doc, o, opts, 0, (1.0, 1.0))?], + InlineObject::Shape { .. } | InlineObject::Group { .. } if opts.boxes => { + let mut inline = drawing_inline(doc, o, opts, 0, (1.0, 1.0), links)?; + if let Inline::Shape { link, .. } | Inline::Group { link, .. } = &mut inline { + *link = links.keep(f.link.as_deref()); + } + vec![inline] + } InlineObject::FieldStart { instr, .. } if opts.fields => vec![Inline::FieldStart(instr.clone())], InlineObject::FieldEnd if opts.fields => vec![Inline::FieldEnd], // Where a bookmark ends, so it covers its text (Word's `_GoBack` is the last edit's spot). @@ -360,7 +389,7 @@ fn frame_freeform(corner: Option, w: f32, h: f32) -> craft_wordmodel::freef /// its size scaled by `scale` (a group's members are in its own coordinates). A shape or text /// box keeps its text, but not notes, comments or boxes of its own. `None` for what a flow has /// no drawing for: a freeform's paths, a picture whose data is missing. -fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize, scale: (f32, f32)) -> Option { +fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize, scale: (f32, f32), links: &mut DrawingLinks) -> Option { use craft_wordmodel::para::ShapeKind; let (sx, sy) = scale; match o { @@ -380,7 +409,7 @@ fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize }; let inner = FlowOpts { notes: false, comments: false, boxes: false, ..opts }; let part = story.and_then(|id| doc.parts.get(&id)); - let blocks = part.map(|p| flow_blocks(doc, &p.blocks, 0, inner)).unwrap_or_default(); + let blocks = part.map(|p| flow_blocks(doc, &p.blocks, 0, inner, links)).unwrap_or_default(); let look = BoxLook { fill: fill.clone().filter(|_| kind != ShapeKind::Line), line: stroke.filter(|_| stroke_width.is_finite() && *stroke_width > 0.0).map(|c| (c, stroke_width.min(12.0))), @@ -400,12 +429,13 @@ fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize }), }; 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 }) + Some(Inline::Shape { kind, w: w * sx, h: h * sy, float: kept_float(float), blocks, look, path, link: None }) } InlineObject::Image { media, w, h, alt, float, ole, crop, .. } => { let data = doc.media.get(media)?; let alt = if o.is_decorative() { "" } else { alt.as_str() }; Some(Inline::Image(Img { + link: None, data: data.clone(), ext: media_ext(media, data), w: w * sx, @@ -416,7 +446,7 @@ fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize crop: if opts.paras { *crop } else { [0.0; 4] }, })) } - InlineObject::Group { w, h, float, ch_w, ch_h, children, .. } if depth < MAX_GROUP_DEPTH => { + InlineObject::Group { w, h, float, ch_w, ch_h, children, .. } if depth <= MAX_GROUP_DEPTH => { let ratio = |outer: f32, inner: f32| { let r = outer / inner; if r.is_finite() && r > 0.0 { r } else { 1.0 } @@ -425,10 +455,15 @@ fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize let members: Vec = children .iter() .filter_map(|c| { - drawing_inline(doc, &c.obj, opts, depth + 1, inner).map(|inline| Member { x: c.x * inner.0, y: c.y * inner.1, inline }) + drawing_inline(doc, &c.obj, opts, depth + 1, inner, links).map(|inline| Member { + link: links.keep(c.link.as_deref()), + x: c.x * inner.0, + y: c.y * inner.1, + inline, + }) }) .collect(); - (!members.is_empty()).then(|| Inline::Group { w: w * sx, h: h * sy, float: kept_float(float), members }) + (!members.is_empty()).then(|| Inline::Group { w: w * sx, h: h * sy, float: kept_float(float), members, link: None }) } _ => None, } @@ -441,9 +476,9 @@ fn kept_float(f: &craft_wordmodel::para::Float) -> Option, opts: FlowOpts) -> FComment { +fn flow_comment(doc: &Document, c: &craft_wordmodel::Comment, parent: Option, opts: FlowOpts, links: &mut DrawingLinks) -> FComment { let story = doc.parts.get(&c.part).map(|p| &p.blocks); - let blocks = story.map(|b| flow_blocks(doc, b, 0, FlowOpts { notes: false, comments: false, ..opts })).unwrap_or_default(); + let blocks = story.map(|b| flow_blocks(doc, b, 0, FlowOpts { notes: false, comments: false, ..opts }, links)).unwrap_or_default(); FComment { author: c.author.clone(), initials: c.initials.clone(), date: c.date.clone(), resolved: c.resolved, parent, blocks } } @@ -495,12 +530,12 @@ fn shown_text(o: &InlineObject) -> &str { } pub fn flow_paras(doc: &Document, p: &Paragraph) -> Vec { - flow_paras_in(doc, p, FlowOpts::default()) + flow_paras_in(doc, p, FlowOpts::default(), &mut DrawingLinks::default()) } /// [`flow_paras`]; `tracked` keeps tracked changes: deleted text stays, and text carries its /// insertion and deletion marks. -fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec { +fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts, links: &mut DrawingLinks) -> Vec { let tracked = opts.tracked; let (kind, list) = para_kind(doc, p); let list = flow_list(doc, kind, list, p, opts); @@ -606,7 +641,7 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec { continue; } let from = out.inlines.len(); - if let Some(items) = obj.and_then(|o| rich_inlines(doc, o, &f, opts)) { + if let Some(items) = obj.and_then(|o| rich_inlines(doc, o, &f, opts, links)) { if !buf.is_empty() { out.push_text(&std::mem::take(&mut buf), &f); } @@ -624,6 +659,7 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec { let alt = if o.is_decorative() { "" } else { alt.as_str() }; match doc.media.get(media) { Some(data) => out.inlines.push(Inline::Image(Img { + link: links.keep(f.link.as_deref()), data: data.clone(), ext: media_ext(media, data), w: *w, @@ -794,8 +830,9 @@ fn graphic_group( line: stroke.filter(|_| stroke_width.is_finite() && *stroke_width > 0.0).map(|c| (c, stroke_width.min(12.0))), ..plain.clone() }; - let inline = Inline::Shape { kind: *kind, w: rect[2] * sx, h: rect[3] * sy, float: None, blocks: Vec::new(), look, path: None }; - Some(Member { x: rect[0] * sx, y: rect[1] * sy, inline }) + let inline = + Inline::Shape { kind: *kind, w: rect[2] * sx, h: rect[3] * sy, float: None, blocks: Vec::new(), look, path: None, link: None }; + Some(Member { link: None, x: rect[0] * sx, y: rect[1] * sy, inline }) } GraphicItem::Text { rect, text, size, color, bold, align, font, .. } if finite(rect) && !text.trim().is_empty() => { let size = if size.is_finite() { size.clamp(1.0, 400.0) } else { 11.0 }; @@ -815,6 +852,7 @@ fn graphic_group( ..Para::default() }; let inline = Inline::Shape { + link: None, kind: ShapeKind::Rectangle, w: bw, h: bh, @@ -823,11 +861,12 @@ fn graphic_group( look: plain.clone(), path: None, }; - Some(Member { x: rect[0] * sx, y, inline }) + Some(Member { link: None, x: rect[0] * sx, y, inline }) } GraphicItem::Image { rect, media } if finite(rect) => { let data = doc.media.get(media)?; let img = Img { + link: None, data: data.clone(), ext: media_ext(media, data), w: rect[2] * sx, @@ -837,7 +876,7 @@ fn graphic_group( object: None, crop: [0.0; 4], }; - Some(Member { x: rect[0] * sx, y: rect[1] * sy, inline: Inline::Image(img) }) + Some(Member { link: None, x: rect[0] * sx, y: rect[1] * sy, inline: Inline::Image(img) }) } _ => None, }) @@ -847,9 +886,9 @@ fn graphic_group( } // A group is as big as its members together (ODF 1.3 §10.3.15): an invisible rectangle the // size of the graphic keeps the room around its drawing. - let frame = Inline::Shape { kind: ShapeKind::Rectangle, w, h, float: None, blocks: Vec::new(), look: plain, path: None }; - let all = std::iter::once(Member { x: 0.0, y: 0.0, inline: frame }).chain(members).collect(); - Some(Inline::Group { w, h, float: kept_float(float), members: all }) + let frame = Inline::Shape { kind: ShapeKind::Rectangle, w, h, float: None, blocks: Vec::new(), look: plain, path: None, link: None }; + let all = std::iter::once(Member { link: None, x: 0.0, y: 0.0, inline: frame }).chain(members).collect(); + Some(Inline::Group { w, h, float: kept_float(float), members: all, link: None }) } /// The mark formatting of `out`, the last piece of `p`, when it holds no text (its height, its @@ -962,11 +1001,11 @@ type ItemText = [Option; 9]; /// item's text: one moved out of it (Enter, then Decrease Indent to the margin, the ruler, the /// Paragraph dialog…) is body text after the list. Asked of the paragraph itself, so whichever /// command moved it, the paragraph is where it shows. -fn flow_paras_at(doc: &Document, p: &Paragraph, opts: FlowOpts, at: &mut ItemText) -> Vec { +fn flow_paras_at(doc: &Document, p: &Paragraph, opts: FlowOpts, at: &mut ItemText, links: &mut DrawingLinks) -> Vec { let rp = doc.styles.resolve_para(&p.props); // (Its own indent, or its style's.) let left = rp.indent_left; - let mut paras = flow_paras_in(doc, p, opts); + let mut paras = flow_paras_in(doc, p, opts, links); if let Some(n) = rp.numbering.filter(|n| n.num != 0) { // The paragraph's own indent, else its level's, else its style's (as Word places it). let level = doc.numbering.level(n.num, n.level).map(|l| l.indent); @@ -995,7 +1034,7 @@ fn flow_paras_at(doc: &Document, p: &Paragraph, opts: FlowOpts, at: &mut ItemTex paras } -fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts) -> Vec { +fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts, links: &mut DrawingLinks) -> Vec { let mut out = Vec::new(); let mut skip = 0usize; let mut at: ItemText = [None; 9]; @@ -1013,7 +1052,7 @@ fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts) -> let from = out.len(); for b in bl.get(i..i + ix.0).unwrap_or(&[]) { if let Block::Para(p) = &**b { - out.extend(flow_paras_at(doc, p, tracked, &mut at).into_iter().map(FBlock::Para)); + out.extend(flow_paras_at(doc, p, tracked, &mut at, links).into_iter().map(FBlock::Para)); } } let n = out.len() - from; @@ -1024,12 +1063,12 @@ fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts) -> continue; } match &**b { - Block::Para(p) => out.extend(flow_paras_at(doc, p, tracked, &mut at).into_iter().map(FBlock::Para)), - Block::Table(t) if depth < MAX_DEPTH => out.push(FBlock::Table(flow_table(doc, t, depth, tracked))), + Block::Para(p) => out.extend(flow_paras_at(doc, p, tracked, &mut at, links).into_iter().map(FBlock::Para)), + Block::Table(t) if depth < MAX_DEPTH => out.push(FBlock::Table(flow_table(doc, t, depth, tracked, links))), Block::Table(t) => { for r in &t.rows { for c in &r.cells { - out.extend(flow_blocks(doc, &c.blocks, depth, tracked)); + out.extend(flow_blocks(doc, &c.blocks, depth, tracked, links)); } } } @@ -1160,7 +1199,7 @@ fn with_cell_text(doc: &Document, blocks: &Blocks, chr: &CharProps, align: Optio .collect() } -fn flow_table(doc: &Document, t: &Table, depth: usize, tracked: FlowOpts) -> FTable { +fn flow_table(doc: &Document, t: &Table, depth: usize, tracked: FlowOpts, links: &mut DrawingLinks) -> FTable { let mut rows = Vec::new(); // Formats that keep cell formatting get the table style's and the table's borders cell by cell. let style = t.props.style.as_deref().and_then(|id| doc.styles.table_style(id)); @@ -1190,8 +1229,8 @@ fn flow_table(doc: &Document, t: &Table, depth: usize, tracked: FlowOpts) -> FTa } } let blocks = match &styled { - Some(st) => flow_blocks(doc, &with_cell_text(doc, &c.blocks, &st.chr, st.align, &st.para), depth + 1, tracked), - None => flow_blocks(doc, &c.blocks, depth + 1, tracked), + Some(st) => flow_blocks(doc, &with_cell_text(doc, &c.blocks, &st.chr, st.align, &st.para), depth + 1, tracked, links), + None => flow_blocks(doc, &c.blocks, depth + 1, tracked, links), }; cells.push(Cell { blocks, @@ -1209,6 +1248,7 @@ fn flow_table(doc: &Document, t: &Table, depth: usize, tracked: FlowOpts) -> FTa picture: c.props.picture.as_deref().filter(|_| tracked.paras).and_then(|p| { let data = doc.media.get(&p.media)?; let img = Img { + link: None, data: data.clone(), ext: media_ext(&p.media, data), w: p.size[0], @@ -1281,13 +1321,13 @@ pub fn from_doc_with(doc: &Document, opts: FlowOpts) -> Flow { /// `blocks` of `doc` (a header, footer or note) as flow blocks, keeping what `opts` asks for. pub fn part_flow(doc: &Document, blocks: &Blocks, opts: FlowOpts) -> Vec { - flow_blocks(doc, blocks, 0, opts) + flow_blocks(doc, blocks, 0, opts, &mut DrawingLinks::default()) } fn flow_of(doc: &Document, tracked: FlowOpts) -> Flow { let c = &doc.core; Flow { - blocks: flow_blocks(doc, &doc.body, 0, tracked), + blocks: flow_blocks(doc, &doc.body, 0, tracked, &mut DrawingLinks::default()), meta: Meta { title: c.title.clone(), author: c.creator.clone(), @@ -1362,3 +1402,57 @@ mod stacking_tests { assert!(super::kept_float(&Float::default()).is_none()); } } + +#[cfg(test)] +mod drawing_link_tests { + use super::*; + + #[test] + fn vml_hyperlinks_share_one_conversion_budget() { + let group = || Inline::Group { + w: 12.0, + h: 8.0, + float: None, + link: Some("root".into()), + members: vec![Member { + x: 0.0, + y: 0.0, + link: Some("member".into()), + inline: Inline::Shape { + kind: craft_wordmodel::para::ShapeKind::Rectangle, + w: 12.0, + h: 8.0, + float: None, + blocks: Vec::new(), + look: BoxLook::default(), + path: None, + link: None, + }, + }], + }; + let flow = Flow { + blocks: vec![ + FBlock::Para(Para { kind: Kind::Normal, inlines: vec![group()], ..Default::default() }), + FBlock::Para(Para { kind: Kind::Normal, inlines: vec![group()], ..Default::default() }), + ], + ..Default::default() + }; + let doc = crate::to_doc(&flow); + // Use the real conversion consumer near its existing limit, without a + // 64 MiB fixture. Both groups and both paragraphs share this same counter. + let mut links = DrawingLinks { bytes: MAX_RUN_STRINGS - 14 }; + let blocks = flow_blocks(&doc, &doc.body, 0, FlowOpts { boxes: true, paras: true, ..Default::default() }, &mut links); + assert_eq!(blocks.len(), 2); + let FBlock::Para(first) = &blocks[0] else { panic!() }; + let FBlock::Para(second) = &blocks[1] else { panic!() }; + let [Inline::Group { link: first_root, members: first_members, .. }] = first.inlines.as_slice() else { panic!("first group") }; + let [Inline::Group { link: second_root, members: second_members, .. }] = second.inlines.as_slice() else { panic!("second group") }; + assert_eq!(first_root.as_deref(), Some("root")); + assert_eq!(first_members.len(), 1); + assert_eq!(first_members[0].link.as_deref(), Some("member")); + assert_eq!(second_members.len(), 1); + assert!(second_members[0].link.is_none(), "later member exceeds the conversion's remaining bytes"); + assert_eq!(second_root.as_deref(), Some("root"), "a fitting root target remains independent of its member"); + assert_eq!(links.bytes, MAX_RUN_STRINGS); + } +} diff --git a/crates/flow/src/media.rs b/crates/flow/src/media.rs index 44e2a24acb..e44d372108 100644 --- a/crates/flow/src/media.rs +++ b/crates/flow/src/media.rs @@ -46,6 +46,7 @@ pub fn sized_img(data: Arc>, ext: &str, natural: Option<(f32, f32)>, w: w = 468.0; } Img { + link: None, data, ext: ext.to_string(), w: w.clamp(1.0, 1584.0), diff --git a/crates/flow/src/to_doc.rs b/crates/flow/src/to_doc.rs index 303dc022cc..dafb9944a5 100644 --- a/crates/flow/src/to_doc.rs +++ b/crates/flow/src/to_doc.rs @@ -217,6 +217,14 @@ fn para_props(p: &Para, list_num: Option) -> ParaProps { out } +fn drawing_link(inline: &Inline) -> Option<&str> { + match inline { + Inline::Image(img) => img.link.as_deref(), + Inline::Shape { link, .. } | Inline::Group { link, .. } => link.as_deref(), + _ => None, + } +} + struct Builder<'a> { doc: &'a mut Document, /// Revisions already in `doc` by (kind, author, date), so each change is added once. @@ -433,7 +441,7 @@ impl<'a> Builder<'a> { graphic: Arc::new(graphic), }) } - Inline::Shape { kind, w, h, float, blocks, look, path } => { + Inline::Shape { kind, w, h, float, blocks, look, path, .. } => { // A text box always has its story; a shape only when it holds text. let story = if *kind == craft_wordmodel::para::ShapeKind::TextBox || !blocks.is_empty() { let story = self.blocks(blocks, 1); @@ -494,14 +502,20 @@ impl<'a> Builder<'a> { }; Some(obj) } - Inline::Group { w, h, float, members } if depth < MAX_GROUP_DEPTH => { + Inline::Group { w, h, float, members, .. } if depth <= MAX_GROUP_DEPTH => { let fit = |v: f32| if v.is_finite() { v.clamp(1.0, 1584.0) } else { 72.0 }; let (w, h) = (fit(*w), fit(*h)); let off = |v: f32| if v.is_finite() { v.clamp(-1584.0, 1584.0) } else { 0.0 }; let children: Vec = members .iter() .take(MAX_GROUP_CHILDREN) - .filter_map(|m| self.drawing(&m.inline, depth + 1).map(|obj| GroupChild { x: off(m.x), y: off(m.y), obj })) + .filter_map(|m| { + let obj = self.drawing(&m.inline, depth + 1)?; + let target = m.link.as_deref().or_else(|| drawing_link(&m.inline)); + let link = target.map(str::trim).filter(|s| !s.is_empty()).and_then(super::kept_link).map(|s| s.to_string()); + let link = self.budget(CharProps { link, ..Default::default() }).link; + Some(GroupChild { x: off(m.x), y: off(m.y), obj, link }) + }) .collect(); (!children.is_empty()).then(|| InlineObject::Group { w, @@ -562,6 +576,14 @@ impl<'a> Builder<'a> { out.props.keep_next = Some(true); } out.section.clone_from(&p.section); + // A legacy paragraph-mark target belongs to its sole drawing, not to an unlinked neighbor. + let single_drawing = p.textless() + && p.inlines + .iter() + .filter(|i| matches!(i, Inline::Image(_) | Inline::Chart(_) | Inline::Shape { .. } | Inline::Group { .. } | Inline::Figure(_))) + .take(2) + .count() + == 1; // Inlines are appended in order, so build the runs directly: inserting each one through // `Paragraph::insert_text` rescans every earlier run and is quadratic in their number. for i in &p.inlines { @@ -595,8 +617,17 @@ impl<'a> Builder<'a> { .mark .as_deref() .filter(|_| p.textless()) - .map(|m| self.budget(CharProps { ins: None, del: None, fmt_change: None, ..m.clone() })) + .map(|m| CharProps { ins: None, del: None, fmt_change: None, ..m.clone() }) .unwrap_or_default(); + if !matches!(i, Inline::Chart(_)) { + let link = drawing_link(i); + if link.is_some() || !single_drawing { + cp.link = link.map(str::trim).filter(|s| !s.is_empty()).and_then(super::kept_link).map(|s| s.to_string()); + } else { + cp.link = cp.link.take().filter(|link| super::kept_link(link).is_some()); + } + } + cp = self.budget(cp); if let Some(f) = obj.float_mut() && f.wrap == craft_wordmodel::para::Wrap::Inline && f.y != 0.0 diff --git a/crates/flow/src/types.rs b/crates/flow/src/types.rs index 357c9c6ff4..a8cacf35eb 100644 --- a/crates/flow/src/types.rs +++ b/crates/flow/src/types.rs @@ -14,7 +14,7 @@ pub const MAX_DEPTH: usize = 8; /// header made 2 million cells and took 3 to 5 GB to convert; past this, rows are left out. pub const MAX_TABLE_CELLS: usize = 1 << 18; -/// Deepest groups in groups kept (hostile files). +/// Deepest subgroup level kept, with the outer group at depth 0 (hostile files). pub const MAX_GROUP_DEPTH: usize = 8; /// Longest font name the importers keep, in bytes (as the .docx reader); a longer one (no real @@ -179,6 +179,8 @@ pub struct Img { /// How much is cut off its left, top, right and bottom, fractions of its size (0..1), for /// formats that keep it (ODT). pub crop: [f32; 4], + /// This picture's own hyperlink target, when it is a paragraph drawing. + pub link: Option, } /// An embedded object WordCraft shows but doesn't edit, kept whole for saving back (ODF 1.3 @@ -290,6 +292,8 @@ pub enum Inline { look: BoxLook, /// A freeform's paths ([`craft_wordmodel::para::ShapeKind::Freeform`]). path: Option>, + /// This shape's own hyperlink target, when it is a paragraph drawing. + link: Option, }, /// The start of a field whose result is the content after it, up to the matching /// [`Inline::FieldEnd`] (a table of contents around its entries); its field code. Only flows @@ -305,6 +309,8 @@ pub enum Inline { h: f32, float: Option>, members: Vec, + /// The group's own target; members retain their separate targets. + link: Option, }, } @@ -316,6 +322,8 @@ pub struct Member { pub x: f32, pub y: f32, pub inline: Inline, + /// This member's own hyperlink target, independent of the containing group. + pub link: Option, } /// How a text box or shape looks: its fill, its outline (colour and width, dash and diff --git a/crates/flow/tests/round_trip.rs b/crates/flow/tests/round_trip.rs index 9be4213d5a..0bfa461246 100644 --- a/crates/flow/tests/round_trip.rs +++ b/crates/flow/tests/round_trip.rs @@ -121,3 +121,173 @@ fn drop_cap_not_repeated_after_page_break() { assert_eq!(paras[1].extra.as_ref().and_then(|x| x.drop_cap_distance), None); assert_eq!(paras[1].extra.as_ref().and_then(|x| x.shading), Some(craft_wordmodel::Rgb(255, 0, 0))); } + +#[test] +fn vml_hyperlinks_survive_flow_for_roots_and_nested_members() { + use craft_flow::{BoxLook, FlowOpts, Member, from_doc_with}; + use craft_wordmodel::{Block, CharProps, para::ShapeKind}; + + let image = |target: Option<&str>| { + let mut img = make_img(PNG.to_vec(), Some(12.0), Some(8.0), "original tiny picture").unwrap(); + img.link = target.map(str::to_string); + img.crop = [0.125, 0.25, 0.0, 0.0]; + Inline::Image(img) + }; + let nested = Inline::Group { + w: 10.0, + h: 10.0, + float: None, + link: None, + members: vec![Member { x: 2.0, y: 1.0, inline: image(None), link: Some("#nested-place".into()) }], + }; + let group = Inline::Group { + w: 40.0, + h: 30.0, + float: None, + link: Some("https://example.com/group".into()), + members: vec![ + Member { x: 1.0, y: 2.0, inline: image(None), link: Some("https://example.com/child".into()) }, + Member { x: 8.0, y: 3.0, inline: nested, link: Some("https://example.com/nested-group".into()) }, + Member { x: 4.0, y: 5.0, inline: image(None), link: None }, + ], + }; + let shape = Inline::Shape { + kind: ShapeKind::Rectangle, + w: 9.0, + h: 6.0, + float: None, + blocks: Vec::new(), + look: BoxLook::default(), + path: None, + link: Some("https://example.com/shape".into()), + }; + let mut paragraph = para(Kind::Normal, vec![group, image(Some("https://example.com/picture")), shape, image(None)]); + paragraph.mark = Some(Box::new(CharProps { link: Some("https://example.com/not-the-object".into()), ..Default::default() })); + let flow = Flow { blocks: vec![FBlock::Para(paragraph)], ..Default::default() }; + let doc = to_doc(&flow); + let Block::Para(p) = &*doc.body[0] else { panic!("drawing paragraph") }; + assert_eq!( + p.runs.iter().map(|r| r.props.link.as_deref()).collect::>(), + [Some("https://example.com/group"), Some("https://example.com/picture"), Some("https://example.com/shape"), None], + "each root's target comes from that object, not the paragraph mark" + ); + let craft_wordmodel::para::InlineObject::Group { children, .. } = &p.objects[0] else { panic!("group") }; + assert_eq!(children[0].link.as_deref(), Some("https://example.com/child")); + assert_eq!(children[1].link.as_deref(), Some("https://example.com/nested-group")); + assert!(children[2].link.is_none()); + let back = from_doc_with(&doc, FlowOpts { boxes: true, paras: true, ..Default::default() }); + let got = paras(&back.blocks); + let [Inline::Group { link, members, .. }, Inline::Image(picture), Inline::Shape { link: shape_link, .. }, Inline::Image(unlinked)] = + got[0].inlines.as_slice() + else { + panic!("all four drawings survive") + }; + assert_eq!(link.as_deref(), Some("https://example.com/group")); + assert_eq!(picture.link.as_deref(), Some("https://example.com/picture")); + assert_eq!(shape_link.as_deref(), Some("https://example.com/shape")); + assert!(unlinked.link.is_none()); + assert_eq!(picture.data.as_slice(), PNG); + assert_eq!((picture.w, picture.h, picture.crop), (12.0, 8.0, [0.125, 0.25, 0.0, 0.0])); + assert_eq!((members[0].x, members[0].y), (1.0, 2.0)); + assert_eq!(members[0].link.as_deref(), Some("https://example.com/child")); + assert_eq!(members[1].link.as_deref(), Some("https://example.com/nested-group")); + assert!(members[2].link.is_none()); + let Inline::Group { link: own, members: inner, .. } = &members[1].inline else { panic!("nested group") }; + assert!(own.is_none(), "the nested group's target is carried by its Member, not duplicated on descendants"); + assert_eq!(inner[0].link.as_deref(), Some("#nested-place")); + + fn check_depth_boundary(image: impl Fn(Option<&str>) -> Inline) { + // DOCX retains an outer group at depth 0 and eight nested subgroups. Flow must + // keep that complete tree rather than lose its last drawable member. + fn linked_chain(leaf: Inline, deepest: usize) -> Inline { + let mut inline = leaf; + for level in (0..=deepest).rev() { + let target = if level == deepest { "#last-picture".to_string() } else { format!("https://example.com/level{}", level + 1) }; + inline = Inline::Group { + w: 12.0, + h: 8.0, + float: None, + link: (level == 0).then(|| "https://example.com/deep-root".into()), + members: vec![Member { x: 0.0, y: 0.0, inline, link: Some(target) }], + }; + } + inline + } + let boundary = Flow { blocks: vec![FBlock::Para(para(Kind::Normal, vec![linked_chain(image(None), 8)]))], ..Default::default() }; + let boundary_doc = to_doc(&boundary); + let boundary_para = boundary_doc.body[0].as_para().unwrap(); + assert_eq!(boundary_para.objects.len(), 1, "root plus eight subgroups remains drawable"); + assert_eq!(boundary_para.props_of_char(0).link.as_deref(), Some("https://example.com/deep-root")); + let mut object = &boundary_para.objects[0]; + for level in 0..=8 { + let craft_wordmodel::para::InlineObject::Group { children, .. } = object else { panic!("group at level {level}") }; + assert_eq!(children.len(), 1); + let target = if level == 8 { "#last-picture".to_string() } else { format!("https://example.com/level{}", level + 1) }; + assert_eq!(children[0].link.as_deref(), Some(target.as_str()), "document target at level {level}"); + object = &children[0].obj; + } + let craft_wordmodel::para::InlineObject::Image { media, .. } = object else { panic!("last picture") }; + assert_eq!(boundary_doc.media.get(media).unwrap().as_slice(), PNG); + let boundary_back = from_doc_with(&boundary_doc, FlowOpts { boxes: true, paras: true, ..Default::default() }); + let boundary_paras = paras(&boundary_back.blocks); + assert_eq!(boundary_paras[0].inlines.len(), 1); + let mut inline = &boundary_paras[0].inlines[0]; + for level in 0..=8 { + let Inline::Group { members, link, .. } = inline else { panic!("flow group at level {level}") }; + assert_eq!(link.as_deref(), (level == 0).then_some("https://example.com/deep-root")); + assert_eq!(members.len(), 1); + let target = if level == 8 { "#last-picture".to_string() } else { format!("https://example.com/level{}", level + 1) }; + assert_eq!(members[0].link.as_deref(), Some(target.as_str()), "flow target at level {level}"); + inline = &members[0].inline; + } + let Inline::Image(last) = inline else { panic!("last flow picture") }; + assert_eq!(last.data.as_slice(), PNG); + + // One further subgroup still exceeds the existing limit. Its root's separate + // drawable sibling survives, so dropping the over-deep branch cannot pass vacuously. + let mut beyond = linked_chain(image(None), 9); + let Inline::Group { members, .. } = &mut beyond else { panic!() }; + members.push(Member { x: 0.0, y: 0.0, inline: image(None), link: Some("https://example.com/sibling".into()) }); + let beyond_flow = Flow { blocks: vec![FBlock::Para(para(Kind::Normal, vec![beyond]))], ..Default::default() }; + let beyond_doc = to_doc(&beyond_flow); + let beyond_para = beyond_doc.body[0].as_para().unwrap(); + assert_eq!(beyond_para.objects.len(), 1); + let craft_wordmodel::para::InlineObject::Group { children, .. } = &beyond_para.objects[0] else { panic!() }; + assert_eq!(children.len(), 1, "the ninth subgroup is still excluded"); + assert_eq!(children[0].link.as_deref(), Some("https://example.com/sibling")); + assert!(matches!(&children[0].obj, craft_wordmodel::para::InlineObject::Image { .. })); + } + check_depth_boundary(image); + + fn check_oversized_drawing_links(image: impl Fn(Option<&str>) -> Inline) { + // Construct valid drawable inputs first; to_doc's own budget must not hide + // the from_doc boundary being checked by this regression. + let group = + Inline::Group { w: 12.0, h: 8.0, float: None, link: None, members: vec![Member { x: 0.0, y: 0.0, inline: image(None), link: None }] }; + let input = Flow { + blocks: vec![FBlock::Para(para(Kind::Normal, vec![group, image(None), image(Some("https://example.com/kept"))]))], + ..Default::default() + }; + let mut doc = to_doc(&input); + let mut paragraph = doc.body[0].as_para().unwrap().clone(); + let offsets = paragraph.object_offsets(); + let oversized = "x".repeat(craft_flow::MAX_LINK + 1); + paragraph.format(offsets[0], offsets[0] + craft_wordmodel::para::OBJ.len_utf8(), &|props| props.link = Some(oversized.clone())).unwrap(); + paragraph.format(offsets[1], offsets[1] + craft_wordmodel::para::OBJ.len_utf8(), &|props| props.link = Some(oversized.clone())).unwrap(); + let craft_wordmodel::para::InlineObject::Group { children, .. } = &mut paragraph.objects[0] else { panic!() }; + children[0].link = Some(oversized); + doc.body = vec![Block::Para(paragraph).into()]; + let back = from_doc_with(&doc, FlowOpts { boxes: true, paras: true, ..Default::default() }); + let got = paras(&back.blocks); + let [Inline::Group { link, members, .. }, Inline::Image(unlinked), Inline::Image(kept)] = got[0].inlines.as_slice() else { + panic!("all drawings remain") + }; + assert!(link.is_none(), "oversized group target is dropped"); + assert_eq!(members.len(), 1); + assert!(members[0].link.is_none(), "oversized member target is dropped"); + assert!(unlinked.link.is_none(), "oversized root image target is dropped"); + assert_eq!(kept.link.as_deref(), Some("https://example.com/kept")); + assert_eq!(kept.data.as_slice(), PNG); + } + check_oversized_drawing_links(image); +} diff --git a/crates/font-catalog/src/catalog.rs b/crates/font-catalog/src/catalog.rs index d2027c029f..01692fc984 100644 --- a/crates/font-catalog/src/catalog.rs +++ b/crates/font-catalog/src/catalog.rs @@ -588,12 +588,20 @@ impl Catalog { /// it. Does nothing once it has started or run, or when no thread can be started (the first /// lookup then scans). pub fn scan_in_background(self: &Arc) { - if self.ready.get().is_none() && !self.scanning.swap(true, Ordering::AcqRel) { - let me = Arc::clone(self); - if std::thread::Builder::new().name("font-catalog-scan".into()).spawn(move || me.background_scan()).is_err() { - self.scanning.store(false, Ordering::Release); - } + drop(self.start_background_scan()); + } + + /// [`Catalog::scan_in_background`], returning the thread it started, if it started one. + pub(crate) fn start_background_scan(self: &Arc) -> Option> { + if self.ready.get().is_some() || self.scanning.swap(true, Ordering::AcqRel) { + return None; } + let me = Arc::clone(self); + let thread = std::thread::Builder::new().name("font-catalog-scan".into()).spawn(move || me.background_scan()); + if thread.is_err() { + self.scanning.store(false, Ordering::Release); + } + thread.ok() } /// The background thread's scan. A scan that panics leaves the catalog unscanned and not diff --git a/crates/font-catalog/src/tests.rs b/crates/font-catalog/src/tests.rs index 54c044fd0b..e8b438154e 100644 --- a/crates/font-catalog/src/tests.rs +++ b/crates/font-catalog/src/tests.rs @@ -586,11 +586,11 @@ fn a_background_scan_that_panics_lets_the_next_call_scan_again() { }); let cat = Arc::new(Catalog::new(linux_env(&root)).with_font_service(false).with_lister(lister)); // Each call starts a scan only when none is running; the second starts once the failed one has ended. - let deadline = std::time::Instant::now() + Duration::from_secs(10); - while !cat.is_ready() && std::time::Instant::now() < deadline { - cat.scan_in_background(); - std::thread::sleep(Duration::from_millis(1)); - } + let failed = cat.start_background_scan().expect("the first call starts a scan"); + assert!(failed.join().is_err(), "the first scan fails"); + assert!(!cat.is_ready()); + let again = cat.start_background_scan().expect("a failed scan must not leave the catalog waiting on it"); + again.join().unwrap(); assert!(cat.is_ready(), "a failed scan must not leave the catalog waiting on it"); assert_eq!(calls.load(Ordering::Relaxed), 2); } @@ -605,13 +605,10 @@ fn adding_fonts_does_not_wait_for_the_installed_fonts() { let (entered, scan_entered) = mpsc::channel(); let (release, scan_released) = mpsc::channel::<()>(); let scan_released = std::sync::Mutex::new(scan_released); - let waited_out = Arc::new(AtomicUsize::new(0)); - let flag = Arc::clone(&waited_out); let lister: Lister = Arc::new(move || { let _ = entered.send(()); - if let Err(mpsc::RecvTimeoutError::Timeout) = scan_released.lock().unwrap().recv_timeout(Duration::from_secs(10)) { - flag.fetch_add(1, Ordering::Relaxed); - } + // The first scan stays here until the test sends on `release`; once it is dropped, scans go straight through. + let _ = scan_released.lock().unwrap().recv(); Vec::new() }); let cat = Arc::new(Catalog::new(linux_env(&root)).with_font_service(false).with_lister(lister)); @@ -619,12 +616,19 @@ fn adding_fonts_does_not_wait_for_the_installed_fonts() { assert!(!cat.is_ready(), "adding started no scan"); cat.scan_in_background(); scan_entered.recv_timeout(Duration::from_secs(10)).unwrap(); - cat.add_bytes(font(&spec("App Face", "Regular", 400)), Source::Bundled, &Limits::default()).unwrap(); + let adding = Arc::clone(&cat); + let (added, add_returned) = mpsc::channel(); + std::thread::spawn(move || { + let _ = added.send(adding.add_bytes(font(&spec("App Face", "Regular", 400)), Source::Bundled, &Limits::default())); + }); + // The scan cannot end before `release` sends, so an add that returns now did not wait for it. The limit only stops a + // test whose add waits. + let returned = add_returned.recv_timeout(Duration::from_secs(10)); release.send(()).unwrap(); // Later scans (the rescans below) go straight through. drop(release); + returned.expect("the add during the scan returned before the scan did").unwrap(); assert_eq!(cat.styles("App Face").len(), 1); - assert_eq!(waited_out.load(Ordering::Relaxed), 0, "the add during the scan returned before the scan did"); // The added Bold comes first; the installed file's Bold is another version of it, not another face. assert_eq!(cat.resolve("Test Sans", "Bold").map(|(f, _)| f), bold.first().cloned()); assert_eq!(cat.versions(&bold[0]).len(), 2); diff --git a/crates/font-manager/src/glyphs.rs b/crates/font-manager/src/glyphs.rs index 25aca72fa5..ccdab018dd 100644 --- a/crates/font-manager/src/glyphs.rs +++ b/crates/font-manager/src/glyphs.rs @@ -1,6 +1,8 @@ //! [`GlyphsPanel`]: Photoshop's Glyphs panel. A family and style picker, a category list (Entire Font, Punctuation, //! Currency, ...), a grid of glyph cells drawn by the app's text engine, a zoom slider, and the recently used //! glyphs in a row at the top. Double-click or Enter inserts the glyph where the app can insert. +//! A secondary click on a grid cell reports that cell ([`GlyphsPanelOutput::menu`]); the app opens +//! the menu from the grid response. #[cfg(feature = "suite")] pub(crate) mod stories; @@ -209,6 +211,19 @@ pub struct GlyphsPanelOutput { pub alternate: Option, /// The family or style changed in the panel's own pickers. pub font_changed: bool, + /// The grid cell a context menu was asked for, with the grid response the menu hangs from. + /// Reported on the secondary click and on every later pass while that menu stays open. + pub menu: Option, +} + +/// A grid cell's context menu: the cell, and the grid response the app hangs the menu from. +#[derive(Debug)] +#[non_exhaustive] +pub struct GlyphCellMenu { + /// The cell. + pub cell: GlyphCell, + /// The grid the menu hangs from. + pub opener: Response, } /// The cell whose popup was used and the picked glyph. @@ -313,6 +328,30 @@ struct Marked { host: Option<(GlyphCell, usize)>, } +/// The glyph a context menu was opened on, and the face it was opened in. Later passes keep this glyph: the grid +/// remembers the row, and another glyph of a same-length list must not take the menu over. A glyph id names a glyph +/// only in its own face, so the menu holds the cell only while that face is shown: the same family and style, and +/// for a glyph id the same source revision, since the source can replace a face under the same names. +#[derive(Clone, Default)] +struct HeldMenu(Option); + +/// A held menu's cell, the family and style it was clicked in, and the source revision then. +#[derive(Clone)] +struct MenuCell { + cell: GlyphCell, + family: String, + style: String, + revision: u64, +} + +impl MenuCell { + /// Whether the cell still names the glyph it was clicked on in `face` at `revision`. A character names the same + /// glyph after the source reads its faces again; a glyph id may not. + fn holds_in(&self, face: (&str, &str), revision: u64) -> bool { + (self.family.as_str(), self.style.as_str()) == face && (matches!(self.cell, GlyphCell::Char(_)) || self.revision == revision) + } +} + /// The alternates popup: whether it is open, the cell it was opened for and that cell's alternates, read once when /// it opened. #[derive(Clone, Default)] @@ -337,10 +376,12 @@ fn recent_cells(recent: &[String]) -> Vec { seen.into_iter().map(GlyphCell::Char).collect() } -/// The cells of the shown set: the recents, or the source's cells of the category. +/// The cells of the shown set: the recents, or the source's cells of the category, read again when the source's +/// `revision` (read once for the pass) is not the one they were read at. fn category_cells( cache: &mut CellsCache, source: &dyn GlyphSource, + revision: u64, family: &str, style: &str, category: &str, @@ -350,7 +391,6 @@ fn category_cells( return Arc::new(recent_cells(recent)); } let key = (family.to_owned(), style.to_owned(), category.to_owned()); - let revision = source.revision(); if cache.key != key || cache.revision != revision { *cache = CellsCache { key, revision, cells: Arc::new(source.cells(family, style, category)) }; } @@ -486,12 +526,13 @@ impl<'a> GlyphsPanel<'a> { }); }); craft_ui::runtime::frame::request_repaint_after(ui.ctx(), SCAN_POLL_SECONDS); - return GlyphsPanelOutput { response: shown.output, activated: None, alternate: None, font_changed: false }; + return GlyphsPanelOutput { response: shown.output, activated: None, alternate: None, font_changed: false, menu: None }; } let ctx = ui.ctx().clone(); let mut activated_out: Option = None; let mut picked: Option = None; let mut font_changed = false; + let mut menu: Option = None; let shown = Stack::new().label(label).command_scope(GlyphsCommand::SCOPE).show(ui, |ui, cx| { cx.publish(GlyphsCommand::Alternates, CommandState::new()); let mut state = read_bind(&mut settings, cx).unwrap_or_default(); @@ -592,8 +633,10 @@ impl<'a> GlyphsPanel<'a> { } } - // The grid. - let cells = category_cells(cx.memory::(), source, face.0, face.1, &state.category, &state.recent); + // The grid. One revision read serves the pass: a menu cell is stamped with the revision its list was read + // at, so a source that moves on mid-pass cannot give an old glyph id the new revision. + let revision = source.revision(); + let cells = category_cells(cx.memory::(), source, revision, face.0, face.1, &state.category, &state.recent); let index_of = |cell: GlyphCell| cells.iter().position(|c| *c == cell); let mut marked = cx.memory::().clone(); let host = marked_cell.and_then(|cell| index_of(cell).map(|at| (cell, at))); @@ -633,6 +676,25 @@ impl<'a> GlyphsPanel<'a> { None => tile, } }); + // The click names the glyph. Later passes keep that glyph: the grid remembers the row, so a + // same-length list must not move the open menu onto whatever glyph is there now. + let clicked = shown_grid.response.events.iter().find_map(|event| match event { + CollectionEvent::ContextMenu(request) => cells.get(request.key).copied(), + _ => None, + }); + let mut held = std::mem::take(cx.memory::()); + if let Some(cell) = clicked { + held = HeldMenu(Some(MenuCell { cell, family: face.0.to_owned(), style: face.1.to_owned(), revision })); + } + // A closed menu lets go of its cell, and so does another face, or a glyph id after the source + // replaced its faces: the same id there is another glyph. + let other_face = held.0.as_ref().is_some_and(|held| !held.holds_in(face, revision)); + if shown_grid.response.menu.is_none() || other_face { + held = HeldMenu(None); + } + let opener = shown_grid.response.response.clone(); + menu = held.0.as_ref().map(|held| GlyphCellMenu { cell: held.cell, opener }); + *cx.memory::() = held; for event in shown_grid.response.events { match event { CollectionEvent::Activate(key) => activated = cells.get(key).copied().or(activated), @@ -718,6 +780,6 @@ impl<'a> GlyphsPanel<'a> { write_bind(&mut settings, cx, state, "Glyphs panel"); } }); - GlyphsPanelOutput { response: shown.output, activated: activated_out, alternate: picked, font_changed } + GlyphsPanelOutput { response: shown.output, activated: activated_out, alternate: picked, font_changed, menu } } } diff --git a/crates/font-manager/src/picker.rs b/crates/font-manager/src/picker.rs index 7e4c8f2c62..45ab39f1d5 100644 --- a/crates/font-manager/src/picker.rs +++ b/crates/font-manager/src/picker.rs @@ -83,6 +83,7 @@ craft_ui::words! { served: "fontPicker.served" = "Not installed"; all_scripts: "fontPicker.allScripts" = "All Scripts"; script_latin: "fontPicker.scriptLatin" = "Latin"; + script_east_asian: "fontPicker.scriptEastAsian" = "East Asian"; script_japanese: "fontPicker.scriptJapanese" = "Japanese"; script_thai: "fontPicker.scriptThai" = "Thai"; any_kind: "fontPicker.anyKind" = "Any Kind"; @@ -202,14 +203,17 @@ fn chosen_sample<'s, 'a>(texts: &'s [SampleText<'a>], settings: Option<&FontPick texts.iter().find(|text| Some(text.key) == key).or_else(|| texts.first()) } -/// Coverage from the face: Latin, the basic Latin letters in the cmap; Japanese, the OS/2 kana or CJK unicode-range -/// bits or the JIS code page bit, or a Japanese family name; Thai, U+0E01 and U+0E32 in the cmap. Read lazily like the -/// class. +/// Coverage from the face: Latin, the basic Latin letters in the cmap; East Asian, the CJK Windows code pages +/// (JIS, Simplified/Traditional Chinese, Wansung, Johab) or CJK ideographs/kana/Hangul when no code pages are declared; +/// Japanese, the OS/2 kana or CJK unicode-range bits or the JIS code page bit, or a Japanese family name; Thai, U+0E01 +/// and U+0E32 in the cmap. Read lazily like the class. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum FontScript { /// The basic Latin letters. Latin, + /// Chinese, Japanese or Korean fonts. + EastAsian, /// Japanese kana and CJK. Japanese, /// Thai. @@ -218,7 +222,7 @@ pub enum FontScript { impl FontScript { /// Every script the script row can offer, in order. - pub const ALL: [FontScript; 3] = [FontScript::Latin, FontScript::Japanese, FontScript::Thai]; + pub const ALL: [FontScript; 4] = [FontScript::Latin, FontScript::EastAsian, FontScript::Japanese, FontScript::Thai]; } /// A family set the host gives (VectorCraft: Document, Recently Added), one filter toggle each. An `ordered` set that diff --git a/crates/font-manager/src/picker/rank.rs b/crates/font-manager/src/picker/rank.rs index 03cebb4dc6..5955c4c5e0 100644 --- a/crates/font-manager/src/picker/rank.rs +++ b/crates/font-manager/src/picker/rank.rs @@ -166,11 +166,22 @@ pub(super) fn shown_name(info: &Info, family: &str, language: &str, english: boo info.localized.iter().find(exact).or_else(|| info.localized.iter().find(same_language)).map_or_else(|| family.to_owned(), |n| n.name.clone()) } +/// Whether a family name of the face is in Japanese. +/// Whether a family name of the face is in any of `languages` (primary subtags, case-insensitive). +fn has_localized_language(face: &FaceInfo, languages: &[&str]) -> bool { + face.localized_families.iter().any(|n| { + n.language.as_deref().and_then(|l| l.split(['-', '_']).next()).is_some_and(|l| languages.iter().any(|wanted| l.eq_ignore_ascii_case(wanted))) + }) +} + /// Whether a family name of the face is in Japanese. fn japanese_name(face: &FaceInfo) -> bool { - face.localized_families - .iter() - .any(|n| n.language.as_deref().and_then(|l| l.split(['-', '_']).next()).is_some_and(|l| l.eq_ignore_ascii_case("ja"))) + has_localized_language(face, &["ja"]) +} + +/// Whether a family name of the face is in an East Asian language (`ja`, `zh`, or `ko`). +fn east_asian_name(face: &FaceInfo) -> bool { + has_localized_language(face, &["ja", "zh", "ko"]) } /// A face's class, PANOSE and weight from its `OS/2` and `post` tables, as the catalog's scan recorded them. @@ -181,21 +192,31 @@ fn read_traits(face: &FaceInfo) -> Traits { /// The JIS/Japan bit of `ulCodePageRange1`. const JIS_CODE_PAGE: u32 = 1 << 17; +/// The five East Asian Windows code pages of `ulCodePageRange1`: JIS/Japan (17), +/// Simplified Chinese (18), Korean Wansung (19), Traditional Chinese (20), Korean Johab (21). +const EAST_ASIAN_CODE_PAGES: u32 = 0b1_1111 << 17; /// The Hiragana (49), Katakana (50) and CJK Unified Ideographs (59) bits of `ulUnicodeRange2`, which holds bits 32 to 63. const JAPANESE_RANGES: u32 = (1 << (49 - 32)) | (1 << (50 - 32)) | (1 << (59 - 32)); +/// Hangul Syllables (56) plus [`JAPANESE_RANGES`]. +const EAST_ASIAN_RANGES: u32 = JAPANESE_RANGES | (1 << (56 - 32)); -/// The scripts a face covers: Latin, the basic Latin letters in its `cmap`; Japanese, the JIS code page, the kana or -/// CJK Unicode ranges of its `OS/2` table, or a Japanese family name; Thai, ก and า in its `cmap`. +/// The scripts a face covers: Latin, the basic Latin letters in its `cmap`; East Asian, its East Asian Windows code +/// pages, CJK/kana/Hangul Unicode ranges, CJK ideographs in `cmap`, or a CJK localized name; Japanese, the JIS code +/// page, the kana or CJK Unicode ranges of its `OS/2` table, or a Japanese family name; Thai, ก and า in its `cmap`. fn read_scripts(catalog: &Catalog, face: &FaceInfo) -> Option> { let data = catalog.load(face).ok()?; let font = FontRef::from_index(&data.bytes, face.index).ok()?; let map = font.charmap(); let mapped = |c: char| map.map(c).is_some(); let latin = ('A'..='Z').chain('a'..='z').all(&mapped); - let ranges = font.os2().ok().map_or(0, |os2| os2.ul_unicode_range_2()); + let os2 = font.os2().ok(); + let ranges = os2.as_ref().map_or(0, |t| t.ul_unicode_range_2()); + let code_page_1 = os2.as_ref().and_then(|t| t.ul_code_page_range_1()).filter(|&p| p != 0).unwrap_or(face.code_pages[0]); + let cjk_glyphs = ['中', '国', '日'].into_iter().all(&mapped); + let east_asian = code_page_1 & EAST_ASIAN_CODE_PAGES != 0 || ranges & EAST_ASIAN_RANGES != 0 || cjk_glyphs || east_asian_name(face); let japanese = face.code_pages[0] & JIS_CODE_PAGE != 0 || ranges & JAPANESE_RANGES != 0 || japanese_name(face); let thai = ['\u{0E01}', '\u{0E32}'].into_iter().all(&mapped); - let scripts = [(FontScript::Latin, latin), (FontScript::Japanese, japanese), (FontScript::Thai, thai)]; + let scripts = [(FontScript::Latin, latin), (FontScript::EastAsian, east_asian), (FontScript::Japanese, japanese), (FontScript::Thai, thai)]; Some(scripts.into_iter().filter_map(|(script, covered)| covered.then_some(script)).collect()) } diff --git a/crates/font-manager/src/picker/rows.rs b/crates/font-manager/src/picker/rows.rs index 124c41610b..3c54d291f4 100644 --- a/crates/font-manager/src/picker/rows.rs +++ b/crates/font-manager/src/picker/rows.rs @@ -347,6 +347,7 @@ const PREVIEW_SIZES: [FontPreviewSize; 3] = [FontPreviewSize::Small, FontPreview fn script_label(script: FontScript, words: &FontPickerWords) -> Label { match script { FontScript::Latin => words.script_latin.clone(), + FontScript::EastAsian => words.script_east_asian.clone(), FontScript::Japanese => words.script_japanese.clone(), FontScript::Thai => words.script_thai.clone(), } @@ -581,15 +582,16 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx: let family = cx.value().cloned().unwrap_or_default(); let settings = read(&mut picker.settings, cx); let plain = picker.kind == FontPickerKind::Plain; - // The plain list has no filters: neither the bar nor the column shows, and nothing narrows the list. - let mut filters = read(&mut picker.filters, cx).filter(|_| !plain); + let bound_filters = read(&mut picker.filters, cx); + // The plain list hides the filter bar and class column while still applying filters bound by the host. + let mut filters = bound_filters.clone().filter(|_| !plain); let actions = picker.actions; let has_filters = filters.is_some(); let chips = picker.filter_layout == FilterLayout::Chips; let on_white = settings.as_ref().is_some_and(|s| s.samples_on_white); let mut preview_size = settings.as_ref().map(|s| s.preview); let (sets, scripts) = (picker.sets, picker.scripts); - let narrowing = filters.clone().unwrap_or_default(); + let narrowing = bound_filters.unwrap_or_default(); let catalog = picker.catalog; let infos = infos_of(&cx.response.ctx, cx.id, catalog); let language_code = ui_language(&cx.env); @@ -734,7 +736,7 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx: } }); over_rows = rows.response.contains_pointer(); - let pointer = ui.ctx().pointer_hover_pos(); + let pointer = craft_ui::runtime::pointer::hover_point_in(ui.ctx(), rows.response.rect); under_pointer = pointer.and_then(|at| rows.shown.iter().find(|row| row.rect.contains(at)).map(|row| row.key.clone())); events = rows.events; }); diff --git a/crates/font-manager/tests/it/glyphs.rs b/crates/font-manager/tests/it/glyphs.rs index c30ee8cdf9..0ce58b6479 100644 --- a/crates/font-manager/tests/it/glyphs.rs +++ b/crates/font-manager/tests/it/glyphs.rs @@ -3,9 +3,13 @@ use std::cell::RefCell; use std::rc::Rc; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use craft_font_manager::glyphs::{CellInfo, GlyphCell, GlyphSource, GlyphsPanel, GlyphsPanelSettings}; -use craft_ui::contract::Bind; +use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; +use craft_ui::menu::{Menu, MenuItem}; +use craft_ui::testing::pointer; use craft_ui::testing::{Fixture, Room, trial}; use egui::{ColorImage, Event}; @@ -43,6 +47,8 @@ struct Seen { marked: Option, reveal: Option, picks: Vec<(GlyphCell, GlyphCell)>, + /// Cells a secondary click asked for a menu on, in order. + menu: Vec, } fn rig() -> (Fixture, Rc>) { @@ -62,9 +68,13 @@ fn rig() -> (Fixture, Rc>) { if let Some(cell) = reveal { panel = panel.reveal(cell); } - if let Some(pick) = panel.show(ui).alternate { + let out = panel.show(ui); + if let Some(pick) = out.alternate { shown.borrow_mut().picks.push((pick.cell, pick.glyph)); } + if let Some(menu) = out.menu { + shown.borrow_mut().menu.push(menu.cell); + } }); fx.in_room(Room::Window); fx.settle(); @@ -158,6 +168,159 @@ fn a_corner_pick_reports_the_cell_and_the_glyph() { assert!(!visible(&fx, 'Ⓑ'), "a pick closes the popup"); } +#[trial] +fn a_secondary_click_reports_the_cell_the_menu_is_for() { + let (mut fx, seen) = rig(); + let cell = fx.by_label(&name(FIRST)).expect("the first cell"); + let at = cell.center(); + fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]); + fx.frame(vec![pointer::secondary(at, false)]); + fx.settle(); + let menu = seen.borrow().menu.clone(); + assert!(!menu.is_empty(), "the secondary click names the cell"); + assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the menu is for the clicked cell: {menu:?}"); +} + +/// A list whose first cell changes, at the same length, when `swapped` is set. The revision changes with it, so the +/// panel reads the list again. +struct Swap(Arc); + +impl GlyphSource for Swap { + fn cells(&self, _: &str, _: &str, _: &str) -> Vec { + let first = if self.0.load(Ordering::Relaxed) { '\u{0102}' } else { FIRST }; + std::iter::once(GlyphCell::Char(first)).chain((1..300).filter_map(|i| char::from_u32(0x100 + i).map(GlyphCell::Char))).collect() + } + + fn glyph(&self, _: &str, _: &str, _: GlyphCell, _: u32) -> Option { + None + } + + fn revision(&self) -> u64 { + u64::from(self.0.load(Ordering::Relaxed)) + } +} + +#[trial] +fn an_open_menu_keeps_the_clicked_cell_when_that_row_changes() { + let swapped = Arc::new(AtomicBool::new(false)); + let source = Swap(Arc::clone(&swapped)); + let seen = Rc::new(RefCell::new(Vec::::new())); + let shown = Rc::clone(&seen); + let (mut family, mut style, mut settings) = ("Plain".to_owned(), "Regular".to_owned(), GlyphsPanelSettings::default()); + let mut fx = Fixture::new(move |ui| { + let out = GlyphsPanel::new("Glyphs", &source, Bind::bound(&mut family), Bind::bound(&mut style), Bind::bound(&mut settings)) + .can_insert(true) + .show(ui); + if let Some(menu) = out.menu { + shown.borrow_mut().push(menu.cell); + Menu::context("Glyph", &menu.opener).show(ui, |ui, _| { + MenuItem::new("Insert Glyph").show(ui); + }); + } + }); + fx.in_room(Room::Window); + fx.settle(); + let cell = fx.by_label(&name(FIRST)).expect("the first cell"); + let at = cell.center(); + fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]); + fx.frame(vec![pointer::secondary(at, false)]); + fx.settle(); + assert!(seen.borrow().contains(&GlyphCell::Char(FIRST)), "the click names the cell"); + + seen.borrow_mut().clear(); + swapped.store(true, Ordering::Relaxed); + fx.frame(Vec::new()); + fx.settle(); + let menu = seen.borrow().clone(); + assert!(!menu.is_empty(), "the menu stays open"); + assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the row's new glyph does not take the menu: {menu:?}"); +} + +/// Unencoded glyphs 1 to 300 in every face and at every revision: the same id names another glyph in another face, +/// or in a face the source replaced under the same names. +struct Unencoded(Arc); + +impl GlyphSource for Unencoded { + fn cells(&self, _: &str, _: &str, _: &str) -> Vec { + (1..=300).map(GlyphCell::Glyph).collect() + } + + fn glyph(&self, _: &str, _: &str, _: GlyphCell, _: u32) -> Option { + None + } + + fn revision(&self) -> u64 { + self.0.load(Ordering::Relaxed) + } +} + +/// A host menu open on glyph 1 of an [`Unencoded`] source, with the family and the revision the test can change. +struct GlyphMenu { + fx: Fixture, + family: Rc>, + revision: Arc, + seen: Rc>>, +} + +impl GlyphMenu { + fn open() -> Self { + let revision = Arc::new(AtomicU64::new(0)); + let source = Unencoded(Arc::clone(&revision)); + let family = Rc::new(RefCell::new("Plain".to_owned())); + let host_family = Rc::clone(&family); + let seen = Rc::new(RefCell::new(Vec::::new())); + let shown = Rc::clone(&seen); + let (mut style, mut settings) = ("Regular".to_owned(), GlyphsPanelSettings::default()); + let mut fx = Fixture::new(move |ui| { + let out = { + let mut family = host_family.borrow_mut(); + GlyphsPanel::new("Glyphs", &source, Bind::bound(&mut *family), Bind::bound(&mut style), Bind::bound(&mut settings)) + .can_insert(true) + .show(ui) + }; + if let Some(menu) = out.menu { + shown.borrow_mut().push(menu.cell); + Menu::context("Glyph", &menu.opener).show(ui, |ui, _| { + MenuItem::new("Insert Glyph").show(ui); + }); + } + }); + fx.in_room(Room::Window); + fx.settle(); + let cell = fx.by_label("1, glyph 1").expect("the first glyph"); + let at = cell.center(); + fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]); + fx.frame(vec![pointer::secondary(at, false)]); + fx.settle(); + assert!(seen.borrow().contains(&GlyphCell::Glyph(1)), "the click names the glyph"); + seen.borrow_mut().clear(); + GlyphMenu { fx, family, revision, seen } + } + + /// The cells the menu reported over the next passes. + fn reported(&mut self) -> Vec { + self.fx.frame(Vec::new()); + self.fx.settle(); + self.seen.borrow().clone() + } +} + +#[trial] +fn an_open_menu_does_not_report_a_glyph_id_from_another_face() { + let mut open = GlyphMenu::open(); + *open.family.borrow_mut() = "Other".to_owned(); + let menu = open.reported(); + assert!(menu.is_empty(), "the clicked id names another glyph in the new face, so the menu reports none: {menu:?}"); +} + +#[trial] +fn an_open_menu_does_not_report_a_glyph_id_after_the_source_replaces_the_face() { + let mut open = GlyphMenu::open(); + open.revision.store(1, Ordering::Relaxed); + let menu = open.reported(); + assert!(menu.is_empty(), "the face behind the same names changed, so the clicked id names another glyph: {menu:?}"); +} + #[trial] fn glyphs_panel_alternates() { let (mut fx, _seen) = rig(); diff --git a/crates/font-manager/tests/it/panel.rs b/crates/font-manager/tests/it/panel.rs index b321381712..363dab42c6 100644 --- a/crates/font-manager/tests/it/panel.rs +++ b/crates/font-manager/tests/it/panel.rs @@ -4,8 +4,8 @@ use std::cell::RefCell; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::rc::Rc; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex, PoisonError}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Condvar, Mutex, PoisonError}; use std::time::Duration; use craft_font_manager::craft_font_catalog::Os; @@ -73,6 +73,36 @@ struct Rig { fx: Fixture, panel: Rc>, store: Arc, + woken: Arc, +} + +/// How long a test waits for another thread before it fails as hung. A result that comes does not depend on it. +const HANG: Duration = Duration::from_secs(10); + +/// Counts the repaints asked for from threads other than the test's, as the preview workers ask for one after each +/// result. +#[derive(Default)] +struct Woken { + count: Mutex, + changed: Condvar, +} + +impl Woken { + fn count(&self) -> u64 { + *self.count.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn wake(&self) { + *self.count.lock().unwrap_or_else(PoisonError::into_inner) += 1; + self.changed.notify_all(); + } + + /// Waits until a repaint is asked for after [`Woken::count`] was `seen`. + fn wait_past(&self, seen: u64) { + let count = self.count.lock().unwrap_or_else(PoisonError::into_inner); + let (count, _) = self.changed.wait_timeout_while(count, HANG, |count| *count == seen).unwrap_or_else(PoisonError::into_inner); + assert!(*count > seen, "previews kept loading"); + } } fn root(name: &str) -> PathBuf { @@ -132,9 +162,16 @@ fn show(panel: FontsPanel, store: Arc, host: Arc) -> Rig { let mut fx = Fixture::new(move |ui| { FontsPanelView::new(&mut shown.borrow_mut()).show(ui); }); + let woken = Arc::new(Woken::default()); + let (counted, test) = (Arc::clone(&woken), std::thread::current().id()); + fx.ctx().set_repaint_observer(move |_| { + if std::thread::current().id() != test { + counted.wake(); + } + }); fx.in_room(Room::Window).host(host); fx.settle(); - Rig { fx, panel, store } + Rig { fx, panel, store, woken } } impl Rig { @@ -367,8 +404,9 @@ fn a_cards_install_menu_chooses_where_the_fonts_go() { struct FakeService { answered: Mutex>, cancelled: Mutex>, - /// Requests that reached the service. - started: AtomicUsize, + /// Requests that reached the service, notified on `arrived` as each one does. + started: Mutex, + arrived: Condvar, held: AtomicBool, /// Answers sample subsets with HTTP 404, as for a sample text the service doesn't have. no_samples: AtomicBool, @@ -378,7 +416,8 @@ struct FakeService { impl Fetch for FakeService { fn get(&self, url: &str, _: u64, cancel: &Cancel) -> Result, FetchError> { - self.started.fetch_add(1, Ordering::SeqCst); + *self.started.lock().unwrap_or_else(PoisonError::into_inner) += 1; + self.arrived.notify_all(); while self.held.load(Ordering::SeqCst) && !cancel.is_cancelled() { std::thread::sleep(Duration::from_millis(2)); } @@ -403,6 +442,18 @@ impl FakeService { std::mem::take(&mut *self.answered.lock().unwrap_or_else(PoisonError::into_inner)) } + /// The requests that reached the service. + fn started(&self) -> usize { + *self.started.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Waits until a request has reached the service. + fn wait_started(&self) { + let started = self.started.lock().unwrap_or_else(PoisonError::into_inner); + let (started, _) = self.arrived.wait_timeout_while(started, HANG, |started| *started == 0).unwrap_or_else(PoisonError::into_inner); + assert!(*started > 0, "the service was asked"); + } + /// The numbers of the families whose `subset` the URLs of `answered` name: `sample`, `ascii`, or `u/` for typed /// characters. fn numbers(answered: &[String], subset: &str) -> Vec { @@ -468,16 +519,22 @@ impl Rig { self.fx.settle(); } - /// Runs passes until the panel has fetched what it asks for and asks for nothing more. + /// Runs passes until the panel has fetched what it asks for and asks for nothing more. While a preview is on its + /// way, the next pass waits for the repaint its worker asks for once the result is ready. fn load(&mut self) { let mut quiet = 0; for _ in 0..500 { + let seen = self.woken.count(); self.fx.frame(Vec::new()); - quiet = if self.panel.borrow().loading_previews() { 0 } else { quiet + 1 }; + if self.panel.borrow().loading_previews() { + quiet = 0; + self.woken.wait_past(seen); + continue; + } + quiet += 1; if quiet == 3 { return; } - std::thread::sleep(Duration::from_millis(1)); } panic!("previews kept loading"); } @@ -563,13 +620,7 @@ fn a_resize_and_a_search_cancel_no_preview() { service.held.store(true, Ordering::SeqCst); let mut rig = service_rig("previews-kept", &service, latin_index()); rig.set_previews(true); - for _ in 0..500 { - if service.started.load(Ordering::SeqCst) > 0 { - break; - } - std::thread::sleep(Duration::from_millis(1)); - } - assert!(service.started.load(Ordering::SeqCst) > 0, "the service was asked"); + service.wait_started(); let shown = rig.numbers(); rig.fx.room(Room::Window.size() + Vec2::new(40.0, 120.0)).settle(); rig.type_into("Search", "Family"); @@ -602,7 +653,7 @@ fn a_family_of_an_added_source_is_not_asked_of_the_service() { rig.open("Added"); rig.load(); rig.named(Role::BUTTON, "Preview"); - assert_eq!(service.started.load(Ordering::SeqCst), 0, "{:?}", service.urls()); + assert_eq!(service.started(), 0, "{:?}", service.urls()); } /// A sample the service has not (another text) is asked for as the sample's characters, once. diff --git a/crates/font-manager/tests/it/picker.rs b/crates/font-manager/tests/it/picker.rs index 58eafab0c6..9f830a4b4a 100644 --- a/crates/font-manager/tests/it/picker.rs +++ b/crates/font-manager/tests/it/picker.rs @@ -1319,3 +1319,33 @@ fn the_closed_field_skips_building_stops_while_idle_and_steps_on_input() { assert_eq!(seen.borrow().picks.last().map(|(f, _)| f.as_str()), Some(all[2].as_str()), "wheel end commits the stepped family"); assert_eq!(craft_font_manager::picker::stop_builds(fx.ctx()), after_wheel, "wheel end and idle frames do not rebuild stops"); } + +#[trial] +fn east_asian_script_filter_keeps_cjk_faces_and_narrows_a_plain_picker() { + const THAI: &[u8] = include_bytes!("../../../font-subset/tests/data/sarabun/Sarabun-Regular.ttf"); + const CJK: &[u8] = include_bytes!("../../../ui-contract/tests/fonts/NotoSansCJKsc-test.otf"); + let catalog = catalog_of(&[INTER_REGULAR, THAI, CJK]); + let mut filters = FontFilters::default(); + filters.script = Some(FontScript::EastAsian); + + let filtered = listed(&catalog, &filters, &[]); + assert!(filtered.iter().any(|family| family.contains("CJK")), "expected East Asian family in {filtered:?}"); + assert!(!filtered.iter().any(|family| family.contains("Inter") || family.contains("Sarabun")), "unexpected non-CJK family in {filtered:?}"); + + let mut family = String::new(); + let mut fx = Fixture::new(move |ui| { + let _ = FontPicker::new("Asian text font", Bind::bound(&mut family), &catalog) + .kind(FontPickerKind::Plain) + .filters(Bind::given(filters.clone())) + .show(ui); + }); + fx.in_room(Room::Window); + fx.settle(); + open(&mut fx); + + let words = FontPickerWords::default(); + assert!(!present(&fx, words.clear_all.as_str()), "plain picker keeps the filter bar hidden"); + assert!(present(&fx, "Noto Sans CJK SC"), "plain picker with East Asian filter lists CJK font"); + assert!(!present(&fx, "Inter"), "plain picker with East Asian filter excludes Latin font"); + assert!(!present(&fx, "Sarabun"), "plain picker with East Asian filter excludes Thai font"); +} diff --git a/crates/font-manager/tests/remote.rs b/crates/font-manager/tests/remote.rs index e8c1062ea0..59413800bd 100644 --- a/crates/font-manager/tests/remote.rs +++ b/crates/font-manager/tests/remote.rs @@ -9,8 +9,9 @@ use std::collections::HashMap; use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use std::path::PathBuf; +use std::sync::mpsc::{Receiver, channel}; use std::sync::{Arc, Condvar, Mutex}; -use std::time::{Duration, Instant}; +use std::time::Duration; use craft_font_manager::craft_font_catalog::Os; use craft_font_manager::store::{FakeStore, Installer, SuiteStore}; @@ -118,7 +119,8 @@ enum Reply { struct Service { base: String, routes: Arc>>, - log: Arc>>, + /// The paths asked for, notified as each one arrives. + log: Arc<(Mutex>, Condvar)>, gate: Arc<(Mutex, Condvar)>, } @@ -143,7 +145,14 @@ impl Service { } fn requests(&self) -> Vec { - self.log.lock().unwrap().clone() + self.log.0.lock().unwrap().clone() + } + + /// Waits until `n` requests have reached the service. + fn wait_for_requests(&self, n: usize) { + let log = self.log.0.lock().unwrap(); + let (log, _) = self.log.1.wait_timeout_while(log, HANG, |log| log.len() < n).unwrap(); + assert!(log.len() >= n, "{} of {n} requests reached the service", log.len()); } fn release(&self) { @@ -152,7 +161,7 @@ impl Service { } } -fn answer(mut s: TcpStream, routes: &Mutex>, log: &Mutex>, gate: &(Mutex, Condvar)) { +fn answer(mut s: TcpStream, routes: &Mutex>, log: &(Mutex>, Condvar), gate: &(Mutex, Condvar)) { let mut head = Vec::new(); let mut b = [0u8; 1]; while !head.ends_with(b"\r\n\r\n") { @@ -162,7 +171,8 @@ fn answer(mut s: TcpStream, routes: &Mutex>, log: &Mutex< } } let path = String::from_utf8_lossy(&head).split_whitespace().nth(1).unwrap_or("/").to_string(); - log.lock().unwrap().push(path.clone()); + log.0.lock().unwrap().push(path.clone()); + log.1.notify_all(); let reply = routes.lock().unwrap().get(&path).cloned(); let body = match reply { Some(Reply::Ok(body)) => body, @@ -182,22 +192,28 @@ fn answer(mut s: TcpStream, routes: &Mutex>, log: &Mutex< let _ = s.write_all(&body); } -/// The results until `n` have come, or two seconds. -fn wait_for(previews: &Previews, n: usize) -> Vec { - let deadline = Instant::now() + Duration::from_secs(2); - let mut out = Vec::new(); - while out.len() < n && Instant::now() < deadline { - out.extend(previews.poll()); - std::thread::sleep(Duration::from_millis(5)); - } - out +/// How long a test waits for a result or a request before it fails as hung. A result that comes does not depend on it. +const HANG: Duration = Duration::from_secs(10); + +/// `previews` and a channel that gets `()` after each result it delivers ([`Previews::on_ready`]). +fn watched(previews: Previews) -> (Previews, Receiver<()>) { + let (ready, results) = channel(); + let previews = previews.on_ready(move || { + let _ = ready.send(()); + }); + (previews, results) } -fn wait_until(mut done: impl FnMut() -> bool) { - let deadline = Instant::now() + Duration::from_secs(2); - while !done() && Instant::now() < deadline { - std::thread::sleep(Duration::from_millis(5)); +/// The results until `n` have come. +fn wait_for(previews: &Previews, ready: &Receiver<()>, n: usize) -> Vec { + let mut out = previews.poll(); + while out.len() < n { + if ready.recv_timeout(HANG).is_err() { + panic!("{} of {n} previews came", out.len()); + } + out.extend(previews.poll()); } + out } #[test] @@ -209,12 +225,12 @@ fn previews_come_from_the_service_then_the_cache_and_only_with_consent() { let broken = PreviewKey::new(&sha(2), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap(); service.serve(&sample, Reply::Ok(WOFF2.to_vec())); service.serve(&broken, Reply::Ok(b"wOF2 but not really".to_vec())); - let previews = Previews::new(store.clone()); + let (previews, ready) = watched(Previews::new(store.clone())); // No service: nothing happens. assert!(!previews.available()); previews.request(sample.clone(), 1); - let got = wait_for(&previews, 1); + let got = wait_for(&previews, &ready, 1); assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::NoService)); // A service, but previews off: no request. @@ -222,7 +238,7 @@ fn previews_come_from_the_service_then_the_cache_and_only_with_consent() { store.set_previews_enabled(false).unwrap(); assert!(!previews.available()); previews.request(sample.clone(), 1); - let got = wait_for(&previews, 1); + let got = wait_for(&previews, &ready, 1); assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::PreviewsOff)); assert!(service.requests().is_empty()); @@ -231,7 +247,7 @@ fn previews_come_from_the_service_then_the_cache_and_only_with_consent() { assert!(previews.available() && !store.downloads_allowed()); previews.request(sample.clone(), 1); previews.request(broken.clone(), 1); - let got = wait_for(&previews, 2); + let got = wait_for(&previews, &ready, 2); let font = |key: &PreviewKey| got.iter().find(|p| &p.key == key).map(|p| p.font.clone()); assert!(font(&sample).unwrap().is_ok_and(|f| is_font(&f))); assert_eq!(font(&broken), Some(Err(PreviewError::NotAFont))); @@ -241,9 +257,9 @@ fn previews_come_from_the_service_then_the_cache_and_only_with_consent() { // A new session reads the disk cache, even with previews off. store.set_previews_enabled(false).unwrap(); - let later = Previews::new(store.clone()); + let (later, later_ready) = watched(Previews::new(store.clone())); later.request(sample.clone(), 1); - assert!(wait_for(&later, 1).first().is_some_and(|p| p.font.as_ref().is_ok_and(|f| is_font(f)))); + assert!(wait_for(&later, &later_ready, 1).first().is_some_and(|p| p.font.as_ref().is_ok_and(|f| is_font(f)))); assert_eq!(service.requests().len(), 2); let _ = std::fs::remove_dir_all(dir); } @@ -276,9 +292,9 @@ fn a_service_marked_down_gets_no_requests() { // The client is shared with, say, the store's installs, which found the service unreachable. let client = Client::default(); client.mark_service_down(&service.base); - let previews = Previews::new(store.clone()).with_fetcher(Arc::new(client)); + let (previews, ready) = watched(Previews::new(store.clone()).with_fetcher(Arc::new(client))); previews.request(key, 1); - let got = wait_for(&previews, 1); + let got = wait_for(&previews, &ready, 1); assert!(matches!(got.first().map(|p| p.font.clone()), Some(Err(PreviewError::Failed(_))))); assert!(service.requests().is_empty()); let _ = std::fs::remove_dir_all(dir); @@ -297,10 +313,10 @@ fn highest_priority_first_and_cancelled_requests_deliver_nothing() { for key in [low, high, dropped] { service.serve(key, Reply::Ok(WOFF2.to_vec())); } - let previews = Previews::new(store.clone()).with_cache(None).with_workers(1); + let (previews, ready) = watched(Previews::new(store.clone()).with_cache(None).with_workers(1)); previews.request(held.clone(), 9); - wait_until(|| !service.requests().is_empty()); + service.wait_for_requests(1); previews.request(low.clone(), 1); previews.request(dropped.clone(), 1); previews.request(high.clone(), 5); @@ -310,11 +326,12 @@ fn highest_priority_first_and_cancelled_requests_deliver_nothing() { // The running request stops while the service still sends nothing. previews.cancel(held); - let got = wait_for(&previews, 2); + let got = wait_for(&previews, &ready, 2); assert_eq!(got.iter().map(|p| &p.key).collect::>(), [high, low]); let path = |k: &PreviewKey| format!("/{}", k.path()); assert_eq!(service.requests(), [path(held), path(high), path(low)]); - std::thread::sleep(Duration::from_millis(100)); + // The one worker delivers in the order it takes requests, and it had ended the held one before it asked for `high`, + // so nothing more can come. assert!(previews.poll().is_empty()); assert_eq!(previews.pending(), 0); service.release(); @@ -343,9 +360,9 @@ fn a_404_comes_back_as_not_found() { let store = Arc::new(FakeStore::new(&dir, HashMap::new())); store.set_preview_service(Some(&service.base)).unwrap(); let key = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap(); - let previews = Previews::new(store.clone()); + let (previews, ready) = watched(Previews::new(store.clone())); previews.request(key, 1); - let got = wait_for(&previews, 1); + let got = wait_for(&previews, &ready, 1); assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::NotFound)); let _ = std::fs::remove_dir_all(dir); } diff --git a/crates/gpu-device/Cargo.toml b/crates/gpu-device/Cargo.toml new file mode 100644 index 0000000000..19f6cfa356 --- /dev/null +++ b/crates/gpu-device/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "craft-gpu-device" +description = "Choosing and opening a wgpu device: an adapter choice the user can set (Auto, high performance, low power, a named adapter, software), fixes for drivers that crash, a software fallback, a capability report, and device health with recovery after a device loss" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[features] +default = ["serde"] +# Reading and writing `Preference` and `AdapterKey` with serde. +serde = ["dep:serde"] +# Native wgpu backends, as in craft-gpu-wgpu. None is on by default; the app turns on the ones it +# ships, through this crate or through craft-gpu-wgpu. +native-vulkan = ["wgpu/vulkan"] +native-dx12 = ["wgpu/dx12"] +native-metal = ["wgpu/metal"] +native-gles = ["wgpu/gles"] + +[dependencies] +craft-gpu = { workspace = true } +log = { workspace = true } +serde = { workspace = true, optional = true } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wgpu = { workspace = true, features = ["webgpu"] } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +pollster = { workspace = true } +wgpu = { workspace = true } + +[dev-dependencies] +# The noop backend opens devices without a GPU in the tests. +wgpu = { workspace = true, features = ["noop"] } +serde_json = { workspace = true } diff --git a/crates/gpu-device/NOTICE b/crates/gpu-device/NOTICE new file mode 100644 index 0000000000..e7ca2f2c92 --- /dev/null +++ b/crates/gpu-device/NOTICE @@ -0,0 +1,10 @@ +craft-gpu-device +Licensed under the MIT license or the Apache License, Version 2.0, at your option. + +The adapter rule and its driver corrections (src/adapter.rs) come from FilmCraft's +`crates/gpu/src/adapter.rs` (https://github.com/storytold/filmcraft, commit +93a88a839aae370740b09434fdec410abb8c24ca), MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and +the FilmCraft contributors. +Device health (src/health.rs) comes from PhotoCraft's `crates/gpu/src/health.rs` +(https://github.com/storytold/photocraft, commit 01a5b5a389acc93f081e5ce6a8d0580d6438774a), +MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors. diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md new file mode 100644 index 0000000000..bb083932ad --- /dev/null +++ b/crates/gpu-device/README.md @@ -0,0 +1,128 @@ +# craft-gpu-device + +Choosing and opening a wgpu device for a Craft app: an adapter choice the user can set, fixes for +drivers that crash, a software fallback, a capability report, and device health with recovery +after a device loss. The crate depends on `craft-gpu`, `wgpu` 30, `pollster` and `log`, with +`serde` as an optional feature (on by default). It depends on no app crate. + +It uses the workspace's `wgpu`, which turns on no native backend, and the WebGPU backend on +`wasm32`. The `native-vulkan`, `native-dx12`, `native-metal` and `native-gles` features turn on +wgpu's backends, as the features of the same names in `craft-gpu-wgpu` do. Cargo merges the +features, so an app can turn them on through either crate. + +The `gpu-device` feature of `craft` exports this crate as `craft::gpu_device`. + +`native_instance` shares one instance across calls on native targets. It reads wgpu's environment +settings for flags and backend options when that instance is first created. `native_descriptor` +reads those settings on every call. + +Licensed under MIT OR Apache-2.0. + +## Contents + +| Item | What | +|---|---| +| `Candidate` | one listed adapter as plain data: name, backend, device type, PCI vendor, device and bus, driver, feature count, and whether it can draw to the window's surface | +| `list(instance, surface)` | every adapter the instance lists, as `wgpu::Adapter`s and as `Candidate`s | +| `native_instance`, `native_descriptor` | a wgpu instance over Vulkan, Metal and DirectX 12, plus OpenGL except on Windows; wgpu's `WGPU_*` flag variables apply | +| `choose(candidates, power)` | wgpu's own adapter rule with two corrections: the newest version of a driver that lists one GPU twice, and DirectX 12 instead of Vulkan on Intel Gen 9 to Gen 11 integrated GPUs (`intel_gen9_to_gen11`) | +| `Preference` | `Auto` (high performance), `LowPower`, `Adapter(AdapterKey)` or `Software`; serde form `{"kind":"auto"}`, `{"kind":"adapter","name":…,"backend":…,"vendor":…,"device":…,"pciBusId":…,"driver":…}` | +| `AdapterKey` | what identifies an adapter across runs: backend, PCI vendor, device and bus, the Vulkan driver's name, and the name when the backend reports no PCI ids | +| `select(candidates, preference)` | the adapter to draw with, as a `Selection` with its `Notice`s | +| `ranked(candidates, preference)` | the order in which to try opening a device: the selection, then the other usable adapters by type with software after hardware, never an older version of a driver listed twice, or the Vulkan entry of an Intel Gen 9 to Gen 11 GPU on Intel's Windows driver | +| `open(instance, surface, preference, request)` | native only, like `list`: opens a device through `ranked`, then wgpu's fallback adapter; returns `Opened` (adapter, device, queue, `Capabilities`, `DeviceHealth`, notices) or `OpenError` | +| `list_async`, `open_async` | `list` and `open` as futures, for a `wasm32` web worker as well as native; in a browser `list_async` gives the high-performance adapter, the one `open_async` opens for `Auto` and a named adapter | +| `pick(adapters, surface, preference)` | `select` over listed adapters, for egui-wgpu's `native_adapter_selector`; the error is an `OpenError` (convert it with `map_err(\|e\| e.to_string())` for that selector) | +| `Capabilities`, `Vendor` | NV12 and P010 (sampled only in wgpu 30), 16-bit norm, `f16` and timestamp support, the largest texture and buffer, the vendor, and whether the adapter is a software one, read from the `craft_gpu::DeviceCaps` it holds (its fields are readable through `Deref`; `From` converts both ways) | +| `DeviceHealth`, `Fault`, `WaitOutcome` | records a device loss or an uncaptured error instead of panicking; polls and bounded waits that do not touch a lost device | +| `Recovery`, `RecoveryPolicy` | the preference to open after a loss: the user's own, and `Software` once the device was lost 3 times in 10 minutes (both values can be set) | +| `device_caps(device)`, `Opened::device_caps` | the `craft_gpu::DeviceCaps` of a device: its own limits, enabled feature names, vendor id and software flag, in the form `craft-gpu-wgpu` reports | +| `DeviceHealth::device_status` | a recorded loss as `craft_gpu::GpuFault::DeviceLost`, in the form of `GpuContext::device_status`; `Fault` converts to `GpuFault` (a loss to `DeviceLost`, an error to `Operation`) | +| `Notice` | the adapter asked for is missing, no software adapter is listed, only a software adapter can draw, an adapter failed to open, or drawing moved to software after losses; the `Display` text is English, for the log | + +## Failure cases + +- With no usable adapter, `select` returns `None`, and `open` and `pick` return + `OpenError::NoAdapter`, or `OpenError::UnsafeDriver` when only a driver that can end the + process can draw. +- In a browser, WebGPU offers one adapter for a power preference, so a named adapter cannot be + chosen. `open_async` asks for the adapter with `Preference::power()` as the power preference, + and gives the automatic choice with `Notice::AdapterMissing` for a named adapter. wgpu 30 + does not pass the fallback-adapter option to the browser, so `Preference::Software` opens the + browser's adapter, with `Notice::NoSoftwareAdapter` unless that adapter is a software one, and + `Recovery` cannot move drawing to software there. `Capabilities` and + `Recovery` otherwise work there as they do on native, and so does `DeviceHealth` apart from `wait`, + `wait_timeout` and `wait_timeout_cancelable`, which are native only. On the browser backend, + wgpu 30 panics on an uncaptured `GPUInternalError` before the handler `DeviceHealth::watch` + installs runs, so such an error is not recorded. Validation and out-of-memory errors are. +- An adapter that lacks `Request::required_features`, whose limits are lower than + `Request::limits`, or whose `request_device` fails, adds a `Notice::DeviceFailed`, and `open` + tries the next one. When every adapter fails, the error lists each failure. +- A named adapter that is no longer listed, or can no longer draw to the surface, gives the + automatic choice and `Notice::AdapterMissing`. +- A driver that ends the process cannot be caught. `choose` and `ranked` never use an older + version of a driver that lists one GPU twice, or the Vulkan entry of an Intel Gen 9 to Gen 11 + GPU on Intel's Windows driver. When those are the only adapters that can draw and wgpu's + fallback adapter does not open either, `open` returns `OpenError::UnsafeDriver` with their + names. When a + driver reports no bus id, a second GPU of the same model on the same driver looks like an + older version, and is used through its other backend (DirectX 12 on Windows, OpenGL + elsewhere). +- Only an error whose cause is wgpu's "Parent device is lost" counts as a loss. The same words in + a resource's label do not count. An error about a destroyed buffer or texture is recorded as an + error. +- `wait`, `wait_timeout` and `wait_timeout_cancelable` wait for one submission index. To wait for + everything submitted so far, pass `queue.submit([])`; work submitted later does not extend the + wait. +- `wait` has no deadline. It polls in slices of at most 100 ms, and a loss or an error other than + out of memory that another clone of the `DeviceHealth` records ends it after the current slice. +- `DeviceHealth::watch` replaces the device's uncaptured-error handler. Polls catch the panic that + `Device::poll` raises on a lost device and record the loss. +- wgpu keeps one device-lost callback per device, and a later `set_device_lost_callback` + replaces the one `DeviceHealth::watch` set. A `craft-gpu` context on a watched device reads + `DeviceHealth::device_status` instead of setting its own callback. +- After an out-of-memory error, polls and waits keep running, so staging memory is reclaimed. + The app reads `DeviceHealth::out_of_memory_count` when it handles the error, frees memory, and + passes the count to `DeviceHealth::clear_out_of_memory`. The device is then healthy again, + unless it was lost, another error was recorded, or a new out-of-memory error came in after the + count was read. + +## After a device loss + +`DeviceHealth::device_status` returns `GpuFault::DeviceLost` once a loss is recorded, and the +caller starts recovery then. `DeviceHealth::device_lost` turns true only when wgpu itself reported +the loss; it stays false for a loss the health layer recorded on its own, such as a bounded wait +that reached its deadline. Nothing made with the lost device can be used again, and wgpu keeps +none of its contents. The caller then: + +1. Drops the old `Opened` and everything made with its device: buffers, textures and their + views, samplers, bind group layouts and bind groups, shader modules, pipeline layouts and + pipelines, query sets, unsubmitted command encoders, and any renderer that holds them (an + egui-wgpu `Renderer`, for example). Work submitted before the loss does not complete, and + waits on it return `false`. +2. Calls `Recovery::lost` with the time and opens a new device with `open` or `open_async`, + using the returned preference and the same `Request`. When the step has a notice + (`Notice::SoftwareAfterLosses`), the app shows it only if the new `Opened::caps.software()` is + true. Otherwise no software adapter opened (in a browser, or with none listed), and the new + `Opened::notices` say what was opened instead. +3. Reads the new `Opened::caps` before choosing pipelines again. The new device can be another + adapter, or a software one, with other features and limits: for example, without NV12 the + planes are drawn into `R8Unorm` and `Rg8Unorm` textures instead. +4. Configures each window surface again with the new device (`Surface::configure`). The surface + itself is kept when it was passed to `open`, which then opens only an adapter that can draw + to it. The new adapter may not support the old configuration (an HDR format, for example), so + the caller reads `Surface::get_capabilities` with the new adapter and picks a format, present + mode and alpha mode from it. +5. Builds the pipelines for the surface format picked in step 4, and the bind groups and + renderers, again, and uploads the textures and buffers again from the app's own copies of + their data. +6. Makes any `craft-gpu` context again on the new device, with the new `Opened::device_caps`, and + submits again the jobs and frames that did not complete. +7. Uses the new `Opened::health`. The old `DeviceHealth` keeps reporting the loss. + +## Tests + +The selection tests run on `Candidate` lists from real machines. The `open` tests use wgpu's noop +backend (the `noop` feature, enabled for tests only), so they do not need a GPU. One test compares +`choose` with wgpu's own `request_adapter` on the machine that runs it, and passes when no adapter +is listed. diff --git a/crates/gpu-device/src/adapter.rs b/crates/gpu-device/src/adapter.rs new file mode 100644 index 0000000000..b837d47b1b --- /dev/null +++ b/crates/gpu-device/src/adapter.rs @@ -0,0 +1,647 @@ +//! Which adapter wgpu's own rule would draw with, and two corrections to it for drivers that crash. +//! +//! On Windows the Vulkan loader takes one driver from each display adapter's driver package. A PC +//! whose GPUs were installed from different packages of one vendor (a laptop with an integrated +//! and a discrete AMD GPU, the first on the manufacturer's old package and the second on a current +//! one) loads two versions of that driver, and the newer GPU is listed once through each. wgpu +//! takes the first entry of the device type it prefers, which is whichever version the loader +//! listed first; a window drawn through the stale one ends the process inside the driver +//! (`amdvlk64.dll`, 0xc0000005), where no Rust error handling runs. +//! +//! [`choose`] is wgpu's own rule (`Instance::request_adapter`: the adapters that can draw to the +//! surface, by device type for the power preference, then as enumerated) with one addition: when +//! the adapter that rule picks is listed again by the same driver, the entry exposing the most +//! features is used, which is the newer version. Without such a duplicate the choice is wgpu's own. +//! Entries of one GPU from different drivers (RADV and AMDVLK, a vendor's driver and Dozen) are +//! left alone, and wgpu's order between them stays. +//! +//! An Intel Gen 9 to Gen 11 integrated GPU draws through its DirectX 12 entry rather than Vulkan +//! ([`intel_gen9_to_gen11`]). Intel's Vulkan driver for them (`igvk64.dll`) ends the process with +//! 0xc0000005 when the device is created, after the adapters are listed. + +use std::cmp::Reverse; +use std::fmt; + +use wgpu::{Adapter, Backend, DeviceType, PowerPreference, Surface}; + +/// One enumerated adapter as plain data, so that [`choose`] and [`crate::select`] are pure +/// functions that tests run without a GPU. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Candidate { + pub name: String, + pub backend: Backend, + pub device_type: DeviceType, + /// PCI vendor and device ids; both zero when the backend reports none (OpenGL). + pub vendor: u32, + pub device: u32, + /// PCI bus id such as `0000:03:00.0`; empty when the driver reports none. + pub pci_bus_id: String, + /// The driver's name (Vulkan) or version (DirectX 12). + pub driver: String, + /// More about the driver, for the log. + pub driver_info: String, + /// How many wgpu features the driver exposes; a newer version of one driver exposes more. + pub features: u32, + /// Whether the surface can be drawn through this adapter (true without a surface). + pub usable: bool, +} + +impl Candidate { + pub fn of(adapter: &Adapter, surface: Option<&Surface<'_>>) -> Self { + let info = adapter.get_info(); + Candidate { + name: info.name, + backend: info.backend, + device_type: info.device_type, + vendor: info.vendor, + device: info.device, + pci_bus_id: info.device_pci_bus_id, + driver: info.driver, + driver_info: info.driver_info, + features: adapter.features().bits().0.iter().map(|word| word.count_ones()).sum(), + usable: surface.is_none_or(|s| adapter.is_surface_supported(s)), + } + } + + /// Whether the adapter draws on the CPU (WARP, llvmpipe, lavapipe, SwiftShader). + pub fn is_software(&self) -> bool { + self.device_type == DeviceType::Cpu + } +} + +impl fmt::Display for Candidate { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let kind = match self.device_type { + DeviceType::DiscreteGpu => "discrete GPU", + DeviceType::IntegratedGpu => "integrated GPU", + DeviceType::VirtualGpu => "virtual GPU", + DeviceType::Cpu => "software", + DeviceType::Other => "unknown type", + }; + let driver = format!("{} {}", self.driver, self.driver_info); + write!(f, "\"{}\" ({:?}, {kind}, driver {}, {} features", self.name, self.backend, driver.trim(), self.features)?; + if !self.pci_bus_id.is_empty() { + write!(f, ", bus {}", self.pci_bus_id)?; + } + if !self.usable { + write!(f, ", cannot draw to the window")?; + } + write!(f, ")") + } +} + +/// Whether `a` and `b` are one GPU listed twice by one driver, through two installed versions of +/// it: the same backend, device type, PCI vendor and device and driver name, and the same bus id +/// when both report one. Adapters without PCI ids (OpenGL reports zeros) are never the same: two +/// of them cannot be told apart. +pub(crate) fn same_gpu_and_driver(a: &Candidate, b: &Candidate) -> bool { + let identified = a.vendor != 0 || a.device != 0; + let same_bus = a.pci_bus_id.is_empty() || b.pci_bus_id.is_empty() || a.pci_bus_id == b.pci_bus_id; + identified + && a.backend == b.backend + && a.device_type == b.device_type + && a.vendor == b.vendor + && a.device == b.device + && a.driver == b.driver + && same_bus +} + +/// wgpu's device type order for `power` (wgpu-core's `Instance::request_adapter`): lower first. +/// Without a preference the adapters stay as enumerated. +pub(crate) fn type_order(device_type: DeviceType, power: PowerPreference) -> u8 { + let prefer_integrated = match power { + PowerPreference::LowPower => true, + PowerPreference::HighPerformance => false, + PowerPreference::None => return 0, + }; + match device_type { + DeviceType::DiscreteGpu if prefer_integrated => 2, + DeviceType::IntegratedGpu if prefer_integrated => 1, + DeviceType::DiscreteGpu => 1, + DeviceType::IntegratedGpu => 2, + DeviceType::Other => 3, + DeviceType::VirtualGpu => 4, + DeviceType::Cpu => 5, + } +} + +/// The index of the adapter wgpu's `request_adapter` picks: the first usable one of the best +/// device type for `power`. `None` without a usable adapter. +pub(crate) fn wgpu_choice(candidates: &[Candidate], power: PowerPreference) -> Option { + let usable = candidates.iter().enumerate().filter(|(_, c)| c.usable); + usable.min_by_key(|(index, c)| (type_order(c.device_type, power), *index)).map(|(index, _)| index) +} + +/// A wgpu instance over the native backends (Vulkan, Metal, DirectX 12), and OpenGL except on +/// Windows. On Windows, OpenGL starts a WGL context thread inside the vendor driver (NVIDIA's +/// `nvoglv64` is both its OpenGL driver and its Vulkan driver), and instances created and devices +/// dropped at the same time can then deadlock in that driver. +/// +/// On native targets, the first call creates one shared instance and reads wgpu's environment +/// settings for flags and backend options. Later calls return clones of that instance. +pub fn native_instance() -> wgpu::Instance { + #[cfg(not(target_arch = "wasm32"))] + { + static SHARED: std::sync::OnceLock = std::sync::OnceLock::new(); + SHARED.get_or_init(|| wgpu::Instance::new(native_descriptor())).clone() + } + #[cfg(target_arch = "wasm32")] + { + wgpu::Instance::new(native_descriptor()) + } +} + +/// [`native_instance`]'s descriptor. wgpu's environment variables apply to its flags and backend +/// options: `WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER=1` lists a Vulkan driver that reports no +/// conformance version, such as Mesa's Dozen (the only one on WSL2), and `WGPU_VALIDATION`, +/// `WGPU_DX12_COMPILER` and the others work too. The backends stay as above whatever +/// `WGPU_BACKEND` says. +/// +/// The descriptor has no display handle, which a headless instance does not need. OpenGL on +/// Wayland needs one to draw to a window: add it with `InstanceDescriptor::with_display_handle`, +/// or pass the descriptor to egui-wgpu as `WgpuSetupCreateNew::instance_descriptor`, where eframe +/// fills in the window's display handle. +pub fn native_descriptor() -> wgpu::InstanceDescriptor { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = if cfg!(windows) { wgpu::Backends::PRIMARY } else { wgpu::Backends::PRIMARY | wgpu::Backends::GL }; + desc.flags = desc.flags.with_env(); + desc.backend_options = desc.backend_options.with_env(); + desc +} + +/// The index of the adapter to draw with for `power`: `wgpu_choice`, or the entry exposing the +/// most features among those that are the same GPU listed by the same driver (the first of them +/// when several expose as many), repeated until the entry is its own newest version. For an Intel +/// Gen 9 to Gen 11 GPU on Intel's Windows Vulkan driver it is the same GPU's DirectX 12 entry, or +/// without one the best other usable adapter. `None` without a usable adapter, and when that +/// Intel Vulkan entry is the only one. The result is never an entry `avoided` excludes. +pub fn choose(candidates: &[Candidate], power: PowerPreference) -> Option { + let first = wgpu_choice(candidates, power)?; + let index = settled(candidates, first); + if candidates.get(index).is_some_and(intel_vulkan_crashes) { + // No usable DirectX 12 entry for that GPU: the best other adapter wgpu would take. + let safe = candidates.iter().enumerate().filter(|(_, c)| c.usable && !intel_vulkan_crashes(c)); + let (other, _) = safe.min_by_key(|(i, c)| (type_order(c.device_type, power), *i))?; + return Some(settled(candidates, other)); + } + Some(index) +} + +/// [`corrected`] applied until it returns the entry it was given. An entry without a bus id can +/// be the same GPU as two entries on different buses, so one correction can land on an entry that +/// has a newer version of its own. Each step moves to an entry exposing more features (or the +/// same number at a lower index), or to a DirectX 12 entry, so the loop ends. +pub(crate) fn settled(candidates: &[Candidate], mut index: usize) -> usize { + for _ in 0..=candidates.len() { + let Some(c) = candidates.get(index) else { + return index; + }; + let next = corrected(candidates, index, c); + if next == index { + return index; + } + index = next; + } + index +} + +/// `index` (the entry `preferred`), or the entry to draw with instead of it. +pub(crate) fn corrected(candidates: &[Candidate], index: usize, preferred: &Candidate) -> usize { + if let Some(dx12) = dx12_instead(candidates, preferred) { + return dx12; + } + let versions = candidates.iter().enumerate().filter(|(_, c)| c.usable && same_gpu_and_driver(preferred, c)); + versions.max_by_key(|(index, c)| (c.features, Reverse(*index))).map_or(index, |(index, _)| index) +} + +/// Whether the entry at `index` is one [`choose`] never draws with: the Vulkan entry of an Intel +/// Gen 9 to Gen 11 GPU on Intel's Windows driver, or an older version of a driver that lists one +/// GPU twice. Creating a device or drawing through either can end the process, so it is never +/// tried as a fallback either. A second GPU of the same model on the same driver, when the +/// driver reports no bus id for either, looks like an older version; it is still listed through +/// the other backends (DirectX 12 on Windows, OpenGL elsewhere). +pub(crate) fn avoided(candidates: &[Candidate], index: usize) -> bool { + let Some(c) = candidates.get(index) else { + return true; + }; + intel_vulkan_crashes(c) || corrected(candidates, index, c) != index +} + +/// PCI vendor id of Intel. +pub(crate) const INTEL: u32 = 0x8086; + +/// Whether `device` is an Intel Gen 9 to Gen 11 integrated GPU: 6th to 10th generation Core, and +/// the Atom, Pentium and Celeron graphics of those years (Skylake, Broxton, Gemini Lake, Kaby +/// Lake, Coffee Lake, Whiskey Lake, Comet Lake, Cannon Lake, Ice Lake, Elkhart Lake, Jasper Lake), +/// by the PCI device ids of Linux's `include/drm/intel/pciids.h`: these prefixes hold those +/// families and no others, except `0x0a84` (Broxton), whose prefix Haswell shares. +/// +/// Their Windows Vulkan driver ends the process with 0xc0000005 in `igvk64.dll` when a device is +/// created, on every version reported, from 25.20.100.6576 (2019) to 31.0.101.2145, the legacy +/// branch that is the last driver Intel ships for them. DirectX 12 works on the same GPUs. +pub fn intel_gen9_to_gen11(device: u32) -> bool { + matches!(device >> 8, 0x19 | 0x1a | 0x31 | 0x3e | 0x45 | 0x4e | 0x59 | 0x5a | 0x87 | 0x8a | 0x9b) || device == 0x0a84 +} + +/// Whether `c` is an Intel Gen 9 to Gen 11 integrated GPU listed through Intel's Windows Vulkan +/// driver ([`intel_gen9_to_gen11`]). Mesa's Vulkan driver for the same GPUs on Linux reports a +/// driver name with "Mesa" in it and is not included. +pub(crate) fn intel_vulkan_crashes(c: &Candidate) -> bool { + c.backend == Backend::Vulkan + && c.device_type == DeviceType::IntegratedGpu + && c.vendor == INTEL + && intel_gen9_to_gen11(c.device) + && !c.driver.to_ascii_lowercase().contains("mesa") +} + +/// For an Intel Gen 9 to Gen 11 integrated GPU listed through Intel's Windows Vulkan driver, the +/// index of the same GPU's usable DirectX 12 entry, if there is one. +fn dx12_instead(candidates: &[Candidate], preferred: &Candidate) -> Option { + if !intel_vulkan_crashes(preferred) { + return None; + } + candidates.iter().position(|c| c.usable && c.backend == Backend::Dx12 && c.vendor == INTEL && c.device == preferred.device) +} + +/// Write the adapters and the choice to the log, with a warning when a correction applied. +pub(crate) fn log_choice(candidates: &[Candidate], index: usize, power: PowerPreference) { + for candidate in candidates { + log::info!("graphics adapter available: {candidate}"); + } + let Some(chosen) = candidates.get(index) else { + return; + }; + let others = candidates.iter().enumerate().filter(|(i, c)| *i != index && c.usable && same_gpu_and_driver(chosen, c)).count(); + if others > 0 { + log::warn!( + "{:?} lists \"{}\" {} times: several versions of its driver are installed, and a window drawn through a stale one can crash. Using the one with the most features; installing one driver package for every GPU removes the others.", + chosen.backend, + chosen.name, + others.saturating_add(1) + ); + } + if let Some(wgpu_own) = wgpu_choice(candidates, power).and_then(|i| candidates.get(i)) + && wgpu_own.backend == Backend::Vulkan + && chosen.backend == Backend::Dx12 + && wgpu_own.vendor == INTEL + && wgpu_own.device == chosen.device + { + log::warn!("Intel's Vulkan driver for \"{}\" crashes when the device is created: drawing through DirectX 12", wgpu_own.name); + } + log::info!("graphics adapter chosen: {chosen}"); +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use wgpu::Backend::{Dx12, Gl, Vulkan}; + use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu, Other}; + use wgpu::PowerPreference::{HighPerformance, LowPower}; + + pub(crate) const AMD: u32 = 0x1002; + pub(crate) const RX_6800M: u32 = 0x73df; + pub(crate) const RADEON_IGPU: u32 = 0x1638; + const POWERS: [PowerPreference; 3] = [PowerPreference::None, LowPower, HighPerformance]; + + #[expect(clippy::too_many_arguments, reason = "one line per adapter in the listings below")] + pub(crate) fn gpu( + name: &str, + backend: Backend, + device_type: DeviceType, + vendor: u32, + device: u32, + bus: &str, + driver: &str, + driver_info: &str, + features: u32, + ) -> Candidate { + Candidate { + name: name.into(), + backend, + device_type, + vendor, + device, + pci_bus_id: bus.into(), + driver: driver.into(), + driver_info: driver_info.into(), + features, + usable: true, + } + } + + /// A laptop with an integrated Radeon on a 2021 driver package and an RX 6800M on a 2026 one, + /// as wgpu 30 lists it: the Vulkan loader has both versions of AMD's driver, and the 2021 one + /// lists the RX 6800M first. A window drawn through that entry ended inside `amdvlk64.dll` + /// (0xc0000005) on every launch. + pub(crate) fn two_amd_drivers() -> Vec { + let amd = "AMD proprietary driver"; + vec![ + gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, "", amd, "26.9.2", 60), + gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, "", amd, "26.9.2 (AMD proprietary shader compiler)", 68), + gpu("AMD Radeon(TM) Graphics", Vulkan, IntegratedGpu, AMD, RADEON_IGPU, "", amd, "21.30.02.13", 56), + gpu("AMD Radeon RX 6800M", Dx12, DiscreteGpu, AMD, RX_6800M, "0000:03:00.0", "32.0.21045.11001", "", 36), + gpu("AMD Radeon(TM) Graphics", Dx12, IntegratedGpu, AMD, RADEON_IGPU, "0000:08:00.0", "30.0.13002.13003", "", 36), + gpu("Microsoft Basic Render Driver", Dx12, Cpu, 0x1414, 0x8c, "", "10.0.26100.9549", "", 36), + ] + } + + #[test] + fn a_gpu_listed_through_two_versions_of_its_driver_draws_with_the_newer_one() { + let adapters = two_amd_drivers(); + for power in [HighPerformance, PowerPreference::None] { + assert_eq!(wgpu_choice(&adapters, power), Some(0), "wgpu takes the stale entry, which crashed"); + assert_eq!(choose(&adapters, power), Some(1)); + } + // whichever version the loader lists first + let mut newer_first = adapters.clone(); + newer_first.swap(0, 1); + assert_eq!(choose(&newer_first, HighPerformance), Some(0)); + // two entries exposing as much: wgpu's, the first + let mut equal = adapters.clone(); + if let Some(c) = equal.get_mut(1) { + c.features = 60; + } + assert_eq!(choose(&equal, HighPerformance), Some(0)); + // three versions: the one exposing the most + let mut three = adapters.clone(); + three.insert(1, gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, "", "AMD proprietary driver", "24.1.1", 64)); + assert_eq!(choose(&three, HighPerformance), Some(2)); + // the stale entries are avoided, the newest is not + assert!(avoided(&three, 0) && avoided(&three, 1) && !avoided(&three, 2)); + } + + #[test] + fn an_entry_without_a_bus_between_two_cards_is_never_drawn_with_when_avoided() { + // two cards of one model on their own buses, and an entry of the same driver without a bus + // id, which can be either card's other version + let radeon = |bus, features| gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, bus, "AMD proprietary driver", "", features); + let adapters = vec![radeon("0000:03:00.0", 60), radeon("", 70), radeon("0000:04:00.0", 80)]; + for power in POWERS { + let chosen = choose(&adapters, power); + assert_eq!(chosen, Some(2), "{power:?}"); + assert!(chosen.is_some_and(|i| !avoided(&adapters, i)), "{power:?}"); + } + assert!(avoided(&adapters, 0) && avoided(&adapters, 1) && !avoided(&adapters, 2)); + } + + #[test] + fn a_newer_version_never_overtakes_another_gpu_or_backend() { + assert_eq!(choose(&two_amd_drivers(), LowPower), Some(2)); + let mut dx12_first = two_amd_drivers(); + dx12_first.rotate_left(3); + for power in [HighPerformance, PowerPreference::None] { + assert_eq!(choose(&dx12_first, power), Some(0)); + } + assert_eq!(choose(&dx12_first, LowPower), wgpu_choice(&dx12_first, LowPower)); + } + + #[test] + fn without_two_versions_of_one_driver_the_choice_is_wgpus() { + let nvidia = |backend, bus, driver, features| gpu("NVIDIA GeForce RTX 4070", backend, DiscreteGpu, 0x10de, 0x2786, bus, driver, "", features); + let intel = + |backend, bus, driver, features| gpu("Intel(R) UHD Graphics 770", backend, IntegratedGpu, 0x8086, 0x4680, bus, driver, "", features); + let radeon = |bus, driver, features| gpu("AMD Radeon RX 7900 XT", Vulkan, DiscreteGpu, AMD, 0x744c, bus, driver, "", features); + let gl = |name: &str, features| gpu(name, Gl, Other, 0, 0, "", "", "", features); + let without = |skip: usize| two_amd_drivers().into_iter().enumerate().filter(|(i, _)| *i != skip).map(|(_, c)| c).collect::>(); + let listings: Vec> = vec![ + vec![], + vec![nvidia(Vulkan, "0000:01:00.0", "NVIDIA", 70)], + // a laptop with two GPUs, through Vulkan and DirectX 12 + vec![ + intel(Vulkan, "0000:00:02.0", "Intel Corporation", 60), + nvidia(Vulkan, "0000:01:00.0", "NVIDIA", 70), + nvidia(Dx12, "0000:01:00.0", "32.0.15.6094", 36), + intel(Dx12, "0000:00:02.0", "31.0.101.5186", 36), + gpu("Microsoft Basic Render Driver", Dx12, Cpu, 0x1414, 0x8c, "", "10.0.26100.1", "", 36), + ], + // one GPU through two different drivers: Linux with AMDVLK and RADV + vec![radeon("0000:03:00.0", "AMD open-source driver", 58), radeon("0000:03:00.0", "radv", 71)], + // a vendor's driver and Dozen (Vulkan on DirectX 12) + vec![nvidia(Vulkan, "", "Dozen", 75), nvidia(Vulkan, "0000:01:00.0", "NVIDIA", 70)], + // two cards of one model, on their own buses + vec![radeon("0000:03:00.0", "AMD proprietary driver", 60), radeon("0000:04:00.0", "AMD proprietary driver", 68)], + // OpenGL reports no ids: two adapters cannot be told apart + vec![gl("ANGLE", 20), gl("ANGLE", 30)], + vec![gpu("llvmpipe (LLVM 19.1.0, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "", 50)], + without(0), + without(1), + ]; + for adapters in &listings { + for power in POWERS { + assert_eq!(choose(adapters, power), wgpu_choice(adapters, power), "{power:?} over {adapters:#?}"); + } + } + assert_eq!(choose(&[], HighPerformance), None); + } + + /// An Intel UHD Graphics 630 (Coffee Lake) on driver 25.20.100.6576 as wgpu 30 lists it. A + /// Vulkan device on it ended inside `igvk64.dll` (0xc0000005) as it was created. + pub(crate) fn uhd_630() -> Vec { + vec![ + gpu("Intel(R) UHD Graphics 630", Vulkan, IntegratedGpu, INTEL, 0x3e91, "", "Intel Corporation", "Intel driver", 44), + gpu("Intel(R) UHD Graphics 630", Dx12, IntegratedGpu, INTEL, 0x3e91, "0000:00:02.0", "25.20.100.6576", "", 36), + gpu("Microsoft Basic Render Driver", Dx12, Cpu, 0x1414, 0x8c, "", "10.0.26100.9711", "", 36), + ] + } + + fn uhd_630_as(name: &str, device: u32) -> Vec { + uhd_630().into_iter().map(|c| if c.vendor == INTEL { Candidate { name: name.into(), device, ..c } } else { c }).collect() + } + + #[test] + fn an_intel_gen9_to_gen11_gpu_draws_through_directx_12() { + for power in POWERS { + assert_eq!(wgpu_choice(&uhd_630(), power), Some(0), "wgpu takes Vulkan, which crashed"); + assert_eq!(choose(&uhd_630(), power), Some(1), "{power:?}"); + } + for (name, device) in [("Intel(R) HD Graphics 520", 0x1916), ("Intel(R) Iris(R) Plus Graphics", 0x8a5a)] { + assert_eq!(choose(&uhd_630_as(name, device), HighPerformance), Some(1), "{name}"); + } + let mut dx12_first = uhd_630(); + dx12_first.swap(0, 1); + assert_eq!(choose(&dx12_first, HighPerformance), Some(0)); + // without a usable DirectX 12 entry, the Vulkan entry is still never drawn with + let vulkan_only: Vec = uhd_630().into_iter().take(1).collect(); + assert_eq!(choose(&vulkan_only, HighPerformance), None); + assert!(avoided(&vulkan_only, 0)); + let mut dx12_unusable = uhd_630(); + if let Some(c) = dx12_unusable.get_mut(1) { + c.usable = false; + } + assert_eq!(choose(&dx12_unusable, HighPerformance), Some(2), "the software adapter"); + // Mesa's Vulkan driver for the same GPU on Linux is drawn with + let mesa = vec![gpu( + "Intel(R) UHD Graphics 630 (CFL GT2)", + Vulkan, + IntegratedGpu, + INTEL, + 0x3e91, + "0000:00:02.0", + "Intel open-source Mesa driver", + "Mesa 25.2.4", + 44, + )]; + assert_eq!(choose(&mesa, HighPerformance), Some(0)); + assert!(!avoided(&mesa, 0)); + // beside a discrete GPU: high performance keeps it; low power takes the Intel GPU's DirectX 12 entry + let mut laptop = uhd_630(); + laptop.insert(1, gpu("NVIDIA GeForce MX250", Vulkan, DiscreteGpu, 0x10de, 0x1d13, "0000:01:00.0", "NVIDIA", "", 70)); + assert_eq!(choose(&laptop, HighPerformance), Some(1)); + assert_eq!(choose(&laptop, LowPower), Some(2)); + assert!(avoided(&laptop, 0)); + } + + #[test] + fn later_intel_gpus_keep_wgpus_choice() { + for (name, device) in [("Intel(R) Iris(R) Xe Graphics", 0x9a49), ("Intel(R) UHD Graphics 770", 0x4680), ("Intel(R) Arc(TM) Graphics", 0x7d55)] + { + let adapters = uhd_630_as(name, device); + for power in POWERS { + assert_eq!(choose(&adapters, power), Some(0), "{name} {power:?}"); + } + } + let discrete: Vec = + uhd_630().into_iter().map(|c| if c.vendor == INTEL { Candidate { device_type: DiscreteGpu, ..c } } else { c }).collect(); + assert_eq!(choose(&discrete, HighPerformance), Some(0)); + } + + #[test] + fn gen9_to_gen11_ids() { + for id in [0x1916, 0x0a84, 0x5a85, 0x3184, 0x5917, 0x87c0, 0x3e91, 0x3ea0, 0x9b41, 0x5a52, 0x8a5a, 0x4571, 0x4e61] { + assert!(intel_gen9_to_gen11(id), "{id:#06x}"); + } + for id in [0x0a16, 0x0a1e, 0x1616, 0x9a49, 0x4c8a, 0x4680, 0x46a6, 0xa780, 0x4905, 0x56a0, 0x7d55, 0x64a0, 0xe20b, 0xb080] { + assert!(!intel_gen9_to_gen11(id), "{id:#06x}"); + } + } + + #[test] + fn two_entries_are_one_gpu_only_with_the_same_ids_type_driver_and_bus() { + let stale = two_amd_drivers().swap_remove(0); + let newer = two_amd_drivers().swap_remove(1); + assert!(same_gpu_and_driver(&stale, &newer) && same_gpu_and_driver(&stale, &stale)); + let on_bus = |bus: &str| Candidate { pci_bus_id: bus.into(), ..newer.clone() }; + assert!(same_gpu_and_driver(&stale, &on_bus("0000:03:00.0"))); + assert!(same_gpu_and_driver(&on_bus("0000:03:00.0"), &on_bus("0000:03:00.0"))); + assert!(!same_gpu_and_driver(&on_bus("0000:03:00.0"), &on_bus("0000:04:00.0"))); + for other in [ + Candidate { backend: Dx12, ..newer.clone() }, + Candidate { device_type: IntegratedGpu, ..newer.clone() }, + Candidate { vendor: 0x10de, ..newer.clone() }, + Candidate { device: RADEON_IGPU, ..newer.clone() }, + Candidate { driver: "radv".into(), ..newer.clone() }, + ] { + assert!(!same_gpu_and_driver(&stale, &other), "{other}"); + } + let unidentified = Candidate { vendor: 0, device: 0, ..newer }; + assert!(!same_gpu_and_driver(&unidentified, &unidentified)); + } + + #[test] + fn adapters_that_cannot_draw_to_the_window_are_left_out() { + let unusable = |which: &dyn Fn(usize, &Candidate) -> bool| { + let mut adapters = two_amd_drivers(); + for (i, c) in adapters.iter_mut().enumerate() { + c.usable = !which(i, c); + } + adapters + }; + assert_eq!(choose(&unusable(&|i, _| i == 1), HighPerformance), Some(0)); + assert_eq!(choose(&unusable(&|i, _| i == 0), HighPerformance), Some(1)); + assert_eq!(choose(&unusable(&|_, c| c.backend == Vulkan), HighPerformance), Some(3)); + assert_eq!(choose(&unusable(&|_, _| true), HighPerformance), None); + } + + #[test] + fn candidates_describe_themselves_for_the_log() { + let adapters = two_amd_drivers(); + let text = adapters.get(1).map(ToString::to_string).unwrap_or_default(); + assert_eq!( + text, + "\"AMD Radeon RX 6800M\" (Vulkan, discrete GPU, driver AMD proprietary driver 26.9.2 (AMD proprietary shader compiler), 68 features)" + ); + let offscreen = adapters.get(4).map(|c| Candidate { usable: false, ..c.clone() }.to_string()).unwrap_or_default(); + assert_eq!( + offscreen, + "\"AMD Radeon(TM) Graphics\" (Dx12, integrated GPU, driver 30.0.13002.13003, 36 features, bus 0000:08:00.0, cannot draw to the window)" + ); + assert!(adapters.get(5).is_some_and(Candidate::is_software)); + assert!(!adapters.first().is_some_and(Candidate::is_software)); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn native_instance_is_shared_across_callers() { + let gate = std::sync::Barrier::new(3); + std::thread::scope(|scope| { + let first = scope.spawn(|| { + gate.wait(); + native_instance() + }); + let second = scope.spawn(|| { + gate.wait(); + native_instance() + }); + gate.wait(); + let first = first.join().unwrap(); + assert_eq!(first, second.join().unwrap()); + assert_eq!(first, native_instance()); + }); + } + + /// The instance reads wgpu's flag variables and keeps its own backends whatever `WGPU_BACKEND` + /// says. Runs in a child process, which has them set. + #[test] + fn native_descriptor_reads_wgpu_flags_but_keeps_its_backends() { + const CHILD: &str = "CRAFT_GPU_DEVICE_TEST_NATIVE_DESCRIPTOR_CHILD"; + if std::env::var_os(CHILD).is_none() { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "adapter::tests::native_descriptor_reads_wgpu_flags_but_keeps_its_backends", "--nocapture"]) + .env(CHILD, "1") + .env("WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER", "1") + .env("WGPU_BACKEND", "gl") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success() && stdout.contains("1 passed"), "{stdout}\n{}", String::from_utf8_lossy(&out.stderr)); + return; + } + let desc = native_descriptor(); + assert!(desc.flags.contains(wgpu::InstanceFlags::ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER), "{:?}", desc.flags); + let backends = if cfg!(windows) { wgpu::Backends::PRIMARY } else { wgpu::Backends::PRIMARY | wgpu::Backends::GL }; + assert_eq!(desc.backends, backends); + } + + /// Against the adapters of the machine running the tests: [`wgpu_choice`] is what wgpu's + /// `request_adapter` returns, and [`choose`] returns that adapter too, or, when wgpu's choice + /// is one [`avoided`] excludes, an adapter it does not exclude: a version exposing more + /// features, an Intel Gen 9 to Gen 11 GPU's DirectX 12 entry, or the best other adapter. + /// `None` only when every usable adapter is that Intel Vulkan entry. Passes without adapters. + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn on_this_host_the_choice_is_wgpus_unless_a_correction_applies() { + let backends = wgpu::Backends::PRIMARY; + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { backends, ..wgpu::InstanceDescriptor::new_without_display_handle() }); + let adapters = pollster::block_on(instance.enumerate_adapters(backends)); + let candidates: Vec = adapters.iter().map(|a| Candidate::of(a, None)).collect(); + for power in POWERS { + let options = wgpu::RequestAdapterOptions { power_preference: power, ..Default::default() }; + let wgpu_own = pollster::block_on(instance.request_adapter(&options)).ok().map(|a| Candidate::of(&a, None)); + assert_eq!(wgpu_choice(&candidates, power).and_then(|i| candidates.get(i)), wgpu_own.as_ref(), "{power:?} over {candidates:#?}"); + let own_index = wgpu_choice(&candidates, power); + let chosen = choose(&candidates, power); + let picked = chosen.and_then(|i| candidates.get(i)); + match (own_index, chosen) { + (Some(own), Some(index)) if own != index => { + assert!(avoided(&candidates, own), "{power:?}: {picked:?} instead of {wgpu_own:?}, which is not avoided"); + assert!(!avoided(&candidates, index), "{power:?}: {picked:?} is avoided"); + } + (Some(own), None) => { + let only_intel_vulkan = candidates.iter().filter(|c| c.usable).all(intel_vulkan_crashes); + assert!(only_intel_vulkan, "{power:?}: nothing instead of {:?}", candidates.get(own)); + } + _ => assert_eq!(picked, wgpu_own.as_ref(), "{power:?}"), + } + } + } +} diff --git a/crates/gpu-device/src/caps.rs b/crates/gpu-device/src/caps.rs new file mode 100644 index 0000000000..ea72379bbe --- /dev/null +++ b/crates/gpu-device/src/caps.rs @@ -0,0 +1,311 @@ +//! What an adapter can do, for choosing a pipeline and for the settings and the log. + +use std::fmt; +use std::ops::Deref; + +use craft_gpu::DeviceCaps; +use wgpu::{AdapterInfo, DeviceType, Features, Limits}; + +/// The maker of a GPU, from its PCI vendor id (or the Khronos vendor id some Vulkan drivers +/// report instead). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum Vendor { + Nvidia, + Amd, + Intel, + Apple, + Qualcomm, + Arm, + ImgTec, + /// Microsoft's software adapter (WARP) and its virtual GPUs. + Microsoft, + /// Mesa's software drivers (llvmpipe, lavapipe). + Mesa, + /// Another id, or none (0). + Other(u32), +} + +impl Vendor { + pub fn from_id(id: u32) -> Vendor { + match id { + 0x10de => Vendor::Nvidia, + 0x1002 | 0x1022 => Vendor::Amd, + 0x8086 => Vendor::Intel, + 0x106b => Vendor::Apple, + 0x5143 => Vendor::Qualcomm, + 0x13b5 => Vendor::Arm, + 0x1010 => Vendor::ImgTec, + 0x1414 => Vendor::Microsoft, + 0x10005 => Vendor::Mesa, + other => Vendor::Other(other), + } + } +} + +impl fmt::Display for Vendor { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let name = match self { + Vendor::Nvidia => "NVIDIA", + Vendor::Amd => "AMD", + Vendor::Intel => "Intel", + Vendor::Apple => "Apple", + Vendor::Qualcomm => "Qualcomm", + Vendor::Arm => "Arm", + Vendor::ImgTec => "Imagination", + Vendor::Microsoft => "Microsoft", + Vendor::Mesa => "Mesa", + Vendor::Other(0) => return f.write_str("unknown vendor"), + Vendor::Other(id) => return write!(f, "vendor {id:#06x}"), + }; + f.write_str(name) + } +} + +/// What a device (or an adapter) can do, read from the [`DeviceCaps`] a `craft-gpu` context +/// reports. It holds only that `DeviceCaps`: the video formats, `f16` and timestamps come from its +/// feature names, the vendor from its vendor id, and its fields (the name, the backend and the +/// limits) can be read through `Deref`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Capabilities(DeviceCaps); + +impl Capabilities { + /// From an adapter's (or a device's) info, features and limits. + pub fn from_parts(info: &AdapterInfo, features: Features, limits: &Limits) -> Self { + Capabilities(device_caps_of(info, features, limits)) + } + + /// What `adapter` offers, for a settings page before a device is opened. A `craft-gpu` + /// context reports [`of_device`](Self::of_device) instead: a device can be granted less. + pub fn of_adapter(adapter: &wgpu::Adapter) -> Self { + Self::from_parts(&adapter.get_info(), adapter.features(), &adapter.limits()) + } + + /// What `device` can do: the features and limits it was opened with. + pub fn of_device(device: &wgpu::Device) -> Self { + Self::from_parts(&device.adapter_info(), device.features(), &device.limits()) + } + + /// The `DeviceCaps` these capabilities read. + pub fn device_caps(&self) -> &DeviceCaps { + &self.0 + } + + pub fn into_device_caps(self) -> DeviceCaps { + self.0 + } + + /// Whether every feature in `features` is named in the caps. + fn has(&self, features: Features) -> bool { + features.iter_names().all(|(name, _)| self.0.has_feature(name)) + } + + /// NV12 textures (8-bit 4:2:0, a luma plane and an interleaved chroma plane) can be created + /// and sampled through plane views. wgpu 30 does not render to them: draw the planes into + /// `R8Unorm` and `Rg8Unorm` textures instead. + pub fn nv12(&self) -> bool { + self.has(Features::TEXTURE_FORMAT_NV12) + } + + /// P010 textures (10 bits in 16-bit words, 4:2:0) can be created and sampled through plane + /// views. wgpu 30 does not render to them: draw the planes into `R16Unorm` and `Rg16Unorm` + /// textures ([`norm16`](Self::norm16)) instead. + pub fn p010(&self) -> bool { + self.has(Features::TEXTURE_FORMAT_P010) + } + + /// `R16Unorm`, `Rg16Unorm` and `Rgba16Unorm` textures, for 10-bit and higher planes without + /// P010. + pub fn norm16(&self) -> bool { + self.has(Features::TEXTURE_FORMAT_16BIT_NORM) + } + + /// `f16` in shaders. + pub fn shader_f16(&self) -> bool { + self.has(Features::SHADER_F16) + } + + /// Timestamp queries, for measuring GPU time per pass. + pub fn timestamps(&self) -> bool { + self.has(Features::TIMESTAMP_QUERY) + } + + pub fn vendor(&self) -> Vendor { + Vendor::from_id(self.0.vendor_id) + } + + /// The adapter draws on the CPU. + pub fn software(&self) -> bool { + self.0.software + } + + /// Whether a `width` × `height` texture fits. + pub fn fits(&self, width: u32, height: u32) -> bool { + let max = self.0.max_texture_dimension_2d; + width > 0 && height > 0 && width <= max && height <= max + } + + /// Whether 10-bit planes can be drawn: 16-bit normalized textures. P010 textures can only be + /// sampled. + pub fn ten_bit(&self) -> bool { + self.norm16() + } + + /// The features from `wanted` this adapter has, to ask for when opening a device. + pub fn available(adapter_features: Features, wanted: Features) -> Features { + adapter_features & wanted + } +} + +impl Deref for Capabilities { + type Target = DeviceCaps; + + fn deref(&self) -> &DeviceCaps { + &self.0 + } +} + +impl From for Capabilities { + fn from(caps: DeviceCaps) -> Self { + Capabilities(caps) + } +} + +impl From for DeviceCaps { + fn from(caps: Capabilities) -> Self { + caps.0 + } +} + +impl fmt::Display for Capabilities { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "\"{}\" ({}, {}", self.0.device_name, self.vendor(), self.0.backend_name)?; + if self.software() { + f.write_str(", software")?; + } + let flags = [ + (self.nv12(), "NV12"), + (self.p010(), "P010"), + (self.norm16(), "16-bit norm"), + (self.shader_f16(), "f16"), + (self.timestamps(), "timestamps"), + ]; + for (on, name) in flags { + if on { + write!(f, ", {name}")?; + } + } + write!(f, ", textures up to {} px)", self.0.max_texture_dimension_2d) + } +} + +/// The [`DeviceCaps`] a `craft-gpu` context reports for `device`: the limits and features the +/// device was opened with, not the adapter's, in the same form `craft-gpu-wgpu` reports for a +/// device it opens itself. +pub fn device_caps(device: &wgpu::Device) -> DeviceCaps { + Capabilities::of_device(device).into_device_caps() +} + +fn device_caps_of(info: &AdapterInfo, features: Features, limits: &Limits) -> DeviceCaps { + DeviceCaps { + backend_name: format!("{:?}", info.backend), + device_name: info.name.clone(), + max_storage_buffer_binding_size: limits.max_storage_buffer_binding_size, + max_buffer_size: limits.max_buffer_size, + max_texture_dimension_2d: limits.max_texture_dimension_2d, + features: features.iter_names().map(|(name, _)| name.to_string()).collect(), + vendor_id: info.vendor, + software: info.device_type == DeviceType::Cpu, + } +} + +#[cfg(test)] +mod tests { + use wgpu::Backend; + + use super::*; + + fn info(name: &str, vendor: u32, device_type: DeviceType) -> AdapterInfo { + AdapterInfo { name: name.into(), vendor, ..AdapterInfo::new(device_type, Backend::Vulkan) } + } + + #[test] + fn vendors_from_pci_and_khronos_ids() { + assert_eq!(Vendor::from_id(0x10de), Vendor::Nvidia); + assert_eq!(Vendor::from_id(0x1002), Vendor::Amd); + assert_eq!(Vendor::from_id(0x8086), Vendor::Intel); + assert_eq!(Vendor::from_id(0x10005), Vendor::Mesa); + assert_eq!(Vendor::from_id(0x1414), Vendor::Microsoft); + assert_eq!(Vendor::from_id(0), Vendor::Other(0)); + assert_eq!(Vendor::Other(0).to_string(), "unknown vendor"); + assert_eq!(Vendor::from_id(0x1234).to_string(), "vendor 0x1234"); + } + + #[test] + fn features_and_limits_become_capabilities() { + let features = Features::TEXTURE_FORMAT_NV12 | Features::TEXTURE_FORMAT_16BIT_NORM | Features::TIMESTAMP_QUERY; + let limits = Limits { max_texture_dimension_2d: 16384, ..Limits::default() }; + let c = Capabilities::from_parts(&info("NVIDIA GeForce RTX 4070", 0x10de, DeviceType::DiscreteGpu), features, &limits); + assert!(c.nv12() && !c.p010() && c.norm16() && c.timestamps() && !c.shader_f16() && !c.software()); + assert!(c.ten_bit()); + assert_eq!(c.vendor(), Vendor::Nvidia); + assert!(c.fits(7680, 4320) && c.fits(16384, 16384)); + assert!(!c.fits(16385, 1) && !c.fits(0, 1080) && !c.fits(1920, 0)); + assert_eq!(c.to_string(), "\"NVIDIA GeForce RTX 4070\" (NVIDIA, Vulkan, NV12, 16-bit norm, timestamps, textures up to 16384 px)"); + } + + #[test] + fn a_software_adapter_without_extras() { + let limits = Limits::downlevel_defaults(); + let c = Capabilities::from_parts(&info("llvmpipe (LLVM 19.1.0, 256 bits)", 0x10005, DeviceType::Cpu), Features::empty(), &limits); + assert!(c.software() && !c.ten_bit() && !c.nv12()); + // P010 alone is sampled, not drawn to + let p010 = Capabilities::from_parts(&info("x", 0x8086, DeviceType::IntegratedGpu), Features::TEXTURE_FORMAT_P010, &limits); + assert!(p010.p010() && !p010.ten_bit()); + assert_eq!(c.max_texture_dimension_2d, 2048); + assert!(!c.fits(3840, 2160)); + assert!(c.to_string().contains("software")); + let wanted = Features::TEXTURE_FORMAT_NV12 | Features::SHADER_F16; + assert_eq!(Capabilities::available(Features::SHADER_F16 | Features::TIMESTAMP_QUERY, wanted), Features::SHADER_F16); + } + + #[test] + fn device_caps_carry_the_device_limits_and_feature_names() { + let limits = + Limits { max_texture_dimension_2d: 16384, max_buffer_size: 1 << 30, max_storage_buffer_binding_size: 1 << 28, ..Limits::default() }; + let features = Features::TEXTURE_FORMAT_NV12 | Features::TIMESTAMP_QUERY; + let caps = device_caps_of(&info("NVIDIA GeForce RTX 4070", 0x10de, DeviceType::DiscreteGpu), features, &limits); + assert_eq!(caps.backend_name, "Vulkan"); + assert_eq!(caps.device_name, "NVIDIA GeForce RTX 4070"); + assert_eq!((caps.max_texture_dimension_2d, caps.max_buffer_size, caps.max_storage_buffer_binding_size), (16384, 1 << 30, 1 << 28)); + assert_eq!((caps.vendor_id, caps.software), (0x10de, false)); + let mut names = caps.features.clone(); + names.sort(); + assert_eq!(names, ["TEXTURE_FORMAT_NV12", "TIMESTAMP_QUERY"]); + // a device opened without features reports none + let bare = device_caps_of(&info("llvmpipe", 0x10005, DeviceType::Cpu), Features::empty(), &Limits::downlevel_defaults()); + assert!(bare.features.is_empty()); + assert_eq!(bare.max_texture_dimension_2d, 2048); + assert_eq!((bare.vendor_id, bare.software), (0x10005, true)); + } + + #[test] + fn caps_from_a_craft_gpu_context_read_as_capabilities() { + let caps = DeviceCaps { + backend_name: "Dx12".into(), + device_name: "Intel(R) Arc(TM) A770".into(), + features: vec!["TEXTURE_FORMAT_P010".into(), "SHADER_F16".into(), "TEXTURE_FORMAT_16BIT_NORM".into()], + vendor_id: 0x8086, + ..DeviceCaps::default() + }; + let c = Capabilities::from(caps.clone()); + assert!(c.p010() && c.shader_f16() && c.ten_bit() && !c.nv12() && !c.timestamps() && !c.software()); + assert_eq!(c.vendor(), Vendor::Intel); + assert_eq!(c.to_string(), "\"Intel(R) Arc(TM) A770\" (Intel, Dx12, P010, 16-bit norm, f16, textures up to 8192 px)"); + assert_eq!(DeviceCaps::from(c), caps); + // the caps of a backend with no device claim nothing + let none = Capabilities::from(DeviceCaps::default()); + assert!(!none.nv12() && !none.p010() && !none.norm16() && !none.shader_f16() && !none.timestamps() && !none.software()); + assert_eq!(none.vendor(), Vendor::Other(0)); + } +} diff --git a/crates/gpu-device/src/health.rs b/crates/gpu-device/src/health.rs new file mode 100644 index 0000000000..9374175a6b --- /dev/null +++ b/crates/gpu-device/src/health.rs @@ -0,0 +1,764 @@ +//! Device health: notices a lost wgpu device or an uncaptured wgpu error, so callers stop issuing +//! GPU work and reopen a device or fall back, instead of panicking. +//! +//! wgpu's default uncaptured-error handler panics, and `Device::poll` panics on a lost device +//! whatever the handler. [`DeviceHealth::watch`] replaces the handler with one that records the +//! fault and registers the device-lost callback, and the polls here run only while the device is +//! healthy, catching the poll's panic as a last resort. Every GPU entry point checks +//! [`DeviceHealth::fault`] first. +//! +//! Builds for the web too: the callbacks only touch atomics and a mutex. + +use std::fmt; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, OnceLock}; + +#[cfg(not(target_arch = "wasm32"))] +use std::time::{Duration, Instant}; + +/// Outcome of a bounded wait for submitted GPU work. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WaitOutcome { + /// The submitted work finished before the deadline, or just after it, when wgpu read the + /// fence again at the end of the last poll. + Finished, + /// The deadline passed (or the device faulted) before the work finished. + TimedOut, + /// The caller canceled the wait before the work finished. + Canceled, +} + +/// Why the GPU cannot be used any more. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Fault { + /// The device was lost (driver reset, the OS ended a submission, `Device::destroy`). + Lost(String), + /// An uncaptured wgpu error (out of memory, validation, internal): the GPU output cannot be + /// trusted, and on most drivers the device is about to be lost anyway. + Error(String), +} + +impl Fault { + /// Whether the device itself was lost (rather than an error reported). + pub fn is_lost(&self) -> bool { + matches!(self, Fault::Lost(_)) + } + + /// An out-of-memory error on a device that still works: freeing memory, calling + /// [`DeviceHealth::clear_out_of_memory`] with the count read from + /// [`DeviceHealth::out_of_memory_count`] and trying again can succeed, unlike after a loss or + /// a validation error. Polls and waits keep running meanwhile. Only wgpu's own out-of-memory + /// error is recorded with exactly [`OUT_OF_MEMORY`]; a validation error that mentions memory + /// is not one. + pub fn is_out_of_memory(&self) -> bool { + matches!(self, Fault::Error(s) if s == OUT_OF_MEMORY) + } + + /// The driver's or wgpu's message. + pub fn detail(&self) -> &str { + match self { + Fault::Lost(s) | Fault::Error(s) => s, + } + } +} + +impl fmt::Display for Fault { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Fault::Lost(s) if s.is_empty() => f.write_str("GPU device lost"), + Fault::Lost(s) => write!(f, "GPU device lost: {s}"), + Fault::Error(s) => write!(f, "GPU error: {s}"), + } + } +} + +/// A loss becomes [`GpuFault::DeviceLost`](craft_gpu::GpuFault::DeviceLost), and any other +/// fault becomes [`GpuFault::Operation`](craft_gpu::GpuFault::Operation), each with the fault's +/// text. +impl From for craft_gpu::GpuFault { + fn from(fault: Fault) -> Self { + match fault { + Fault::Lost(s) => craft_gpu::GpuFault::DeviceLost(s), + Fault::Error(s) => craft_gpu::GpuFault::Operation(s), + } + } +} + +/// The message an out-of-memory [`Fault::Error`] carries (wgpu's `Error::OutOfMemory`). +pub const OUT_OF_MEMORY: &str = "Out of Memory"; + +/// The state wgpu's callbacks write and callers read, without a lock: flags in atomics and each +/// fault's text in a [`OnceLock`], whose `get` does not wait. A `set` that races another `set` +/// of the same slot waits only for that one store. +#[derive(Default)] +struct Inner { + /// The first device loss. + lost: OnceLock, + /// Out-of-memory errors seen. + out_of_memory_seen: AtomicU64, + /// Out-of-memory errors the caller cleared ([`DeviceHealth::clear_out_of_memory`]). + out_of_memory_cleared: AtomicU64, + /// The first other error. + error: OnceLock, + errors: AtomicU64, + /// wgpu itself reported the device lost (see [`DeviceHealth::device_lost`]). + device_lost: AtomicBool, +} + +/// Shared health flag of one wgpu device. Cheap to clone; every clone sees the same state. +#[derive(Clone, Default)] +pub struct DeviceHealth(Arc); + +impl fmt::Debug for DeviceHealth { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DeviceHealth").field("fault", &self.fault()).field("errors", &self.errors()).finish() + } +} + +impl DeviceHealth { + /// A healthy flag not attached to a device (tests, CPU-only callers). + pub fn new() -> Self { + Self::default() + } + + /// Watch `device`: its device-lost callback and uncaptured errors mark the returned flag + /// instead of panicking. Replaces any handler set before (wgpu keeps one of each). On the + /// browser backend, wgpu 30 panics on an uncaptured `GPUInternalError` before this handler + /// runs, so such an error is not recorded; validation and out-of-memory errors are. + pub fn watch(device: &wgpu::Device) -> Self { + let health = Self::new(); + let lost = health.clone(); + // Called by wgpu with its own locks held: only record, never call back into wgpu. + device.set_device_lost_callback(move |reason, message| { + let detail = match (reason, message.is_empty()) { + (wgpu::DeviceLostReason::Destroyed, true) => "device destroyed".to_string(), + (_, true) => "lost by the driver".to_string(), + (_, false) => message, + }; + log::error!("wgpu device lost ({reason:?}): {detail}"); + // The loss first: a caller that sees `device_lost` then also sees the fault. + lost.mark(Fault::Lost(detail)); + lost.0.device_lost.store(true, Ordering::Release); + }); + let errors = health.clone(); + device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| errors.uncaptured(&e))); + health + } + + /// Record an uncaptured wgpu error. + fn uncaptured(&self, e: &wgpu::Error) { + self.0.errors.fetch_add(1, Ordering::Relaxed); + log::error!("uncaptured wgpu error: {e}"); + self.mark(fault_of(e)); + } + + /// Record an error an error scope caught. + /// + /// The uncaptured-error handler never sees a scoped error, so without this a watched device + /// would keep being handed work after it failed. Polls first: a lost device is a + /// [`Fault::Lost`], and its callback may not have run yet (it runs on a poll). The poll does + /// not block. + pub fn caught(&self, device: &wgpu::Device, error: &wgpu::Error) { + if self.lost() { + return; + } + #[cfg(not(target_arch = "wasm32"))] + self.poll(device); + #[cfg(target_arch = "wasm32")] + let _ = device; + if self.lost() { + return; + } + self.mark(fault_of(error)); + } + + fn lost(&self) -> bool { + self.fault().is_some_and(|f| f.is_lost()) + } + + /// Mark the device unusable. The first fault is kept; a later device loss replaces an error, + /// and a later out-of-memory error is reported over another error, so a caller still sees + /// that freeing memory may help after a validation error in the same frame. + pub fn mark(&self, fault: Fault) { + if fault.is_out_of_memory() { + self.0.out_of_memory_seen.fetch_add(1, Ordering::AcqRel); + return; + } + // A slot already set keeps its first text. + let _ = match fault { + Fault::Lost(text) => self.0.lost.set(text), + Fault::Error(text) => self.0.error.set(text), + }; + } + + /// Out-of-memory errors recorded so far. Read it when handling an out-of-memory fault, and + /// pass it to [`clear_out_of_memory`](Self::clear_out_of_memory) once memory was freed. + pub fn out_of_memory_count(&self) -> u64 { + self.0.out_of_memory_seen.load(Ordering::Acquire) + } + + /// Clear the out-of-memory errors up to `count` (from + /// [`out_of_memory_count`](Self::out_of_memory_count)) after the caller freed memory. One + /// recorded after `count` was read stays. The device counts as healthy again unless it was + /// lost or another error was recorded, which [`fault`](Self::fault) then reports. + pub fn clear_out_of_memory(&self, count: u64) { + let count = count.min(self.0.out_of_memory_seen.load(Ordering::Acquire)); + self.0.out_of_memory_cleared.fetch_max(count, Ordering::AcqRel); + } + + /// Whether an out-of-memory error is recorded and not cleared. + fn out_of_memory(&self) -> bool { + let cleared = self.0.out_of_memory_cleared.load(Ordering::Acquire); + self.0.out_of_memory_seen.load(Ordering::Acquire) > cleared + } + + /// Whether the device may still be used: no fault was recorded, or only out-of-memory errors + /// that [`clear_out_of_memory`](Self::clear_out_of_memory) cleared. + pub fn is_ok(&self) -> bool { + self.0.lost.get().is_none() && self.0.error.get().is_none() && !self.out_of_memory() + } + + /// Whether polls and waits still run: the device was not lost and reported no error other + /// than out of memory. A poll reclaims the staging memory that recovering from an + /// out-of-memory error needs. + fn pollable(&self) -> bool { + self.0.lost.get().is_none() && self.0.error.get().is_none() + } + + /// Why the device cannot be used, if it cannot. + pub fn fault(&self) -> Option { + if let Some(text) = self.0.lost.get() { + return Some(Fault::Lost(text.clone())); + } + if self.out_of_memory() { + return Some(Fault::Error(OUT_OF_MEMORY.into())); + } + self.0.error.get().map(|text| Fault::Error(text.clone())) + } + + /// The device loss in the form of `craft_gpu::GpuContext::device_status`: + /// [`GpuFault::DeviceLost`](craft_gpu::GpuFault::DeviceLost) once a loss is recorded, + /// otherwise `Ok`. Other errors are reported by [`fault`](Self::fault). wgpu keeps one + /// device-lost callback per device, so a `craft-gpu` context on a device that + /// [`watch`](Self::watch) watches reads the loss here instead of setting its own callback. + pub fn device_status(&self) -> Result<(), craft_gpu::GpuFault> { + match self.0.lost.get() { + Some(text) => Err(craft_gpu::GpuFault::DeviceLost(text.clone())), + None => Ok(()), + } + } + + /// Uncaptured wgpu errors seen so far. + pub fn errors(&self) -> u64 { + self.0.errors.load(Ordering::Relaxed) + } + + /// Whether wgpu itself reported the device lost: its device-lost callback ran, or polling it + /// panicked. A fault recorded with [`mark`](Self::mark) is not one. After a real loss nothing + /// drawn with the device reaches the screen, the window's own frames included. + pub fn device_lost(&self) -> bool { + self.0.device_lost.load(Ordering::Acquire) + } + + /// Non-blocking poll that runs even after a fault was recorded, so a device that is lost + /// later (a driver reset while the app sat idle, or the PC slept) is noticed before the next + /// frame is drawn with it. Skipped once [`device_lost`](Self::device_lost). + pub fn probe(&self, device: &wgpu::Device) { + if self.device_lost() { + return; + } + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Poll))).is_err() { + self.lost_by_poll(); + } + } + + /// `Device::poll` panicked: wgpu found the device lost. + fn lost_by_poll(&self) { + self.mark(Fault::Lost("the device stopped responding".into())); + self.0.device_lost.store(true, Ordering::Release); + } + + /// Block until the work up to `index` finished, unless the device was lost or reported an + /// error other than out of memory. To wait for everything submitted so far, pass the index of + /// an empty submission (`queue.submit([])`); work submitted after it does not extend the + /// wait. Returns whether the work finished with the device still usable: `false` when it was + /// lost or reported such an error, before or during the wait, and when the poll itself + /// failed, so the work may still be running. After an out-of-memory error the wait still + /// runs. The wait has no deadline, but it polls in slices of at most 100 ms, so a loss or an + /// error other than out of memory that another clone records while the work has not finished + /// ends it after the current slice. A panic in `Device::poll` is caught and recorded as a + /// loss. Native only: the web has no blocking wait. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait(&self, device: &wgpu::Device, index: wgpu::SubmissionIndex) -> bool { + const SLICE: Duration = Duration::from_millis(100); + self.wait_unbounded(|| { + let poll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + device.poll(wgpu::PollType::Wait { submission_index: Some(index.clone()), timeout: Some(SLICE) }) + })); + match poll { + Ok(Ok(_)) => SlicePoll::Done, + Ok(Err(wgpu::PollError::Timeout)) => SlicePoll::Pending, + Ok(Err(e)) => { + log::warn!("wgpu poll: {e}"); + SlicePoll::Failed + } + Err(_) => { + self.lost_by_poll(); + SlicePoll::Failed + } + } + }) + } + + /// [`Self::wait`]'s loop: `poll` runs one slice and reports what wgpu returned. The loop ends + /// when a slice finished or failed, and before the next slice once a clone of this flag + /// recorded a loss or an error other than out of memory. + #[cfg(not(target_arch = "wasm32"))] + fn wait_unbounded(&self, mut poll: impl FnMut() -> SlicePoll) -> bool { + loop { + if !self.pollable() { + return false; + } + match poll() { + SlicePoll::Done => return self.pollable(), + SlicePoll::Pending => {} + SlicePoll::Failed => return false, + } + } + } + + /// Non-blocking poll (reclaims staging memory), skipped once the device was lost or reported + /// an error other than out of memory. + pub fn poll(&self, device: &wgpu::Device) { + if !self.pollable() { + return; + } + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Poll))).is_err() { + self.lost_by_poll(); + } + } + + /// Like [`Self::wait`], but bounded: returns whether the work up to `index` finished within + /// `timeout`. To wait for everything submitted so far, pass the index of an empty submission + /// (`queue.submit([])`); work submitted after it does not extend the wait. A timeout marks the + /// device faulted, so later work stops going to a GPU that no longer answers. A submission + /// index the device never issued returns `false` and leaves the device healthy. A zero + /// `timeout`, or one that passes before the first poll, returns `false` and leaves the device + /// healthy. A device that was already lost, or that reported an error other than out of + /// memory, returns `false` unchanged. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait_timeout(&self, device: &wgpu::Device, index: wgpu::SubmissionIndex, timeout: Duration) -> bool { + self.wait_timeout_cancelable(device, index, timeout, &|| false) == WaitOutcome::Finished + } + + /// [`Self::wait_timeout`] that polls in slices of at most 100 ms and checks `canceled` between + /// them, keeping the same overall deadline. Every slice waits for the same `index`. A slice + /// that times out means the work has not finished yet; only the overall deadline (or a poll + /// that panics) marks the device faulted. A loss or an error other than out of memory that + /// another clone records during the wait ends it after the current slice, with + /// [`WaitOutcome::TimedOut`]. wgpu reads the fence again after a slice's own timeout, so work + /// that finishes in that gap, just after the deadline, is [`WaitOutcome::Finished`]. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait_timeout_cancelable( + &self, + device: &wgpu::Device, + index: wgpu::SubmissionIndex, + timeout: Duration, + canceled: &(dyn Fn() -> bool + Sync), + ) -> WaitOutcome { + if !self.pollable() { + return WaitOutcome::TimedOut; + } + let mut wrong_index = false; + let mut polled = false; + let start = Instant::now(); + let elapsed = || start.elapsed(); + let outcome = wait_slices(timeout, canceled, elapsed, |slice| { + polled = true; + let poll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + device.poll(wgpu::PollType::Wait { submission_index: Some(index.clone()), timeout: Some(slice) }) + })); + match poll { + Ok(Ok(_)) => self.after_slice(true), + Ok(Err(wgpu::PollError::Timeout)) => self.after_slice(false), + // A submission index the device never issued: the caller's mistake, not the GPU's. + Ok(Err(e)) => { + log::warn!("wgpu poll: {e}"); + wrong_index = true; + SlicePoll::Failed + } + Err(_) => { + self.lost_by_poll(); + SlicePoll::Failed + } + } + }); + // A deadline that passed before the first poll says nothing about the device. + if outcome == WaitOutcome::TimedOut && polled && !wrong_index && self.pollable() { + self.mark(Fault::Lost(format!("GPU wait timed out after {:.1} s", timeout.as_secs_f64()))); + } + outcome + } + + /// What a slice that returned reports, `finished` or not: failed once a clone of this flag + /// recorded a loss or an error other than out of memory, so the next slice does not poll a + /// device that is not to be used. + #[cfg(not(target_arch = "wasm32"))] + fn after_slice(&self, finished: bool) -> SlicePoll { + if !self.pollable() { + SlicePoll::Failed + } else if finished { + SlicePoll::Done + } else { + SlicePoll::Pending + } + } +} + +/// What one bounded poll reported. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SlicePoll { + Done, + Pending, + Failed, +} + +/// Wait for `total`, polling in slices no longer than 100 ms and checking `canceled` between +/// them. `elapsed` gives the time since the wait started. A slice that times out is pending, not +/// a failure; only the overall deadline or a failed poll ends the wait early. +#[cfg(not(target_arch = "wasm32"))] +fn wait_slices( + total: Duration, + canceled: &(dyn Fn() -> bool + Sync), + mut elapsed: impl FnMut() -> Duration, + mut poll: impl FnMut(Duration) -> SlicePoll, +) -> WaitOutcome { + const SLICE: Duration = Duration::from_millis(100); + loop { + if canceled() { + return WaitOutcome::Canceled; + } + let remaining = total.saturating_sub(elapsed()); + if remaining.is_zero() { + return WaitOutcome::TimedOut; + } + match poll(remaining.min(SLICE)) { + SlicePoll::Done => return WaitOutcome::Finished, + SlicePoll::Pending => {} + SlicePoll::Failed => return WaitOutcome::TimedOut, + } + } +} + +/// The whole message of wgpu's `DeviceError::Lost`. +const LOST_CAUSE: &str = "Parent device is lost"; + +/// Whether one of the errors that caused `e` (its `source` chain) is wgpu's `DeviceError::Lost`: +/// an error whose whole message is [`LOST_CAUSE`]. A resource label is part of another error's +/// message, so a label never matches. +fn caused_by_loss(e: &wgpu::Error) -> bool { + let source: &(dyn std::error::Error + 'static) = match e { + wgpu::Error::Validation { source, .. } | wgpu::Error::Internal { source, .. } => source.as_ref(), + _ => return false, + }; + std::iter::successors(Some(source), |c| c.source()).any(|c| c.to_string().trim().eq_ignore_ascii_case(LOST_CAUSE)) +} + +/// The fault a wgpu error stands for. An error caused by a lost device ([`caused_by_loss`]) +/// follows a device loss whose callback may not have run yet (it runs on the next poll), so it +/// counts as a loss rather than as an error. An error about a destroyed buffer or texture is an +/// error. Only wgpu's own out-of-memory error is [`OUT_OF_MEMORY`]. The text keeps the causes +/// ([`one_line`]). +fn fault_of(e: &wgpu::Error) -> Fault { + let text = e.to_string(); + if matches!(e, wgpu::Error::OutOfMemory { .. }) { + Fault::Error(OUT_OF_MEMORY.into()) + } else if caused_by_loss(e) { + Fault::Lost(one_line(&text)) + } else { + Fault::Error(one_line(&text)) + } +} + +/// wgpu's multi-line error text on one line: the heading and each cause, joined with ": ", +/// without wgpu's "Caused by:" line, cut to 200 characters. +fn one_line(s: &str) -> String { + const MAX: usize = 200; + let mut out = String::new(); + let mut count = 0; + let lines = s.lines().map(str::trim).filter(|l| !l.is_empty() && !l.eq_ignore_ascii_case("Caused by:")); + for (i, line) in lines.enumerate() { + let separator = if i == 0 { "" } else { ": " }; + for c in separator.chars().chain(line.chars()) { + if count == MAX { + out.push('…'); + return out; + } + out.push(c); + count += 1; + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn first_fault_wins_but_loss_replaces_an_error() { + let h = DeviceHealth::new(); + assert!(h.is_ok()); + assert_eq!(h.fault(), None); + h.mark(Fault::Error("out of memory".into())); + assert!(!h.is_ok()); + let c = h.clone(); + c.mark(Fault::Error("second".into())); + assert_eq!(h.fault(), Some(Fault::Error("out of memory".into()))); + c.mark(Fault::Lost("reset".into())); + assert_eq!(h.fault(), Some(Fault::Lost("reset".into()))); + c.mark(Fault::Lost("later".into())); + assert_eq!(h.fault().map(|f| f.to_string()).as_deref(), Some("GPU device lost: reset")); + // a recorded loss is not wgpu reporting the device lost + assert!(!h.device_lost()); + } + + #[test] + fn faults_in_the_craft_gpu_form() { + use craft_gpu::GpuFault; + let h = DeviceHealth::new(); + assert_eq!(h.device_status(), Ok(())); + // an error, out of memory included, is not a loss + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + h.mark(Fault::Error("Validation Error".into())); + assert_eq!(h.device_status(), Ok(())); + h.mark(Fault::Lost("reset".into())); + assert_eq!(h.device_status(), Err(GpuFault::DeviceLost("reset".into()))); + assert_eq!(GpuFault::from(Fault::Lost("reset".into())), GpuFault::DeviceLost("reset".into())); + assert_eq!(GpuFault::from(Fault::Error(OUT_OF_MEMORY.into())), GpuFault::Operation(OUT_OF_MEMORY.into())); + assert_eq!(h.fault().map(GpuFault::from), Some(GpuFault::DeviceLost("reset".into()))); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn wait_slices_cancel_timeout_and_completion() { + let never = || false; + // a clock that does not move: only the polls end these waits + let still = || Duration::ZERO; + assert_eq!(wait_slices(Duration::ZERO, &never, still, |_| SlicePoll::Done), WaitOutcome::TimedOut); + assert_eq!(wait_slices(Duration::from_secs(1), &never, still, |_| SlicePoll::Done), WaitOutcome::Finished); + assert_eq!(wait_slices(Duration::from_secs(1), &never, still, |_| SlicePoll::Failed), WaitOutcome::TimedOut); + + let mut polls = 0; + let outcome = wait_slices(Duration::from_secs(1), &never, still, |_| { + polls += 1; + if polls < 3 { SlicePoll::Pending } else { SlicePoll::Done } + }); + assert_eq!(outcome, WaitOutcome::Finished); + assert_eq!(polls, 3, "a timed-out slice is retried, not treated as a failure"); + + let canceled = || true; + let mut called = false; + assert_eq!( + wait_slices(Duration::from_secs(1), &canceled, still, |_| { + called = true; + SlicePoll::Done + }), + WaitOutcome::Canceled + ); + assert!(!called, "cancellation is checked before polling"); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn wait_slices_end_at_the_deadline_of_a_moving_clock() { + let never = || false; + let now = std::cell::Cell::new(Duration::ZERO); + let mut slices = Vec::new(); + let clock = || now.get(); + let outcome = wait_slices(Duration::from_millis(250), &never, clock, |slice| { + slices.push(slice); + now.set(now.get() + slice); + SlicePoll::Pending + }); + assert_eq!(outcome, WaitOutcome::TimedOut); + assert_eq!(slices, [Duration::from_millis(100), Duration::from_millis(100), Duration::from_millis(50)]); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn wait_slices_observes_cancel_while_pending() { + let flag = AtomicBool::new(false); + let canceled = || flag.load(Ordering::SeqCst); + let mut polls = 0; + let still = || Duration::ZERO; + let outcome = wait_slices(Duration::from_secs(1), &canceled, still, |_| { + polls += 1; + flag.store(true, Ordering::SeqCst); + SlicePoll::Pending + }); + assert_eq!(outcome, WaitOutcome::Canceled); + assert_eq!(polls, 1, "a cancel set during a pending poll ends the wait"); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn a_fault_recorded_during_a_wait_stops_the_next_slice() { + let h = DeviceHealth::new(); + assert_eq!(h.after_slice(false), SlicePoll::Pending); + assert_eq!(h.after_slice(true), SlicePoll::Done); + // out of memory alone: polls keep reclaiming memory + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert_eq!(h.after_slice(false), SlicePoll::Pending); + // another clone records a validation error while a slice is pending + h.clone().mark(Fault::Error("Validation Error".into())); + assert_eq!(h.after_slice(false), SlicePoll::Failed, "the next slice must not poll"); + assert_eq!(h.after_slice(true), SlicePoll::Failed); + let lost = DeviceHealth::new(); + lost.clone().mark(Fault::Lost("reset".into())); + assert_eq!(lost.after_slice(false), SlicePoll::Failed); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn a_fault_recorded_during_an_unbounded_wait_ends_it() { + let h = DeviceHealth::new(); + let other = h.clone(); + let mut polls = 0; + let finished = h.wait_unbounded(|| { + polls += 1; + if polls == 2 { + other.mark(Fault::Error("Validation Error".into())); + } + assert!(polls <= 2, "a slice ran after the fault"); + SlicePoll::Pending + }); + assert!(!finished); + assert_eq!(polls, 2); + // out of memory alone keeps the wait going until the work finishes + let oom = DeviceHealth::new(); + oom.mark(Fault::Error(OUT_OF_MEMORY.into())); + let mut polls = 0; + assert!(oom.wait_unbounded(|| { + polls += 1; + if polls < 3 { SlicePoll::Pending } else { SlicePoll::Done } + })); + assert_eq!(polls, 3); + assert!(!DeviceHealth::new().wait_unbounded(|| SlicePoll::Failed)); + } + + #[test] + fn fault_text() { + assert_eq!(Fault::Lost(String::new()).to_string(), "GPU device lost"); + assert_eq!(Fault::Error("x".into()).to_string(), "GPU error: x"); + assert_eq!(one_line("\n Buffer 'pc' is invalid\nmore"), "Buffer 'pc' is invalid: more"); + assert_eq!(one_line(&"a".repeat(300)).chars().count(), 201); + assert_eq!(one_line(&"a".repeat(200)), "a".repeat(200)); + assert_eq!(one_line(&format!("{}\nb", "a".repeat(199))), format!("{}:…", "a".repeat(199))); + assert!(Fault::Error("Out of Memory".into()).is_out_of_memory()); + assert!(!Fault::Error("Validation Error".into()).is_out_of_memory()); + assert!(!Fault::Error("Validation Error: buffer allocation would run out of memory".into()).is_out_of_memory()); + let h = DeviceHealth::new(); + h.mark(Fault::Error("Validation Error".into())); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(h.fault().is_some_and(|f| f.is_out_of_memory())); + h.mark(Fault::Lost("reset".into())); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(h.fault().is_some_and(|f| f.is_lost())); + assert!(!Fault::Lost("out of memory".into()).is_out_of_memory()); + } + + #[test] + fn out_of_memory_keeps_polls_running_until_cleared() { + let h = DeviceHealth::new(); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(!h.is_ok()); + assert!(h.pollable(), "polls reclaim the memory that recovery needs"); + let seen = h.out_of_memory_count(); + // one recorded while the caller freed memory is not cleared with the earlier ones + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + h.clear_out_of_memory(seen); + assert!(h.fault().is_some_and(|f| f.is_out_of_memory())); + h.clear_out_of_memory(h.out_of_memory_count()); + assert!(h.is_ok()); + assert_eq!(h.fault(), None); + // a count larger than the ones recorded does not hide later errors + h.clear_out_of_memory(u64::MAX); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(!h.is_ok()); + h.clear_out_of_memory(h.out_of_memory_count()); + // an earlier error is still there once the out-of-memory error is cleared + h.mark(Fault::Error("Validation Error".into())); + assert!(!h.pollable()); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(!h.pollable(), "a later out-of-memory error does not undo the earlier error"); + h.clear_out_of_memory(h.out_of_memory_count()); + assert_eq!(h.fault(), Some(Fault::Error("Validation Error".into()))); + assert!(!h.is_ok() && !h.pollable()); + let lost = DeviceHealth::new(); + lost.mark(Fault::Error(OUT_OF_MEMORY.into())); + lost.mark(Fault::Lost("reset".into())); + assert!(!lost.pollable()); + } + + #[test] + fn marks_from_several_threads_keep_the_loss() { + let h = DeviceHealth::new(); + let threads: Vec<_> = (0..8) + .map(|i| { + let h = h.clone(); + std::thread::spawn(move || h.mark(if i == 5 { Fault::Lost("reset".into()) } else { Fault::Error(format!("e{i}")) })) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + assert_eq!(h.fault(), Some(Fault::Lost("reset".into()))); + } + + /// An error and the errors that caused it, outermost first, as wgpu-core chains them. + #[derive(Debug)] + struct Cause(&'static str, Option>); + + impl fmt::Display for Cause { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.0) + } + } + + impl std::error::Error for Cause { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + self.1.as_deref().map(|c| c as _) + } + } + + /// A validation error with the causes `chain` and wgpu's description of them. + fn validation(chain: &[&'static str]) -> wgpu::Error { + let source = chain.iter().rev().fold(None, |inner, text| Some(Box::new(Cause(text, inner)))); + let mut description = String::from("Validation Error\n\nCaused by:\n"); + for c in chain { + description.push_str(&format!(" {c}\n")); + } + wgpu::Error::Validation { source: source.unwrap_or_else(|| Box::new(Cause("", None))), description } + } + + #[test] + fn only_a_lost_device_counts_as_a_loss() { + let lost = validation(&["In Device::create_buffer", "Parent device is lost"]); + assert!(fault_of(&lost).is_lost(), "{:?}", fault_of(&lost)); + let destroyed = validation(&["In Queue::submit", "Buffer 'pc' has been destroyed"]); + // the stored text names what failed, not only wgpu's heading + assert_eq!(fault_of(&destroyed), Fault::Error("Validation Error: In Queue::submit: Buffer 'pc' has been destroyed".into())); + assert_eq!(fault_of(&lost), Fault::Lost("Validation Error: In Device::create_buffer: Parent device is lost".into())); + let texture = validation(&["Texture with 'frame' label has been destroyed"]); + assert!(!fault_of(&texture).is_lost()); + // a label is the caller's text, not the cause, even on a line of its own + let labeled = validation(&["In Queue::submit", "Buffer 'device is lost' has been destroyed"]); + assert_eq!(fault_of(&labeled), Fault::Error("Validation Error: In Queue::submit: Buffer 'device is lost' has been destroyed".into())); + for label in ["Buffer 'Parent device is lost' has been destroyed", "Buffer 'a\nParent device is lost\nb' has been destroyed"] { + let labeled = validation(&["In Queue::submit", label]); + assert!(!fault_of(&labeled).is_lost(), "{label:?}"); + } + } +} diff --git a/crates/gpu-device/src/lib.rs b/crates/gpu-device/src/lib.rs new file mode 100644 index 0000000000..a2988b90d2 --- /dev/null +++ b/crates/gpu-device/src/lib.rs @@ -0,0 +1,43 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! Choosing and opening a wgpu device for a Craft app. +//! +//! - [`list`] gives every adapter as plain [`Candidate`] data for a settings page, and +//! [`AdapterKey`] identifies one across runs. +//! - [`select`] and [`ranked`] choose an adapter for a [`Preference`] (Auto, low power, a named +//! adapter, software) with wgpu's own rule and two corrections for drivers that crash +//! ([`choose`]); [`Notice`] says when the choice was not the one asked for. +//! - [`open`] opens a device, moving to the next adapter and last to a software one when a device +//! fails to open. [`pick`] fits egui-wgpu's adapter selector for a window. `list` and `open` +//! block on wgpu's futures and are native only; [`list_async`] and [`open_async`] are the same +//! as futures, for a `wasm32` web worker as well as native. +//! - In a browser, WebGPU offers one adapter for a power preference, so a named adapter cannot be +//! chosen, and wgpu 30 cannot ask for the browser's fallback (software) adapter. `open_async` +//! asks for the adapter with [`Preference::power`]. [`Capabilities`] and [`Recovery`] work +//! there as they do on native, and so does [`DeviceHealth`] apart from its blocking waits, +//! which are native only. +//! - [`Capabilities`] reads what the device can do (NV12 and P010 textures, 16-bit norm formats, +//! `f16`, timestamps, the vendor, a software adapter, sizes) from the `craft_gpu::DeviceCaps` +//! it holds, which [`device_caps`] and [`Opened::device_caps`] give for a `craft-gpu` context. +//! - [`DeviceHealth`] records a device loss or an uncaptured error instead of panicking, and +//! [`Recovery`] says what to open after a loss. [`DeviceHealth::device_status`] reports a loss +//! as `craft_gpu::GpuFault::DeviceLost`, and a [`Fault`] converts to a `craft_gpu::GpuFault`. +//! +//! The selection functions are pure, so tests run without a GPU. + +mod adapter; +mod caps; +mod health; +mod open; +mod preference; +mod recovery; + +pub use adapter::{Candidate, choose, intel_gen9_to_gen11, native_descriptor, native_instance}; +pub use caps::{Capabilities, Vendor, device_caps}; +pub use health::{DeviceHealth, Fault, OUT_OF_MEMORY, WaitOutcome}; +pub use open::{OpenError, Opened, Request, list_async, open_async, pick}; +#[cfg(not(target_arch = "wasm32"))] +pub use open::{list, open}; +pub use preference::{AdapterKey, Notice, Preference, Selection, backend_name, ranked, select}; +pub use recovery::{Recovery, RecoveryPolicy, RecoveryStep}; diff --git a/crates/gpu-device/src/open.rs b/crates/gpu-device/src/open.rs new file mode 100644 index 0000000000..cb55cdfcc3 --- /dev/null +++ b/crates/gpu-device/src/open.rs @@ -0,0 +1,474 @@ +//! Listing adapters and opening a device, trying the next adapter when one fails. + +use std::fmt; + +use wgpu::{Adapter, Features, Instance, Limits, Surface}; + +use crate::adapter::{Candidate, avoided, log_choice}; +use crate::caps::Capabilities; +use crate::health::DeviceHealth; +use crate::preference::{Notice, Preference, Selection, asked_for, ranked, select}; + +/// What the device is opened with. +#[derive(Clone, Debug, Default)] +pub struct Request<'a> { + pub label: Option<&'a str>, + /// Features the device must have. An adapter without them is skipped. + pub required_features: Features, + /// Features asked for when the adapter has them. Experimental features + /// (`Features::all_experimental_mask`) are left out here: the device descriptor does not + /// enable experimental features, and wgpu refuses a device that asks for one without that. + pub optional_features: Features, + /// The limits to ask for; `None` asks for the adapter's own limits. An adapter whose limits + /// are lower is skipped. + pub limits: Option, +} + +/// An opened device. +#[derive(Debug)] +pub struct Opened { + pub adapter: Adapter, + pub device: wgpu::Device, + pub queue: wgpu::Queue, + /// The adapter as plain data. + pub candidate: Candidate, + /// What the device was opened with, as the `craft_gpu::DeviceCaps` it reports. + pub caps: Capabilities, + /// Watches the device for a loss and for uncaptured errors. + pub health: DeviceHealth, + /// What to tell the user about the choice. + pub notices: Vec, +} + +impl Opened { + /// The device's [`DeviceCaps`](craft_gpu::DeviceCaps) for a `craft-gpu` context + /// ([`device_caps`](crate::device_caps)). + pub fn device_caps(&self) -> craft_gpu::DeviceCaps { + self.caps.device_caps().clone() + } +} + +/// Why no device could be opened. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum OpenError { + /// No adapter is listed that can draw (to the surface, when there is one). + NoAdapter, + /// Every adapter tried failed to open a device; each failure is a [`Notice::DeviceFailed`]. + NoDevice(Vec), + /// The only adapters that can draw are ones [`choose`](crate::choose) never draws with, + /// because their driver can end the process; these are their names. + UnsafeDriver(Vec), +} + +impl fmt::Display for OpenError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + OpenError::NoAdapter => f.write_str("no graphics adapter is available"), + OpenError::NoDevice(notices) => { + f.write_str("no graphics adapter could be opened")?; + for n in notices { + if let Notice::DeviceFailed { adapter, error } = n { + write!(f, "; \"{adapter}\": {error}")?; + } + } + Ok(()) + } + OpenError::UnsafeDriver(names) => { + let names = names.iter().map(|n| format!("\"{n}\"")).collect::>().join(", "); + write!(f, "the only graphics adapters that can draw ({names}) use a driver that can crash; update the graphics driver") + } + } + } +} + +impl std::error::Error for OpenError {} + +/// Every adapter `instance` lists over its backends, as adapters and as plain data. `surface` +/// marks the adapters that cannot draw to it as unusable. Native only: it blocks on wgpu's +/// future, which on the web would wait on the thread that must resolve it. [`list_async`] works +/// on both. +#[cfg(not(target_arch = "wasm32"))] +pub fn list(instance: &Instance, surface: Option<&Surface<'_>>) -> (Vec, Vec) { + pollster::block_on(list_async(instance, surface)) +} + +/// [`list`] as a future, for a `wasm32` web worker as well as native. In a browser, WebGPU offers +/// one adapter for a power preference, and the list holds the high-performance one, which +/// [`open_async`] opens for `Auto` and for a named adapter. +pub async fn list_async(instance: &Instance, surface: Option<&Surface<'_>>) -> (Vec, Vec) { + #[cfg(not(target_arch = "wasm32"))] + let adapters = instance.enumerate_adapters(wgpu::Backends::all()).await; + #[cfg(target_arch = "wasm32")] + let adapters = browser_adapter(instance, surface, wgpu::PowerPreference::HighPerformance).await; + let candidates = adapters.iter().map(|a| Candidate::of(a, surface)).collect(); + (adapters, candidates) +} + +/// The adapter a browser offers for `power`, if any. +#[cfg(target_arch = "wasm32")] +async fn browser_adapter(instance: &Instance, surface: Option<&Surface<'_>>, power: wgpu::PowerPreference) -> Vec { + let options = wgpu::RequestAdapterOptions { power_preference: power, compatible_surface: surface, ..Default::default() }; + instance.request_adapter(&options).await.into_iter().collect() +} + +/// The adapter to draw with for `preference`, from adapters already listed, with the choice in the +/// log. This fits egui-wgpu's `native_adapter_selector` for a window, which then opens the device +/// itself; that selector takes a `String` error, so convert with `map_err(|e| e.to_string())`. +/// With no usable adapter the error is [`OpenError::UnsafeDriver`] when only adapters that +/// [`choose`](crate::choose) never draws with can draw, and [`OpenError::NoAdapter`] otherwise, +/// with the listed adapters in the log. +pub fn pick(adapters: &[Adapter], surface: Option<&Surface<'_>>, preference: &Preference) -> Result<(Adapter, Selection), OpenError> { + let candidates: Vec = adapters.iter().map(|a| Candidate::of(a, surface)).collect(); + let Some(selection) = select(&candidates, preference) else { + return Err(unselected(&candidates)); + }; + log_choice(&candidates, selection.index, preference.power()); + for notice in &selection.notices { + log::warn!("{notice}"); + } + let adapter = adapters.get(selection.index).cloned().ok_or(OpenError::NoAdapter)?; + Ok((adapter, selection)) +} + +/// The error for `candidates` among which `select` found no adapter, with the list in the log +/// when it is not [`OpenError::UnsafeDriver`]. +fn unselected(candidates: &[Candidate]) -> OpenError { + let left_out = left_out(candidates); + if !left_out.is_empty() { + return OpenError::UnsafeDriver(left_out); + } + let listed = candidates.iter().map(ToString::to_string).collect::>().join(", "); + log::warn!("no usable graphics adapter among {}: {listed}", candidates.len()); + OpenError::NoAdapter +} + +/// Open a device for `preference`: the selected adapter first, then the others in [`ranked`] +/// order, and last wgpu's fallback adapter (a software one) when none of those opened. An adapter +/// without `request.required_features`, or whose device fails to open, adds a +/// [`Notice::DeviceFailed`] and the next one is tried. Native only, like [`list`]; [`open_async`] +/// works on both. +#[cfg(not(target_arch = "wasm32"))] +pub fn open(instance: &Instance, surface: Option<&Surface<'_>>, preference: &Preference, request: &Request<'_>) -> Result { + pollster::block_on(open_async(instance, surface, preference, request)) +} + +/// [`open`] as a future, for a `wasm32` web worker as well as native. On native it lists every +/// adapter, as `open` does. In a browser, WebGPU offers one adapter for a power preference, so +/// `open_async` asks for the adapter with [`Preference::power`]. A named adapter then gives the +/// automatic choice with [`Notice::AdapterMissing`]. wgpu 30 does not pass the fallback-adapter +/// option to the browser, so [`Preference::Software`] gives the browser's adapter with +/// [`Notice::NoSoftwareAdapter`] unless that adapter is itself a software one. +pub async fn open_async( + instance: &Instance, + surface: Option<&Surface<'_>>, + preference: &Preference, + request: &Request<'_>, +) -> Result { + let (adapters, candidates) = adapters_for(instance, surface, preference).await; + // Whether drawing is in software depends on the adapter that opens, which `finish` knows. + let mut notices: Vec = + select(&candidates, preference).map(|s| s.notices).unwrap_or_default().into_iter().filter(|n| *n != Notice::SoftwareOnly).collect(); + let order = ranked(&candidates, preference); + if let Some(first) = order.first() { + log_choice(&candidates, *first, preference.power()); + } + let mut tried: Vec<&Candidate> = Vec::new(); + for index in order { + let (Some(adapter), Some(candidate)) = (adapters.get(index), candidates.get(index)) else { + continue; + }; + tried.push(candidate); + match open_on(adapter, request).await { + Ok((device, queue)) => return Ok(finish(adapter.clone(), device, queue, candidate.clone(), preference, notices)), + Err(error) => { + log::warn!("graphics adapter {candidate} could not be opened: {error}"); + notices.push(Notice::DeviceFailed { adapter: candidate.name.clone(), error }); + } + } + } + // wgpu's fallback adapter, unless the loop above already tried it. In a browser the request + // below would ask for the same adapter again. + if cfg!(not(target_arch = "wasm32")) { + let options = wgpu::RequestAdapterOptions { force_fallback_adapter: true, compatible_surface: surface, ..Default::default() }; + let fallback = instance.request_adapter(&options).await.ok().map(|a| (Candidate::of(&a, surface), a)); + if let Some((candidate, adapter)) = fallback.filter(|(c, _)| !tried.contains(&c)) { + match open_on(&adapter, request).await { + Ok((device, queue)) => { + log::info!("graphics adapter chosen: {candidate}"); + return Ok(finish(adapter, device, queue, candidate, preference, notices)); + } + Err(error) => notices.push(Notice::DeviceFailed { adapter: candidate.name.clone(), error }), + } + } + } + if notices.iter().any(|n| matches!(n, Notice::DeviceFailed { .. })) { + return Err(OpenError::NoDevice(notices)); + } + let left_out = left_out(&candidates); + if left_out.is_empty() { Err(OpenError::NoAdapter) } else { Err(OpenError::UnsafeDriver(left_out)) } +} + +/// The names of the adapters that can draw but that [`choose`](crate::choose) never draws with. +fn left_out(candidates: &[Candidate]) -> Vec { + candidates.iter().enumerate().filter(|(i, c)| c.usable && avoided(candidates, *i)).map(|(_, c)| c.name.clone()).collect() +} + +/// The adapters `open_async` chooses among: every listed one on native, and in a browser the one +/// it offers for the preference's power. +async fn adapters_for(instance: &Instance, surface: Option<&Surface<'_>>, preference: &Preference) -> (Vec, Vec) { + #[cfg(not(target_arch = "wasm32"))] + { + let _ = preference; + list_async(instance, surface).await + } + #[cfg(target_arch = "wasm32")] + { + let adapters = browser_adapter(instance, surface, preference.power()).await; + let candidates = adapters.iter().map(|a| Candidate::of(a, surface)).collect(); + (adapters, candidates) + } +} + +fn finish( + adapter: Adapter, + device: wgpu::Device, + queue: wgpu::Queue, + candidate: Candidate, + preference: &Preference, + mut notices: Vec, +) -> Opened { + let caps = Capabilities::of_device(&device); + // wgpu's fallback adapter can be a software one that the listing did not show. + if candidate.is_software() { + notices.retain(|n| *n != Notice::NoSoftwareAdapter); + } + if candidate.is_software() && !asked_for(preference, &candidate) { + notices.push(Notice::SoftwareOnly); + } + for notice in ¬ices { + log::warn!("{notice}"); + } + log::info!("graphics device opened: {caps}"); + let health = DeviceHealth::watch(&device); + Opened { adapter, device, queue, candidate, caps, health, notices } +} + +/// Open a device on `adapter`, or say why it cannot be. +async fn open_on(adapter: &Adapter, request: &Request<'_>) -> Result<(wgpu::Device, wgpu::Queue), String> { + let has = adapter.features(); + if !has.contains(request.required_features) { + return Err(format!("it lacks the features {:?}", request.required_features - has)); + } + let required_limits = request.limits.clone().unwrap_or_else(|| adapter.limits()); + let desc = wgpu::DeviceDescriptor { + label: request.label, + required_features: request.required_features | (request.optional_features & has & !Features::all_experimental_mask()), + required_limits, + ..Default::default() + }; + adapter.request_device(&desc).await.map_err(|e| e.to_string()) +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + use crate::preference::AdapterKey; + + /// An instance whose only adapter is wgpu's noop one, which opens devices without a GPU. wgpu + /// 30 lists it as a software adapter whatever `NoopBackendOptions::device_type` says. + fn noop(features: Option) -> Instance { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + desc.backend_options.noop = wgpu::NoopBackendOptions { enable: true, features, ..Default::default() }; + Instance::new(desc) + } + + #[test] + fn a_device_opens_with_the_optional_features_the_adapter_has() { + let instance = noop(Some(Features::TEXTURE_FORMAT_NV12 | Features::TIMESTAMP_QUERY)); + let request = Request { optional_features: Features::TEXTURE_FORMAT_NV12 | Features::SHADER_F16, ..Default::default() }; + let opened = open(&instance, None, &Preference::Software, &request).unwrap(); + assert!(opened.caps.nv12(), "{}", opened.caps); + assert!(!opened.caps.shader_f16() && !opened.caps.timestamps(), "only the features asked for: {}", opened.caps); + assert!(opened.notices.is_empty(), "{:?}", opened.notices); + assert!(opened.health.is_ok()); + // the craft-gpu caps name only the features the device was opened with + let caps = opened.device_caps(); + assert_eq!(caps.features, ["TEXTURE_FORMAT_NV12"]); + assert_eq!(&caps, opened.caps.device_caps()); + assert_eq!(caps, crate::device_caps(&opened.device)); + assert_eq!(caps.max_texture_dimension_2d, opened.device.limits().max_texture_dimension_2d); + assert!(caps.software && caps.vendor_id == opened.candidate.vendor, "{caps:?}"); + assert_eq!(opened.health.device_status(), Ok(())); + } + + #[test] + fn open_async_opens_as_open_does() { + let instance = noop(Some(Features::TEXTURE_FORMAT_P010)); + let request = Request { optional_features: Features::TEXTURE_FORMAT_P010 | Features::SHADER_F16, ..Default::default() }; + let opened = pollster::block_on(open_async(&instance, None, &Preference::Auto, &request)).unwrap(); + let blocking = open(&instance, None, &Preference::Auto, &request).unwrap(); + assert!(opened.caps.p010() && !opened.caps.shader_f16(), "{}", opened.caps); + assert_eq!(opened.caps, blocking.caps); + assert_eq!(opened.notices, vec![Notice::SoftwareOnly]); + assert_eq!(opened.notices, blocking.notices); + let (adapters, candidates) = pollster::block_on(list_async(&instance, None)); + assert_eq!((adapters.len(), candidates), (1, list(&instance, None).1)); + // the same errors + let missing = Request { required_features: Features::SHADER_F16, ..Default::default() }; + let err = pollster::block_on(open_async(&instance, None, &Preference::Auto, &missing)).unwrap_err(); + assert!(matches!(&err, OpenError::NoDevice(n) if n.len() == 1), "{err}"); + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + let none = Instance::new(desc); + assert_eq!(pollster::block_on(open_async(&none, None, &Preference::Auto, &Request::default())).unwrap_err(), OpenError::NoAdapter); + } + + #[test] + fn a_software_device_drops_the_no_software_notice() { + let instance = noop(None); + let opened = open(&instance, None, &Preference::Software, &Request::default()).unwrap(); + assert!(opened.candidate.is_software()); + // as when the listing showed no software adapter and wgpu's fallback adapter opened + let notices = vec![Notice::NoSoftwareAdapter]; + let again = finish(opened.adapter, opened.device, opened.queue, opened.candidate, &Preference::Software, notices); + assert!(again.notices.is_empty(), "{:?}", again.notices); + } + + #[test] + fn an_optional_experimental_feature_does_not_stop_the_device_opening() { + let instance = noop(Some(Features::EXPERIMENTAL_RAY_QUERY | Features::TEXTURE_FORMAT_NV12)); + let request = Request { optional_features: Features::EXPERIMENTAL_RAY_QUERY | Features::TEXTURE_FORMAT_NV12, ..Default::default() }; + let opened = open(&instance, None, &Preference::Software, &request).unwrap(); + assert!(opened.caps.nv12(), "{}", opened.caps); + assert!(!opened.device.features().contains(Features::EXPERIMENTAL_RAY_QUERY)); + // a required one still fails as before + let required = Request { required_features: Features::EXPERIMENTAL_RAY_QUERY, ..Default::default() }; + assert!(matches!(open(&instance, None, &Preference::Software, &required), Err(OpenError::NoDevice(_)))); + } + + #[test] + fn an_adapter_without_a_required_feature_is_reported() { + let instance = noop(Some(Features::empty())); + let request = Request { required_features: Features::SHADER_F16, ..Default::default() }; + let err = open(&instance, None, &Preference::Auto, &request).unwrap_err(); + let OpenError::NoDevice(notices) = &err else { panic!("{err}") }; + assert!(notices.iter().any(|n| matches!(n, Notice::DeviceFailed { error, .. } if error.contains("SHADER_F16"))), "{notices:?}"); + assert!(err.to_string().starts_with("no graphics adapter could be opened"), "{err}"); + } + + #[test] + fn an_adapter_below_the_requested_limits_is_reported() { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + desc.backend_options.noop = wgpu::NoopBackendOptions { enable: true, limits: Some(Limits::default()), ..Default::default() }; + let instance = Instance::new(desc); + let over = Limits::default().max_texture_dimension_2d + 1; + let request = Request { limits: Some(Limits { max_texture_dimension_2d: over, ..Limits::default() }), ..Default::default() }; + let err = open(&instance, None, &Preference::Software, &request).unwrap_err(); + let OpenError::NoDevice(notices) = &err else { panic!("{err}") }; + assert!( + notices.iter().any(|n| matches!(n, Notice::DeviceFailed { error, .. } + if error.contains("max_texture_dimension_2d"))), + "{notices:?}" + ); + // limits within the adapter's still open + let within = Request { limits: Some(Limits::downlevel_defaults()), ..Default::default() }; + assert!(open(&instance, None, &Preference::Software, &within).is_ok()); + } + + #[test] + fn a_software_adapter_is_reported_unless_it_was_asked_for() { + let cpu = noop(None); + let opened = open(&cpu, None, &Preference::Auto, &Request::default()).unwrap(); + assert!(opened.caps.software()); + assert_eq!(opened.notices, vec![Notice::SoftwareOnly]); + let asked = open(&cpu, None, &Preference::Software, &Request::default()).unwrap(); + assert!(asked.notices.is_empty(), "{:?}", asked.notices); + // the software adapter picked by name is what was asked for + let named = open(&cpu, None, &Preference::Adapter(AdapterKey::of(&asked.candidate)), &Request::default()).unwrap(); + assert!(named.notices.is_empty(), "{:?}", named.notices); + // a named adapter that is gone: the automatic choice, with both notices + let gone = + AdapterKey { name: "gone".into(), backend: "vulkan".into(), vendor: 0x10de, device: 1, pci_bus_id: String::new(), driver: String::new() }; + let opened = open(&cpu, None, &Preference::Adapter(gone.clone()), &Request::default()).unwrap(); + assert_eq!(opened.notices, vec![Notice::AdapterMissing(gone), Notice::SoftwareOnly]); + } + + #[test] + fn no_adapter_is_an_error() { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + let instance = Instance::new(desc); + assert_eq!(open(&instance, None, &Preference::Auto, &Request::default()).unwrap_err(), OpenError::NoAdapter); + assert_eq!(OpenError::NoAdapter.to_string(), "no graphics adapter is available"); + assert_eq!( + OpenError::UnsafeDriver(vec!["Intel(R) UHD Graphics 630".into()]).to_string(), + "the only graphics adapters that can draw (\"Intel(R) UHD Graphics 630\") use a driver that can crash; update the graphics driver" + ); + assert_eq!(pick(&[], None, &Preference::Auto).unwrap_err(), OpenError::NoAdapter); + } + + #[test] + fn pick_says_when_only_a_driver_that_can_crash_can_draw() { + let vulkan_only: Vec = crate::adapter::tests::uhd_630().into_iter().take(1).collect(); + assert_eq!(select(&vulkan_only, &Preference::Auto), None); + assert_eq!(unselected(&vulkan_only), OpenError::UnsafeDriver(vec!["Intel(R) UHD Graphics 630".into()])); + assert_eq!(unselected(&[]), OpenError::NoAdapter); + } + + #[test] + fn a_zero_timeout_leaves_a_healthy_device_healthy() { + let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + let everything = opened.queue.submit([]); + assert!(!opened.health.wait_timeout(&opened.device, everything.clone(), std::time::Duration::ZERO)); + assert!(opened.health.is_ok(), "{:?}", opened.health.fault()); + assert!(opened.health.wait_timeout(&opened.device, everything, std::time::Duration::from_secs(5))); + // an index from another device's queue is one this device never issued + let other = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + other.queue.submit([]); + let index = other.queue.submit([]); + assert!(!opened.health.wait_timeout(&opened.device, index, std::time::Duration::from_secs(5))); + assert!(opened.health.is_ok(), "{:?}", opened.health.fault()); + } + + #[test] + fn waits_run_after_an_out_of_memory_error() { + use crate::health::{Fault, OUT_OF_MEMORY}; + let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + let health = opened.health.clone(); + health.mark(Fault::Error(OUT_OF_MEMORY.into())); + let index = opened.queue.submit([]); + assert!(health.wait(&opened.device, index.clone()), "{health:?}"); + assert!(health.wait_timeout(&opened.device, index.clone(), std::time::Duration::from_secs(5)), "{health:?}"); + health.clear_out_of_memory(health.out_of_memory_count()); + assert!(health.is_ok(), "{health:?}"); + // any other error still stops them + health.mark(Fault::Error("Validation Error".into())); + assert!(!health.wait(&opened.device, index)); + } + + #[test] + fn a_lost_device_is_seen_by_its_health() { + let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + let health = opened.health.clone(); + let index = opened.queue.submit([]); + opened.device.destroy(); + health.probe(&opened.device); + assert!(health.fault().is_some_and(|f| f.is_lost()), "{health:?}"); + assert!(!health.is_ok()); + assert!(matches!(health.device_status(), Err(craft_gpu::GpuFault::DeviceLost(_))), "{health:?}"); + // a later wait does not touch the lost device + assert!(!health.wait(&opened.device, index)); + } + + #[test] + fn pick_returns_the_selected_adapter() { + let instance = noop(None); + let (adapters, candidates) = list(&instance, None); + assert_eq!(candidates.len(), 1); + let (adapter, selection) = pick(&adapters, None, &Preference::Auto).unwrap(); + assert_eq!(selection.index, 0); + assert_eq!(Candidate::of(&adapter, None), candidates[0]); + } +} diff --git a/crates/gpu-device/src/preference.rs b/crates/gpu-device/src/preference.rs new file mode 100644 index 0000000000..542bf66305 --- /dev/null +++ b/crates/gpu-device/src/preference.rs @@ -0,0 +1,422 @@ +//! The adapter the user asked for, and what was drawn with instead when it is not there. + +use std::fmt; + +use wgpu::{Backend, PowerPreference}; + +use crate::adapter::{Candidate, avoided, choose, intel_vulkan_crashes, settled, type_order}; + +/// Which adapter to draw with. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(rename_all = "camelCase", tag = "kind"))] +pub enum Preference { + /// The fastest adapter: a discrete GPU before an integrated one, hardware before software. + #[default] + Auto, + /// An integrated GPU before a discrete one, for battery life. + LowPower, + /// One adapter the user picked from [`crate::list`]. + Adapter(AdapterKey), + /// A software adapter that draws on the CPU. + Software, +} + +impl Preference { + /// The power preference that orders the adapters for this preference: low power for + /// [`Preference::LowPower`], high performance otherwise. + pub fn power(&self) -> PowerPreference { + match self { + Preference::LowPower => PowerPreference::LowPower, + _ => PowerPreference::HighPerformance, + } + } +} + +/// What identifies an adapter across runs: the backend, the PCI ids and bus, the driver name, and +/// the name. The order in which the system lists adapters can change between runs, so an index +/// cannot be kept. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(rename_all = "camelCase", default))] +pub struct AdapterKey { + pub name: String, + /// wgpu's lowercase backend name (`vulkan`, `dx12`, `metal`, `gl`). + pub backend: String, + pub vendor: u32, + pub device: u32, + /// Empty when the driver reports none. + pub pci_bus_id: String, + /// The Vulkan driver's name, which tells apart two Vulkan drivers for one GPU (such as two on + /// Linux) and stays the same across versions of a driver. Empty on the other backends, and + /// when the driver reports none. + pub driver: String, +} + +impl AdapterKey { + pub fn of(candidate: &Candidate) -> Self { + AdapterKey { + name: candidate.name.clone(), + backend: backend_name(candidate.backend).to_string(), + vendor: candidate.vendor, + device: candidate.device, + pci_bus_id: candidate.pci_bus_id.clone(), + // DirectX 12 reports the driver's version here, which changes with every update. + driver: if candidate.backend == Backend::Vulkan { candidate.driver.clone() } else { String::new() }, + } + } + + /// Whether `candidate` is this adapter: the same backend and PCI ids, the same bus and the + /// same driver when both report one, and the same name when the backend reports no PCI ids. + pub fn matches(&self, candidate: &Candidate) -> bool { + let identified = self.vendor != 0 || self.device != 0; + let same = |a: &str, b: &str| a.is_empty() || b.is_empty() || a == b; + self.backend == backend_name(candidate.backend) + && self.vendor == candidate.vendor + && self.device == candidate.device + && same(&self.pci_bus_id, &candidate.pci_bus_id) + && same(&self.driver, &candidate.driver) + && (identified || self.name == candidate.name) + } +} + +impl fmt::Display for AdapterKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "\"{}\" ({})", self.name, self.backend) + } +} + +/// wgpu's lowercase name of `backend`. +pub fn backend_name(backend: Backend) -> &'static str { + backend.to_str() +} + +/// Something the app tells the user about the adapter it draws with. The [`fmt::Display`] text is +/// English, for the log; an app shows its own translated text for each variant. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Notice { + /// The adapter the user picked is not listed (unplugged, disabled, or its driver removed). + /// The automatic choice draws instead. + AdapterMissing(AdapterKey), + /// Software was asked for and no software adapter is listed. The automatic choice draws + /// instead. + NoSoftwareAdapter, + /// The only adapter that can draw is a software one: drawing is slower and uses the CPU. + SoftwareOnly, + /// An adapter could not open a device, and the next one was tried. + DeviceFailed { adapter: String, error: String }, + /// The device was lost this many times in a short time, so drawing moved to software. + SoftwareAfterLosses(u32), +} + +impl fmt::Display for Notice { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Notice::AdapterMissing(key) => write!(f, "the graphics adapter {key} is not available; using the automatic choice"), + Notice::NoSoftwareAdapter => f.write_str("no software graphics adapter is available; using the automatic choice"), + Notice::SoftwareOnly => f.write_str("no graphics hardware can be used; drawing in software, which is slower"), + Notice::DeviceFailed { adapter, error } => { + write!(f, "the graphics adapter \"{adapter}\" could not be opened ({error}); trying the next one") + } + Notice::SoftwareAfterLosses(n) => write!(f, "the graphics device stopped working {n} times; drawing in software"), + } + } +} + +/// The adapter chosen for a preference, and what the user should be told about it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Selection { + /// Index into the candidates. + pub index: usize, + pub notices: Vec, +} + +/// The adapter to draw with for `preference`, or `None` when no adapter is usable. +/// +/// - [`Preference::Auto`] and [`Preference::LowPower`] use [`choose`]. +/// - [`Preference::Adapter`] uses the usable entry that matches the key (the one exposing the most +/// features when a driver lists it twice), with [`choose`]'s corrections; without one, or when +/// it is an Intel Vulkan entry [`choose`] never draws with, the automatic choice and +/// [`Notice::AdapterMissing`]. +/// - [`Preference::Software`] uses the first usable software adapter, with [`choose`]'s +/// corrections; without one, the automatic choice and [`Notice::NoSoftwareAdapter`]. +/// +/// A software adapter that the automatic choice took adds [`Notice::SoftwareOnly`]. +pub fn select(candidates: &[Candidate], preference: &Preference) -> Option { + let mut notices = Vec::new(); + let wanted = match preference { + Preference::Auto | Preference::LowPower => None, + Preference::Adapter(key) => { + // An entry that reports no bus id matches any saved bus. When it is the same model on + // the same driver it cannot be told apart from an older version of that driver, and + // the correction draws with the entry exposing the most features. + let found = + candidates.iter().enumerate().filter(|(_, c)| c.usable && key.matches(c)).max_by_key(|(i, c)| (c.features, std::cmp::Reverse(*i))); + let found = found.and_then(|(index, _)| drawn_with(candidates, index)); + if found.is_none() { + notices.push(Notice::AdapterMissing(key.clone())); + } + found + } + Preference::Software => { + let found = candidates.iter().position(|c| c.usable && c.is_software()).and_then(|index| drawn_with(candidates, index)); + if found.is_none() { + notices.push(Notice::NoSoftwareAdapter); + } + found + } + }; + let index = match wanted { + Some(index) => index, + None => { + let index = choose(candidates, preference.power())?; + if candidates.get(index).is_some_and(Candidate::is_software) { + notices.push(Notice::SoftwareOnly); + } + index + } + }; + Some(Selection { index, notices }) +} + +/// The entry to draw with when the entry at `index` is asked for, with [`choose`]'s corrections: +/// the newest version of a driver that lists the GPU twice, or the DirectX 12 entry of an Intel +/// GPU whose Vulkan entry [`choose`] never draws with. `None` when that Intel Vulkan entry has no +/// usable DirectX 12 entry. +fn drawn_with(candidates: &[Candidate], index: usize) -> Option { + candidates.get(index)?; + let index = settled(candidates, index); + (!candidates.get(index).is_some_and(intel_vulkan_crashes)).then_some(index) +} + +/// Whether `preference` asked for `candidate` itself: software for a software adapter, or the key +/// of this adapter. +pub(crate) fn asked_for(preference: &Preference, candidate: &Candidate) -> bool { + match preference { + Preference::Software => candidate.is_software(), + Preference::Adapter(key) => key.matches(candidate), + Preference::Auto | Preference::LowPower => false, + } +} + +/// The order in which to try opening a device for `preference`: [`select`]'s choice first, then +/// every other usable adapter by device type for the preference's power (software after +/// hardware), leaving out the entries [`choose`] never draws with: an older version of a driver +/// listed twice, and the Vulkan entry of an Intel Gen 9 to Gen 11 GPU on Intel's Windows driver. +/// Empty when no adapter is usable. +pub fn ranked(candidates: &[Candidate], preference: &Preference) -> Vec { + let Some(first) = select(candidates, preference).map(|s| s.index) else { + return Vec::new(); + }; + let power = preference.power(); + let mut rest: Vec = + (0..candidates.len()).filter(|&i| i != first && candidates.get(i).is_some_and(|c| c.usable) && !avoided(candidates, i)).collect(); + rest.sort_by_key(|&i| (candidates.get(i).map_or(u8::MAX, |c| type_order(c.device_type, power)), i)); + let mut order = vec![first]; + order.extend(rest); + order +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::adapter::tests::{gpu, two_amd_drivers, uhd_630}; + use wgpu::Backend::{Dx12, Vulkan}; + use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu}; + + fn key_of(candidates: &[Candidate], index: usize) -> AdapterKey { + candidates.get(index).map(AdapterKey::of).unwrap_or_default() + } + + #[test] + fn auto_and_low_power_are_the_corrected_wgpu_choice() { + let adapters = two_amd_drivers(); + assert_eq!(select(&adapters, &Preference::Auto), Some(Selection { index: 1, notices: vec![] })); + assert_eq!(select(&adapters, &Preference::LowPower).map(|s| s.index), Some(2)); + assert_eq!(select(&[], &Preference::Auto), None); + assert_eq!(Preference::default(), Preference::Auto); + } + + #[test] + fn a_named_adapter_is_found_wherever_it_is_listed() { + let adapters = two_amd_drivers(); + // the integrated Radeon through DirectX 12, picked by the user + let key = key_of(&adapters, 4); + assert_eq!(select(&adapters, &Preference::Adapter(key.clone())).map(|s| s.index), Some(4)); + // listed in another order on the next run + let mut reordered = adapters.clone(); + reordered.reverse(); + assert_eq!(select(&reordered, &Preference::Adapter(key)).map(|s| s.index), Some(1)); + // the stale Vulkan entry of the RX 6800M stored as the choice: the newer version draws + let stale = key_of(&adapters, 0); + assert_eq!(select(&adapters, &Preference::Adapter(stale)).map(|s| s.index), Some(1)); + } + + #[test] + fn a_named_intel_gen9_vulkan_entry_draws_through_directx_12() { + let adapters = uhd_630(); + let vulkan = key_of(&adapters, 0); + assert_eq!(select(&adapters, &Preference::Adapter(vulkan.clone())).map(|s| s.index), Some(1)); + // without the DirectX 12 entry, the named Vulkan entry is not available + let mut dx12_unusable = adapters.clone(); + dx12_unusable[1].usable = false; + let s = select(&dx12_unusable, &Preference::Adapter(vulkan.clone())); + assert_eq!(s.map(|s| (s.index, s.notices)), Some((2, vec![Notice::AdapterMissing(vulkan), Notice::SoftwareOnly]))); + } + + #[test] + fn a_missing_named_adapter_falls_back_to_auto_with_a_notice() { + let adapters = two_amd_drivers(); + let gone = AdapterKey { + name: "NVIDIA GeForce RTX 4090".into(), + backend: "vulkan".into(), + vendor: 0x10de, + device: 0x2684, + pci_bus_id: String::new(), + driver: "NVIDIA".into(), + }; + let s = select(&adapters, &Preference::Adapter(gone.clone())); + assert_eq!(s, Some(Selection { index: 1, notices: vec![Notice::AdapterMissing(gone.clone())] })); + // listed but unable to draw to the window counts as missing + let mut unusable = adapters.clone(); + for c in &mut unusable { + c.usable = c.backend != Vulkan; + } + let vulkan_key = key_of(&adapters, 1); + let s = select(&unusable, &Preference::Adapter(vulkan_key.clone())); + assert_eq!(s.map(|s| (s.index, s.notices)), Some((3, vec![Notice::AdapterMissing(vulkan_key)]))); + // nothing usable at all + assert_eq!(select(&[], &Preference::Adapter(gone)), None); + } + + #[test] + fn keys_tell_apart_backends_buses_and_unidentified_names() { + let adapters = two_amd_drivers(); + let dx12 = key_of(&adapters, 3); + assert!(dx12.matches(&adapters[3])); + assert!(!dx12.matches(&adapters[1]), "same GPU, other backend"); + let other_bus = Candidate { pci_bus_id: "0000:04:00.0".into(), ..adapters[3].clone() }; + assert!(!dx12.matches(&other_bus)); + // a key stored without a bus id still matches an entry that reports one + let no_bus = AdapterKey { pci_bus_id: String::new(), ..dx12.clone() }; + assert!(no_bus.matches(&adapters[3])); + // two Vulkan drivers for one GPU are told apart by the driver name; a key saved without + // one matches either + let radv = gpu("AMD Radeon RX 6800M (RADV NAVI22)", Vulkan, DiscreteGpu, 0x1002, 0x73df, "0000:03:00.0", "radv", "Mesa 25.2.4", 70); + let amdvlk = gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, 0x1002, 0x73df, "0000:03:00.0", "AMD open-source driver", "2025.Q2.1", 72); + let two = vec![radv.clone(), amdvlk.clone()]; + assert_eq!(select(&two, &Preference::Adapter(AdapterKey::of(&radv))).map(|s| s.index), Some(0)); + assert_eq!(select(&two, &Preference::Adapter(AdapterKey::of(&amdvlk))).map(|s| s.index), Some(1)); + let old = AdapterKey { driver: String::new(), ..AdapterKey::of(&radv) }; + assert!(old.matches(&radv) && old.matches(&amdvlk)); + // a DirectX 12 key keeps matching after a driver update changes the reported version + assert!(dx12.driver.is_empty()); + let updated = Candidate { driver: "32.0.21045.12000".into(), ..adapters[3].clone() }; + assert!(dx12.matches(&updated)); + // OpenGL reports no ids: the name decides + let angle = gpu("ANGLE (D3D11)", wgpu::Backend::Gl, wgpu::DeviceType::Other, 0, 0, "", "", "", 20); + let swiftshader = gpu("SwiftShader", wgpu::Backend::Gl, wgpu::DeviceType::Other, 0, 0, "", "", "", 20); + let key = AdapterKey::of(&angle); + assert!(key.matches(&angle) && !key.matches(&swiftshader)); + assert_eq!(dx12.to_string(), "\"AMD Radeon RX 6800M\" (dx12)"); + } + + #[test] + fn software_is_used_when_asked_and_reported_when_it_is_all_there_is() { + let adapters = two_amd_drivers(); + assert_eq!(select(&adapters, &Preference::Software), Some(Selection { index: 5, notices: vec![] })); + let hardware_only: Vec = adapters.iter().filter(|c| !c.is_software()).cloned().collect(); + assert_eq!(select(&hardware_only, &Preference::Software), Some(Selection { index: 1, notices: vec![Notice::NoSoftwareAdapter] })); + let llvmpipe = vec![gpu("llvmpipe (LLVM 19.1.0, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "", 50)]; + assert_eq!(select(&llvmpipe, &Preference::Auto), Some(Selection { index: 0, notices: vec![Notice::SoftwareOnly] })); + assert_eq!(select(&llvmpipe, &Preference::Software), Some(Selection { index: 0, notices: vec![] })); + // picked by name, it is what was asked for + let named = Preference::Adapter(AdapterKey::of(&llvmpipe[0])); + assert_eq!(select(&llvmpipe, &named), Some(Selection { index: 0, notices: vec![] })); + #[cfg(not(target_arch = "wasm32"))] + { + assert!(asked_for(&named, &llvmpipe[0]) && asked_for(&Preference::Software, &llvmpipe[0])); + assert!(!asked_for(&Preference::Auto, &llvmpipe[0]) && !asked_for(&Preference::Software, &adapters[1])); + } + } + + #[test] + fn software_draws_with_the_newer_version_of_a_driver_listed_twice() { + let stale = gpu("llvmpipe (LLVM 15.0.7, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "Mesa 23.0.4", 40); + let newer = gpu("llvmpipe (LLVM 19.1.0, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "Mesa 25.2.4", 50); + let hardware = gpu("AMD Radeon RX 6800M", Dx12, DiscreteGpu, 0x1002, 0x73df, "0000:03:00.0", "32.0.21045.11001", "", 36); + let adapters = vec![stale, newer, hardware]; + assert_eq!(select(&adapters, &Preference::Software), Some(Selection { index: 1, notices: vec![] })); + // the stale entry is never tried, and the newer one is not left out + assert_eq!(ranked(&adapters, &Preference::Software), vec![1, 2]); + } + + #[test] + fn the_fallback_order_never_tries_entries_that_can_crash() { + let adapters = two_amd_drivers(); + // the newer RX 6800M, then the other hardware by type for high performance, then software; + // the stale RX 6800M entry is never tried + assert_eq!(ranked(&adapters, &Preference::Auto), vec![1, 3, 2, 4, 5]); + assert_eq!(ranked(&adapters, &Preference::LowPower), vec![2, 4, 1, 3, 5]); + assert_eq!(ranked(&adapters, &Preference::Software), vec![5, 1, 3, 2, 4]); + // two cards of one model on one driver, one without a Vulkan bus id: the second card's + // Vulkan entry looks like an older version, and the card is tried through DirectX 12 + let card = |bus: &str| gpu("AMD Radeon RX 7900 XT", Vulkan, DiscreteGpu, 0x1002, 0x744c, bus, "AMD proprietary driver", "", 68); + let dx12 = |bus: &str| gpu("AMD Radeon RX 7900 XT", Dx12, DiscreteGpu, 0x1002, 0x744c, bus, "32.0.21045.11001", "", 36); + let twins = vec![card("0000:03:00.0"), card(""), dx12("0000:03:00.0"), dx12("0000:04:00.0")]; + assert_eq!(ranked(&twins, &Preference::Auto), vec![0, 2, 3]); + // the same bus id on both entries: one GPU, and the older version is never tried + let mut versions = vec![card("0000:03:00.0"), card("0000:03:00.0")]; + versions[1].features = 70; + assert_eq!(ranked(&versions, &Preference::Auto), vec![1]); + // a third entry without a bus id and with more features: both older entries are left out + versions.push(card("")); + versions[2].features = 80; + assert_eq!(ranked(&versions, &Preference::Auto), vec![2]); + // two GPUs on different buses are both tried + let cards = vec![card("0000:03:00.0"), card("0000:04:00.0")]; + assert_eq!(ranked(&cards, &Preference::Auto), vec![0, 1]); + // the Intel Gen 9 Vulkan entry is never tried, with or without a usable DirectX 12 entry + assert_eq!(ranked(&uhd_630(), &Preference::Auto), vec![1, 2]); + let mut dx12_unusable = uhd_630(); + dx12_unusable[1].usable = false; + assert_eq!(ranked(&dx12_unusable, &Preference::Auto), vec![2]); + assert!(ranked(&uhd_630()[..1], &Preference::Auto).is_empty()); + assert!(ranked(&[], &Preference::Auto).is_empty()); + let unusable: Vec = adapters.iter().map(|c| Candidate { usable: false, ..c.clone() }).collect(); + assert!(ranked(&unusable, &Preference::Auto).is_empty()); + } + + #[test] + fn a_laptop_with_two_vendors_keeps_the_named_gpu_across_reorders() { + let intel = gpu("Intel(R) UHD Graphics 770", Dx12, IntegratedGpu, 0x8086, 0x4680, "0000:00:02.0", "31.0.101.5186", "", 36); + let nvidia = gpu("NVIDIA GeForce RTX 4070 Laptop GPU", Dx12, DiscreteGpu, 0x10de, 0x2820, "0000:01:00.0", "32.0.15.6094", "", 36); + let a = vec![intel.clone(), nvidia.clone()]; + let b = vec![nvidia, intel]; + let picked = Preference::Adapter(key_of(&a, 0)); + assert_eq!(select(&a, &picked).map(|s| s.index), Some(0)); + assert_eq!(select(&b, &picked).map(|s| s.index), Some(1)); + assert_eq!(ranked(&b, &picked), vec![1, 0]); + } + + #[cfg(feature = "serde")] + #[test] + fn preferences_read_back_what_they_write() { + let key = AdapterKey { + name: "AMD Radeon RX 6800M".into(), + backend: "dx12".into(), + vendor: 0x1002, + device: 0x73df, + pci_bus_id: "0000:03:00.0".into(), + driver: String::new(), + }; + for p in [Preference::Auto, Preference::LowPower, Preference::Software, Preference::Adapter(key)] { + let text = serde_json::to_string(&p).unwrap(); + assert_eq!(serde_json::from_str::(&text).unwrap(), p, "{text}"); + } + assert_eq!(serde_json::to_string(&Preference::Auto).unwrap(), r#"{"kind":"auto"}"#); + // a key written by an older version without some fields + let p: Preference = serde_json::from_str(r#"{"kind":"adapter","name":"x","backend":"vulkan"}"#).unwrap(); + assert_eq!(p, Preference::Adapter(AdapterKey { name: "x".into(), backend: "vulkan".into(), ..Default::default() })); + assert!(serde_json::from_str::(r#"{"kind":"fastest"}"#).is_err()); + } +} diff --git a/crates/gpu-device/src/recovery.rs b/crates/gpu-device/src/recovery.rs new file mode 100644 index 0000000000..2732d8c986 --- /dev/null +++ b/crates/gpu-device/src/recovery.rs @@ -0,0 +1,153 @@ +//! What to open after a device loss. +//! +//! A device is lost when the driver resets the GPU, the OS ends a long submission, the PC sleeps, +//! or the GPU is unplugged. The app drops everything it made with the device and opens a new one. +//! [`Recovery`] decides with what preference: the user's own, until the device has been lost +//! [`RecoveryPolicy::max_losses`] times within [`RecoveryPolicy::window`], and software after that, +//! so a GPU that keeps failing does not stop the app from drawing. + +use std::collections::VecDeque; +use std::time::Duration; + +use crate::preference::{Notice, Preference}; + +/// When repeated losses move drawing to software. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RecoveryPolicy { + /// Losses within [`window`](Self::window) after which the next device is a software one. + /// 0 never moves to software. + pub max_losses: u32, + pub window: Duration, +} + +impl Default for RecoveryPolicy { + fn default() -> Self { + RecoveryPolicy { max_losses: 3, window: Duration::from_secs(600) } + } +} + +/// The preference to open the next device with. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RecoveryStep { + pub preference: Preference, + /// [`Notice::SoftwareAfterLosses`] when this step moved drawing to software. + pub notice: Option, +} + +/// Device losses seen so far, against the user's preference. +#[derive(Clone, Debug)] +pub struct Recovery { + preference: Preference, + policy: RecoveryPolicy, + /// When each loss inside the window happened, oldest first. + losses: VecDeque, + software: bool, +} + +impl Recovery { + pub fn new(preference: Preference, policy: RecoveryPolicy) -> Self { + Recovery { preference, policy, losses: VecDeque::new(), software: false } + } + + /// The preference to open a device with now. + pub fn preference(&self) -> &Preference { + if self.software { &Preference::Software } else { &self.preference } + } + + /// The user changed the preference: losses counted so far no longer apply. + pub fn set_preference(&mut self, preference: Preference) { + self.preference = preference; + self.losses.clear(); + self.software = false; + } + + /// Record a loss at `at`, a monotonic time the caller keeps (since the app started), and + /// return what to open next. A time earlier than the last loss counts as the same time. + pub fn lost(&mut self, at: Duration) -> RecoveryStep { + let at = self.losses.back().map_or(at, |last| at.max(*last)); + self.losses.push_back(at); + // Only the last `max_losses` losses decide anything, so no more are kept. + let keep = usize::try_from(self.policy.max_losses.max(1)).unwrap_or(usize::MAX); + while self.losses.len() > keep || self.losses.front().is_some_and(|first| at.saturating_sub(*first) > self.policy.window) { + self.losses.pop_front(); + } + let count = u32::try_from(self.losses.len()).unwrap_or(u32::MAX); + let mut notice = None; + if !self.software && self.policy.max_losses > 0 && count >= self.policy.max_losses && self.preference != Preference::Software { + self.software = true; + notice = Some(Notice::SoftwareAfterLosses(count)); + } + RecoveryStep { preference: self.preference().clone(), notice } + } + + /// Losses inside the window, as of the last one, counting at most + /// [`RecoveryPolicy::max_losses`] (at least 1). + pub fn recent_losses(&self) -> usize { + self.losses.len() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn s(secs: u64) -> Duration { + Duration::from_secs(secs) + } + + #[test] + fn the_third_loss_in_ten_minutes_moves_to_software() { + let mut r = Recovery::new(Preference::Auto, RecoveryPolicy::default()); + assert_eq!(r.lost(s(10)), RecoveryStep { preference: Preference::Auto, notice: None }); + assert_eq!(r.lost(s(100)), RecoveryStep { preference: Preference::Auto, notice: None }); + assert_eq!(r.lost(s(300)), RecoveryStep { preference: Preference::Software, notice: Some(Notice::SoftwareAfterLosses(3)) }); + // it stays on software, and says so once + assert_eq!(r.lost(s(400)), RecoveryStep { preference: Preference::Software, notice: None }); + assert_eq!(r.preference(), &Preference::Software); + } + + #[test] + fn losses_outside_the_window_are_forgotten() { + let mut r = Recovery::new(Preference::LowPower, RecoveryPolicy::default()); + r.lost(s(0)); + r.lost(s(500)); + // the first loss is more than 600 s before this one + assert_eq!(r.lost(s(601)).preference, Preference::LowPower); + assert_eq!(r.recent_losses(), 2); + // a clock that goes back counts as the last loss's time + assert_eq!(r.lost(s(1)).preference, Preference::Software); + } + + #[test] + fn changing_the_preference_starts_over() { + let mut r = Recovery::new(Preference::Auto, RecoveryPolicy { max_losses: 2, window: s(60) }); + r.lost(s(1)); + assert_eq!(r.lost(s(2)).preference, Preference::Software); + r.set_preference(Preference::LowPower); + assert_eq!(r.preference(), &Preference::LowPower); + assert_eq!(r.recent_losses(), 0); + assert_eq!(r.lost(s(3)).preference, Preference::LowPower); + } + + #[test] + fn software_and_a_zero_limit_never_add_a_notice() { + let mut r = Recovery::new(Preference::Software, RecoveryPolicy::default()); + for t in 0..5 { + assert_eq!(r.lost(s(t)), RecoveryStep { preference: Preference::Software, notice: None }); + } + let mut never = Recovery::new(Preference::Auto, RecoveryPolicy { max_losses: 0, window: s(60) }); + for t in 0..10 { + assert_eq!(never.lost(s(t)).preference, Preference::Auto); + } + assert_eq!(never.recent_losses(), 1); + } + + #[test] + fn the_loss_history_stays_bounded() { + let mut r = Recovery::new(Preference::Software, RecoveryPolicy { max_losses: 3, window: Duration::MAX }); + for _ in 0..10_000 { + r.lost(s(5)); + } + assert_eq!(r.recent_losses(), 3); + } +} diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index 60742bea84..3871c44891 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -46,6 +46,8 @@ fn probe_caps_native() -> DeviceCaps { max_buffer_size: limits.max_buffer_size, max_texture_dimension_2d: limits.max_texture_dimension_2d, features: Vec::new(), + vendor_id: info.vendor, + software: info.device_type == wgpu::DeviceType::Cpu, } } @@ -144,6 +146,8 @@ mod native { max_buffer_size: device_limits.max_buffer_size, max_texture_dimension_2d: device_limits.max_texture_dimension_2d, features: device.features().iter_names().map(|(name, _)| name.to_string()).collect(), + vendor_id: info.vendor, + software: info.device_type == wgpu::DeviceType::Cpu, }; let backing = Backing::Device(DeviceBacking { device, queue, buffers: Vec::new(), lost, pending: Vec::new() }); Some((caps, backing)) diff --git a/crates/gpu-yuv/Cargo.toml b/crates/gpu-yuv/Cargo.toml new file mode 100644 index 0000000000..28053d83b1 --- /dev/null +++ b/crates/gpu-yuv/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "craft-gpu-yuv" +description = "RGBA to NV12, P010 and I420 on the GPU with scaling, in BT.601, BT.709 and BT.2020 at limited or full range, as a craft-gpu provider, with a CPU reference of the same conversion" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-gpu = { workspace = true } +wgpu = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +pollster = { workspace = true } + +# The device tests (src/tests.rs) open a native adapter. The backends are on for this crate's own +# tests only; crates that depend on craft-gpu-yuv get the workspace wgpu with `std` and `wgsl`. +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +wgpu = { workspace = true, features = ["dx12", "metal", "vulkan", "gles"] } + +[dev-dependencies] +craft-gpu-null = { workspace = true } +pollster = { workspace = true } +# The independent reference the oracle tests compare with (BSD-3-Clause OR Apache-2.0). +yuv = { version = "0.8.20", default-features = false, features = ["professional_mode"] } diff --git a/crates/gpu-yuv/README.md b/crates/gpu-yuv/README.md new file mode 100644 index 0000000000..9a39ce0ff3 --- /dev/null +++ b/crates/gpu-yuv/README.md @@ -0,0 +1,148 @@ +# craft-gpu-yuv + +RGBA to 4:2:0 Y'CbCr for the Craft apps' encoders and scopes: NV12, P010 and I420, scaled to the +output size, in the BT.601, BT.709 and BT.2020 matrices at limited or full range. `YuvProvider` is +the `craft.yuv` provider of the `craft-gpu` job layer. `Converter` records the same conversion as +render passes into a caller's own encoder, and `cpu::convert` is the same conversion on the CPU. + +Licensed under MIT OR Apache-2.0. + +## Contents + +| Item | What | +|---|---| +| `YuvProvider` | the `craft.yuv` `GpuProvider`; `new()` converts on the CPU on any `GpuContext`, `with_device(device, queue)` converts with the render passes on that device (not on `wasm32`) | +| `YuvJob` | one job's conversion, source size and output size; `params()` writes them, `parse` reads them, `job(input)` makes the `GpuJob` | +| `PROVIDER_ID` | `"craft.yuv"` | +| `Format` | `Nv12` (8-bit luma, then interleaved Cb and Cr), `P010` (10-bit values in the high bits of little-endian 16-bit words, same planes as NV12) and `I420` (8-bit luma, Cb, then Cr) | +| `Matrix`, `Range` | BT.601, BT.709 and BT.2020 non-constant luminance; limited range (luma 16 to 235, chroma 16 to 240, times 4 at 10 bits) or full range (every code, chroma centered on 128 or 512) | +| `Conversion` | one format, matrix and range | +| `Converter::new(device, conversion)` | the two render pipelines of one conversion; no per-frame state | +| `Converter::bind(device, view)` | a source texture view bound once, as a `Source` | +| `Converter::planes(device, width, height)` | the plane textures of one output size, as `Planes` | +| `Converter::draw(encoder, source, planes)` | records a luma pass and a chroma pass | +| `Planes::copy_to_buffer(encoder, buffer, offset)` | records the copies of every plane into a read-back buffer | +| `FrameLayout` | each plane's size, its offset and row pitch in a read-back buffer (`buffer_size`), and the size of a packed frame (`frame_bytes`); `unpack` copies a mapped buffer into a packed frame | +| `cpu::convert(rgba, src_width, src_height, conversion, width, height)` | the conversion of an RGBA8 picture on the CPU, as one packed frame | + +## Jobs + +A host registers `YuvProvider` in a `ProviderRegistry` and dispatches jobs made by `YuvJob::job`: + +```rust +let mut registry = craft_gpu::ProviderRegistry::new(); +registry.register(Box::new(craft_gpu_yuv::YuvProvider::new())); +let input = ctx.upload_buffer("rgba", &rgba)?; +let job = craft_gpu_yuv::YuvJob::new(conversion, 1920, 1080, 1280, 720).job(input); +let outcome = registry.dispatch(&mut ctx, &job)?; +let frame = ctx.read_buffer(outcome.outputs[0])?; +``` + +A job has one input, an RGBA8 buffer of exactly `src_width × src_height × 4` bytes, and no +outputs; its outcome has one output, a new buffer that holds the packed frame. The parameters are +ASCII `key:value` fields separated by `;`: +`fmt:nv12;matrix:bt709;range:limited;sw:1920;sh:1080;w:1280;h:720`. `fmt` is `nv12`, `p010` or +`i420`, `matrix` is `bt601`, `bt709` or `bt2020`, `range` is `limited` or `full`, and the four sides +are decimal digits. + +The provider checks the job against the context's `DeviceCaps` on every context, the null one +included: each source and output side must be at most `max_texture_dimension_2d`, and the +read-back layout with its padded rows (`FrameLayout::buffer_size`) and the RGBA8 input at most +`max_buffer_size` bytes. Each output side must also be at most `cpu::MAX_SIDE` (16384), with or +without a device. It checks the input's length before reading it. A +malformed, missing, repeated or unknown parameter, a wrong input count or length, and a size the +caps or the conversion do not allow are `GpuFault::InvalidJob`. With a device, the provider also +checks the device's own limits, and an error the device reports during the job is +`GpuFault::Operation`. Each conversion's pipelines are made once per provider. + +`YuvProvider::new()` runs `cpu::convert`, so a consumer's tests and CI run on `craft-gpu-null` +without a graphics adapter. `YuvProvider::with_device` runs the render passes on the given device +and waits for each job to finish; the input and the output still move through the context's +buffers. + +## Plane layout + +A packed frame of `w × h` (both even) holds its planes one after another, each row without +padding: + +| Format | Plane | Offset | Row bytes | Rows | +|---|---|---|---|---| +| NV12 | Y' | 0 | `w` | `h` | +| NV12 | Cb, Cr interleaved | `w·h` | `w` | `h/2` | +| P010 | Y' | 0 | `2w` | `h` | +| P010 | Cb, Cr interleaved | `2w·h` | `2w` | `h/2` | +| I420 | Y' | 0 | `w` | `h` | +| I420 | Cb | `w·h` | `w/2` | `h/2` | +| I420 | Cr | `w·h + w·h/4` | `w/2` | `h/2` | + +A frame is `1.5·w·h` bytes in NV12 and I420 and `3·w·h` bytes in P010. Each P010 word holds the +10-bit value in its high bits, with the 6 low bits zero. NV12 and I420 follow the W3C WebCodecs +definitions (), and NV12 and P010 follow +the Linux media API's sample images +(). + +In a read-back buffer, `FrameLayout` pads each row to a multiple of +`wgpu::COPY_BYTES_PER_ROW_ALIGNMENT` (256) bytes, as a texture-to-buffer copy needs, and puts each +plane right after the previous plane's padded rows. `FrameLayout::unpack` removes the padding. + +## Code values + +Luma and chroma follow BT.601-7 section 2.5, BT.709-6 items 3.2 to 3.5 and BT.2020-2 tables 4 and +5 at limited range, and BT.2100-3 table 9 at full range. A half rounds away from zero, as `INT` in +BT.709 and BT.2020 and `Round` in BT.2100 do, so a full-range Cb or Cr that computes to 0.5 is +code 1. + +## Sampling + +The source is scaled to the output size; the caller keeps the aspect ratio. Each output texel +(luma at the output size, chroma at half the output size in both directions) takes the average +of up to 4 × 4 bilinear taps spread over the part of the source it covers: 1 tap per axis while +the source is at most twice the plane's size, and one more for each further 2:1 of reduction. +At the same size, each chroma sample is the average of the 2 × 2 pixels it covers, and its +position is the center of those pixels. A reduction of more than 8:1 along an axis skips part of +the source between taps. + +`cpu::convert` scales with these same taps rather than with a resampling crate such as +`fast_image_resize`, because it is the reference the shader is tested against, and a different +kernel would differ from the shader at every edge. A caller that wants another filter on the CPU +can resize first with such a crate and convert at the same size. + +The passes write unsigned-integer textures (`R8Uint`, `Rg8Uint`, `R16Uint`, `Rg16Uint`), so P010 +does not need wgpu's 16-bit norm feature. + +## Limits + +- The matrix applies to the stored values: the source must already be in the output's primaries + and transfer function. An sRGB view of the source gives linear values, which the matrix does + not expect; bind a non-sRGB view. Alpha is ignored, so premultiplied pixels convert as if they + were over black. +- Output sides must be even and not zero (`Error::OutputSize`), and no larger than the device's + largest 2D texture (`Error::TooLarge`). A layout whose byte sizes do not fit in `u32` rows, `u64` + offsets or a `usize` frame is `Error::Overflow`. `Converter::planes` refuses a read-back layout + larger than the device's largest buffer (`Error::BufferLimit`), and `cpu::convert` refuses an + output side over `cpu::MAX_SIDE` (16384). +- The source view must be a 2D view of a filterable float format, such as `Rgba8Unorm`, + `Bgra8Unorm` or `Rgba16Float`. +- `copy_to_buffer` needs an offset that is a multiple of `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT` + (`Error::Offset`) and a buffer of at least `buffer_size` bytes from it (`Error::BufferSize`). + `draw` refuses planes made for another format (`Error::Mismatch`). + +## Tests + +- `oracle_tests.rs` checks the conversion against sources outside the crate. It computes the + code values of 729 colors in `f64` from each recommendation's Kr, Kb and quantization, and + checks the nominal levels the recommendations state (white, black, neutral chroma and the + chroma extremes). It compares every format, matrix and range with the `yuv` crate's conversion + of the same pictures (`yuv` 0.8, a dev-dependency), within 1 code value at 8 bits and 2 at + 10 bits. It checks the packed plane sizes against the planes `yuv` allocates, and a 4 × 4 frame + against the byte offsets of the public format definitions. The GPU passes are checked against + the same equations, within 1 code value. +- `job_tests.rs` runs `craft.yuv` through a `ProviderRegistry` on `craft-gpu-null`, and with a + device. It checks the parameters, the inputs and outputs, the caps limits, and a device whose + limits are smaller than the context's. +- `tests.rs` checks standard code values, each format's plane order, the area average of a + reduction and the read-back layout. It also compares the GPU passes with `cpu::convert` on + pictures with hard edges at the same size and on smooth pictures at five scales, within 2 code + values at 8 bits and 6 at 10 bits. + +A machine without a graphics adapter skips the GPU tests and prints that it did so. diff --git a/crates/gpu-yuv/src/cpu.rs b/crates/gpu-yuv/src/cpu.rs new file mode 100644 index 0000000000..b96bc90ed3 --- /dev/null +++ b/crates/gpu-yuv/src/cpu.rs @@ -0,0 +1,142 @@ +//! The conversion on the CPU, sample for sample the rule the GPU passes follow. Tests compare the +//! two, and a caller without a GPU can use it directly. +//! +//! Each output texel (luma at the output size, chroma at half of it) takes the area of the source +//! under it: up to 4 × 4 bilinear taps spread over the texel's footprint, 1 per axis while the +//! source is at most twice the plane's size, one more for each further 2:1 of reduction. The +//! average of the taps goes through the matrix. At the same size the chroma tap lands between +//! four source pixels, so each chroma sample is the average of the 2 × 2 pixels it covers. +//! +//! The scaler here takes the shader's taps at the shader's positions instead of using a +//! resampling crate such as `fast_image_resize`: this function is the reference the shader is +//! tested against, and another kernel would differ from the shader at every edge. For another +//! filter, resize with such a crate first and convert at the same size. + +use crate::layout::FrameLayout; +use crate::spec::{Coefficients, Conversion, Error}; + +/// The largest output side [`convert`] takes. +pub const MAX_SIDE: u32 = 16384; + +/// The taps along one axis for a reduction of `r` (source size over plane size). +pub(crate) fn taps(r: f32) -> u32 { + ((r * 0.5 - 0.001).ceil() as i32).clamp(1, 4) as u32 +} + +struct Image<'a> { + rgba: &'a [u8], + width: usize, + height: usize, +} + +impl Image<'_> { + fn pixel(&self, x: i64, y: i64) -> [f32; 3] { + let x = x.clamp(0, self.width as i64 - 1) as usize; + let y = y.clamp(0, self.height as i64 - 1) as usize; + let i = (y * self.width + x) * 4; + match self.rgba.get(i..i + 3) { + Some(p) => [f32::from(p[0]) / 255.0, f32::from(p[1]) / 255.0, f32::from(p[2]) / 255.0], + None => [0.0; 3], + } + } + + /// The linear filter at `(x, y)` in pixels (pixel centers at .5), clamped to the edges. + fn bilinear(&self, x: f32, y: f32) -> [f32; 3] { + let (x, y) = (x - 0.5, y - 0.5); + let (x0, y0) = (x.floor(), y.floor()); + let (fx, fy) = (x - x0, y - y0); + let (xi, yi) = (x0 as i64, y0 as i64); + let [a, b, c, d] = [self.pixel(xi, yi), self.pixel(xi + 1, yi), self.pixel(xi, yi + 1), self.pixel(xi + 1, yi + 1)]; + let mut out = [0.0; 3]; + for k in 0..3 { + let top = a[k] + (b[k] - a[k]) * fx; + let bottom = c[k] + (d[k] - c[k]) * fx; + out[k] = top + (bottom - top) * fy; + } + out + } + + /// The average color under the texel centered at `pos` of a plane of `size` texels. + fn area(&self, pos: [f32; 2], size: [f32; 2]) -> [f32; 3] { + let s = [self.width as f32, self.height as f32]; + let r = [s[0] / size[0], s[1] / size[1]]; + let n = [taps(r[0]), taps(r[1])]; + let nf = [n[0] as f32, n[1] as f32]; + let step = [r[0] / nf[0], r[1] / nf[1]]; + let center = [pos[0] / size[0] * s[0], pos[1] / size[1] * s[1]]; + let mut sum = [0.0f32; 3]; + for j in 0..n[1] { + for i in 0..n[0] { + let px = center[0] + (i as f32 + 0.5 - nf[0] * 0.5) * step[0]; + let py = center[1] + (j as f32 + 0.5 - nf[1] * 0.5) * step[1]; + let c = self.bilinear(px, py); + for k in 0..3 { + sum[k] += c[k]; + } + } + } + let count = nf[0] * nf[1]; + [sum[0] / count, sum[1] / count, sum[2] / count] + } +} + +/// An empty vector with room for `len` values, or [`Error::Memory`] when the room cannot be +/// allocated. +pub(crate) fn reserve(len: usize) -> Result, Error> { + let mut v = Vec::new(); + v.try_reserve_exact(len).map_err(|_| Error::Memory { bytes: len.saturating_mul(size_of::()) })?; + Ok(v) +} + +/// `rgba` (`src_width × src_height`, 4 bytes per pixel; alpha is ignored, so premultiplied +/// pixels convert as if over black) scaled to `width × height` and converted, as one tightly +/// packed frame in [`FrameLayout`] order. +pub fn convert(rgba: &[u8], src_width: u32, src_height: u32, conversion: Conversion, width: u32, height: u32) -> Result, Error> { + let bytes = (src_width as usize).checked_mul(src_height as usize).and_then(|n| n.checked_mul(4)); + if src_width == 0 || src_height == 0 || bytes != Some(rgba.len()) { + return Err(Error::Source { width: src_width, height: src_height, bytes: rgba.len() }); + } + if width > MAX_SIDE || height > MAX_SIDE { + return Err(Error::TooLarge { width, height, limit: MAX_SIDE }); + } + let layout = FrameLayout::new(conversion.format, width, height)?; + let image = Image { rgba, width: src_width as usize, height: src_height as usize }; + let c = Coefficients::of(conversion); + let (shift, wide) = (conversion.format.shift(), conversion.format.sample_bytes() == 2); + let (cw, ch) = (width / 2, height / 2); + let mut out = reserve(layout.frame_bytes())?; + let mut cr: Vec = if conversion.format == crate::Format::I420 { reserve(cw as usize * ch as usize)? } else { Vec::new() }; + let mut put = |v: u16| { + let v = v << shift; + if wide { + out.extend_from_slice(&v.to_le_bytes()); + } else { + out.push(v as u8); + } + }; + let plane = |pw: u32, ph: u32, pick: &mut dyn FnMut([u16; 3])| { + let size = [pw as f32, ph as f32]; + for j in 0..ph { + for i in 0..pw { + pick(c.codes(image.area([i as f32 + 0.5, j as f32 + 0.5], size))); + } + } + }; + plane(width, height, &mut |v| put(v[0])); + match conversion.format { + crate::Format::Nv12 | crate::Format::P010 => plane(cw, ch, &mut |v| { + put(v[1]); + put(v[2]); + }), + crate::Format::I420 => { + plane(cw, ch, &mut |v| { + put(v[1]); + cr.push(v[2]); + }); + for v in cr { + put(v); + } + } + } + Ok(out) +} diff --git a/crates/gpu-yuv/src/gpu.rs b/crates/gpu-yuv/src/gpu.rs new file mode 100644 index 0000000000..a77e3316c5 --- /dev/null +++ b/crates/gpu-yuv/src/gpu.rs @@ -0,0 +1,360 @@ +//! The conversion as render passes: one pass draws the luma plane, one draws the chroma plane or +//! planes, each into unsigned-integer textures that hold the exact stored words. + +use wgpu::util::DeviceExt; + +use crate::layout::FrameLayout; +use crate::spec::{Coefficients, Conversion, Error, Format}; + +/// The render pipelines of one [`Conversion`]. Make it once per device and conversion; it holds +/// no per-frame state. +pub struct Converter { + conversion: Conversion, + plane_layout: wgpu::BindGroupLayout, + source_layout: wgpu::BindGroupLayout, + luma: wgpu::RenderPipeline, + chroma: wgpu::RenderPipeline, + sampler: wgpu::Sampler, +} + +/// A source texture view bound for a [`Converter`]. Keep one per texture that is converted more +/// than once. +pub struct Source { + bind: wgpu::BindGroup, +} + +/// The plane textures of one output size, and their read-back layout. +pub struct Planes { + layout: FrameLayout, + textures: Vec, + views: Vec, + luma_bind: wgpu::BindGroup, + chroma_bind: wgpu::BindGroup, +} + +fn plane_formats(format: Format) -> &'static [wgpu::TextureFormat] { + use wgpu::TextureFormat as T; + match format { + Format::Nv12 => &[T::R8Uint, T::Rg8Uint], + Format::P010 => &[T::R16Uint, T::Rg16Uint], + Format::I420 => &[T::R8Uint, T::R8Uint, T::R8Uint], + } +} + +fn attachment(view: &wgpu::TextureView) -> Option> { + Some(wgpu::RenderPassColorAttachment { + view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store }, + }) +} + +fn vec3(w: [f32; 3]) -> String { + format!("vec3({:?}, {:?}, {:?})", w[0], w[1], w[2]) +} + +/// The WGSL of `conversion`, with its weights and scale written in as constants. +pub(crate) fn shader(conversion: Conversion) -> String { + let k = Coefficients::of(conversion); + let chroma = match conversion.format { + Format::Nv12 | Format::P010 => { + "@fragment fn fs_chroma(@builtin(position) pos: vec4) -> @location(0) vec4 { + let c = area(pos.xy); + return vec4(code(dot(c, CB) * CS + CO), code(dot(c, CR) * CS + CO), 0u, 0u); +}" + } + Format::I420 => { + "struct Chroma { @location(0) cb: vec4, @location(1) cr: vec4 } +@fragment fn fs_chroma(@builtin(position) pos: vec4) -> Chroma { + let c = area(pos.xy); + var o: Chroma; + o.cb = vec4(code(dot(c, CB) * CS + CO), 0u, 0u, 0u); + o.cr = vec4(code(dot(c, CR) * CS + CO), 0u, 0u, 0u); + return o; +}" + } + }; + format!( + "const KY = {ky}; +const CB = {cb}; +const CR = {cr}; +const YS = {ys:?}; +const YO = {yo:?}; +const CS = {cs:?}; +const CO = {co:?}; +const MAX = {max:?}; +const SHIFT = {shift}u; + +struct Plane {{ size: vec2, pad: vec2 }} +@group(0) @binding(0) var plane: Plane; +@group(1) @binding(0) var tex: texture_2d; +@group(1) @binding(1) var samp: sampler; + +@vertex fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 {{ + let x = f32((vi << 1u) & 2u); + let y = f32(vi & 2u); + return vec4(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0); +}} + +fn taps(r: f32) -> i32 {{ + return clamp(i32(ceil(r * 0.5 - 0.001)), 1, 4); +}} + +// The average color under the texel centered at `pos`: up to 4 x 4 bilinear taps over its +// footprint in the source. +fn area(pos: vec2) -> vec3 {{ + let src = vec2(textureDimensions(tex)); + let r = src / plane.size; + let n = vec2(taps(r.x), taps(r.y)); + let nf = vec2(n); + let step = r / nf; + let center = pos / plane.size * src; + var sum = vec3(0.0); + for (var j = 0; j < n.y; j++) {{ + for (var i = 0; i < n.x; i++) {{ + let p = center + (vec2(f32(i), f32(j)) + 0.5 - nf * 0.5) * step; + sum += textureSampleLevel(tex, samp, p / src, 0.0).rgb; + }} + }} + return sum / (nf.x * nf.y); +}} + +// A half rounds up, as INT and Round do in the recommendations; WGSL's round() takes it to the +// even neighbor. The fraction v - floor(v) is exact in f32, while floor(v + 0.5) takes a value +// just below a half up, because v + 0.5 rounds to the next integer. Values below 0 clamp to 0. +fn code(v: f32) -> u32 {{ + let f = floor(v); + return u32(clamp(select(f, f + 1.0, v - f >= 0.5), 0.0, MAX)) << SHIFT; +}} + +@fragment fn fs_luma(@builtin(position) pos: vec4) -> @location(0) vec4 {{ + return vec4(code(dot(area(pos.xy), KY) * YS + YO), 0u, 0u, 0u); +}} + +{chroma} +", + ky = vec3(k.y), + cb = vec3(k.cb), + cr = vec3(k.cr), + ys = k.y_scale, + yo = k.y_offset, + cs = k.c_scale, + co = k.c_offset, + max = k.max, + shift = conversion.format.shift(), + ) +} + +impl Converter { + /// The pipelines of `conversion` on `device`. + pub fn new(device: &wgpu::Device, conversion: Conversion) -> Converter { + let plane_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("yuv plane"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: wgpu::BufferSize::new(16), + }, + count: None, + }], + }); + let source_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("yuv source"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + multisampled: false, + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("yuv"), + bind_group_layouts: &[Some(&plane_layout), Some(&source_layout)], + immediate_size: 0, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some(conversion.format.name()), + source: wgpu::ShaderSource::Wgsl(shader(conversion).into()), + }); + let target = |format| Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL }); + let formats = plane_formats(conversion.format); + let pipeline = |label: &str, fs: &str, targets: &[Option]| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(&layout), + vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { module: &module, entry_point: Some(fs), targets, compilation_options: Default::default() }), + multiview_mask: None, + cache: None, + }) + }; + let luma = pipeline("yuv luma", "fs_luma", &[target(formats[0])]); + let chroma_targets: Vec<_> = formats[1..].iter().map(|f| target(*f)).collect(); + let chroma = pipeline("yuv chroma", "fs_chroma", &chroma_targets); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("yuv linear"), + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + Converter { conversion, plane_layout, source_layout, luma, chroma, sampler } + } + + pub fn conversion(&self) -> Conversion { + self.conversion + } + + /// Bind `view` as a source. The view must be a 2D view of a filterable float format, such as + /// `Rgba8Unorm` or `Bgra8Unorm`; an sRGB view gives linear values, which the matrix does not + /// expect. + pub fn bind(&self, device: &wgpu::Device, view: &wgpu::TextureView) -> Source { + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("yuv source"), + layout: &self.source_layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(view) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.sampler) }, + ], + }); + Source { bind } + } + + /// Plane textures for frames of `width × height`. Both sides must be even, not zero, and no + /// larger than the device's largest 2D texture. + pub fn planes(&self, device: &wgpu::Device, width: u32, height: u32) -> Result { + let limit = device.limits().max_texture_dimension_2d; + if width > limit || height > limit { + return Err(Error::TooLarge { width, height, limit }); + } + let layout = FrameLayout::new(self.conversion.format, width, height)?; + let max = device.limits().max_buffer_size; + if layout.buffer_size > max { + return Err(Error::BufferLimit { needed: layout.buffer_size, limit: max }); + } + let formats = plane_formats(self.conversion.format); + let textures: Vec = layout + .planes + .iter() + .zip(formats) + .map(|(p, format)| { + device.create_texture(&wgpu::TextureDescriptor { + label: Some("yuv plane"), + size: wgpu::Extent3d { width: p.width, height: p.height, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: *format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }) + }) + .collect(); + let views = textures.iter().map(|t| t.create_view(&wgpu::TextureViewDescriptor::default())).collect(); + let uniform = |w: u32, h: u32| { + let mut bytes = [0u8; 16]; + bytes[..4].copy_from_slice(&(w as f32).to_le_bytes()); + bytes[4..8].copy_from_slice(&(h as f32).to_le_bytes()); + let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("yuv plane size"), + contents: &bytes, + usage: wgpu::BufferUsages::UNIFORM, + }); + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("yuv plane"), + layout: &self.plane_layout, + entries: &[wgpu::BindGroupEntry { binding: 0, resource: buffer.as_entire_binding() }], + }) + }; + let luma_bind = uniform(width, height); + let chroma_bind = uniform(width / 2, height / 2); + Ok(Planes { layout, textures, views, luma_bind, chroma_bind }) + } + + /// Record the passes that convert `source` into `planes`. + pub fn draw(&self, encoder: &mut wgpu::CommandEncoder, source: &Source, planes: &Planes) -> Result<(), Error> { + if planes.layout.format != self.conversion.format { + return Err(Error::Mismatch { converter: self.conversion.format, planes: planes.layout.format }); + } + // No allocation per frame: one luma view, then one or two chroma views. + let chroma_count = planes.views.len().saturating_sub(1).min(2); + let luma = [planes.views.first().and_then(attachment)]; + let chroma = [planes.views.get(1).and_then(attachment), planes.views.get(2).and_then(attachment)]; + let passes: [(&wgpu::RenderPipeline, &wgpu::BindGroup, &[Option>]); 2] = + [(&self.luma, &planes.luma_bind, &luma), (&self.chroma, &planes.chroma_bind, &chroma[..chroma_count])]; + for (pipeline, plane, attachments) in passes { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("yuv"), + color_attachments: attachments, + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, plane, &[]); + pass.set_bind_group(1, &source.bind, &[]); + pass.draw(0..3, 0..1); + } + Ok(()) + } +} + +impl Planes { + pub fn layout(&self) -> &FrameLayout { + &self.layout + } + + /// The plane textures, luma first. + pub fn textures(&self) -> &[wgpu::Texture] { + &self.textures + } + + /// Record copies of every plane into `buffer` from `offset`, in the [`FrameLayout`]'s + /// places. `offset` must be a multiple of `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`, and the + /// buffer must hold `layout().buffer_size` bytes from it. + pub fn copy_to_buffer(&self, encoder: &mut wgpu::CommandEncoder, buffer: &wgpu::Buffer, offset: u64) -> Result<(), Error> { + if !offset.is_multiple_of(u64::from(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)) { + return Err(Error::Offset(offset)); + } + let needed = offset.saturating_add(self.layout.buffer_size); + if buffer.size() < needed { + return Err(Error::BufferSize { needed, actual: buffer.size() }); + } + for (texture, p) in self.textures.iter().zip(&self.layout.planes) { + encoder.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyBufferInfo { + buffer, + layout: wgpu::TexelCopyBufferLayout { + offset: offset + p.offset, + bytes_per_row: Some(p.bytes_per_row), + rows_per_image: Some(p.height), + }, + }, + wgpu::Extent3d { width: p.width, height: p.height, depth_or_array_layers: 1 }, + ); + } + Ok(()) + } +} diff --git a/crates/gpu-yuv/src/job.rs b/crates/gpu-yuv/src/job.rs new file mode 100644 index 0000000000..4f98dccca8 --- /dev/null +++ b/crates/gpu-yuv/src/job.rs @@ -0,0 +1,365 @@ +//! The conversion as a `craft-gpu` job: [`YuvProvider`] answers [`GpuJob`]s whose provider id is +//! [`PROVIDER_ID`], dispatched through a [`craft_gpu::ProviderRegistry`]. +//! +//! A job has one input, an RGBA8 buffer of `src_width × src_height × 4` bytes in the context, and +//! [`YuvJob::params`] as its parameters. Its outcome has one output: a new buffer that holds the +//! packed frame in [`FrameLayout`] order. Every side must be no larger than the context's +//! [`DeviceCaps::max_texture_dimension_2d`](craft_gpu::DeviceCaps), and the input and the frame no +//! larger than its `max_buffer_size`, on every context, so that a job that runs on the null context +//! also runs on a device with the same caps. + +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuJobParams, GpuProvider, HandleId}; + +use crate::cpu; +use crate::layout::FrameLayout; +use crate::spec::{Conversion, Error, Format, Matrix, Range}; + +/// The provider id of [`YuvProvider`]. +pub const PROVIDER_ID: &str = "craft.yuv"; + +/// The parameter keys, in the order [`YuvJob::params`] writes them. +const KEYS: [&str; 7] = ["fmt", "matrix", "range", "sw", "sh", "w", "h"]; + +/// The parameters of one `craft.yuv` job: the conversion, the source size and the output size. +/// +/// They are written as ASCII `key:value` fields separated by `;`, for example +/// `fmt:nv12;matrix:bt709;range:limited;sw:1920;sh:1080;w:1280;h:720`. `fmt` is `nv12`, `p010` or +/// `i420`; `matrix` is `bt601`, `bt709` or `bt2020`; `range` is `limited` or `full`; the sides are +/// decimal digits. A missing, repeated or unknown key, or a value outside these, is +/// [`GpuFault::InvalidJob`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct YuvJob { + pub conversion: Conversion, + pub src_width: u32, + pub src_height: u32, + pub width: u32, + pub height: u32, +} + +fn invalid(message: impl std::fmt::Display) -> GpuFault { + GpuFault::InvalidJob(format!("{PROVIDER_ID}: {message}")) +} + +/// A conversion error as a fault: device errors and allocation failures are +/// [`GpuFault::Operation`], the rest describe a job that cannot run and are +/// [`GpuFault::InvalidJob`]. +fn fault(e: Error) -> GpuFault { + match e { + Error::Device(_) | Error::Memory { .. } => GpuFault::Operation(format!("{PROVIDER_ID}: {e}")), + _ => invalid(e), + } +} + +fn format_token(f: Format) -> &'static str { + match f { + Format::Nv12 => "nv12", + Format::P010 => "p010", + Format::I420 => "i420", + } +} + +fn matrix_token(m: Matrix) -> &'static str { + match m { + Matrix::Bt601 => "bt601", + Matrix::Bt709 => "bt709", + Matrix::Bt2020 => "bt2020", + } +} + +fn range_token(r: Range) -> &'static str { + match r { + Range::Limited => "limited", + Range::Full => "full", + } +} + +impl YuvJob { + pub fn new(conversion: Conversion, src_width: u32, src_height: u32, width: u32, height: u32) -> YuvJob { + YuvJob { conversion, src_width, src_height, width, height } + } + + /// The job's parameters. + pub fn params(&self) -> GpuJobParams { + let c = self.conversion; + let text = format!( + "fmt:{};matrix:{};range:{};sw:{};sh:{};w:{};h:{}", + format_token(c.format), + matrix_token(c.matrix), + range_token(c.range), + self.src_width, + self.src_height, + self.width, + self.height + ); + GpuJobParams(text.into_bytes()) + } + + /// A `craft.yuv` job that converts the RGBA8 buffer `input`. + pub fn job(&self, input: HandleId) -> GpuJob { + GpuJob { provider_id: PROVIDER_ID.into(), params: self.params(), inputs: vec![input], outputs: Vec::new() } + } + + /// Read parameters written by [`YuvJob::params`]. + pub fn parse(params: &GpuJobParams) -> Result { + let text = std::str::from_utf8(¶ms.0).map_err(|_| invalid("the parameters are not UTF-8"))?; + let mut values: [Option<&str>; KEYS.len()] = [None; KEYS.len()]; + for field in text.split(';') { + let (key, value) = field.split_once(':').ok_or_else(|| invalid(format!("`{field}` is not a key:value field")))?; + let i = KEYS.iter().position(|k| *k == key).ok_or_else(|| invalid(format!("unknown key `{key}`")))?; + if values[i].replace(value).is_some() { + return Err(invalid(format!("`{key}` is given twice"))); + } + } + let get = |i: usize| values[i].ok_or_else(|| invalid(format!("`{}` is missing", KEYS[i]))); + let token = |i: usize, value: &str| invalid(format!("`{value}` is not a value of `{}`", KEYS[i])); + let format = match get(0)? { + "nv12" => Format::Nv12, + "p010" => Format::P010, + "i420" => Format::I420, + v => return Err(token(0, v)), + }; + let matrix = match get(1)? { + "bt601" => Matrix::Bt601, + "bt709" => Matrix::Bt709, + "bt2020" => Matrix::Bt2020, + v => return Err(token(1, v)), + }; + let range = match get(2)? { + "limited" => Range::Limited, + "full" => Range::Full, + v => return Err(token(2, v)), + }; + let side = |i: usize| -> Result { + let v = get(i)?; + if v.is_empty() || !v.bytes().all(|b| b.is_ascii_digit()) { + return Err(token(i, v)); + } + v.parse().map_err(|_| token(i, v)) + }; + Ok(YuvJob { + conversion: Conversion::new(format, matrix, range), + src_width: side(3)?, + src_height: side(4)?, + width: side(5)?, + height: side(6)?, + }) + } +} + +/// The `craft.yuv` provider. +/// +/// [`YuvProvider::new`] converts with [`cpu::convert`], on any context: the null context in tests +/// and CI, or a context whose device a provider cannot reach. [`YuvProvider::with_device`] +/// converts with the render passes on a device the caller holds, such as the one it already draws +/// with; the RGBA8 input and the output frame still move through the context's buffers. Both give +/// the same frame within the tolerance the crate's tests state. +pub struct YuvProvider { + device: Option, +} + +impl Default for YuvProvider { + fn default() -> Self { + Self::new() + } +} + +impl YuvProvider { + /// A provider that converts on the CPU. + pub fn new() -> YuvProvider { + YuvProvider { device: None } + } + + /// A provider that converts with the render passes on `device`. Each job waits for the device + /// to finish, so this is not available on `wasm32`, where a buffer map completes only from the + /// browser's event loop. + #[cfg(not(target_arch = "wasm32"))] + pub fn with_device(device: wgpu::Device, queue: wgpu::Queue) -> YuvProvider { + YuvProvider { device: Some(device::DeviceRunner::new(device, queue)) } + } + + /// Whether jobs run on a device. + pub fn has_device(&self) -> bool { + self.device.is_some() + } + + fn convert(&self, rgba: &[u8], job: &YuvJob) -> Result, Error> { + match &self.device { + Some(d) => d.convert(rgba, job), + None => cpu::convert(rgba, job.src_width, job.src_height, job.conversion, job.width, job.height), + } + } +} + +impl GpuProvider for YuvProvider { + fn id(&self) -> &'static str { + PROVIDER_ID + } + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + let spec = YuvJob::parse(&job.params)?; + let [input] = job.inputs.as_slice() else { + return Err(invalid(format!("expects one RGBA8 input, not {}", job.inputs.len()))); + }; + if !job.outputs.is_empty() { + return Err(invalid("makes its own output buffer, so the job names no outputs")); + } + let YuvJob { conversion, src_width, src_height, width, height } = spec; + let layout = FrameLayout::new(conversion.format, width, height).map_err(fault)?; + let caps = ctx.caps(); + // An output side is also held to `cpu::MAX_SIDE`, so that both provider modes take the + // same jobs. + let limit = caps.max_texture_dimension_2d; + for (w, h, limit) in [(src_width, src_height, limit), (width, height, limit.min(cpu::MAX_SIDE))] { + if w > limit || h > limit { + return Err(fault(Error::TooLarge { width: w, height: h, limit })); + } + } + // The read-back buffer with its padded rows is the largest buffer a device run makes, so + // the null context refuses the same jobs a device with these caps does. + let needed = layout.buffer_size.max(layout.frame_bytes() as u64); + if needed > caps.max_buffer_size { + return Err(fault(Error::BufferLimit { needed, limit: caps.max_buffer_size })); + } + // The input's size is checked before its bytes are read. + let bytes = ctx.buffer_len(*input)?; + let expected = (src_width as usize).checked_mul(src_height as usize).and_then(|n| n.checked_mul(4)); + if src_width == 0 || src_height == 0 || expected != Some(bytes) { + return Err(fault(Error::Source { width: src_width, height: src_height, bytes })); + } + let input_bytes = bytes as u64; + if input_bytes > caps.max_buffer_size { + return Err(fault(Error::BufferLimit { needed: input_bytes, limit: caps.max_buffer_size })); + } + let rgba = ctx.read_buffer(*input)?; + let frame = self.convert(&rgba, &spec).map_err(fault)?; + let output = ctx.upload_buffer("craft.yuv.frame", &frame)?; + Ok(GpuJobOutcome { outputs: vec![output], data: None }) + } +} + +#[cfg(not(target_arch = "wasm32"))] +mod device { + use std::sync::Mutex; + + use crate::gpu::{Converter, Planes}; + use crate::spec::{Conversion, Error}; + + use super::YuvJob; + + /// A device, its queue, and the converters made on it so far, one per conversion. + pub(super) struct DeviceRunner { + device: wgpu::Device, + queue: wgpu::Queue, + converters: Mutex>, + } + + fn device_error(e: impl std::fmt::Display) -> Error { + Error::Device(e.to_string()) + } + + impl DeviceRunner { + pub(super) fn new(device: wgpu::Device, queue: wgpu::Queue) -> DeviceRunner { + DeviceRunner { device, queue, converters: Mutex::new(Vec::new()) } + } + + /// `rgba` converted on the device, as one packed frame. Errors the device reports go to + /// error scopes and come back as [`Error::Device`]; a frame that cannot be allocated is + /// [`Error::Memory`]. + pub(super) fn convert(&self, rgba: &[u8], job: &YuvJob) -> Result, Error> { + let (sw, sh) = (job.src_width, job.src_height); + let limit = self.device.limits().max_texture_dimension_2d; + if sw > limit || sh > limit { + return Err(Error::TooLarge { width: sw, height: sh, limit }); + } + // A converter leaves the cache while a job uses it, and goes back only when the device + // reported no error, so a converter whose pipelines failed is not used again. + let mut converters = self.converters.lock().map_err(|_| device_error("the converter cache lock is poisoned"))?; + let cached = take(&mut converters, job.conversion); + drop(converters); + let oom = self.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let validation = self.device.push_error_scope(wgpu::ErrorFilter::Validation); + let internal = self.device.push_error_scope(wgpu::ErrorFilter::Internal); + let converter = cached.unwrap_or_else(|| Converter::new(&self.device, job.conversion)); + let recorded = self.record(&converter, rgba, job); + // The scopes are popped on every path, in the reverse of the order they were pushed, + // so that none stays open on the device. + let errors = [pollster::block_on(internal.pop()), pollster::block_on(validation.pop()), pollster::block_on(oom.pop())]; + if let Some(e) = errors.into_iter().flatten().next() { + return Err(device_error(e)); + } + if let Ok(mut converters) = self.converters.lock() { + converters.push(converter); + } + let (planes, buffer) = recorded?; + let (tx, rx) = std::sync::mpsc::channel(); + buffer.map_async(wgpu::MapMode::Read, .., move |result| { + let _ = tx.send(result); + }); + self.device.poll(wgpu::PollType::wait_indefinitely()).map_err(device_error)?; + rx.try_recv().map_err(|_| device_error("the read-back map did not complete"))?.map_err(device_error)?; + let mapped = buffer.get_mapped_range(..).map_err(device_error)?; + let bytes = planes.layout().frame_bytes(); + let mut frame = crate::cpu::reserve(bytes)?; + frame.resize(bytes, 0u8); + let unpacked = planes.layout().unpack(&mapped, &mut frame); + drop(mapped); + buffer.unmap(); + unpacked.map(|()| frame) + } + + /// Upload `rgba` and record and submit the passes and the copy into a read-back buffer. + fn record(&self, converter: &Converter, rgba: &[u8], job: &YuvJob) -> Result<(Planes, wgpu::Buffer), Error> { + // The output size is checked against the device before the source is uploaded, so a + // rejected job queues no upload. + let planes = converter.planes(&self.device, job.width, job.height)?; + let (sw, sh) = (job.src_width, job.src_height); + let size = wgpu::Extent3d { width: sw, height: sh, depth_or_array_layers: 1 }; + let texture = self.device.create_texture(&wgpu::TextureDescriptor { + label: Some("craft.yuv source"), + size, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let layout = wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(sw * 4), rows_per_image: Some(sh) }; + self.queue.write_texture(texture.as_image_copy(), rgba, layout, size); + let source = converter.bind(&self.device, &texture.create_view(&wgpu::TextureViewDescriptor::default())); + let buffer = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("craft.yuv read-back"), + size: planes.layout().buffer_size, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("craft.yuv") }); + converter.draw(&mut encoder, &source, &planes)?; + planes.copy_to_buffer(&mut encoder, &buffer, 0)?; + self.queue.submit([encoder.finish()]); + Ok((planes, buffer)) + } + } + + /// Remove and return the converter of `conversion` from `converters`, if there is one. + fn take(converters: &mut Vec, conversion: Conversion) -> Option { + let i = converters.iter().position(|c| c.conversion() == conversion)?; + Some(converters.swap_remove(i)) + } +} + +#[cfg(target_arch = "wasm32")] +mod device { + use crate::spec::Error; + + use super::YuvJob; + + /// No device runs jobs on `wasm32`: [`super::YuvProvider::with_device`] is native only. + pub(super) enum DeviceRunner {} + + impl DeviceRunner { + pub(super) fn convert(&self, _rgba: &[u8], _job: &YuvJob) -> Result, Error> { + match *self {} + } + } +} diff --git a/crates/gpu-yuv/src/job_tests.rs b/crates/gpu-yuv/src/job_tests.rs new file mode 100644 index 0000000000..c1a723da4b --- /dev/null +++ b/crates/gpu-yuv/src/job_tests.rs @@ -0,0 +1,261 @@ +//! `craft.yuv` through the job contract: on `craft-gpu-null`, which needs no hardware, and with a +//! device when the machine has a graphics adapter. + +use craft_gpu::{DeviceCaps, GpuContext, GpuFault, GpuJob, GpuJobParams, HandleId, ProviderRegistry, ReadOutcome, ReadRequest, WorkerKind}; +use craft_gpu_null::NullContext; + +use super::*; + +const ALL: [Format; 3] = [Format::Nv12, Format::P010, Format::I420]; +const MATRICES: [Matrix; 3] = [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020]; +const RANGES: [Range; 2] = [Range::Limited, Range::Full]; + +/// A null context with caps of the test's choosing, which counts the buffers read. +struct Capped { + inner: NullContext, + caps: DeviceCaps, + reads: usize, +} + +impl Capped { + fn new(caps: DeviceCaps) -> Capped { + Capped { inner: NullContext::new(WorkerKind::Main), caps, reads: 0 } + } +} + +impl GpuContext for Capped { + fn caps(&self) -> DeviceCaps { + self.caps.clone() + } + fn worker_kind(&self) -> WorkerKind { + self.inner.worker_kind() + } + fn upload_buffer(&mut self, label: &str, bytes: &[u8]) -> Result { + self.inner.upload_buffer(label, bytes) + } + fn buffer_len(&self, handle: HandleId) -> Result { + self.inner.buffer_len(handle) + } + fn request_read(&mut self, handle: HandleId) -> Result { + self.reads += 1; + self.inner.request_read(handle) + } + fn poll_reads(&mut self) -> Vec { + self.inner.poll_reads() + } + fn free_buffer(&mut self, handle: HandleId) { + self.inner.free_buffer(handle); + } + fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { + self.reads += 1; + self.inner.read_buffer(handle) + } +} + +fn registry(provider: YuvProvider) -> ProviderRegistry { + let mut r = ProviderRegistry::new(); + r.register(Box::new(provider)); + r +} + +/// Run `job` on `ctx` and read its one output back. +fn dispatch(r: &ProviderRegistry, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result, GpuFault> { + let outcome = r.dispatch(ctx, job)?; + assert_eq!(outcome.outputs.len(), 1); + assert_eq!(outcome.data, None); + ctx.read_buffer(outcome.outputs[0]) +} + +fn invalid(result: Result) -> String { + match result { + Err(GpuFault::InvalidJob(message)) => message, + other => panic!("expected an invalid job, got {other:?}"), + } +} + +#[test] +fn the_registry_runs_craft_yuv_on_the_null_context() { + let r = registry(YuvProvider::new()); + let mut ctx = NullContext::new(WorkerKind::Main); + let px = tests::noise(64, 36); + let input = ctx.upload_buffer("rgba", &px).unwrap(); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + for (w, h) in [(64, 36), (32, 18), (100, 50)] { + let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 36, w, h).job(input)).unwrap(); + assert_eq!(frame, cpu::convert(&px, 64, 36, c, w, h).unwrap(), "{c:?} {w}×{h}"); + assert_eq!(frame.len(), FrameLayout::new(format, w, h).unwrap().frame_bytes()); + } + } + } + } +} + +#[test] +fn parameters_read_back_as_written() { + let job = YuvJob::new(Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited), 1920, 1080, 1280, 720); + assert_eq!(job.params().0, b"fmt:nv12;matrix:bt709;range:limited;sw:1920;sh:1080;w:1280;h:720"); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let job = YuvJob::new(Conversion::new(format, matrix, range), 7, u32::MAX, 0, 4); + assert_eq!(YuvJob::parse(&job.params()), Ok(job)); + } + } + } + let job = YuvJob::new(Conversion::new(Format::P010, Matrix::Bt2020, Range::Full), 3, 5, 8, 6).job(HandleId(9)); + assert_eq!((job.provider_id.as_str(), job.inputs.as_slice(), job.outputs.len()), (PROVIDER_ID, [HandleId(9)].as_slice(), 0)); +} + +#[test] +fn bad_parameters_are_invalid_jobs() { + let good = "fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4"; + let cases: [(&[u8], &str); 14] = [ + (b"", "is not a key:value field"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4", "`h` is missing"), + (b"fmt:nv12;fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4", "`fmt` is given twice"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4;alpha:1", "unknown key `alpha`"), + (b"fmt:NV12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4", "`NV12` is not a value of `fmt`"), + (b"fmt:nv12;matrix:bt2100;range:limited;sw:4;sh:4;w:4;h:4", "`bt2100` is not a value of `matrix`"), + (b"fmt:nv12;matrix:bt709;range:studio;sw:4;sh:4;w:4;h:4", "`studio` is not a value of `range`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:+4;sh:4;w:4;h:4", "`+4` is not a value of `sw`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:-4;w:4;h:4", "`-4` is not a value of `sh`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:;h:4", "`` is not a value of `w`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4294967296", "`4294967296` is not a value of `h`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4;", "`` is not a key:value field"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4.0", "`4.0` is not a value of `h`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:\xff", "not UTF-8"), + ]; + assert!(YuvJob::parse(&GpuJobParams(good.as_bytes().to_vec())).is_ok()); + for (params, want) in cases { + let message = invalid(YuvJob::parse(&GpuJobParams(params.to_vec()))); + assert!(message.starts_with("craft.yuv: ") && message.contains(want), "{message:?} for {:?}", String::from_utf8_lossy(params)); + } +} + +#[test] +fn inputs_outputs_and_sizes_are_checked_before_any_read() { + let r = registry(YuvProvider::new()); + let mut ctx = Capped::new(DeviceCaps::default()); + let c = Conversion::new(Format::I420, Matrix::Bt601, Range::Limited); + let input = ctx.upload_buffer("rgba", &tests::noise(8, 4)).unwrap(); + let mut job = YuvJob::new(c, 8, 4, 8, 4).job(input); + job.inputs.clear(); + assert!(invalid(r.dispatch(&mut ctx, &job)).contains("expects one RGBA8 input, not 0")); + job.inputs = vec![input, input]; + assert!(invalid(r.dispatch(&mut ctx, &job)).contains("not 2")); + job.inputs = vec![input]; + job.outputs = vec![input]; + assert!(invalid(r.dispatch(&mut ctx, &job)).contains("names no outputs")); + // A buffer whose size is not the source's, an odd or zero side, and a missing buffer. + let wrong = [ + YuvJob::new(c, 8, 8, 8, 4).job(input), + YuvJob::new(c, 0, 4, 8, 4).job(input), + YuvJob::new(c, 8, 4, 7, 4).job(input), + YuvJob::new(c, 8, 4, 8, 0).job(input), + YuvJob::new(c, u32::MAX, u32::MAX, 8, 4).job(input), + ]; + for job in &wrong { + invalid(r.dispatch(&mut ctx, job)); + } + assert!(matches!(r.dispatch(&mut ctx, &YuvJob::new(c, 8, 4, 8, 4).job(HandleId(99))), Err(GpuFault::InvalidJob(_)))); + assert_eq!(ctx.reads, 0, "no job above reads its input"); + assert!(r.dispatch(&mut ctx, &YuvJob::new(c, 8, 4, 8, 4).job(input)).is_ok()); + assert_eq!(ctx.reads, 1); +} + +#[test] +fn jobs_past_the_context_caps_are_refused() { + let r = registry(YuvProvider::new()); + let caps = DeviceCaps { max_texture_dimension_2d: 64, max_buffer_size: 16128, ..DeviceCaps::default() }; + let mut ctx = Capped::new(caps); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + let small = ctx.upload_buffer("small", &tests::noise(64, 4)).unwrap(); + let wide = ctx.upload_buffer("wide", &tests::noise(66, 2)).unwrap(); + // The source and the output sides against the largest texture side. + assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 66, 2, 64, 2).job(wide))).contains("66×2 is larger than the largest texture side, 64")); + assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 64, 4, 66, 4).job(small))).contains("66×4")); + // NV12 read-back rows at width 64 are padded to 256 bytes: 64 × 44 packs into 4224 bytes + // but reads back through 256 × (44 + 22) = 16896, more than the 16128-byte limit; 64 × 42 + // reads back through exactly 16128. + assert_eq!(FrameLayout::new(Format::Nv12, 64, 44).unwrap().frame_bytes(), 4224); + let refused = invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 64, 4, 64, 44).job(small))); + assert!(refused.contains("16896 bytes is larger than the largest buffer, 16128"), "{refused}"); + assert!(dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 4, 64, 42).job(small)).is_ok()); +} + +#[test] +fn an_output_side_past_the_cpu_limit_is_refused_before_the_input_is_read() { + let r = registry(YuvProvider::new()); + let side = cpu::MAX_SIDE + 2; + let caps = DeviceCaps { max_texture_dimension_2d: side, ..DeviceCaps::default() }; + let mut ctx = Capped::new(caps); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + let input = ctx.upload_buffer("input", &tests::noise(2, 2)).unwrap(); + let refused = invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 2, 2, side, 2).job(input))); + assert!(refused.contains(&format!("{side}×2 is larger than the largest texture side, {}", cpu::MAX_SIDE)), "{refused}"); + assert_eq!(ctx.reads, 0, "the refused input is not read"); +} + +#[test] +fn an_input_past_the_buffer_limit_is_refused_before_it_is_read() { + let r = registry(YuvProvider::new()); + let caps = DeviceCaps { max_texture_dimension_2d: 64, max_buffer_size: 16128, ..DeviceCaps::default() }; + let mut ctx = Capped::new(caps); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + // 64 × 64 × 4 = 16384 bytes, more than the 16128-byte limit; 64 × 63 × 4 is exactly 16128. + let large = ctx.upload_buffer("large", &tests::noise(64, 64)).unwrap(); + let at_limit = ctx.upload_buffer("at limit", &tests::noise(64, 63)).unwrap(); + let refused = invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 64, 64, 64, 4).job(large))); + assert!(refused.contains("16384 bytes is larger than the largest buffer, 16128"), "{refused}"); + assert_eq!(ctx.reads, 0, "the refused input is not read"); + assert!(dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 63, 64, 4).job(at_limit)).is_ok()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_provider_with_a_device_matches_the_cpu_through_the_registry() { + let Some((device, queue)) = tests::device() else { return }; + let provider = YuvProvider::with_device(device, queue); + assert!(provider.has_device() && !YuvProvider::new().has_device()); + let r = registry(provider); + let mut ctx = NullContext::new(WorkerKind::Main); + let (noise, ramps) = (tests::noise(64, 36), tests::ramps(160, 90)); + let (n, s) = (ctx.upload_buffer("noise", &noise).unwrap(), ctx.upload_buffer("ramps", &ramps).unwrap()); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 36, 64, 36).job(n)).unwrap(); + tests::assert_close(&frame, &cpu::convert(&noise, 64, 36, c, 64, 36).unwrap(), c, "64×36 through the registry"); + } + } + // Each conversion's converter is made once and used again: the second run of a + // conversion gives the same frame. + let c = Conversion::new(format, Matrix::Bt709, Range::Limited); + for (w, h) in [(80, 46), (240, 136)] { + let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 160, 90, w, h).job(s)).unwrap(); + tests::assert_close(&frame, &cpu::convert(&ramps, 160, 90, c, w, h).unwrap(), c, &format!("160×90 to {w}×{h} through the registry")); + assert_eq!(frame, dispatch(&r, &mut ctx, &YuvJob::new(c, 160, 90, w, h).job(s)).unwrap()); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_device_smaller_than_the_context_caps_refuses_the_job_without_a_device_error() { + let Some((device, queue)) = tests::device_with(|l| wgpu::Limits { max_texture_dimension_2d: 64, ..l }) else { return }; + let r = registry(YuvProvider::with_device(device, queue)); + // The null context's caps allow 8192, so only the device's own limit stops these. + let mut ctx = NullContext::new(WorkerKind::Main); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + let big = ctx.upload_buffer("big", &tests::noise(128, 2)).unwrap(); + let small = ctx.upload_buffer("small", &tests::noise(8, 2)).unwrap(); + assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 128, 2, 8, 2).job(big))).contains("128×2 is larger than the largest texture side, 64")); + assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 8, 2, 128, 2).job(small))).contains("128×2")); + // The device still runs a job that fits after refusing two. + let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 8, 2, 8, 2).job(small)).unwrap(); + tests::assert_close(&frame, &cpu::convert(&tests::noise(8, 2), 8, 2, c, 8, 2).unwrap(), c, "8×2 after two refusals"); +} diff --git a/crates/gpu-yuv/src/layout.rs b/crates/gpu-yuv/src/layout.rs new file mode 100644 index 0000000000..93b3f77269 --- /dev/null +++ b/crates/gpu-yuv/src/layout.rs @@ -0,0 +1,123 @@ +//! Where each plane sits in a read-back buffer and in a tightly packed frame. + +use crate::spec::{Error, Format}; + +/// One plane: its size in texels, the bytes of one texel, and where its rows start in a +/// read-back buffer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PlaneLayout { + pub width: u32, + pub height: u32, + /// Bytes per texel: 1 or 2 for one sample, 2 or 4 for an interleaved Cb and Cr pair. + pub texel_bytes: u32, + /// The plane's first byte in the read-back buffer. + pub offset: u64, + /// Bytes from one row to the next in the read-back buffer, a multiple of + /// `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`. + pub bytes_per_row: u32, +} + +impl PlaneLayout { + /// Bytes of one row in a packed frame, or `u32::MAX` when the fields give more. + pub fn row_bytes(&self) -> u32 { + self.width.saturating_mul(self.texel_bytes) + } +} + +/// The planes of one frame of `format` at `width × height`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FrameLayout { + pub format: Format, + pub width: u32, + pub height: u32, + pub planes: Vec, + /// Bytes a read-back buffer needs from its offset. + pub buffer_size: u64, +} + +fn aligned(n: u32) -> Option { + let a = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + n.div_ceil(a).checked_mul(a) +} + +/// The planes of `format` at `width × height` (the first `count` of the array) and the read-back +/// buffer size. +fn planes_of(format: Format, width: u32, height: u32) -> Result<([PlaneLayout; 3], usize, u64), Error> { + if width == 0 || height == 0 || width % 2 == 1 || height % 2 == 1 { + return Err(Error::OutputSize { width, height }); + } + let s = format.sample_bytes(); + let (cw, ch) = (width / 2, height / 2); + let (sizes, count) = match format { + Format::Nv12 | Format::P010 => ([(width, height, s), (cw, ch, 2 * s), (0, 0, 0)], 2), + Format::I420 => ([(width, height, s), (cw, ch, s), (cw, ch, s)], 3), + }; + let overflow = Error::Overflow { width, height }; + let mut offset = 0u64; + let mut tight = 0u64; + let mut planes = [PlaneLayout { width: 0, height: 0, texel_bytes: 0, offset: 0, bytes_per_row: 0 }; 3]; + for (plane, (w, h, texel_bytes)) in planes.iter_mut().zip(sizes).take(count) { + let row = w.checked_mul(texel_bytes).ok_or(overflow.clone())?; + let bytes_per_row = aligned(row).ok_or(overflow.clone())?; + *plane = PlaneLayout { width: w, height: h, texel_bytes, offset, bytes_per_row }; + offset = offset.checked_add(u64::from(bytes_per_row) * u64::from(h)).ok_or(overflow.clone())?; + tight = tight.checked_add(u64::from(row) * u64::from(h)).ok_or(overflow.clone())?; + } + // A packed frame must also fit in memory on this target. + usize::try_from(tight).map_err(|_| overflow)?; + Ok((planes, count, offset)) +} + +impl FrameLayout { + /// The layout of `format` at `width × height`; both sides must be even and not zero. + pub fn new(format: Format, width: u32, height: u32) -> Result { + let (planes, count, buffer_size) = planes_of(format, width, height)?; + Ok(FrameLayout { format, width, height, planes: planes[..count].to_vec(), buffer_size }) + } + + /// Whether the fields are what [`FrameLayout::new`] gives for the format and size. It does not + /// allocate, so a frame loop can call it. + fn is_valid(&self) -> bool { + matches!(planes_of(self.format, self.width, self.height), + Ok((planes, count, size)) if planes[..count] == self.planes[..] && size == self.buffer_size) + } + + /// Bytes of one tightly packed frame: the planes one after another, each row without padding. + /// Fields changed after [`FrameLayout::new`] that give more than `usize::MAX` give + /// `usize::MAX`. + pub fn frame_bytes(&self) -> usize { + self.planes + .iter() + .fold(0usize, |n, p| n.saturating_add((p.width as usize).saturating_mul(p.texel_bytes as usize).saturating_mul(p.height as usize))) + } + + /// Copy the planes from `padded` (a mapped read-back buffer, from the offset it was copied to) + /// into `frame` without the row padding. `frame` must be [`FrameLayout::frame_bytes`] long. + /// A layout whose fields differ from what [`FrameLayout::new`] gives is [`Error::Layout`]. + pub fn unpack(&self, padded: &[u8], frame: &mut [u8]) -> Result<(), Error> { + if !self.is_valid() { + return Err(Error::Layout); + } + if (padded.len() as u64) < self.buffer_size { + return Err(Error::BufferSize { needed: self.buffer_size, actual: padded.len() as u64 }); + } + let tight = self.frame_bytes(); + if frame.len() != tight { + return Err(Error::BufferSize { needed: tight as u64, actual: frame.len() as u64 }); + } + let mut out = frame; + for p in &self.planes { + let (row, padded_row) = (p.row_bytes() as usize, p.bytes_per_row as usize); + let (dst, rest) = out.split_at_mut(row * p.height as usize); + let src = padded.get(p.offset as usize..).unwrap_or_default(); + for (d, s) in dst.chunks_exact_mut(row).zip(src.chunks(padded_row)) { + // The layout and size checks above leave every row whole. + if let Some(s) = s.get(..row) { + d.copy_from_slice(s); + } + } + out = rest; + } + Ok(()) + } +} diff --git a/crates/gpu-yuv/src/lib.rs b/crates/gpu-yuv/src/lib.rs new file mode 100644 index 0000000000..24afb1a4aa --- /dev/null +++ b/crates/gpu-yuv/src/lib.rs @@ -0,0 +1,36 @@ +//! RGBA to 4:2:0 Y'CbCr on the GPU, for encoders and scopes. +//! +//! - [`YuvProvider`] is the `craft.yuv` [`craft_gpu::GpuProvider`]: a host registers it in a +//! [`craft_gpu::ProviderRegistry`] and dispatches [`YuvJob`]s, on the null context or on a device. +//! - [`Converter`] holds the render pipelines of one [`Conversion`]: a [`Format`] (NV12, P010 or +//! I420), a [`Matrix`] (BT.601, BT.709 or BT.2020) and a [`Range`] (limited or full), for a +//! caller that records the passes into its own command encoder. +//! - [`Converter::bind`] binds a source texture view once; [`Converter::planes`] makes the plane +//! textures of one output size; [`Converter::draw`] records the two passes. The source is scaled +//! to the output size. +//! - [`Planes::copy_to_buffer`] records the copies into a read-back buffer, and +//! [`FrameLayout::unpack`] turns the mapped buffer into one tightly packed frame. +//! - [`cpu::convert`] is the same conversion on the CPU. +//! +//! The matrix applies to the stored values as they are: the input must already be in the +//! output's primaries and transfer, and alpha is ignored. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod cpu; +mod gpu; +mod job; +mod layout; +mod spec; + +pub use gpu::{Converter, Planes, Source}; +pub use job::{PROVIDER_ID, YuvJob, YuvProvider}; +pub use layout::{FrameLayout, PlaneLayout}; +pub use spec::{Conversion, Error, Format, Matrix, Range}; + +#[cfg(test)] +mod job_tests; +#[cfg(test)] +mod oracle_tests; +#[cfg(test)] +mod tests; diff --git a/crates/gpu-yuv/src/oracle_tests.rs b/crates/gpu-yuv/src/oracle_tests.rs new file mode 100644 index 0000000000..303abad3c7 --- /dev/null +++ b/crates/gpu-yuv/src/oracle_tests.rs @@ -0,0 +1,350 @@ +//! Checks against sources outside this crate: code values computed here in `f64` from the Kr and +//! Kb values and the quantization each ITU-R recommendation states, the `yuv` crate's conversion +//! of the same pictures, and the plane layouts the formats' public definitions give. None of these +//! checks reads `spec::Coefficients`. +//! +//! - BT.601-7 section 2.5, : Kr 0.299, Kb 0.114. +//! - BT.709-6 items 3.2 to 3.5, : Kr 0.2126, Kb 0.0722; +//! limited range `INT[(219 E'Y + 16) 2^(n-8)]` and `INT[(224 E'C + 128) 2^(n-8)]`, where INT +//! rounds a fraction of 0.5 up. +//! - BT.2020-2 tables 4 and 5, : Kr 0.2627, Kb 0.0593, +//! quantized as in BT.709. +//! - BT.2100-3 table 9, : full range +//! `Round[(2^n - 1) E'Y]` and `Round[(2^n - 1) E'C + 2^(n-1)]`, with +//! `Round(x) = Sign(x) Floor(|x| + 0.5)`. +//! - NV12 and I420: the W3C WebCodecs `VideoPixelFormat` definitions, +//! . +//! - NV12 and P010: the Linux media API's semi-planar YUV formats and their sample 4×4 images, +//! . + +use super::*; + +const ALL: [Format; 3] = [Format::Nv12, Format::P010, Format::I420]; +const MATRICES: [Matrix; 3] = [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020]; +const RANGES: [Range; 2] = [Range::Limited, Range::Full]; + +/// Kr and Kb as each recommendation states them. +fn kr_kb(m: Matrix) -> (f64, f64) { + match m { + Matrix::Bt601 => (0.299, 0.114), + Matrix::Bt709 => (0.2126, 0.0722), + Matrix::Bt2020 => (0.2627, 0.0593), + } +} + +/// The unrounded luma, Cb and Cr code values of an 8-bit RGB color. +fn exact(rgb: [f64; 3], c: Conversion) -> [f64; 3] { + let (kr, kb) = kr_kb(c.matrix); + let [r, g, b] = rgb.map(|v| v / 255.0); + let y = kr * r + (1.0 - kr - kb) * g + kb * b; + let pb = (b - y) / (2.0 * (1.0 - kb)); + let pr = (r - y) / (2.0 * (1.0 - kr)); + let n = c.format.bits() as i32; + match c.range { + Range::Limited => { + let s = 2f64.powi(n - 8); + [(219.0 * y + 16.0) * s, (224.0 * pb + 128.0) * s, (224.0 * pr + 128.0) * s] + } + Range::Full => { + let m = 2f64.powi(n) - 1.0; + let half = 2f64.powi(n - 1); + [m * y, m * pb + half, m * pr + half] + } + } +} + +/// `Round(x) = Sign(x) Floor(|x| + 0.5)`, clamped to the codes of `bits`. `f64::round` is that +/// function; adding 0.5 in `f64` would take the largest value below a half up to 1. +fn round(x: f64, bits: u32) -> u16 { + x.round().clamp(0.0, f64::from((1u32 << bits) - 1)) as u16 +} + +/// Whether `got` is the rounded `exact` value. A value within 0.001 of a half may round either +/// way in `f32`, so there the floor and the ceiling of `exact`, clamped to the codes, both pass. +fn rounds_to(got: u16, exact: f64, bits: u32) -> bool { + let near_half = ((exact - exact.floor()) - 0.5).abs() < 1e-3; + let code = |v: f64| v.clamp(0.0, f64::from((1u32 << bits) - 1)) as u16; + got == round(exact, bits) || near_half && (got == code(exact.floor()) || got == code(exact.ceil())) +} + +#[test] +fn a_value_near_a_half_passes_only_as_its_floor_or_ceiling() { + assert!(rounds_to(128, 128.5, 8)); + assert!(rounds_to(129, 128.5, 8)); + assert!(!rounds_to(130, 128.5, 8)); + assert!(!rounds_to(127, 128.5, 8)); + assert!(rounds_to(255, 254.9995, 8)); + assert!(!rounds_to(254, 254.9, 8)); + assert!(rounds_to(0, -0.5, 8)); + assert!(!rounds_to(1, -0.5, 8)); + assert_eq!(round(0.5 - f64::EPSILON / 4.0, 8), 0); + assert_eq!(round(2.5, 8), 3); +} + +/// Every sample of a frame as its value (P010 words shifted down by 6). +fn samples(frame: &[u8], format: Format) -> Vec { + match format { + Format::P010 => frame.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b) >> 6).collect(), + Format::Nv12 | Format::I420 => frame.iter().map(|&b| u16::from(b)).collect(), + } +} + +/// The luma sample of pixel `(x, y)` and the Cb and Cr samples of the chroma texel over it, in +/// a packed frame of `w × h`. +fn at(s: &[u16], format: Format, w: usize, h: usize, x: usize, y: usize) -> [u16; 3] { + let luma = w * h; + let (cw, ch) = (w / 2, h / 2); + let c = (y / 2) * cw + x / 2; + match format { + Format::Nv12 | Format::P010 => [s[y * w + x], s[luma + 2 * c], s[luma + 2 * c + 1]], + Format::I420 => [s[y * w + x], s[luma + c], s[luma + cw * ch + c]], + } +} + +/// Channel values that include black, white, the 75% level (191), the limited-range nominal +/// levels and values one step from the ends. +const LEVELS: [u8; 9] = [0, 1, 16, 64, 128, 191, 235, 254, 255]; + +/// A picture of every color whose channels are in [`LEVELS`], each as a 2 × 2 block, so that no +/// sample depends on how chroma is subsampled. Returns the pixels, the side and the colors. +fn blocks() -> (Vec, u32, Vec<[u8; 3]>) { + let colors: Vec<[u8; 3]> = LEVELS.iter().flat_map(|&r| LEVELS.iter().flat_map(move |&g| LEVELS.iter().map(move |&b| [r, g, b]))).collect(); + let per_row = 27usize; + let side = per_row * 2; + let mut px = vec![0u8; side * side * 4]; + for (k, rgb) in colors.iter().enumerate() { + let (bx, by) = (k % per_row, k / per_row); + for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { + let i = ((by * 2 + dy) * side + bx * 2 + dx) * 4; + px[i..i + 4].copy_from_slice(&[rgb[0], rgb[1], rgb[2], 255]); + } + } + (px, side as u32, colors) +} + +/// Every block of `frame` against the equations. `slack` is 0 for the CPU and 1 for the GPU. +fn check_blocks(frame: &[u8], c: Conversion, side: u32, colors: &[[u8; 3]], slack: u16, what: &str) { + let s = samples(frame, c.format); + let side = side as usize; + for (k, rgb) in colors.iter().enumerate() { + let (x, y) = ((k % 27) * 2, (k / 27) * 2); + let got = at(&s, c.format, side, side, x, y); + let want = exact(rgb.map(f64::from), c); + for i in 0..3 { + let ok = rounds_to(got[i], want[i], c.format.bits()) || got[i].abs_diff(round(want[i], c.format.bits())) <= slack; + assert!(ok, "{what} {c:?} {rgb:?}: component {i} is {} where the equations give {:.4}", got[i], want[i]); + } + } +} + +#[test] +fn the_cpu_gives_the_codes_of_the_published_equations() { + let (px, side, colors) = blocks(); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let frame = cpu::convert(&px, side, side, c, side, side).unwrap(); + check_blocks(&frame, c, side, &colors, 0, "CPU"); + } + } + } +} + +#[test] +fn nominal_levels_have_the_codes_the_recommendations_state() { + // White, black and neutral chroma are 235, 16 and 128 at limited range, 255, 0 and 128 at + // full range, times 4 (and 1023 for full white) at 10 bits. Chroma reaches 240 (960) for blue's + // Cb and red's Cr, and 16 (64) for yellow's Cb and cyan's Cr. At full range those are + // Round(255.5) and Round(0.5), clamped to 255 (1023) and 1. + for format in ALL { + let ten = format.bits() == 10; + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let (white, black, mid, high, low) = match (range, ten) { + (Range::Limited, false) => (235, 16, 128, 240, 16), + (Range::Limited, true) => (940, 64, 512, 960, 64), + (Range::Full, false) => (255, 0, 128, 255, 1), + (Range::Full, true) => (1023, 0, 512, 1023, 1), + }; + let code = |rgb: [u8; 3]| { + let frame = cpu::convert(&(0..4).flat_map(|_| [rgb[0], rgb[1], rgb[2], 255]).collect::>(), 2, 2, c, 2, 2).unwrap(); + at(&samples(&frame, format), format, 2, 2, 0, 0) + }; + assert_eq!(code([255, 255, 255]), [white, mid, mid], "{c:?} white"); + assert_eq!(code([0, 0, 0]), [black, mid, mid], "{c:?} black"); + assert_eq!(code([0, 0, 255])[1], high, "{c:?} blue Cb"); + assert_eq!(code([255, 0, 0])[2], high, "{c:?} red Cr"); + assert_eq!(code([255, 255, 0])[1], low, "{c:?} yellow Cb"); + assert_eq!(code([0, 255, 255])[2], low, "{c:?} cyan Cr"); + } + } + } +} + +fn yuv_range(r: Range) -> yuv::YuvRange { + match r { + Range::Limited => yuv::YuvRange::Limited, + Range::Full => yuv::YuvRange::Full, + } +} + +fn yuv_matrix(m: Matrix) -> yuv::YuvStandardMatrix { + match m { + Matrix::Bt601 => yuv::YuvStandardMatrix::Bt601, + Matrix::Bt709 => yuv::YuvStandardMatrix::Bt709, + Matrix::Bt2020 => yuv::YuvStandardMatrix::Bt2020, + } +} + +/// The `yuv` crate's conversion of `px` (`w × h`) as one packed frame in this crate's order. +/// P010 takes 10-bit RGB there, so each channel is scaled to 0..=1023 and rounded first. +fn yuv_convert(px: &[u8], w: u32, h: u32, c: Conversion) -> Vec { + use yuv::{YuvBiPlanarImageMut, YuvChromaSubsampling, YuvConversionMode, YuvPlanarImageMut}; + let (range, matrix, mode) = (yuv_range(c.range), yuv_matrix(c.matrix), YuvConversionMode::Professional); + match c.format { + Format::Nv12 => { + let mut img = YuvBiPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + yuv::rgba_to_yuv_nv12(&mut img, px, w * 4, range, matrix, mode).unwrap(); + [img.y_plane.borrow(), img.uv_plane.borrow()].concat() + } + Format::I420 => { + let mut img = YuvPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + yuv::rgba_to_yuv420(&mut img, px, w * 4, range, matrix, mode).unwrap(); + [img.y_plane.borrow(), img.u_plane.borrow(), img.v_plane.borrow()].concat() + } + Format::P010 => { + let wide: Vec = px.iter().map(|&v| (f64::from(v) * 1023.0 / 255.0).round() as u16).collect(); + let mut img = YuvBiPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + yuv::rgba10_to_p010(&mut img, &wide, w * 4, range, matrix).unwrap(); + [img.y_plane.borrow(), img.uv_plane.borrow()].concat().iter().flat_map(|v| v.to_le_bytes()).collect() + } + } +} + +/// The largest difference allowed from the `yuv` crate: 1 code value at 8 bits, and 2 at 10 bits, +/// where its input was rounded to 10 bits first. +fn yuv_tolerance(format: Format) -> u16 { + if format.bits() == 10 { 2 } else { 1 } +} + +#[test] +fn the_cpu_matches_the_yuv_crate() { + let (px, side, _) = blocks(); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let ours = samples(&cpu::convert(&px, side, side, c, side, side).unwrap(), format); + let theirs = samples(&yuv_convert(&px, side, side, c), format); + assert_eq!(ours.len(), theirs.len(), "{c:?}"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + assert!(a.abs_diff(*b) <= yuv_tolerance(format), "{c:?}: sample {i} is {a} here and {b} in the yuv crate"); + } + } + } + } +} + +#[test] +fn packed_planes_have_the_sizes_the_yuv_crate_allocates() { + use yuv::{YuvBiPlanarImageMut, YuvChromaSubsampling, YuvPlanarImageMut}; + for (w, h) in [(2, 2), (4, 4), (16, 10), (1920, 1080), (3840, 2160)] { + for format in ALL { + let l = FrameLayout::new(format, w, h).unwrap(); + let s = format.sample_bytes() as usize; + let packed: Vec<(usize, usize)> = l.planes.iter().map(|p| (p.row_bytes() as usize, p.row_bytes() as usize * p.height as usize)).collect(); + let theirs: Vec<(usize, usize)> = match format { + Format::Nv12 | Format::P010 => { + let img = YuvBiPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + vec![(img.y_stride as usize * s, img.y_plane.borrow().len() * s), (img.uv_stride as usize * s, img.uv_plane.borrow().len() * s)] + } + Format::I420 => { + let img = YuvPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + vec![ + (img.y_stride as usize, img.y_plane.borrow().len()), + (img.u_stride as usize, img.u_plane.borrow().len()), + (img.v_stride as usize, img.v_plane.borrow().len()), + ] + } + }; + assert_eq!(packed, theirs, "{format} {w}×{h}: row bytes and plane bytes"); + assert_eq!(l.frame_bytes(), theirs.iter().map(|p| p.1).sum::(), "{format} {w}×{h}"); + } + } +} + +/// Sixteen different colors for a 4 × 4 picture. +fn sixteen() -> Vec<[u8; 3]> { + (0..16u32).map(|k| [(k * 17) as u8, ((k * 53 + 30) % 256) as u8, ((k * 91 + 60) % 256) as u8]).collect() +} + +/// The byte offset of luma sample `(x, y)`. +type LumaAt = fn(usize, usize) -> usize; +/// The byte offsets of the Cb and Cr samples of chroma texel `(x, y)`. +type ChromaAt = fn(usize, usize) -> (usize, usize); + +/// Where the public definitions put each sample of a 4 × 4 frame. +fn documented_offsets(format: Format) -> (LumaAt, ChromaAt) { + match format { + // "start + 0: Y'00 Y'01 Y'02 Y'03 ... start + 16: Cb00 Cr00 Cb01 Cr01, start + 20: Cb10 Cr10 Cb11 Cr11" + Format::Nv12 => (|x, y| y * 4 + x, |x, y| (16 + y * 4 + x * 2, 17 + y * 4 + x * 2)), + // Rows of 8 bytes: "start + 8: Y'10 ... start + 32: Cb00 Cr00 Cb01 Cr01, start + 40: Cb10 ..." + Format::P010 => (|x, y| y * 8 + x * 2, |x, y| (32 + y * 8 + x * 4, 34 + y * 8 + x * 4)), + // Y, then U, then V; each chroma plane has 2 rows of 2 samples. + Format::I420 => (|x, y| y * 4 + x, |x, y| (16 + y * 2 + x, 20 + y * 2 + x)), + } +} + +#[test] +fn a_4x4_frame_puts_each_sample_where_the_format_definitions_do() { + let colors = sixteen(); + let px: Vec = colors.iter().flat_map(|c| [c[0], c[1], c[2], 255]).collect(); + for format in ALL { + let c = Conversion::new(format, Matrix::Bt709, Range::Limited); + let frame = cpu::convert(&px, 4, 4, c, 4, 4).unwrap(); + assert_eq!(frame.len(), 4 * 4 * 3 / 2 * format.sample_bytes() as usize, "{format}"); + let read = |offset: usize| match format { + Format::P010 => { + let word = u16::from_le_bytes([frame[offset], frame[offset + 1]]); + assert_eq!(word & 0x3f, 0, "{format}: the 6 low bits are zero"); + word >> 6 + } + Format::Nv12 | Format::I420 => u16::from(frame[offset]), + }; + let (luma, chroma) = documented_offsets(format); + for y in 0..4 { + for x in 0..4 { + let want = exact(colors[y * 4 + x].map(f64::from), c)[0]; + assert!(rounds_to(read(luma(x, y)), want, format.bits()), "{format}: luma {x},{y}"); + } + } + for y in 0..2 { + for x in 0..2 { + // Each chroma sample is the code of the average of the 2 × 2 pixels under it. + let quad = [(0, 0), (1, 0), (0, 1), (1, 1)].map(|(dx, dy)| colors[(y * 2 + dy) * 4 + x * 2 + dx]); + let mean = [0, 1, 2].map(|i| quad.iter().map(|p| f64::from(p[i])).sum::() / 4.0); + let want = exact(mean, c); + let (cb, cr) = chroma(x, y); + assert!(rounds_to(read(cb), want[1], format.bits()), "{format}: Cb {x},{y}"); + assert!(rounds_to(read(cr), want[2], format.bits()), "{format}: Cr {x},{y}"); + } + } + } +} + +#[test] +fn the_gpu_gives_the_codes_of_the_published_equations() { + let Some((device, queue)) = tests::device() else { return }; + let (px, side, colors) = blocks(); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let frame = tests::gpu_convert(&device, &queue, (&px, side, side), c, (side, side)); + check_blocks(&frame, c, side, &colors, 1, "GPU"); + } + } + } +} diff --git a/crates/gpu-yuv/src/spec.rs b/crates/gpu-yuv/src/spec.rs new file mode 100644 index 0000000000..2e311a9401 --- /dev/null +++ b/crates/gpu-yuv/src/spec.rs @@ -0,0 +1,193 @@ +//! What a conversion produces: the plane format, the matrix and the range, and the code values +//! they give. + +use std::fmt; + +/// The 4:2:0 layout a conversion writes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Format { + /// 8 bits: the luma plane, then one plane of interleaved Cb and Cr samples. + Nv12, + /// 10 bits in the high bits of little-endian 16-bit words: the luma plane, then one plane of + /// interleaved Cb and Cr samples. + P010, + /// 8 bits: the luma plane, then the Cb plane, then the Cr plane. + I420, +} + +impl Format { + /// Bits per sample value. + pub fn bits(self) -> u32 { + match self { + Format::P010 => 10, + Format::Nv12 | Format::I420 => 8, + } + } + + /// Bytes each sample takes in memory. + pub fn sample_bytes(self) -> u32 { + match self { + Format::P010 => 2, + Format::Nv12 | Format::I420 => 1, + } + } + + /// The left shift from a sample value to the stored word: 6 for P010, else 0. + pub fn shift(self) -> u32 { + match self { + Format::P010 => 6, + Format::Nv12 | Format::I420 => 0, + } + } + + /// The format's usual name: `NV12`, `P010` or `I420`. + pub fn name(self) -> &'static str { + match self { + Format::Nv12 => "NV12", + Format::P010 => "P010", + Format::I420 => "I420", + } + } +} + +impl fmt::Display for Format { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +/// The RGB to Y'CbCr matrix (ITU-R BT.601, BT.709 and BT.2020 non-constant luminance). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Matrix { + Bt601, + Bt709, + Bt2020, +} + +impl Matrix { + /// The red and blue luma weights, Kr and Kb. + pub fn kr_kb(self) -> (f32, f32) { + match self { + Matrix::Bt601 => (0.299, 0.114), + Matrix::Bt709 => (0.2126, 0.0722), + Matrix::Bt2020 => (0.2627, 0.0593), + } + } +} + +/// The code values the signal spans. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Range { + /// Luma from 16 to 235 and chroma from 16 to 240, scaled by 4 at 10 bits. + Limited, + /// Every code value, from 0 to 255 (1023 at 10 bits); chroma is centered on 128 (512). + Full, +} + +/// One conversion: the plane format, the matrix and the range. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Conversion { + pub format: Format, + pub matrix: Matrix, + pub range: Range, +} + +impl Conversion { + pub fn new(format: Format, matrix: Matrix, range: Range) -> Conversion { + Conversion { format, matrix, range } + } +} + +/// The weights and the scale of one conversion. The code value of luma is +/// `dot(y, rgb) * y_scale + y_offset`, of Cb `dot(cb, rgb) * c_scale + c_offset`, and of Cr +/// `dot(cr, rgb) * c_scale + c_offset`, rounded with halves away from zero and clamped to +/// `0..=max`, for `rgb` from 0 to 1. That rounding is `INT` in BT.709 and BT.2020 and `Round` in +/// BT.2100. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Coefficients { + pub y: [f32; 3], + pub cb: [f32; 3], + pub cr: [f32; 3], + pub y_scale: f32, + pub y_offset: f32, + pub c_scale: f32, + pub c_offset: f32, + pub max: f32, +} + +impl Coefficients { + pub fn of(c: Conversion) -> Coefficients { + let (kr, kb) = c.matrix.kr_kb(); + let kg = 1.0 - kr - kb; + let (db, dr) = (2.0 * (1.0 - kb), 2.0 * (1.0 - kr)); + let bits = c.format.bits(); + let max = ((1u32 << bits) - 1) as f32; + let step = (1u32 << (bits - 8)) as f32; + let (y_scale, y_offset, c_scale, c_offset) = match c.range { + Range::Limited => (219.0 * step, 16.0 * step, 224.0 * step, 128.0 * step), + Range::Full => (max, 0.0, max, (1u32 << (bits - 1)) as f32), + }; + Coefficients { y: [kr, kg, kb], cb: [-kr / db, -kg / db, 0.5], cr: [0.5, -kg / dr, -kb / dr], y_scale, y_offset, c_scale, c_offset, max } + } + + /// The code values of luma, Cb and Cr for `rgb`. + pub fn codes(&self, rgb: [f32; 3]) -> [u16; 3] { + let dot = |w: [f32; 3]| w[0] * rgb[0] + w[1] * rgb[1] + w[2] * rgb[2]; + let code = |v: f32| v.round().clamp(0.0, self.max) as u16; + [ + code(dot(self.y) * self.y_scale + self.y_offset), + code(dot(self.cb) * self.c_scale + self.c_offset), + code(dot(self.cr) * self.c_scale + self.c_offset), + ] + } +} + +/// What a conversion cannot do. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Error { + /// An output side is zero or odd; 4:2:0 needs both sides even. + OutputSize { width: u32, height: u32 }, + /// A side is larger than the device's largest 2D texture. + TooLarge { width: u32, height: u32, limit: u32 }, + /// The frame's byte sizes do not fit in the integer types that hold them. + Overflow { width: u32, height: u32 }, + /// A buffer the job uses (the RGBA8 input, or the read-back buffer for the frame) would be + /// larger than the device's largest buffer. + BufferLimit { needed: u64, limit: u64 }, + /// A source side is zero, or the pixels are not `width × height × 4` bytes. + Source { width: u32, height: u32, bytes: usize }, + /// A buffer or a frame does not have the size the layout needs. + BufferSize { needed: u64, actual: u64 }, + /// A buffer offset is not a multiple of `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`. + Offset(u64), + /// The planes were made for another format than the converter's. + Mismatch { converter: Format, planes: Format }, + /// A frame layout's fields are not what [`crate::FrameLayout::new`] gives for its format and + /// size. + Layout, + /// A buffer of `bytes` bytes for the frame could not be allocated. + Memory { bytes: usize }, + /// The device reported an error (validation, out of memory, a failed map or poll) while + /// [`crate::YuvProvider`] ran a job on it. + Device(String), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::OutputSize { width, height } => write!(f, "a 4:2:0 picture of {width}×{height} needs both sides even and not zero"), + Error::TooLarge { width, height, limit } => write!(f, "{width}×{height} is larger than the largest texture side, {limit}"), + Error::Overflow { width, height } => write!(f, "a frame of {width}×{height} is too large to hold"), + Error::BufferLimit { needed, limit } => write!(f, "a buffer of {needed} bytes is larger than the largest buffer, {limit}"), + Error::Source { width, height, bytes } => write!(f, "{bytes} bytes are not an RGBA picture of {width}×{height}"), + Error::BufferSize { needed, actual } => write!(f, "{actual} bytes where {needed} are needed"), + Error::Offset(offset) => write!(f, "buffer offset {offset} is not a multiple of {}", wgpu::COPY_BYTES_PER_ROW_ALIGNMENT), + Error::Mismatch { converter, planes } => write!(f, "{planes} planes given to a {converter} converter"), + Error::Layout => f.write_str("the frame layout does not match its format and size"), + Error::Memory { bytes } => write!(f, "a buffer of {bytes} bytes could not be allocated"), + Error::Device(message) => write!(f, "the device reported an error: {message}"), + } + } +} + +impl std::error::Error for Error {} diff --git a/crates/gpu-yuv/src/tests.rs b/crates/gpu-yuv/src/tests.rs new file mode 100644 index 0000000000..b0c601e773 --- /dev/null +++ b/crates/gpu-yuv/src/tests.rs @@ -0,0 +1,468 @@ +use super::*; + +const ALL: [Format; 3] = [Format::Nv12, Format::P010, Format::I420]; +const MATRICES: [Matrix; 3] = [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020]; +const RANGES: [Range; 2] = [Range::Limited, Range::Full]; + +fn solid(w: u32, h: u32, rgb: [u8; 3]) -> Vec { + (0..w * h).flat_map(|_| [rgb[0], rgb[1], rgb[2], 255]).collect() +} + +/// The first luma sample and the first Cb and Cr samples of a converted frame, as values. +fn first(frame: &[u8], format: Format, w: u32, h: u32) -> [u16; 3] { + let s = samples(frame, format); + let luma = (w * h) as usize; + let quarter = luma / 4; + match format { + Format::Nv12 | Format::P010 => [s[0], s[luma], s[luma + 1]], + Format::I420 => [s[0], s[luma], s[luma + quarter]], + } +} + +/// Every sample of a frame as its value (P010 words shifted down by 6). +fn samples(frame: &[u8], format: Format) -> Vec { + match format { + Format::P010 => frame.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b) >> 6).collect(), + Format::Nv12 | Format::I420 => frame.iter().map(|&b| u16::from(b)).collect(), + } +} + +fn cpu(rgb: [u8; 3], c: Conversion) -> [u16; 3] { + let frame = cpu::convert(&solid(2, 2, rgb), 2, 2, c, 2, 2).unwrap(); + first(&frame, c.format, 2, 2) +} + +#[test] +fn bt709_limited_colors_have_their_standard_codes() { + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + assert_eq!(cpu([255, 255, 255], c), [235, 128, 128]); + assert_eq!(cpu([0, 0, 0], c), [16, 128, 128]); + assert_eq!(cpu([255, 0, 0], c), [63, 102, 240]); + assert_eq!(cpu([0, 0, 255], c), [32, 240, 118]); +} + +#[test] +fn each_matrix_weights_red_by_its_kr() { + let red = |m| cpu([255, 0, 0], Conversion::new(Format::Nv12, m, Range::Limited)); + assert_eq!(red(Matrix::Bt601), [81, 90, 240]); + assert_eq!(red(Matrix::Bt2020), [74, 97, 240]); +} + +#[test] +fn full_range_spans_every_code() { + let c = Conversion::new(Format::I420, Matrix::Bt709, Range::Full); + assert_eq!(cpu([255, 255, 255], c), [255, 128, 128]); + assert_eq!(cpu([0, 0, 0], c), [0, 128, 128]); + assert_eq!(cpu([255, 0, 0], c), [54, 99, 255]); +} + +#[test] +fn p010_holds_ten_bit_codes_in_the_high_bits() { + let limited = Conversion::new(Format::P010, Matrix::Bt2020, Range::Limited); + assert_eq!(cpu([255, 255, 255], limited), [940, 512, 512]); + assert_eq!(cpu([0, 0, 0], limited), [64, 512, 512]); + let full = Conversion::new(Format::P010, Matrix::Bt2020, Range::Full); + assert_eq!(cpu([255, 255, 255], full), [1023, 512, 512]); + let frame = cpu::convert(&solid(2, 2, [255, 255, 255]), 2, 2, limited, 2, 2).unwrap(); + assert_eq!(&frame[..2], &(940u16 << 6).to_le_bytes()); + assert_eq!(frame.len(), 12); +} + +#[test] +fn planes_follow_each_format_s_order() { + let red = solid(4, 2, [255, 0, 0]); + let nv12 = cpu::convert(&red, 4, 2, Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited), 4, 2).unwrap(); + assert_eq!(nv12, [63, 63, 63, 63, 63, 63, 63, 63, 102, 240, 102, 240]); + let i420 = cpu::convert(&red, 4, 2, Conversion::new(Format::I420, Matrix::Bt709, Range::Limited), 4, 2).unwrap(); + assert_eq!(i420, [63, 63, 63, 63, 63, 63, 63, 63, 102, 102, 240, 240]); +} + +#[test] +fn chroma_at_the_same_size_averages_the_four_pixels_it_covers() { + // Red over blue: chroma is the code of their average, magenta at half strength. + let mut px = solid(2, 1, [255, 0, 0]); + px.extend(solid(2, 1, [0, 0, 255])); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Full); + let frame = cpu::convert(&px, 2, 2, c, 2, 2).unwrap(); + let half = cpu([128, 0, 128], c); + assert!(frame[4].abs_diff(half[1] as u8) <= 1 && frame[5].abs_diff(half[2] as u8) <= 1, "{frame:?} {half:?}"); +} + +#[test] +fn a_reduction_averages_the_area_under_each_texel() { + // One white column in four: a 4:1 reduction gives a quarter of white, where one bilinear tap + // at the texel's center would land between two black columns. + let px: Vec = (0..16).flat_map(|i| if i % 4 == 0 { [255, 255, 255, 255] } else { [0, 0, 0, 255] }).collect(); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Full); + let frame = cpu::convert(&px, 8, 2, c, 2, 2).unwrap(); + assert_eq!(&frame[..4], &[64, 64, 64, 64]); +} + +#[test] +fn the_tap_count_grows_with_the_reduction_up_to_four() { + assert_eq!([0.5, 1.0, 2.0, 2.01, 4.0, 4.5, 8.0, 100.0].map(cpu::taps), [1, 1, 1, 2, 2, 3, 4, 4]); +} + +#[test] +fn bad_sizes_are_errors() { + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + let px = solid(2, 2, [0, 0, 0]); + assert_eq!(cpu::convert(&px, 2, 2, c, 3, 2).unwrap_err(), Error::OutputSize { width: 3, height: 2 }); + assert_eq!(cpu::convert(&px, 2, 2, c, 0, 0).unwrap_err(), Error::OutputSize { width: 0, height: 0 }); + assert_eq!(cpu::convert(&px, 2, 3, c, 2, 2).unwrap_err(), Error::Source { width: 2, height: 3, bytes: 16 }); + assert_eq!(cpu::convert(&[], 0, 0, c, 2, 2).unwrap_err(), Error::Source { width: 0, height: 0, bytes: 0 }); + assert_eq!(FrameLayout::new(Format::P010, 4, 5).unwrap_err(), Error::OutputSize { width: 4, height: 5 }); + let big = cpu::MAX_SIDE + 2; + assert_eq!(cpu::convert(&px, 2, 2, c, big, 2).unwrap_err(), Error::TooLarge { width: big, height: 2, limit: cpu::MAX_SIDE }); + // Byte sizes past the integer types are an error, not an overflow. + let huge = u32::MAX - 1; + assert_eq!(FrameLayout::new(Format::P010, huge, 2).unwrap_err(), Error::Overflow { width: huge, height: 2 }); + assert_eq!(FrameLayout::new(Format::Nv12, huge, 2).unwrap_err(), Error::Overflow { width: huge, height: 2 }); + assert_eq!(Error::OutputSize { width: 3, height: 2 }.to_string(), "a 4:2:0 picture of 3×2 needs both sides even and not zero"); +} + +#[test] +fn a_frame_buffer_that_cannot_be_allocated_is_an_error() { + // A request past `isize::MAX` bytes fails on every allocator, so the failure path runs + // without exhausting memory. + assert_eq!(cpu::reserve::(usize::MAX).unwrap_err(), Error::Memory { bytes: usize::MAX }); + assert_eq!(cpu::reserve::(usize::MAX / 2).unwrap_err(), Error::Memory { bytes: usize::MAX - 1 }); + let room = cpu::reserve::(4096).unwrap(); + assert!(room.is_empty() && room.capacity() >= 4096); + assert_eq!(Error::Memory { bytes: 16 }.to_string(), "a buffer of 16 bytes could not be allocated"); +} + +#[test] +fn layouts_pad_rows_for_copies_and_unpack_without_the_padding() { + let l = FrameLayout::new(Format::Nv12, 1920, 1080).unwrap(); + assert_eq!( + l.planes.iter().map(|p| (p.width, p.height, p.offset, p.bytes_per_row)).collect::>(), + [(1920, 1080, 0, 2048), (960, 540, 2048 * 1080, 2048)] + ); + assert_eq!((l.buffer_size, l.frame_bytes()), (2048 * 1620, 1920 * 1620)); + let p = FrameLayout::new(Format::P010, 640, 360).unwrap(); + assert_eq!((p.planes[0].bytes_per_row, p.planes[1].texel_bytes, p.frame_bytes()), (1280, 4, 640 * 360 * 3)); + let i = FrameLayout::new(Format::I420, 4, 2).unwrap(); + assert_eq!(i.planes.iter().map(|p| p.offset).collect::>(), [0, 512, 768]); + let mut padded = vec![0u8; i.buffer_size as usize]; + padded[..4].copy_from_slice(&[1, 2, 3, 4]); + padded[256..260].copy_from_slice(&[5, 6, 7, 8]); + padded[512..514].copy_from_slice(&[9, 10]); + padded[768..770].copy_from_slice(&[11, 12]); + let mut frame = vec![0u8; i.frame_bytes()]; + i.unpack(&padded, &mut frame).unwrap(); + assert_eq!(frame, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); + assert_eq!(i.unpack(&padded[..100], &mut frame).unwrap_err(), Error::BufferSize { needed: 1024, actual: 100 }); + assert_eq!(i.unpack(&padded, &mut [0; 3]).unwrap_err(), Error::BufferSize { needed: 12, actual: 3 }); +} + +#[test] +fn unpack_refuses_a_layout_that_was_changed_after_it_was_made() { + let l = FrameLayout::new(Format::I420, 4, 2).unwrap(); + let padded = vec![0u8; l.buffer_size as usize]; + let changes: [fn(&mut FrameLayout); 6] = [ + |l| l.planes[0].bytes_per_row = 0, + |l| l.planes[0].width = 0, + |l| l.planes[0].texel_bytes = 0, + |l| l.planes[0].offset = 768, + |l| l.planes[0].bytes_per_row = 2, + |l| l.planes.truncate(1), + ]; + for (n, change) in changes.iter().enumerate() { + let mut bad = l.clone(); + change(&mut bad); + let mut frame = vec![0u8; bad.frame_bytes()]; + assert_eq!(bad.unpack(&padded, &mut frame), Err(Error::Layout), "change {n}"); + } + assert_eq!(Error::Layout.to_string(), "the frame layout does not match its format and size"); +} + +#[test] +fn sizes_of_a_changed_layout_saturate_instead_of_overflowing() { + let mut l = FrameLayout::new(Format::I420, 4, 2).unwrap(); + let huge = PlaneLayout { width: u32::MAX, height: u32::MAX, texel_bytes: 4, offset: 0, bytes_per_row: 0 }; + assert_eq!(huge.row_bytes(), u32::MAX); + l.planes = vec![PlaneLayout { height: 1, ..huge }]; + let full = usize::try_from(u64::from(u32::MAX) * 4).unwrap_or(usize::MAX); + assert_eq!(l.frame_bytes(), full, "a row past u32::MAX bytes counts in full"); + l.planes = vec![huge; 3]; + assert_eq!(l.frame_bytes(), usize::MAX); + assert_eq!(l.unpack(&[], &mut []), Err(Error::Layout)); +} + +#[test] +fn an_enlarged_solid_color_keeps_its_codes() { + for format in ALL { + let c = Conversion::new(format, Matrix::Bt709, Range::Limited); + let frame = cpu::convert(&solid(3, 1, [10, 200, 90]), 3, 1, c, 8, 6).unwrap(); + let expect = cpu([10, 200, 90], c); + let s = samples(&frame, format); + assert_eq!(s.len(), 8 * 6 * 3 / 2); + assert!(s[..48].iter().all(|&v| v == expect[0]), "{format}"); + } +} + +#[test] +fn shaders_write_no_value_wgsl_cannot_read() { + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let s = gpu::shader(Conversion::new(format, matrix, range)); + assert!(!s.contains("NaN") && !s.contains("inf"), "{s}"); + assert!(s.contains("fn fs_chroma") && s.contains("fn fs_luma")); + } + } + } +} + +// The GPU half: the passes against the CPU reference. A machine without a graphics adapter skips +// these comparisons and says so on stderr. + +pub(crate) fn device() -> Option<(wgpu::Device, wgpu::Queue)> { + device_with(|l| l) +} + +/// A device with the adapter's limits as `limits` changes them. +pub(crate) fn device_with(limits: impl FnOnce(wgpu::Limits) -> wgpu::Limits) -> Option<(wgpu::Device, wgpu::Queue)> { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let Ok(adapter) = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) else { + eprintln!("no graphics adapter: the GPU half of this test is skipped"); + return None; + }; + let desc = wgpu::DeviceDescriptor { required_limits: limits(adapter.limits()), ..Default::default() }; + match pollster::block_on(adapter.request_device(&desc)) { + Ok(d) => Some(d), + Err(e) => { + eprintln!("the graphics adapter did not open ({e}): the GPU half of this test is skipped"); + None + } + } +} + +/// `src` (its pixels, width and height) converted on the GPU to `out` (width and height). +pub(crate) fn gpu_convert(device: &wgpu::Device, queue: &wgpu::Queue, src: (&[u8], u32, u32), c: Conversion, out: (u32, u32)) -> Vec { + let ((rgba, sw, sh), (w, h)) = (src, out); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: sw, height: sh, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + queue.write_texture( + texture.as_image_copy(), + rgba, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(sw * 4), rows_per_image: Some(sh) }, + wgpu::Extent3d { width: sw, height: sh, depth_or_array_layers: 1 }, + ); + let converter = Converter::new(device, c); + let source = converter.bind(device, &texture.create_view(&wgpu::TextureViewDescriptor::default())); + let planes = converter.planes(device, w, h).unwrap(); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 256 + planes.layout().buffer_size, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); + converter.draw(&mut enc, &source, &planes).unwrap(); + planes.copy_to_buffer(&mut enc, &buffer, 256).unwrap(); + queue.submit([enc.finish()]); + buffer.map_async(wgpu::MapMode::Read, 256.., |r| r.unwrap()); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let view = buffer.get_mapped_range(256..).unwrap(); + let mut frame = vec![0; planes.layout().frame_bytes()]; + planes.layout().unpack(&view, &mut frame).unwrap(); + frame +} + +/// The tolerance in code values: 2 at 8 bits and 6 at 10 bits. GPUs filter with fewer bits of +/// weight than `f32` and may round a half the other way. +fn tolerance(format: Format) -> u16 { + if format.bits() == 10 { 6 } else { 2 } +} + +pub(crate) fn assert_close(gpu: &[u8], cpu: &[u8], c: Conversion, what: &str) { + assert_eq!(gpu.len(), cpu.len(), "{what}"); + let (g, k) = (samples(gpu, c.format), samples(cpu, c.format)); + let worst = g.iter().zip(&k).enumerate().max_by_key(|(_, (a, b))| a.abs_diff(**b)); + if let Some((i, (a, b))) = worst { + assert!(a.abs_diff(*b) <= tolerance(c.format), "{what} {c:?}: sample {i} is {a} on the GPU and {b} on the CPU"); + } +} + +/// A picture with hard edges: each pixel's channels from a fixed pseudo-random sequence. +pub(crate) fn noise(w: u32, h: u32) -> Vec { + let mut x = 0x2545_f491_u32; + (0..w * h * 4) + .map(|i| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + if i % 4 == 3 { 255 } else { (x >> 24) as u8 } + }) + .collect() +} + +/// A smooth picture: three ramps at different angles. +pub(crate) fn ramps(w: u32, h: u32) -> Vec { + (0..h) + .flat_map(|y| { + (0..w).flat_map(move |x| { + let (u, v) = (x as f32 / w as f32, y as f32 / h as f32); + [(u * 255.0) as u8, (v * 255.0) as u8, ((1.0 - (u + v) * 0.5) * 255.0) as u8, 255] + }) + }) + .collect() +} + +#[test] +fn the_gpu_matches_the_cpu_at_the_same_size() { + let Some((device, queue)) = device() else { return }; + let px = noise(64, 36); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let g = gpu_convert(&device, &queue, (&px, 64, 36), c, (64, 36)); + assert_close(&g, &cpu::convert(&px, 64, 36, c, 64, 36).unwrap(), c, "64×36 at the same size"); + } + } + } +} + +#[test] +fn the_gpu_matches_the_cpu_when_scaling() { + let Some((device, queue)) = device() else { return }; + let px = ramps(160, 90); + for format in ALL { + let c = Conversion::new(format, Matrix::Bt709, Range::Limited); + for (w, h) in [(80, 46), (32, 18), (16, 10), (240, 136)] { + let g = gpu_convert(&device, &queue, (&px, 160, 90), c, (w, h)); + assert_close(&g, &cpu::convert(&px, 160, 90, c, w, h).unwrap(), c, &format!("160×90 to {w}×{h}")); + } + let odd = ramps(37, 23); + let g = gpu_convert(&device, &queue, (&odd, 37, 23), c, (20, 12)); + assert_close(&g, &cpu::convert(&odd, 37, 23, c, 20, 12).unwrap(), c, "37×23 to 20×12"); + } +} + +#[test] +fn the_gpu_rounds_a_value_just_below_a_half_down() { + let Some((device, queue)) = device() else { return }; + // The shader's own code(), driven by one extra entry point. The values are built from the + // texel position so that no compiler folds them: k is 0 at the only texel's center. + // 0x3effffff is 0.49999997, the largest f32 below 0.5, and 0x3f7fffff is 0.99999994. + let probe = "@fragment fn fs_probe(@builtin(position) pos: vec4) -> @location(0) vec4 { + let k = u32(pos.x); + let z = f32(k); + return vec4(code(bitcast(0x3effffffu + k)), code(0.5 + z), code(2.5 + z), code(bitcast(0x3f7fffffu + k))); +}"; + let wgsl = gpu::shader(Conversion::new(Format::Nv12, Matrix::Bt709, Range::Full)) + probe; + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(wgsl.into()) }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: None, + layout: None, + vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs_probe"), + targets: &[Some(wgpu::ColorTargetState { format: wgpu::TextureFormat::Rgba8Uint, blend: None, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Uint, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 256, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); + { + let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(&pipeline); + pass.draw(0..3, 0..1); + } + enc.copy_texture_to_buffer( + texture.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &buffer, + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256), rows_per_image: Some(1) }, + }, + wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, + ); + queue.submit([enc.finish()]); + buffer.map_async(wgpu::MapMode::Read, .., |r| r.unwrap()); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let got = buffer.get_mapped_range(..4).unwrap().to_vec(); + assert_eq!(got, [0, 1, 3, 1], "code() of 0.49999997, 0.5, 2.5 and 0.99999994"); +} + +#[test] +fn planes_larger_than_the_device_allows_are_errors() { + // The queue stays alive: a device whose queue was dropped cannot make an encoder. + let Some((device, _queue)) = device() else { return }; + let converter = Converter::new(&device, Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited)); + let limit = device.limits().max_texture_dimension_2d; + let too_big = (limit + 2) & !1; + assert_eq!(converter.planes(&device, too_big, 2).err(), Some(Error::TooLarge { width: too_big, height: 2, limit })); + let planes = converter.planes(&device, 4, 2).unwrap(); + let other = Converter::new(&device, Conversion::new(Format::P010, Matrix::Bt709, Range::Limited)); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: 4, height: 2, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }); + let source = other.bind(&device, &texture.create_view(&wgpu::TextureViewDescriptor::default())); + let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); + assert_eq!(other.draw(&mut enc, &source, &planes).unwrap_err(), Error::Mismatch { converter: Format::P010, planes: Format::Nv12 }); + let small = + device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 256, usage: wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }); + assert_eq!(planes.copy_to_buffer(&mut enc, &small, 0).unwrap_err(), Error::BufferSize { needed: 768, actual: 256 }); + assert_eq!(planes.copy_to_buffer(&mut enc, &small, 4).unwrap_err(), Error::Offset(4)); +} + +#[test] +fn planes_whose_read_back_is_larger_than_the_largest_buffer_are_errors() { + let Some((device, _queue)) = device_with(|l| wgpu::Limits { max_buffer_size: 1 << 20, ..l }) else { return }; + let converter = Converter::new(&device, Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited)); + // 1024 × 1024 NV12 reads back 1.5 MiB. + assert_eq!(converter.planes(&device, 1024, 1024).err(), Some(Error::BufferLimit { needed: 1024 * 1536, limit: 1 << 20 })); + assert!(converter.planes(&device, 512, 512).is_ok()); +} diff --git a/crates/gpu/src/caps.rs b/crates/gpu/src/caps.rs index 75dcf173d0..1ae87a0d30 100644 --- a/crates/gpu/src/caps.rs +++ b/crates/gpu/src/caps.rs @@ -20,6 +20,20 @@ pub struct DeviceCaps { /// never on what the adapter merely advertised. #[serde(default)] pub features: Vec, + /// The PCI vendor id of the device's adapter (or the Khronos vendor id some Vulkan drivers + /// report instead); 0 when unknown or on backends with no device. + #[serde(default)] + pub vendor_id: u32, + /// The device draws on the CPU (a software adapter such as WARP, llvmpipe or lavapipe). + #[serde(default)] + pub software: bool, +} + +impl DeviceCaps { + /// Whether the feature named `name` (as in [`features`](Self::features)) is enabled. + pub fn has_feature(&self, name: &str) -> bool { + self.features.iter().any(|f| f == name) + } } impl Default for DeviceCaps { @@ -31,6 +45,8 @@ impl Default for DeviceCaps { max_buffer_size: 256 * 1024 * 1024, max_texture_dimension_2d: 8192, features: Vec::new(), + vendor_id: 0, + software: false, } } } diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 528b2e587d..25ee131bc3 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -126,3 +126,15 @@ fn chunk_buffer_splits_on_storage_binding_limit() { let chunks = chunk_buffer(&caps, b"abcdef").expect("chunk_buffer"); assert_eq!(chunks, vec![&b"abcd"[..], &b"ef"[..]]); } + +#[test] +fn caps_without_vendor_or_software_read_as_unknown_hardware() { + let json = r#"{"backend_name":"Vulkan","device_name":"gpu","max_storage_buffer_binding_size":1,"max_buffer_size":2,"max_texture_dimension_2d":3,"features":["TEXTURE_FORMAT_NV12"]}"#; + let caps: DeviceCaps = serde_json::from_str(json).expect("caps"); + assert_eq!((caps.vendor_id, caps.software), (0, false)); + assert!(caps.has_feature("TEXTURE_FORMAT_NV12")); + assert!(!caps.has_feature("TEXTURE_FORMAT_P010") && !caps.has_feature("")); + let software = DeviceCaps { vendor_id: 0x10005, software: true, ..caps }; + let back: DeviceCaps = serde_json::from_str(&serde_json::to_string(&software).expect("json")).expect("caps"); + assert_eq!(back, software); +} diff --git a/crates/host/src/queue.rs b/crates/host/src/queue.rs index 8133d17e64..2dc1d34f60 100644 --- a/crates/host/src/queue.rs +++ b/crates/host/src/queue.rs @@ -47,9 +47,20 @@ impl Priority { /// The cancel flag a running job reads. The queue sets it when the job's key is dropped /// ([`JobQueue::reprioritize`] returning `None`, [`JobQueue::shutdown`], dropping the queue); a /// long job checks [`is_cancelled`](Cancel::is_cancelled) between steps and returns early. A -/// cancelled job's result is never delivered. Cloning shares the flag. +/// cancelled job's result is never delivered. A job that has nothing to do until it is cancelled +/// blocks in [`wait`](Cancel::wait) or [`wait_timeout`](Cancel::wait_timeout). Cloning shares the +/// flag. #[derive(Clone, Debug, Default)] -pub struct Cancel(Arc); +pub struct Cancel(Arc); + +/// The shared state behind a [`Cancel`]: the flag, and the lock and condition variable that wake +/// its waiters when it is set. +#[derive(Debug, Default)] +struct CancelFlag { + set: AtomicBool, + lock: Mutex<()>, + changed: Condvar, +} impl Cancel { /// A flag that is not set (tests call a decoder with it). @@ -59,12 +70,32 @@ impl Cancel { /// Whether the job should stop. pub fn is_cancelled(&self) -> bool { - self.0.load(Ordering::Relaxed) + self.0.set.load(Ordering::Relaxed) } - /// Sets the flag. + /// Sets the flag and wakes every thread blocked in [`wait`](Cancel::wait) or + /// [`wait_timeout`](Cancel::wait_timeout). pub fn cancel(&self) { - self.0.store(true, Ordering::Relaxed); + let guard = self.0.lock.lock().unwrap_or_else(|e| e.into_inner()); + self.0.set.store(true, Ordering::Relaxed); + drop(guard); + self.0.changed.notify_all(); + } + + /// Blocks the calling thread until the flag is set, and returns at once when it already is. + /// Another thread must call [`cancel`](Cancel::cancel): on wasm32, where a job runs on the + /// thread that would cancel it, a call that has to wait never returns. + pub fn wait(&self) { + let guard = self.0.lock.lock().unwrap_or_else(|e| e.into_inner()); + drop(self.0.changed.wait_while(guard, |_| !self.0.set.load(Ordering::Relaxed)).unwrap_or_else(|e| e.into_inner())); + } + + /// Blocks the calling thread until the flag is set or `timeout` has passed, and returns + /// whether the flag is set. A zero `timeout` reads the flag without waiting. + pub fn wait_timeout(&self, timeout: Duration) -> bool { + let guard = self.0.lock.lock().unwrap_or_else(|e| e.into_inner()); + drop(self.0.changed.wait_timeout_while(guard, timeout, |_| !self.0.set.load(Ordering::Relaxed)).unwrap_or_else(|e| e.into_inner())); + self.is_cancelled() } } diff --git a/crates/host/src/queue_tests.rs b/crates/host/src/queue_tests.rs index 86565c9792..bbd4ca99a7 100644 --- a/crates/host/src/queue_tests.rs +++ b/crates/host/src/queue_tests.rs @@ -1,9 +1,12 @@ //! `JobQueue` and `ManualJobs`: order, replacement, one job per key, cancellation, wakes and //! inline runs. Every test drives lanes with `ManualJobs` (or `lanes: 0`), so nothing depends on -//! thread timing. +//! thread timing. The tests of `Cancel::wait` block a second thread and hand off over channels. use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc::{self, TryRecvError}; +use std::thread; +use std::time::Duration; use crate::queue::{Cancel, Finished, JobQueue, Priority, QueueOptions, QueueOrder}; use crate::{ManualJobs, Wake}; @@ -83,6 +86,62 @@ fn queue_dropped_keys_are_cancelled() { assert!(!queue.contains(&"waiting") && !queue.contains(&"running")); } +// `wait_timeout` reads the flag, a clone shares it, and `wait` returns at once on a set flag. +#[test] +fn cancel_wait_timeout_reports_the_flag() { + let cancel = Cancel::new(); + let shared = cancel.clone(); + assert!(!cancel.wait_timeout(Duration::ZERO)); + shared.cancel(); + assert!(cancel.is_cancelled()); + assert!(cancel.wait_timeout(Duration::ZERO)); + cancel.wait(); +} + +// A thread blocked in `wait` returns once another thread cancels. The 60-second bound only fails +// the test when the wake never comes. +#[test] +fn cancel_wait_returns_once_another_thread_cancels() { + let cancel = Cancel::new(); + let (started, has_started) = mpsc::channel(); + let (returned, has_returned) = mpsc::channel(); + let waiter = { + let cancel = cancel.clone(); + thread::spawn(move || { + let _ = started.send(()); + cancel.wait(); + let _ = returned.send(()); + }) + }; + has_started.recv().expect("the waiter starts"); + assert_eq!(has_returned.try_recv(), Err(TryRecvError::Empty), "wait returned before the cancel"); + cancel.cancel(); + has_returned.recv_timeout(Duration::from_secs(60)).expect("wait returns after the cancel"); + waiter.join().expect("the waiter ends"); +} + +// A running job blocked in `wait` ends when the queue drops its key, and its result never arrives. +#[test] +fn a_job_waiting_on_its_cancel_ends_when_its_key_is_dropped() { + let (queue, jobs, wakes) = queue(1); + let (started, has_started) = mpsc::channel(); + queue.submit("running", Priority::VISIBLE, move |cancel: &Cancel| { + let _ = started.send(()); + cancel.wait(); + "running" + }); + let (ran, has_run) = mpsc::channel(); + let lane = thread::spawn(move || { + let _ = ran.send(jobs.run_all()); + }); + has_started.recv().expect("the job starts"); + assert_eq!(queue.reprioritize(|_, _| None), ["running"]); + assert_eq!(has_run.recv_timeout(Duration::from_secs(60)), Ok(1), "the job ends after the cancel"); + lane.join().expect("the lane ends"); + assert!(drain(&queue).is_empty()); + assert_eq!(wakes.load(Ordering::Relaxed), 0); +} + // The wake is called once per finished job, never for a dropped or cancelled one. // With `lanes == 0` nothing runs on submit; `run_inline(1)` runs the best job and returns 1. diff --git a/crates/i18n/src/scripts.rs b/crates/i18n/src/scripts.rs index 2ce64ae78b..214c5b981e 100644 --- a/crates/i18n/src/scripts.rs +++ b/crates/i18n/src/scripts.rs @@ -324,6 +324,9 @@ impl Subtags { let base = tag.split(['.', '@']).next().unwrap_or("").replace('_', "-"); let mut parts = base.split('-').filter(|p| !p.is_empty()); let language = parts.next().unwrap_or("").to_owned(); + if language.len() == 1 { + return Subtags { language, script: None, region: None }; + } let mut script = match tag.split_once('@').map(|(_, m)| m) { Some("latin") => Some("latn".to_owned()), Some("cyrillic") => Some("cyrl".to_owned()), @@ -331,6 +334,11 @@ impl Subtags { }; let mut region = None; for part in parts { + // Stop at BCP 47 extension or private-use singletons (`-u-`, `-t-`, `-x-`) so their + // subtags are never mistaken for a script or region. + if part.len() == 1 { + break; + } if part.len() == 4 && part.bytes().all(|b| b.is_ascii_alphabetic()) { script.get_or_insert_with(|| part.to_owned()); } else if super::is_region(part) { diff --git a/crates/i18n/src/tests.rs b/crates/i18n/src/tests.rs index 2a3669dece..fe6254cd63 100644 --- a/crates/i18n/src/tests.rs +++ b/crates/i18n/src/tests.rs @@ -316,3 +316,23 @@ fn plural_forms_follow_cldr_for_every_offered_language() { assert_eq!(found.len(), 1, "{found:?}"); assert!(found[0].starts_with("de/common: line 1: expected 2"), "{found:?}"); } + +#[test] +fn extensions_and_private_use_do_not_set_script_or_region() { + use Script::{Guru, Hebr, Latn}; + for (tag, want, dir) in [ + ("en-u-arab", &[Latn][..], Direction::Ltr), + ("en-u-nu-arab", &[Latn], Direction::Ltr), + ("en-t-hebr", &[Latn], Direction::Ltr), + ("en-x-arab", &[Latn], Direction::Ltr), + ("x-arab", &[Latn], Direction::Ltr), + ("x-he-arab", &[Latn], Direction::Ltr), + ("he-u-latn", &[Hebr], Direction::Rtl), + ("he-u-nu-latn", &[Hebr], Direction::Rtl), + ("sr-Latn-u-arab", &[Latn], Direction::Ltr), + ("pa-u-pk", &[Guru], Direction::Ltr), + ] { + assert_eq!(scripts(tag), want, "{tag}"); + assert_eq!(direction(tag), dir, "{tag}"); + } +} diff --git a/crates/ical/src/values.rs b/crates/ical/src/values.rs index 1f75a804d7..1cd021bef8 100644 --- a/crates/ical/src/values.rs +++ b/crates/ical/src/values.rs @@ -49,9 +49,12 @@ pub(crate) fn valid_time(t: NaiveDateTime) -> NaiveDateTime { /// A date from `YYYY-MM-DD` or `YYYYMMDD`, years 1 to 9999. fn parse_iso_date(s: &str) -> Option { - let s = s.trim(); - let digits: String = s.chars().filter(char::is_ascii_digit).collect(); - if digits.len() != 8 || s.chars().any(|c| !c.is_ascii_digit() && c != '-') { + let digits: String = match s.len() { + 8 => s.to_string(), + 10 if s.as_bytes().get(4) == Some(&b'-') && s.as_bytes().get(7) == Some(&b'-') => s.chars().filter(char::is_ascii_digit).collect(), + _ => return None, + }; + if digits.len() != 8 || !digits.bytes().all(|b| b.is_ascii_digit()) { return None; } let year: i32 = digits.get(0..4)?.parse().ok()?; @@ -293,6 +296,12 @@ mod tests { "20261312", "20260230", "00000101", + "2026-1011", + "-20261012", + "20-261012", + "20261012-", + "2026101-2T090000", + "20261012 T090000", "20261012T", "20261012T25", "20261012T240000", diff --git a/crates/image-codecs/src/codecs/avif.rs b/crates/image-codecs/src/codecs/avif.rs index 042b5684b1..062b3f0539 100644 --- a/crates/image-codecs/src/codecs/avif.rs +++ b/crates/image-codecs/src/codecs/avif.rs @@ -225,7 +225,7 @@ pub fn encode_avif_hdr( mod tests { #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] #[test] - fn sdr_avif_uses_requested_alpha_quality() { + fn feature_config_sdr_avif_uses_requested_alpha_quality() { use crate::{ChannelLayout, Image}; let pixels: Vec = (0..1024).map(|i| ravif::RGBA8::new(100, 120, 140, ((i * 37) % 256) as u8)).collect(); @@ -246,7 +246,7 @@ mod tests { #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] #[test] - fn sdr_avif_keeps_exif_metadata() { + fn feature_config_sdr_avif_keeps_exif_metadata() { use crate::{ChannelLayout, Image}; let exif = b"II*\0shared-avif-exif".to_vec(); @@ -259,7 +259,7 @@ mod tests { #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] #[test] - fn hlg_mapping_matches_reference_white_and_peak() { + fn feature_config_hlg_mapping_matches_reference_white_and_peak() { let white = super::hlg_signal([1.0; 3]); assert!(white.iter().all(|&value| (value - 0.75).abs() < 0.005), "{white:?}"); @@ -272,7 +272,7 @@ mod tests { #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] #[test] - fn hlg_encoded_output_signals_bt2020_hlg() { + fn feature_config_hlg_encoded_output_signals_bt2020_hlg() { let avif = super::encode_avif_hdr(1, 1, &[1.0; 3], 100, 10, None, super::HdrTransfer::Hlg).unwrap(); let nclx = avif.windows(4).position(|window| window == b"nclx").expect("the AVIF has nclx color metadata"); let color = avif.get(nclx + 4..nclx + 11).expect("complete nclx color metadata"); @@ -284,7 +284,7 @@ mod tests { #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] #[test] - fn hlg_encoded_pixels_preserve_reference_white_and_peak() { + fn feature_config_hlg_encoded_pixels_preserve_reference_white_and_peak() { let mut rgb = Vec::new(); for _ in 0..32 { for x in 0..64 { diff --git a/crates/image-codecs/src/codecs/avif_decode.rs b/crates/image-codecs/src/codecs/avif_decode.rs index 4435da66bf..22f1f8aaec 100644 --- a/crates/image-codecs/src/codecs/avif_decode.rs +++ b/crates/image-codecs/src/codecs/avif_decode.rs @@ -1004,7 +1004,7 @@ mod tests { } #[test] - fn libaom_420_limited_range_matches_dav1d() { + fn feature_config_libaom_420_limited_range_matches_dav1d() { let img = crate::decode(QUAD_420).unwrap(); assert_eq!((img.width(), img.height(), img.layout(), img.sample_type()), (33, 17, ChannelLayout::Rgb, SampleType::U8)); assert_eq!(img.cicp.map(|c| (c.matrix, c.full_range)), Some((1, false)), "BT.709 matrix, limited range"); @@ -1025,7 +1025,7 @@ mod tests { } #[test] - fn libaom_lossless_identity_matrix_is_exact() { + fn feature_config_libaom_lossless_identity_matrix_is_exact() { let img = crate::decode(QUAD_GBR_LOSSLESS).unwrap(); assert_eq!((img.width(), img.height(), img.sample_type()), (33, 17, SampleType::U8)); assert_eq!(img.cicp.map(|c| (c.matrix, c.full_range)), Some((0, true))); @@ -1033,7 +1033,7 @@ mod tests { } #[test] - fn limits_are_checked_before_decoding() { + fn feature_config_limits_are_checked_before_decoding() { let tight = |max_pixels, max_alloc| DecodeOptions { limits: Limits { max_pixels, max_alloc, ..Limits::default() }, ..Default::default() }; assert!(matches!(crate::decode_with(QUAD_420, &tight(33 * 17 - 1, u64::MAX)), Err(CodecError::LimitExceeded(_)))); // The 16-bit intermediate counts: 33 × 17 RGB at 2 bytes. @@ -1049,14 +1049,14 @@ mod tests { } #[test] - fn a_picture_that_differs_from_its_ispe_is_refused() { + fn feature_config_a_picture_that_differs_from_its_ispe_is_refused() { let (av1, cfg) = av1_of(QUAD_420); let file = build(&[(1, b"av01", &av1, &[1, 2])], &[ispe(32, 17), bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat())], &[]); assert!(matches!(crate::decode(&file), Err(CodecError::Malformed { .. }))); } #[test] - fn a_grid_is_assembled_from_its_tiles_and_cropped() { + fn feature_config_a_grid_is_assembled_from_its_tiles_and_cropped() { // Two copies of the 33 × 17 picture side by side, cropped to 60 × 15 by the grid. let (av1, cfg) = av1_of(QUAD_GBR_LOSSLESS); let av1c = bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat()); @@ -1087,7 +1087,7 @@ mod tests { } #[test] - fn container_rotation_and_mirror_are_applied_unless_kept() { + fn feature_config_container_rotation_and_mirror_are_applied_unless_kept() { let (av1, cfg) = av1_of(QUAD_GBR_LOSSLESS); let av1c = bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat()); let file = build(&[(1, b"av01", &av1, &[1, 2, 3, 4])], &[ispe(33, 17), av1c, bx(b"irot", &[1]), bx(b"imir", &[0])], &[]); @@ -1112,7 +1112,7 @@ mod tests { } #[test] - fn clean_aperture_sizes_are_unsigned() { + fn feature_config_clean_aperture_sizes_are_unsigned() { let (av1, cfg) = av1_of(QUAD_GBR_LOSSLESS); let av1c = bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat()); // A 2 × 2 aperture with its width written as 0x80000000 / 0x40000000, centred one pixel @@ -1134,7 +1134,7 @@ mod tests { } #[test] - fn repeated_transforms_are_refused() { + fn feature_config_repeated_transforms_are_refused() { let (av1, cfg) = av1_of(QUAD_GBR_LOSSLESS); let av1c = bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat()); // the same irot associated twice, and through two ipma entries for the item @@ -1171,7 +1171,7 @@ mod tests { } #[test] - fn alpha_with_transforms_of_its_own_is_refused() { + fn feature_config_alpha_with_transforms_of_its_own_is_refused() { let (av1, cfg) = av1_of(QUAD_GBR_LOSSLESS); let av1c = bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat()); let auxc = fbx(b"auxC", b"urn:mpeg:mpegB:cicp:systems:auxiliary:alpha\0"); @@ -1188,7 +1188,7 @@ mod tests { } #[test] - fn transforms_rotate_mirror_and_crop() { + fn feature_config_transforms_rotate_mirror_and_crop() { // 3 × 2, one channel, value = index let cv = || Canvas { w: 3, h: 2, ch: 1, data: (0..6).collect() }; let r = apply_transforms(cv(), &[Transform::Rot(1)]); @@ -1206,7 +1206,7 @@ mod tests { } #[test] - fn hostile_files_are_errors_not_panics() { + fn feature_config_hostile_files_are_errors_not_panics() { for file in [QUAD_420, QUAD_GBR_LOSSLESS] { // every truncation for n in 0..file.len() { @@ -1233,14 +1233,14 @@ mod tests { } #[test] - fn an_animated_avif_is_unsupported() { + fn feature_config_an_animated_avif_is_unsupported() { let mut b = bx(b"ftyp", b"avis\0\0\0\0avis"); b.extend(bx(b"moov", &[])); assert!(matches!(crate::decode(&b), Err(CodecError::Unsupported { format: Format::Avif, .. }))); } #[test] - fn zero_width_iloc_extents_are_capped() { + fn feature_config_zero_width_iloc_extents_are_capped() { // iloc v2 with zero-byte offset/length/base/index fields: each extent costs no input bytes let mut iloc = vec![2, 0, 0, 0, 0, 0]; iloc.extend_from_slice(&3u32.to_be_bytes()); @@ -1256,7 +1256,7 @@ mod tests { } #[test] - fn item_data_larger_than_the_file_is_refused() { + fn feature_config_item_data_larger_than_the_file_is_refused() { // one item whose 1000 extents each repeat the whole file (length 0 = to the end) let mut iloc = vec![1, 0, 0, 0, 0x44, 0]; iloc.extend_from_slice(&1u16.to_be_bytes()); @@ -1275,7 +1275,7 @@ mod tests { } #[test] - fn unsupported_matrices_are_errors() { + fn feature_config_unsupported_matrices_are_errors() { for m in [8u16, 10, 11, 13, 14] { assert!(matches!(coefficients(m, 1), Err(CodecError::Unsupported { .. })), "{m}"); } @@ -1311,7 +1311,7 @@ mod tests { } #[test] - fn ravif_rgb_round_trip_is_10_bit() { + fn feature_config_ravif_rgb_round_trip_is_10_bit() { let (w, h) = (48, 32); let src = Image::from_u8(w as u32, h as u32, ChannelLayout::Rgb, card(w, h, 3)).unwrap(); let file = encode_avif_with_speed(&src, 95, 10).unwrap(); @@ -1325,7 +1325,7 @@ mod tests { } #[test] - fn ravif_alpha_round_trips() { + fn feature_config_ravif_alpha_round_trips() { let (w, h) = (40, 24); let src = Image::from_u8(w as u32, h as u32, ChannelLayout::Rgba, card(w, h, 4)).unwrap(); let file = encode_avif_with_speed(&src, 95, 10).unwrap(); @@ -1339,7 +1339,7 @@ mod tests { } #[test] - fn exif_is_read_from_its_item() { + fn feature_config_exif_is_read_from_its_item() { let mut src = Image::from_u8(16, 8, ChannelLayout::Rgb, card(16, 8, 3)).unwrap(); let exif = b"II*\0\x08\0\0\0\0\0\0\0\0\0".to_vec(); src.meta.exif = Some(exif.clone()); @@ -1349,7 +1349,7 @@ mod tests { } #[test] - fn hdr_round_trips_keep_highlights_above_white() { + fn feature_config_hdr_round_trips_keep_highlights_above_white() { let (w, h) = (32usize, 16usize); // linear BT.2020: left half grey 0.18, right half 4 × SDR white let rgb: Vec = (0..w * h).flat_map(|i| if i % w < w / 2 { [0.18f32; 3] } else { [4.0; 3] }).collect(); diff --git a/crates/image-codecs/src/codecs/heif.rs b/crates/image-codecs/src/codecs/heif.rs index c3fb33508e..40c392d20a 100644 --- a/crates/image-codecs/src/codecs/heif.rs +++ b/crates/image-codecs/src/codecs/heif.rs @@ -95,7 +95,7 @@ mod tests { #[cfg(not(feature = "heif"))] #[test] - fn without_the_feature_heif_is_a_clear_unsupported_error() { + fn feature_config_without_the_feature_heif_is_a_clear_unsupported_error() { let header = b"\0\0\0\x18ftypheic\0\0\0\0mif1heic"; assert_eq!(crate::detect(header), Some(F), "still recognised"); let r = crate::decode(header); @@ -108,7 +108,7 @@ mod tests { #[cfg(feature = "heif")] #[test] - fn with_the_feature_heif_is_readable_and_errors_map() { + fn feature_config_with_the_feature_heif_is_readable_and_errors_map() { assert!(crate::caps(F).read); let r = crate::decode(b"\0\0\0\x18ftypmsf1\0\0\0\0msf1hevc"); assert!(matches!(&r, Err(CodecError::Unsupported { format: Format::Heif, reason }) if reason.contains("sequence")), "{r:?}"); @@ -127,7 +127,7 @@ mod tests { #[cfg(feature = "heif")] #[test] - fn a_heic_rs_panic_is_a_malformed_file_error() { + fn feature_config_a_heic_rs_panic_is_a_malformed_file_error() { assert_eq!(crate::detect(&HEIC_RS_BOX_PANIC), Some(Format::Heif)); for opts in [crate::DecodeOptions::default(), crate::DecodeOptions { keep_orientation: true, ..Default::default() }] { let r = crate::decode_with(&HEIC_RS_BOX_PANIC, &opts); diff --git a/crates/image-codecs/src/codecs/png.rs b/crates/image-codecs/src/codecs/png.rs index e68c9acefe..b3332f7f77 100644 --- a/crates/image-codecs/src/codecs/png.rs +++ b/crates/image-codecs/src/codecs/png.rs @@ -1757,7 +1757,8 @@ fn deflate_rows( /// and completes the flush: when a sync flush fills the buffer, miniz_oxide (flate2's former Rust /// backend) can return before compressing the last lookahead bytes, and the next call only /// drains the pending output, so a resumed flush silently drops data. `None` (the caller then -/// uses the serial encoder) if the single call did not finish. +/// uses the serial encoder) if the single call did not finish. The returned bytes keep no +/// spare capacity, because the caller holds every band until it joins them into one stream. fn deflate_band(filtered: &[u8], lvl: flate2::Compression, last: bool) -> Option> { let mut c = flate2::Compress::new(lvl, false); // Stored blocks cost 5 bytes per 64 KiB, the flush an empty stored block: 1/8 is ample. @@ -1766,7 +1767,10 @@ fn deflate_band(filtered: &[u8], lvl: flate2::Compression, last: bool) -> Option let flush = if last { flate2::FlushCompress::Finish } else { flate2::FlushCompress::Sync }; let status = c.compress_vec(filtered, &mut z, flush).ok()?; let done = if last { status == flate2::Status::StreamEnd } else { c.total_in() as usize == filtered.len() && z.len() < z.capacity() }; - done.then_some(z) + done.then(|| { + z.shrink_to_fit(); + z + }) } /// One scanline with the adaptive filter choice, appended to `out` (type byte + data). @@ -2256,6 +2260,19 @@ mod parallel_tests { } } + /// Every band is held until the stream is joined, so a band keeps only the bytes it holds, + /// not the worst-case buffer it was deflated into (about 1.125 times the image in all). + #[test] + fn deflated_bands_keep_no_spare_capacity() { + let (w, h, bpp) = (1024usize, 600usize, 3usize); + let px: Vec = (0..w * h * bpp).map(|i| (i % 7) as u8).collect(); + let parts = deflate_rows(&px, None, w * bpp, bpp, band_rows(w * bpp), flate2::Compression::default(), true, 2).unwrap(); + assert!(parts.len() > 2); + for (i, p) in parts.iter().enumerate() { + assert!(p.z.capacity() <= p.z.len() + 64, "band {i}: capacity {} for {} bytes of {}", p.z.capacity(), p.z.len(), p.len); + } + } + /// The bytes depend on the image, not on the machine: one, two and 32 worker threads /// (and the machine's own count, through `encode`) give the same stream. #[test] @@ -2365,10 +2382,15 @@ mod streamed_tests { xmp: Some("".into()), ..Default::default() }; - let img = Image::from_raw(w, h, layout, sample, noise(w as usize * h as usize * ch * bytes, 7)) - .unwrap() - .with_icc(Some((0..600u32).map(|i| (i % 251) as u8).collect())) - .with_meta(meta); + // Distinct nonconstant row runs retain carry and row-order sensitivity across pushes. + let stride = w as usize * ch * bytes; + let row = noise(stride, 7); + let mut pixels = row.repeat(h as usize); + for row in pixels.chunks_exact_mut(stride).skip(h as usize / 2) { + row[0] ^= 0x5a; + } + let img = + Image::from_raw(w, h, layout, sample, pixels).unwrap().with_icc(Some((0..600u32).map(|i| (i % 251) as u8).collect())).with_meta(meta); for level in [PngCompression::Fast, PngCompression::Default] { let opts = EncodeOptions { png_compression: level, ..Default::default() }; let one_band = [h]; diff --git a/crates/image-codecs/src/codecs/sgi.rs b/crates/image-codecs/src/codecs/sgi.rs index 64c80299c3..25a4cbf149 100644 --- a/crates/image-codecs/src/codecs/sgi.rs +++ b/crates/image-codecs/src/codecs/sgi.rs @@ -276,7 +276,7 @@ mod tests { } #[test] - fn rle_round_trips_every_layout_in_8_bits() { + fn feature_config_rle_round_trips_every_layout_in_8_bits() { for layout in [ChannelLayout::Gray, ChannelLayout::GrayA, ChannelLayout::Rgb, ChannelLayout::Rgba] { let img = gradient(37, 11, layout); let plan = Plan { layout, sample: SampleType::U8 }; @@ -289,7 +289,7 @@ mod tests { } #[test] - fn rle_round_trips_16_bits_with_long_runs() { + fn feature_config_rle_round_trips_16_bits_with_long_runs() { let (w, h) = (300u32, 4u32); let samples: Vec = (0..w * h * 3).map(|i| if (i / 3) % 200 < 150 { 4242 } else { (i * 31) as u16 }).collect(); let img = Image::from_u16(w, h, ChannelLayout::Rgb, &samples).unwrap(); @@ -301,7 +301,7 @@ mod tests { /// A hand-built verbatim file: two rows, one plane, stored bottom to top. #[test] - fn verbatim_files_read_bottom_to_top() { + fn feature_config_verbatim_files_read_bottom_to_top() { let mut f = vec![0u8; HEADER]; f[0..2].copy_from_slice(&MAGIC.to_be_bytes()); f[2] = 0; // verbatim @@ -317,7 +317,7 @@ mod tests { } #[test] - fn hostile_input_is_an_error_not_a_panic() { + fn feature_config_hostile_input_is_an_error_not_a_panic() { let img = gradient(16, 8, ChannelLayout::Rgb); let good = encode(&img, Plan { layout: ChannelLayout::Rgb, sample: SampleType::U8 }).unwrap(); // Every truncation fails cleanly. @@ -361,7 +361,7 @@ mod tests { /// The format lets table entries share one compressed row: eight rows, one payload. #[test] - fn rows_may_share_compressed_data() { + fn feature_config_rows_may_share_compressed_data() { let table = HEADER + 8 * 8; let f = rle_file(1, &[table as u32; 8], 3, &[0x81, 255, 0]); assert_eq!(f.len(), table + 3); @@ -371,7 +371,7 @@ mod tests { /// Compressed rows start after both tables: an offset into a table is refused. #[test] - fn rows_may_not_start_inside_the_offset_tables() { + fn feature_config_rows_may_not_start_inside_the_offset_tables() { // 3x1: the tables end at 520; 515 reads the table's own bytes as a packet list. let f = rle_file(3, &[515], 3, &[0, 0, 0, 0, 0]); assert!(decode(&f, &Limits::default()).is_err()); @@ -380,13 +380,13 @@ mod tests { /// FFmpeg's decoder, run as an oracle, also reads a row that ends with its last packet and no /// zero terminator; so does this one. #[test] - fn a_row_without_its_terminator_still_reads() { + fn feature_config_a_row_without_its_terminator_still_reads() { let f = rle_file(1, &[520], 2, &[0x81, 42]); assert_eq!(decode(&f, &Limits::default()).unwrap().data(), &[42]); } #[test] - fn palette_mapped_files_are_unsupported() { + fn feature_config_palette_mapped_files_are_unsupported() { let img = gradient(4, 4, ChannelLayout::Gray); let mut f = encode(&img, Plan { layout: ChannelLayout::Gray, sample: SampleType::U8 }).unwrap(); f[104..108].copy_from_slice(&1u32.to_be_bytes()); diff --git a/crates/image-codecs/src/codecs/sunraster.rs b/crates/image-codecs/src/codecs/sunraster.rs index 85c24acc51..d39af21ffd 100644 --- a/crates/image-codecs/src/codecs/sunraster.rs +++ b/crates/image-codecs/src/codecs/sunraster.rs @@ -192,7 +192,7 @@ mod tests { } #[test] - fn round_trips_gray_rgb_and_rgba_with_odd_widths() { + fn feature_config_round_trips_gray_rgb_and_rgba_with_odd_widths() { for layout in [ChannelLayout::Gray, ChannelLayout::Rgb, ChannelLayout::Rgba] { let img = pattern(13, 7, layout); let bytes = encode(&img, Plan { layout, sample: SampleType::U8 }).unwrap(); @@ -213,7 +213,7 @@ mod tests { } #[test] - fn standard_type_is_blue_first_and_rle_expands() { + fn feature_config_standard_type_is_blue_first_and_rle_expands() { let f = file(24, 1, &[], 0, 1, 1, &[1, 2, 3, 0]); assert_eq!(decode(&f, &Limits::default()).unwrap().data(), &[3, 2, 1]); // 0x80 0x00 is a literal 0x80; 0x80 n v is n + 1 copies of v. The 2x2 image has stride 2. @@ -224,7 +224,7 @@ mod tests { } #[test] - fn colour_mapped_and_one_bit_files() { + fn feature_config_colour_mapped_and_one_bit_files() { // Two entries: red plane, green plane, blue plane. let map = [10, 20, 30, 40, 50, 60]; let f = file(8, 1, &map, 1, 2, 1, &[0, 1]); @@ -237,7 +237,7 @@ mod tests { } #[test] - fn one_bit_files_with_a_colour_map_read_as_colour() { + fn feature_config_one_bit_files_with_a_colour_map_read_as_colour() { // Two entries: red plane, green plane, blue plane; bit 0 is entry 0. let map = [10, 20, 30, 40, 50, 60]; let f = file(1, 1, &map, 1, 3, 1, &[0b0100_0000, 0]); @@ -248,7 +248,7 @@ mod tests { } #[test] - fn the_unused_first_byte_of_standard_32_bit_pixels_is_not_alpha() { + fn feature_config_the_unused_first_byte_of_standard_32_bit_pixels_is_not_alpha() { let img = decode(&file(32, 1, &[], 0, 1, 1, &[0, 30, 20, 10]), &Limits::default()).unwrap(); assert_eq!((img.layout(), img.data()), (ChannelLayout::Rgba, &[10, 20, 30, 255][..])); // In the RGB-ordered type the first byte is the alpha the writer stores there. @@ -257,13 +257,13 @@ mod tests { } #[test] - fn an_output_buffer_too_large_to_allocate_is_an_error() { + fn feature_config_an_output_buffer_too_large_to_allocate_is_an_error() { assert!(reserve(usize::MAX).is_err()); assert!(reserve(16).is_ok()); } #[test] - fn hostile_input_is_an_error_not_a_panic() { + fn feature_config_hostile_input_is_an_error_not_a_panic() { let img = pattern(9, 5, ChannelLayout::Rgb); let good = encode(&img, Plan { layout: ChannelLayout::Rgb, sample: SampleType::U8 }).unwrap(); for len in 0..good.len() { diff --git a/crates/image-codecs/src/codecs/tiff/decode.rs b/crates/image-codecs/src/codecs/tiff/decode.rs index c365d01581..dcccadde66 100644 --- a/crates/image-codecs/src/codecs/tiff/decode.rs +++ b/crates/image-codecs/src/codecs/tiff/decode.rs @@ -747,8 +747,8 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result = REAL_FILES.iter().map(|f| f.0).collect(); let pinned: Vec<&str> = REAL_FILE_SHA256.iter().map(|p| p.0).collect(); diff --git a/crates/image-codecs/tests/it/detect_caps.rs b/crates/image-codecs/tests/it/detect_caps.rs index f6c4808ffa..1333053107 100644 --- a/crates/image-codecs/tests/it/detect_caps.rs +++ b/crates/image-codecs/tests/it/detect_caps.rs @@ -10,7 +10,7 @@ use craft_image_codecs::*; // --------------------------------------------------------------------------- #[test] -fn every_enabled_format_is_symmetric_or_whitelisted() { +fn feature_config_every_enabled_format_is_symmetric_or_whitelisted() { for f in Format::ALL { let c = caps(f); if !(c.read || c.write) { @@ -34,7 +34,7 @@ fn exceptions_are_documented_and_unique() { } #[test] -fn never_write_only_without_exception() { +fn feature_config_never_write_only_without_exception() { // Stronger form: no format may be writable-but-unreadable unless listed. for f in writable_formats() { if !caps(f).read { @@ -44,7 +44,7 @@ fn never_write_only_without_exception() { } #[test] -fn default_build_formats_all_symmetric() { +fn feature_config_default_build_formats_all_symmetric() { let expected = [ Format::Png, Format::Jpeg, @@ -74,7 +74,7 @@ fn default_build_formats_all_symmetric() { } #[test] -fn avif_is_readable_only_with_the_decode_feature() { +fn feature_config_avif_is_readable_only_with_the_decode_feature() { assert_eq!(caps(Format::Avif).read, cfg!(all(feature = "avif-decode", not(target_arch = "wasm32")))); assert_eq!(caps(Format::Avif).write, cfg!(feature = "avif")); let header = decode_as(Format::Avif, b"\0\0\0\x1cftypavif"); @@ -86,7 +86,7 @@ fn avif_is_readable_only_with_the_decode_feature() { } #[test] -fn heif_is_detected_always_and_readable_only_with_the_feature() { +fn feature_config_heif_is_detected_always_and_readable_only_with_the_feature() { let header = b"\0\0\0\x18ftypheic\0\0\0\0mif1heic"; assert_eq!(detect(header), Some(Format::Heif)); assert_eq!(from_extension("IMG_0001.HEIC"), Some(Format::Heif)); @@ -149,7 +149,7 @@ fn caps_are_internally_consistent() { } #[test] -fn caps_function_matches_method() { +fn feature_config_caps_function_matches_method() { for f in Format::ALL { assert_eq!(caps(f), f.caps()); } @@ -160,7 +160,7 @@ fn caps_function_matches_method() { // --------------------------------------------------------------------------- #[test] -fn detect_encoded_output_of_every_format() { +fn feature_config_detect_encoded_output_of_every_format() { for f in writable_formats() { let img = test_image(ChannelLayout::Rgba, SampleType::U8); let bytes = encode(&img, f, &EncodeOptions::default()).unwrap(); @@ -258,7 +258,7 @@ fn detect_magic_iff() { } #[cfg(feature = "sgi")] #[test] -fn detect_magic_sgi() { +fn feature_config_detect_magic_sgi() { use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, encode}; let img = Image::from_u8(5, 3, ChannelLayout::Rgba, (0..60).collect()).unwrap(); let bytes = encode(&img, Format::Sgi, &EncodeOptions::default()).unwrap(); @@ -522,7 +522,7 @@ fn a_detector_keeps_its_place_between_calls() { #[cfg(feature = "sunraster")] #[test] -fn detect_magic_sun_raster() { +fn feature_config_detect_magic_sun_raster() { use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, encode}; let img = Image::from_u8(5, 3, ChannelLayout::Rgb, (0..45).collect()).unwrap(); let bytes = encode(&img, Format::SunRaster, &EncodeOptions::default()).unwrap(); @@ -626,7 +626,7 @@ fn extensions_unique_across_formats() { #[cfg(not(feature = "sgi"))] #[test] -fn sgi_requires_explicit_feature() { +fn feature_config_sgi_requires_explicit_feature() { use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, encode}; assert!(!caps(Format::Sgi).read && !caps(Format::Sgi).write); assert!(decode_as(Format::Sgi, &[]).is_err()); @@ -639,7 +639,7 @@ fn sgi_requires_explicit_feature() { #[cfg(not(feature = "sunraster"))] #[test] -fn sun_raster_disabled_by_default() { +fn feature_config_sun_raster_disabled_by_default() { use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, encode}; let bytes = [0x59, 0xa6, 0x6a, 0x95, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 8, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 42, 0]; assert_ne!(detect(&bytes), Some(Format::SunRaster)); diff --git a/crates/image-codecs/tests/it/fidelity.rs b/crates/image-codecs/tests/it/fidelity.rs index cad19485ef..317e9ec3ca 100644 --- a/crates/image-codecs/tests/it/fidelity.rs +++ b/crates/image-codecs/tests/it/fidelity.rs @@ -184,7 +184,7 @@ fn ico_oversize_is_fatal() { assert!(w.contains(&W::DimensionsExceeded { max_width: 256, max_height: 256 })); } #[test] -fn avif_default_build_write_unsupported() { +fn feature_config_avif_default_build_write_unsupported() { let w = warns(&test_image(ChannelLayout::Rgb, SampleType::U8), Format::Avif); if cfg!(feature = "avif") { assert!(w.contains(&W::LossyCompression)); @@ -221,7 +221,7 @@ fn every_warning_has_a_message() { /// The warnings must agree with what actually comes back from the file. #[test] -fn warnings_match_actual_roundtrip_behaviour() { +fn feature_config_warnings_match_actual_roundtrip_behaviour() { // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs every N-th format, layout and sample type. let step = craft_media_testkit::hostile::divisor(); let mut index = 0usize; diff --git a/crates/image-codecs/tests/it/heif.rs b/crates/image-codecs/tests/it/heif.rs index 07c15f65eb..be2abc15b1 100644 --- a/crates/image-codecs/tests/it/heif.rs +++ b/crates/image-codecs/tests/it/heif.rs @@ -61,7 +61,7 @@ fn keep() -> DecodeOptions { } #[test] -fn heif_is_read_only_and_listed() { +fn feature_config_heif_is_read_only_and_listed() { let c = caps(Format::Heif); assert!(c.read && !c.write); assert!(ASYMMETRIC_EXCEPTIONS.iter().any(|(f, _)| *f == Format::Heif)); @@ -74,14 +74,14 @@ fn heif_is_read_only_and_listed() { } #[test] -fn detect_heif_brands() { +fn feature_config_detect_heif_brands() { for f in [checker_64(), strips_96(), checker_grid(), with_exif()] { assert_eq!(detect(f), Some(Format::Heif)); } } #[test] -fn single_picture_matches_apple_decode() { +fn feature_config_single_picture_matches_apple_decode() { for (heic, png) in [(checker_64(), "heic-rs/checker-64.ref.png"), (strips_96(), "heic-rs/rgb-strips-96.ref.png")] { let img = decode(heic).unwrap(); let want = reference(&corpus(png)); @@ -93,7 +93,7 @@ fn single_picture_matches_apple_decode() { } #[test] -fn grid_tiled_photo_matches_apple_decode() { +fn feature_config_grid_tiled_photo_matches_apple_decode() { // iPhone photos are grids of 512x512 HEVC tiles: here 2x2. let img = decode(checker_grid()).unwrap(); let want = reference(&corpus("heic-rs/checker-1024.ref.png")); @@ -102,7 +102,7 @@ fn grid_tiled_photo_matches_apple_decode() { } #[test] -fn rgb_strips_keep_their_colours() { +fn feature_config_rgb_strips_keep_their_colours() { // Three vertical strips, pure red, green and blue: catches swapped channels or matrices. let img = decode(strips_96()).unwrap(); for (x, c) in [(16, 0), (48, 1), (80, 2)] { @@ -114,7 +114,7 @@ fn rgb_strips_keep_their_colours() { } #[test] -fn container_rotation_is_applied_once() { +fn feature_config_container_rotation_is_applied_once() { // irot 1 = 90° anticlockwise: the red strip (left) ends at the bottom, blue (right) on top. let rotated = with_irot(strips_96(), 1); let img = decode(&rotated).unwrap(); @@ -126,7 +126,7 @@ fn container_rotation_is_applied_once() { } #[test] -fn exif_and_xmp_survive_and_exif_orientation_is_not_applied_twice() { +fn feature_config_exif_and_xmp_survive_and_exif_orientation_is_not_applied_twice() { // HEIF's EXIF Orientation repeats what irot says; the container is the authority. let tagged = with_exif_orientation(with_exif(), 6); let img = decode(&tagged).unwrap(); @@ -142,7 +142,7 @@ fn exif_and_xmp_survive_and_exif_orientation_is_not_applied_twice() { } #[test] -fn limits_are_checked_before_decoding() { +fn feature_config_limits_are_checked_before_decoding() { let tight = |limits| DecodeOptions { limits, ..Default::default() }; let small = Limits { max_width: 512, ..Default::default() }; assert!(matches!(decode_with(checker_grid(), &tight(small)), Err(CodecError::LimitExceeded(_)))); @@ -153,7 +153,7 @@ fn limits_are_checked_before_decoding() { } #[test] -fn unsupported_and_broken_files_are_clear_errors() { +fn feature_config_unsupported_and_broken_files_are_clear_errors() { // An ftyp and nothing else: a HEIF image sequence would have a moov here instead of a meta. let r = decode(b"\0\0\0\x18ftypmsf1\0\0\0\0msf1hevc"); assert!(matches!(&r, Err(CodecError::Unsupported { format: Format::Heif, reason }) if reason.contains("sequence")), "{r:?}"); @@ -162,7 +162,7 @@ fn unsupported_and_broken_files_are_clear_errors() { } #[test] -fn every_truncation_errors_or_decodes_never_panics() { +fn feature_config_every_truncation_errors_or_decodes_never_panics() { for bytes in [checker_64(), strips_96(), checker_grid()] { for cut in 0..bytes.len() { let _ = decode_as(Format::Heif, &bytes[..cut]); @@ -171,7 +171,7 @@ fn every_truncation_errors_or_decodes_never_panics() { } #[test] -fn ten_bit_with_alpha_decodes_to_16_bit_rgba() { +fn feature_config_ten_bit_with_alpha_decodes_to_16_bit_rgba() { // pillow-heif's fixture: a 16-bit RGBA gradient (the .src.png) encoded as 10-bit HEIF by libheif/x265. let img = decode(&corpus("pillow-heif/heif/RGBA_10__29x100.heif")).unwrap(); let src = decode_as(Format::Png, &corpus("pillow-heif/non_heif/RGBA_16__29x100.png")).unwrap(); diff --git a/crates/image-codecs/tests/it/jxl_decode.rs b/crates/image-codecs/tests/it/jxl_decode.rs index fad3b51d1f..10bceb4370 100644 --- a/crates/image-codecs/tests/it/jxl_decode.rs +++ b/crates/image-codecs/tests/it/jxl_decode.rs @@ -9,7 +9,7 @@ fn rgba_8bit() -> Image { } #[test] -fn an_eight_bit_export_decodes_back_to_the_same_pixels() { +fn feature_config_an_eight_bit_export_decodes_back_to_the_same_pixels() { let input = rgba_8bit(); let bytes = encode(&input, Format::Jxl, &EncodeOptions::default()).unwrap(); let out = decode(&bytes).unwrap(); @@ -18,7 +18,7 @@ fn an_eight_bit_export_decodes_back_to_the_same_pixels() { } #[test] -fn a_sixteen_bit_gray_export_decodes_back_to_the_same_samples() { +fn feature_config_a_sixteen_bit_gray_export_decodes_back_to_the_same_samples() { let samples: Vec = (0..12).map(|i| i * 5461).collect(); let input = Image::from_u16(4, 3, ChannelLayout::Gray, &samples).unwrap(); let bytes = encode(&input, Format::Jxl, &EncodeOptions::default()).unwrap(); @@ -28,7 +28,7 @@ fn a_sixteen_bit_gray_export_decodes_back_to_the_same_samples() { } #[test] -fn the_pixel_limit_is_an_error_not_an_allocation() { +fn feature_config_the_pixel_limit_is_an_error_not_an_allocation() { let bytes = encode(&rgba_8bit(), Format::Jxl, &EncodeOptions::default()).unwrap(); let opts = DecodeOptions { limits: Limits { max_pixels: 4, ..Limits::default() }, ..DecodeOptions::default() }; let err = decode_with(&bytes, &opts); @@ -36,7 +36,7 @@ fn the_pixel_limit_is_an_error_not_an_allocation() { } #[test] -fn every_prefix_of_a_file_is_an_error_or_an_image_never_a_panic() { +fn feature_config_every_prefix_of_a_file_is_an_error_or_an_image_never_a_panic() { let bytes = encode(&rgba_8bit(), Format::Jxl, &EncodeOptions::default()).unwrap(); for end in 0..bytes.len() { let _ = decode(&bytes[..end]); diff --git a/crates/image-codecs/tests/it/jxl_export.rs b/crates/image-codecs/tests/it/jxl_export.rs index 129aa1a3b2..7902814910 100644 --- a/crates/image-codecs/tests/it/jxl_export.rs +++ b/crates/image-codecs/tests/it/jxl_export.rs @@ -5,7 +5,7 @@ use craft_image_codecs::{ }; #[test] -fn jpeg_xl_is_export_only_without_the_jxl_feature_and_detects_both_signatures() { +fn feature_config_jpeg_xl_is_export_only_without_the_jxl_feature_and_detects_both_signatures() { let c = caps(Format::Jxl); assert!(c.write); assert_eq!(c.read, cfg!(feature = "jxl")); diff --git a/crates/image-codecs/tests/it/limits.rs b/crates/image-codecs/tests/it/limits.rs index ec86753ebe..32158a13fa 100644 --- a/crates/image-codecs/tests/it/limits.rs +++ b/crates/image-codecs/tests/it/limits.rs @@ -39,7 +39,7 @@ fn read_bounded_reads_one_byte_past_its_cap() { } #[test] -fn max_pixels_enforced_for_every_format() { +fn feature_config_max_pixels_enforced_for_every_format() { for f in rw_formats() { let b = encoded(f); let l = Limits { max_pixels: 1000, ..Limits::default() }; @@ -50,7 +50,7 @@ fn max_pixels_enforced_for_every_format() { } #[test] -fn max_width_enforced_for_every_format() { +fn feature_config_max_width_enforced_for_every_format() { for f in rw_formats() { let l = Limits { max_width: 63, ..Limits::default() }; assert!(is_limit(decode_with(&encoded(f), &opts(l))), "{f:?}"); @@ -58,7 +58,7 @@ fn max_width_enforced_for_every_format() { } #[test] -fn max_height_enforced_for_every_format() { +fn feature_config_max_height_enforced_for_every_format() { for f in rw_formats() { let l = Limits { max_height: 47, ..Limits::default() }; assert!(is_limit(decode_with(&encoded(f), &opts(l))), "{f:?}"); @@ -66,7 +66,7 @@ fn max_height_enforced_for_every_format() { } #[test] -fn max_alloc_enforced_for_every_format() { +fn feature_config_max_alloc_enforced_for_every_format() { for f in rw_formats() { let l = Limits { max_alloc: 64 * 48, ..Limits::default() }; assert!(decode_with(&encoded(f), &opts(l)).is_err(), "{f:?}"); @@ -74,7 +74,7 @@ fn max_alloc_enforced_for_every_format() { } #[test] -fn limits_none_accepts() { +fn feature_config_limits_none_accepts() { for f in rw_formats() { assert!(decode_with(&encoded(f), &opts(Limits::none())).is_ok(), "{f:?}"); } diff --git a/crates/image-codecs/tests/it/malformed.rs b/crates/image-codecs/tests/it/malformed.rs index bd6bd605b7..9c4166bd1a 100644 --- a/crates/image-codecs/tests/it/malformed.rs +++ b/crates/image-codecs/tests/it/malformed.rs @@ -42,7 +42,7 @@ fn no_panic(f: Format, bytes: &[u8]) { } #[test] -fn truncated_at_many_offsets() { +fn feature_config_truncated_at_many_offsets() { for (f, bytes) in samples() { let n = bytes.len(); let step = (n / 97).max(1); @@ -56,7 +56,7 @@ fn truncated_at_many_offsets() { } #[test] -fn truncated_files_mostly_error() { +fn feature_config_truncated_files_mostly_error() { // Chopping off the second half must not silently succeed for formats // with length-checked rasters. for (f, bytes) in samples() { @@ -75,7 +75,7 @@ fn truncated_files_mostly_error() { } #[test] -fn bit_flips_never_panic() { +fn feature_config_bit_flips_never_panic() { // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs 1/N of the flips. let rounds = 150usize.div_ceil(craft_media_testkit::hostile::divisor()); let mut rng = common::Rng::new(42); @@ -93,7 +93,7 @@ fn bit_flips_never_panic() { } #[test] -fn byte_overwrites_in_header_never_panic() { +fn feature_config_byte_overwrites_in_header_never_panic() { // CRAFT_HOSTILE_DIVISOR=N (pull requests) overwrites every N-th byte, from a different offset // for each sample, so the samples together still reach every header position. let step = craft_media_testkit::hostile::divisor(); @@ -112,7 +112,7 @@ fn byte_overwrites_in_header_never_panic() { } #[test] -fn empty_input_errors_for_every_format() { +fn feature_config_empty_input_errors_for_every_format() { for f in Format::ALL { assert!(decode_as(f, &[]).is_err(), "{f:?}"); } @@ -194,7 +194,7 @@ proptest! { } #[test] - fn random_bytes_with_magic_never_panic(idx in 0usize..14, data in proptest::collection::vec(any::(), 0..1024)) { + fn feature_config_random_bytes_with_magic_never_panic(idx in 0usize..14, data in proptest::collection::vec(any::(), 0..1024)) { let magics: [&[u8]; 14] = [ b"\x89PNG\r\n\x1a\n", &[0xFF, 0xD8, 0xFF], b"II*\0", b"RIFF\0\0\0\0WEBP", b"GIF89a", b"BM", &[0, 0, 1, 0, 1, 0], b"P6\n", b"qoif", &[0x76, 0x2F, 0x31, 0x01], b"#?RADIANCE\n", b"P7\n", b"PF\n", @@ -206,12 +206,12 @@ proptest! { } #[test] - fn random_bytes_each_format_never_panic(idx in 0usize..Format::ALL.len(), data in proptest::collection::vec(any::(), 0..512)) { + fn feature_config_random_bytes_each_format_never_panic(idx in 0usize..Format::ALL.len(), data in proptest::collection::vec(any::(), 0..512)) { let _ = decode_as_with(Format::ALL[idx], &data, &tight()); } #[test] - fn mutated_valid_files_never_panic(which in 0usize..40, pos in any::(), val in any::(), cut in any::()) { + fn feature_config_mutated_valid_files_never_panic(which in 0usize..40, pos in any::(), val in any::(), cut in any::()) { let s = samples_cached(); let (f, bytes) = &s[which % s.len()]; let mut b = bytes.clone(); diff --git a/crates/image-codecs/tests/it/orientation.rs b/crates/image-codecs/tests/it/orientation.rs index 4eaf188a89..7c44910eb8 100644 --- a/crates/image-codecs/tests/it/orientation.rs +++ b/crates/image-codecs/tests/it/orientation.rs @@ -661,7 +661,7 @@ fn long_orientation_reads_and_rewrites_in_both_byte_orders() { /// `probe_size` reads the size `decode` returns from the header alone, for every format it /// covers, and a file cut short inside its header is refused rather than given a size. #[test] -fn probe_size_matches_decode() { +fn feature_config_probe_size_matches_decode() { let img = synth(7, 5, ChannelLayout::Rgb, SampleType::U8, 3, 0.0); let probed = [ Format::Png, diff --git a/crates/image-codecs/tests/it/png_jpeg.rs b/crates/image-codecs/tests/it/png_jpeg.rs index af11f72949..cad8f33e9a 100644 --- a/crates/image-codecs/tests/it/png_jpeg.rs +++ b/crates/image-codecs/tests/it/png_jpeg.rs @@ -530,7 +530,7 @@ fn png_rows_fail_like_decode_on_damaged_files() { #[cfg(feature = "corpus")] #[test] -fn pngsuite_corpus_matches_oracle() { +fn feature_config_pngsuite_corpus_matches_oracle() { let mut checked = 0; for (name, bytes) in common::pngsuite::pngs() { let oracle = image::load_from_memory_with_format(&bytes, image::ImageFormat::Png); @@ -637,7 +637,7 @@ fn png_preflight_uses_the_output_layout() { #[cfg(feature = "corpus")] #[test] -fn png_rows_equal_decode_on_the_pngsuite_corpus() { +fn feature_config_png_rows_equal_decode_on_the_pngsuite_corpus() { let mut checked = 0; for (name, bytes) in common::pngsuite::pngs() { assert_steps_equal_decode(&bytes, &name); @@ -650,7 +650,7 @@ fn png_rows_equal_decode_on_the_pngsuite_corpus() { /// but the interlaced ones), and fails where `decode` fails. #[cfg(feature = "corpus")] #[test] -fn pngsuite_corpus_rows_match_the_whole_decode() { +fn feature_config_pngsuite_corpus_rows_match_the_whole_decode() { let opts = DecodeOptions { keep_orientation: true, ..Default::default() }; let (mut streamed, mut refused, mut skipped) = (0, 0, 0); for (name, bytes) in common::pngsuite::pngs() { diff --git a/crates/image-codecs/tests/it/roundtrip.rs b/crates/image-codecs/tests/it/roundtrip.rs index 6ff2e58187..f531a472a9 100644 --- a/crates/image-codecs/tests/it/roundtrip.rs +++ b/crates/image-codecs/tests/it/roundtrip.rs @@ -316,7 +316,7 @@ fn webp_lossy_request_is_a_lossy_file() { } #[test] -fn one_pixel_images_roundtrip() { +fn feature_config_one_pixel_images_roundtrip() { for f in rw_formats() { // The JPEG XL encoder refuses images narrower than two pixels (jxl_export.rs pins the error). if f == Format::Jxl { @@ -337,7 +337,7 @@ fn ico_rejects_oversize() { } #[test] -fn empty_image_rejected() { +fn feature_config_empty_image_rejected() { let img = Image::new(0, 5, ChannelLayout::Rgb, SampleType::U8).unwrap(); for f in writable_formats() { assert!(encode(&img, f, &EncodeOptions::default()).is_err(), "{f:?}"); diff --git a/crates/imaging/src/layer_style/draft.rs b/crates/imaging/src/layer_style/draft.rs index ecef782e2e..239338e38d 100644 --- a/crates/imaging/src/layer_style/draft.rs +++ b/crates/imaging/src/layer_style/draft.rs @@ -26,7 +26,7 @@ pub struct LayerStyleDraft { pub blend_if_channel: usize, /// The Preview check box: whether the host shows the draft on the canvas. On by default. pub preview: bool, - /// The shadow drag in progress, from its press to its release. + /// The shadow or Satin drag in progress, from its press to its release. pub shadow_drag: Option, /// The Gradient Overlay offset drag in progress, from its press to its release. pub gradient_drag: Option, @@ -245,6 +245,53 @@ impl LayerStyleDraft { self.style != before } + /// Whether a drag on the image moves the selected Satin's angle and distance. + pub fn drags_satin(&self) -> bool { + self.selected_kind() == Some(EffectKind::Satin) + } + + /// Whether a drag on the image edits the selected page: a shadow's, a Satin's or a Gradient + /// Overlay's. The host passes the canvas gesture through the dialog on these pages. + pub fn drags_on_canvas(&self) -> bool { + self.drags_shadow() || self.drags_satin() || self.drags_gradient() + } + + /// A drag on the image with a Satin page selected, as [`drag_shadow`](Self::drag_shadow) is for + /// a shadow: `defaults` are the Satin's spec defaults, `start` is the press (it records the + /// angle and distance shown) and `total` the pointer's movement since, in document pixels. The + /// values follow [`ShadowDrag::satin_moved`]. A Satin has no Use Global Light, so only this + /// instance changes. The drag shares [`shadow_drag`](Self::shadow_drag), which the host clears + /// on release. Returns whether the style changed; does nothing on other pages. + pub fn drag_satin(&mut self, defaults: &StyleParams, start: bool, total: [f64; 2]) -> bool { + let LayerStylePage::Effect(id) = self.page else { + return false; + }; + if !self.drags_satin() { + return false; + } + let Some(instance) = self.style.effect(id) else { + return false; + }; + let shown = instance.params.over(defaults); + let shown_angle = shown.number("angle").unwrap_or(19.0); + let shown_distance = shown.number("distance").unwrap_or(11.0); + if start || self.shadow_drag.is_none() { + self.shadow_drag = Some(ShadowDrag::begin(shown_angle, shown_distance)); + } + let Some((angle, distance)) = self.shadow_drag.and_then(|drag| drag.satin_moved(total, shown_angle)) else { + return false; + }; + // The values already shown (a press, or a drag back to where the page stands): write nothing, + // so a sparse instance does not gain explicit parameters it never had. + if angle == shown_angle && distance == shown_distance { + return false; + } + let before = self.style.clone(); + self.set_param(id, "angle", StyleValue::Number(angle)); + self.set_param(id, "distance", StyleValue::Number(distance)); + self.style != before + } + /// An id one past the highest `fxN`, or the lowest free number when that overflows. fn next_id(&self) -> EffectId { let max = self.style.effects.iter().map(|e| e.id.0).max().unwrap_or(0); diff --git a/crates/imaging/src/layer_style/drag.rs b/crates/imaging/src/layer_style/drag.rs index 09f65140e1..ece824f1c5 100644 --- a/crates/imaging/src/layer_style/drag.rs +++ b/crates/imaging/src/layer_style/drag.rs @@ -33,6 +33,33 @@ impl ShadowDrag { let angle = if d >= 0.5 { oy.atan2(-ox).to_degrees().round() } else { self.start_angle }; Some((angle, d.round().clamp(0.0, 30000.0))) } + + /// The Satin's `(angle, distance)` after the pointer moved `total` document pixels since the + /// press: the start offset plus `total`, as for a shadow, but the distance is its length + /// **truncated** to a whole pixel and clamped to 1..=250, and the angle `atan2(oy, −ox)` + /// truncated toward zero to a whole degree (−116.57 gives −116). A new offset at (0, 0), float + /// noise aside, keeps `shown_angle`, the angle the page shows; a quarter pixel still has a + /// direction. No travel gives the start values back unchanged, fractions included. `None` when + /// the result is not finite. + pub fn satin_moved(self, total: [f64; 2], shown_angle: f64) -> Option<(f64, f64)> { + if total == [0.0, 0.0] { + return Some((self.start_angle, self.start_distance)); + } + let a = self.start_angle.to_radians(); + let (ox, oy) = (-a.cos() * self.start_distance + total[0], a.sin() * self.start_distance + total[1]); + let d = ox.hypot(oy); + if !d.is_finite() { + return None; + } + let angle = if d > 1e-6 { + let deg = oy.atan2(-ox).to_degrees(); + // Float noise a hair under a whole degree (145.999…) must not lose that degree. + (deg + 1e-9 * deg.signum()).trunc() + } else { + shown_angle + }; + Some((angle, d.trunc().clamp(1.0, 250.0))) + } } /// The largest offset a Gradient Overlay drag writes, in layer sizes, either way. diff --git a/crates/imaging/src/layer_style/tests.rs b/crates/imaging/src/layer_style/tests.rs index b637dcbf31..1dc70affb3 100644 --- a/crates/imaging/src/layer_style/tests.rs +++ b/crates/imaging/src/layer_style/tests.rs @@ -76,6 +76,134 @@ fn shadow_drag_uses_whole_degrees_and_pixels_and_moves_the_global_angle() { assert!(!draft.drag_shadow(&defaults, true, [10.0, 10.0])); } +/// A Satin at `angle` / `distance` on its selected page, with a Drop Shadow beside it. +fn satin_draft(angle: f64, distance: f64) -> LayerStyleDraft { + let mut draft = LayerStyleDraft::new(style_with(&[(1, EffectKind::Satin), (2, EffectKind::DropShadow)])); + draft.page = LayerStylePage::Effect(EffectId(1)); + draft.set_param(EffectId(1), "angle", StyleValue::Number(angle)); + draft.set_param(EffectId(1), "distance", StyleValue::Number(distance)); + draft +} + +fn satin_shown(draft: &LayerStyleDraft) -> (Option, Option) { + let params = &draft.style.effect(EffectId(1)).expect("the Satin").params; + (params.number("angle"), params.number("distance")) +} + +// From Angle 90 / Distance 20, each drag gives the angle and distance measured in the reference +// application: both truncated (not rounded), negative angles toward zero. +#[trial] +fn satin_drag_truncates_the_angle_and_distance() { + let defaults = EffectSpec::photoshop(EffectKind::Satin).defaults; + for (total, want) in [ + ([30.0, 0.0], (146.0, 36.0)), + ([0.0, -30.0], (-90.0, 10.0)), + ([0.0, 30.0], (90.0, 50.0)), + ([-30.0, 0.0], (33.0, 36.0)), + ([20.0, -20.0], (180.0, 20.0)), + ([5.0, 0.0], (104.0, 20.0)), + ([5.0, -30.0], (-116.0, 11.0)), + ([-5.0, -30.0], (-63.0, 11.0)), + ([30.0, 10.0], (135.0, 42.0)), + ] { + let mut draft = satin_draft(90.0, 20.0); + assert!(draft.drags_satin() && draft.drags_on_canvas()); + draft.drag_satin(&defaults, true, [0.0, 0.0]); + draft.drag_satin(&defaults, false, total); + assert_eq!(satin_shown(&draft), (Some(want.0), Some(want.1)), "drag {total:?}"); + } +} + +// The zero offset gives Distance 1 and keeps the angle shown, also when one drag passes through it; +// a quarter pixel still has a direction; Distance stays within 1..=250; a non-finite drag and a +// press change nothing, fractions included; a drag back to the press restores the start values. +#[trial] +fn satin_drag_keeps_the_angle_at_zero_and_the_values_without_travel() { + let defaults = EffectSpec::photoshop(EffectKind::Satin).defaults; + let mut draft = satin_draft(90.0, 20.0); + draft.drag_satin(&defaults, true, [0.0, 0.0]); + draft.drag_satin(&defaults, false, [0.0, -20.0]); + assert_eq!(satin_shown(&draft), (Some(90.0), Some(1.0))); + + let mut draft = satin_draft(90.0, 20.0); + draft.drag_satin(&defaults, true, [0.0, 0.0]); + draft.drag_satin(&defaults, false, [30.0, 0.0]); + draft.drag_satin(&defaults, false, [0.0, -20.0]); + assert_eq!(satin_shown(&draft), (Some(146.0), Some(1.0)), "the angle shown, not the press's"); + + let mut draft = satin_draft(90.0, 20.0); + draft.drag_satin(&defaults, true, [0.0, 0.0]); + draft.drag_satin(&defaults, false, [0.25, -20.0]); + assert_eq!(satin_shown(&draft), (Some(180.0), Some(1.0))); + + let mut draft = satin_draft(90.0, 20.0); + draft.drag_satin(&defaults, true, [0.0, 0.0]); + draft.drag_satin(&defaults, false, [0.0, 380.0]); + assert_eq!(satin_shown(&draft).1, Some(250.0)); + assert!(!draft.drag_satin(&defaults, true, [f64::NAN, 0.0])); + + let mut draft = satin_draft(90.5, 20.75); + assert!(!draft.drag_satin(&defaults, true, [0.0, 0.0]), "a press writes nothing"); + assert!(draft.shadow_drag.is_some()); + draft.drag_satin(&defaults, false, [30.0, 0.0]); + assert_eq!(satin_shown(&draft), (Some(145.0), Some(36.0))); + draft.drag_satin(&defaults, false, [0.0, 0.0]); + assert_eq!(satin_shown(&draft), (Some(90.5), Some(20.75))); + draft.end_drag(); + assert!(draft.shadow_drag.is_none()); +} + +// A press and release on a Satin whose angle and distance are not stored (they come from the spec +// defaults) leaves its parameters empty; a drag that leaves and comes back does store them. +#[trial] +fn satin_press_without_travel_keeps_a_sparse_instance_sparse() { + let defaults = EffectSpec::photoshop(EffectKind::Satin).defaults; + let mut draft = LayerStyleDraft::new(style_with(&[(1, EffectKind::Satin)])); + draft.page = LayerStylePage::Effect(EffectId(1)); + draft.style.effect_mut(EffectId(1)).expect("the Satin").params = StyleParams::default(); + let before = draft.style.clone(); + assert!(!draft.drag_satin(&defaults, true, [0.0, 0.0])); + assert!(!draft.drag_satin(&defaults, false, [0.0, 0.0])); + draft.end_drag(); + assert_eq!(draft.style, before, "the parameter map is unchanged"); + assert_eq!(satin_shown(&draft), (None, None)); + + draft.drag_satin(&defaults, true, [0.0, 0.0]); + assert!(draft.drag_satin(&defaults, false, [30.0, 0.0])); + assert!(draft.drag_satin(&defaults, false, [0.0, 0.0]), "back to the start values"); +} + +// Only the Satin page takes the Satin drag; it leaves Global Light and the shadow alone, and the +// shadow drag does not take a Satin page. Shadow, Satin and Gradient Overlay pages take canvas drags. +#[trial] +fn satin_drag_is_the_satin_pages_alone() { + let satin = EffectSpec::photoshop(EffectKind::Satin).defaults; + let shadow = EffectSpec::photoshop(EffectKind::DropShadow).defaults; + let mut draft = satin_draft(90.0, 20.0); + let light = draft.style.global_light; + let before = draft.style.effect(EffectId(2)).cloned(); + assert!(!draft.drags_shadow()); + assert!(!draft.drag_shadow(&shadow, true, [30.0, 0.0])); + assert_eq!(satin_shown(&draft), (Some(90.0), Some(20.0))); + draft.drag_satin(&satin, true, [0.0, 0.0]); + assert!(draft.drag_satin(&satin, false, [30.0, 0.0])); + assert_eq!(draft.style.global_light, light); + assert_eq!(draft.style.effect(EffectId(2)).cloned(), before); + + draft.end_drag(); + draft.page = LayerStylePage::Effect(EffectId(2)); + assert!(!draft.drags_satin() && draft.drags_on_canvas()); + assert!(!draft.drag_satin(&satin, true, [30.0, 0.0])); + assert_eq!(draft.style.effect(EffectId(2)).cloned(), before); + draft.page = LayerStylePage::Blending; + assert!(!draft.drags_on_canvas()); + let mut gradient = LayerStyleDraft::new(style_with(&[(1, EffectKind::GradientOverlay), (2, EffectKind::ColorOverlay)])); + gradient.page = LayerStylePage::Effect(EffectId(1)); + assert!(gradient.drags_on_canvas()); + gradient.page = LayerStylePage::Effect(EffectId(2)); + assert!(!gradient.drags_on_canvas()); +} + // An instance without angle and distance starts the drag from the spec's defaults, not from 120° // and 0. diff --git a/crates/imaging/src/ui/curve/editor.rs b/crates/imaging/src/ui/curve/editor.rs index 02de94f546..a1797c3edc 100644 --- a/crates/imaging/src/ui/curve/editor.rs +++ b/crates/imaging/src/ui/curve/editor.rs @@ -142,6 +142,12 @@ pub struct CurveEditor<'a> { /// The selected point, kept by the host: the editor shows it and reports changes in the output. #[prop] selection: Option>, + /// Ctrl+Tab and Ctrl+Shift+Tab select the next and the previous point, wrapping round, while a point is selected. + #[prop(flag)] + tab_steps: bool, + /// Delete and Backspace on an end point, which stays, deselect it. + #[prop(flag)] + end_delete_deselects: bool, /// The host's rows between the graph and the fields. #[prop(func = "FnMut(&mut Ui, &mut BodyCx<'_>)")] between: Option>, @@ -167,6 +173,8 @@ impl<'a> CurveEditor<'a> { histogram: None, overlays: &[], selection: None, + tab_steps: false, + end_delete_deselects: false, between: None, } } @@ -196,6 +204,8 @@ impl<'a> CurveEditor<'a> { histogram, overlays, selection: host_selection, + tab_steps, + end_delete_deselects, mut between, } = self; let words = craft_ui::runtime::env::Env::of(ui).words::(); @@ -239,6 +249,12 @@ impl<'a> CurveEditor<'a> { if percent { graph = graph.percent(); } + if tab_steps { + graph = graph.tab_steps(); + } + if end_delete_deselects { + graph = graph.end_delete_deselects(); + } let CurveGraphOutput { mut edit, selected } = graph.show(ui); if let Some(rows) = between.as_mut() { (rows.0)(ui, root); diff --git a/crates/imaging/src/ui/curve/graph.rs b/crates/imaging/src/ui/curve/graph.rs index 9a539fb4b1..f1ccdb4938 100644 --- a/crates/imaging/src/ui/curve/graph.rs +++ b/crates/imaging/src/ui/curve/graph.rs @@ -32,6 +32,9 @@ const PLUS: [Chord; 3] = [Chord::plain(Key::Plus), Chord::plain(Key::Equals), Ch const MINUS: Chord = Chord::plain(Key::Minus); const INSERT: [Chord; 3] = [Chord::plain(Key::Insert), Chord::new(Mods::CMD, Key::Enter), Chord::new(Mods::CTRL, Key::Enter)]; const DELETE: [Chord; 2] = [Chord::plain(Key::Delete), Chord::plain(Key::Backspace)]; +/// The next and the previous point with [`CurveGraph::tab_steps`]. +const NEXT_POINT: Chord = Chord::new(Mods::CTRL, Key::Tab); +const PREVIOUS_POINT: Chord = Chord::new(Mods { ctrl: true, shift: true, ..Mods::NONE }, Key::Tab); /// Levels one arrow key moves a point, and with Shift. const NUDGE: f32 = 1.0; @@ -367,6 +370,12 @@ pub struct CurveGraph<'a> { /// The selected point. #[prop] selection: Option, + /// Ctrl+Tab and Ctrl+Shift+Tab select the next and the previous point, wrapping round, while a point is selected. + #[prop(flag)] + tab_steps: bool, + /// Delete and Backspace on an end point, which stays, deselect it. + #[prop(flag)] + end_delete_deselects: bool, /// The selection after `update`, for the output. chosen: Option, } @@ -389,6 +398,8 @@ impl<'a> CurveGraph<'a> { histogram: None, overlays: &[], selection: None, + tab_steps: false, + end_delete_deselects: false, chosen: None, } .label(label) @@ -540,7 +551,7 @@ impl Component for CurveGraph<'_> { fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { let frame = self.frame(rect, cx.style); cx.part(PLOT, frame.plot) - .sense(Sense::CLICK | Sense::DRAG | Sense::TAKE_FOCUS) + .sense(Sense::CLICK | Sense::CONTEXT_CLICK | Sense::DRAG | Sense::TAKE_FOCUS) .value_part() .pointer_only("the point keys and the arrow keys edit the points"); let shown = cx.value().cloned(); @@ -548,7 +559,7 @@ impl Component for CurveGraph<'_> { for (i, p) in points.iter().enumerate() { let reach = Rect::from_center_size(frame.map.screen(*p), Vec2::splat(2.0 * cx.style.hit)); cx.part(POINT.at(i as u64), reach) - .sense(Sense::CLICK | Sense::DRAG | Sense::TAKE_FOCUS) + .sense(Sense::CLICK | Sense::CONTEXT_CLICK | Sense::DRAG | Sense::TAKE_FOCUS) .priority(HitPriority::new(HitLevel::Body, 0)) .pointer_only("the plot's point keys select and move the points"); } @@ -669,6 +680,11 @@ impl Component for CurveGraph<'_> { for chord in PLUS.into_iter().chain([MINUS]).chain(INSERT).chain(DELETE) { cx.claim(chord); } + // Only with a point selected, after this pass's keys: otherwise Ctrl+Tab stays the app's. + if self.tab_steps && selected.is_some() { + cx.claim(NEXT_POINT); + cx.claim(PREVIOUS_POINT); + } self.chosen = selected; } @@ -765,37 +781,38 @@ impl CurveGraph<'_> { if n == 0 { return selected; } - let mut plus = 0; - for chord in PLUS { - while cx.take_claimed(chord) { - plus += 1; - } - } - for _ in 0..plus { - selected = Some(selected.map_or(0, |i| (i + 1).min(n - 1))); - } - while cx.take_claimed(MINUS) { - selected = Some(selected.map_or(n - 1, |i| i.saturating_sub(1))); - } - let mut insert = false; - for chord in INSERT { - while cx.take_claimed(chord) { - insert = true; - } - } - if insert { - // A gap too narrow for a point adds nothing and keeps the selection. - let drawn = curve.points().map(|points| self.samples(points, &curve.corner_flags())).unwrap_or_default(); - if let Some((next, i)) = rules.inserted(curve, selected, &drawn) { - cx.set(next.clone()); - *curve = next; - selected = Some(i); - } - } - let mut delete = false; - for chord in DELETE { - while cx.take_claimed(chord) { - delete = true; + // The claimed keys in the order they were pressed, each as if it came alone: a Delete and then a Ctrl+Tab in + // one frame delete the point that was selected, not the next one. + let chords: Vec = PLUS.into_iter().chain([MINUS, NEXT_POINT, PREVIOUS_POINT]).chain(INSERT).chain(DELETE).collect(); + while let Some(chord) = cx.take_first_claimed(&chords) { + let n = curve.points().map_or(0, <[_]>::len); + if PLUS.contains(&chord) { + selected = Some(selected.map_or(0, |i| (i + 1).min(n - 1))); + } else if chord == MINUS { + selected = Some(selected.map_or(n - 1, |i| i.saturating_sub(1))); + } else if chord == NEXT_POINT { + selected = selected.map(|i| (i + 1) % n); + } else if chord == PREVIOUS_POINT { + selected = selected.map(|i| (i + n - 1) % n); + } else if INSERT.contains(&chord) { + // A gap too narrow for a point adds nothing and keeps the selection. + let drawn = curve.points().map(|points| self.samples(points, &curve.corner_flags())).unwrap_or_default(); + if let Some((next, i)) = rules.inserted(curve, selected, &drawn) { + cx.set(next.clone()); + *curve = next; + selected = Some(i); + } + } else if let Some(at) = selected { + match CurveRules::deleted(curve, at) { + Some(next) => { + cx.set(next.clone()); + *curve = next; + selected = None; + } + // An end point stays, and so does the selection on it unless `end_delete_deselects`. + None if self.end_delete_deselects => selected = None, + None => {} + } } } let rtl = cx.flow.is_rtl(); @@ -816,13 +833,6 @@ impl CurveGraph<'_> { by = [by[0] + dx * steps, by[1] + dy * steps]; } let Some(at) = selected else { return selected }; - if delete { - // An end point stays, and so does the selection on it. - let Some(next) = CurveRules::deleted(curve, at) else { return selected }; - cx.set(next.clone()); - *curve = next; - return None; - } if by != [0.0, 0.0] && let Some(next) = rules.nudged(curve, at, by) { diff --git a/crates/imaging/src/ui/fill/stories.rs b/crates/imaging/src/ui/fill/stories.rs index d1de28716a..e5fa8608f1 100644 --- a/crates/imaging/src/ui/fill/stories.rs +++ b/crates/imaging/src/ui/fill/stories.rs @@ -102,12 +102,7 @@ impl FillSource for StorySource { match self.preview { Preview::Loading => Job::new(|progress, cancel| { progress.report(LOADING_PROGRESS); - for _ in 0..LOADING_SECONDS { - if cancel.is_cancelled() { - break; - } - std::thread::sleep(Duration::from_secs(1)); - } + cancel.wait_timeout(Duration::from_secs(LOADING_SECONDS)); Ok(PreviewDone::new(Duration::ZERO)) }), Preview::Failed => Job::new(|_, _| Err("nothing to sample from: the sampling area has no pixels outside the fill area".to_owned())), diff --git a/crates/imaging/src/ui/filter_gallery/stories.rs b/crates/imaging/src/ui/filter_gallery/stories.rs index 900e7cb1da..cecc8033d0 100644 --- a/crates/imaging/src/ui/filter_gallery/stories.rs +++ b/crates/imaging/src/ui/filter_gallery/stories.rs @@ -27,8 +27,6 @@ use crate::ui::wide_angle::PreviewDone; const NOTE: Duration = Duration::from_millis(120); /// How far the loading render has come, as a fraction. const PROGRESS: f32 = 0.4; -/// How often the loading render looks for its cancellation. -const POLL: Duration = Duration::from_millis(20); // --- the fake app --- @@ -136,9 +134,7 @@ impl FilterGallerySource for MockSource { if self.rendering { Job::new(|progress, cancel| { progress.report(PROGRESS); - while !cancel.is_cancelled() { - std::thread::sleep(POLL); - } + cancel.wait(); Err(String::new()) }) } else { diff --git a/crates/imaging/src/ui/layer_style/hosted.rs b/crates/imaging/src/ui/layer_style/hosted.rs index ed5c1e5ff5..2586ffad78 100644 --- a/crates/imaging/src/ui/layer_style/hosted.rs +++ b/crates/imaging/src/ui/layer_style/hosted.rs @@ -366,7 +366,7 @@ impl StackDialog for HostedLayerStyle { .show(ui, |ui, cx, draft| { if let Some(canvas) = *canvas { cx.keep_view_open(canvas); - if draft.drags_shadow() || draft.drags_gradient() { + if draft.drags_on_canvas() { cx.pass_canvas_gesture(canvas, CanvasGesture::PRIMARY); } } diff --git a/crates/imaging/src/ui/select/magnetic.rs b/crates/imaging/src/ui/select/magnetic.rs index 2f49645543..fe15487cd3 100644 --- a/crates/imaging/src/ui/select/magnetic.rs +++ b/crates/imaging/src/ui/select/magnetic.rs @@ -44,7 +44,7 @@ pub trait EdgeTracer { /// The Magnetic Lasso's options bar, persisted by the app (decisions §2.4). The options bar edits /// [`MagneticLassoTool::settings_mut`]; `[` and `]` change `width` ([`step_width`](Self::step_width)): the tool while an /// outline is open, the app's shortcuts otherwise. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase", default)] #[non_exhaustive] pub struct MagneticSettings { diff --git a/crates/imaging/src/ui/select_mask/stories.rs b/crates/imaging/src/ui/select_mask/stories.rs index 2bfd781a72..3ffb2d9bb6 100644 --- a/crates/imaging/src/ui/select_mask/stories.rs +++ b/crates/imaging/src/ui/select_mask/stories.rs @@ -27,9 +27,6 @@ use crate::ui::wide_angle::PreviewDone; /// The limits a story runs under: PhotoCraft's. const LIMITS: SelectMaskLimits = SelectMaskLimits { edits: 4096, edit_points: 100_000, strokes: 4096, stroke_points: 100_000 }; -/// How often a never-finishing preview job looks for its cancellation. -const POLL: Duration = Duration::from_millis(50); - /// The app's side over `MockImage`: the picture as the view, the house as the selection. struct StorySource { image: MockImage, @@ -54,9 +51,7 @@ impl SelectMaskSource for StorySource { fn preview_job(&self, _: &SelectMaskPreviewRequest) -> Job { if self.loading { Job::new(|_, cancel| { - while !cancel.is_cancelled() { - std::thread::sleep(POLL); - } + cancel.wait(); Err("cancelled".to_owned()) }) } else { diff --git a/crates/imaging/src/ui/warp/cylinder.rs b/crates/imaging/src/ui/warp/cylinder.rs index 5262295371..a11073363e 100644 --- a/crates/imaging/src/ui/warp/cylinder.rs +++ b/crates/imaging/src/ui/warp/cylinder.rs @@ -405,7 +405,7 @@ impl Component for CylinderWarp<'_> { results.push((handle, result.press)); } } - if let Some((hover_pos, press)) = cx.part_if_declared(BODY).map(|result| (result.hover_pos, result.press)) { + if let Some((hover_pos, press)) = cx.part_if_declared(BODY).map(|result| (cx.hover_pos(BODY), result.press)) { let on_surface = hover_pos.is_some_and(|at| self.mesh.surface_at(space.view.to_doc(at)).is_some()); if on_surface { cx.cursor(CursorIcon::Move, craft_behavior::CursorPriority::Part); diff --git a/crates/imaging/src/ui/warp/grid.rs b/crates/imaging/src/ui/warp/grid.rs index 46579dacc8..8f8a764cf3 100644 --- a/crates/imaging/src/ui/warp/grid.rs +++ b/crates/imaging/src/ui/warp/grid.rs @@ -288,7 +288,11 @@ impl<'a> WarpGrid<'a> { None => cx.part_if_declared(SURFACE), }; let Some(result) = found else { continue }; - let (hover_at, press) = (result.hover_pos, result.press); + let hover_at = match point { + Some(index) => cx.hover_pos(POINT.at(index as u64)), + None => cx.hover_pos(SURFACE), + }; + let press = result.press; if hover.is_none() && let Some(at) = hover_at { diff --git a/crates/imaging/src/ui/warp/pin/overlay.rs b/crates/imaging/src/ui/warp/pin/overlay.rs index 31605062b6..78cbfb7b92 100644 --- a/crates/imaging/src/ui/warp/pin/overlay.rs +++ b/crates/imaging/src/ui/warp/pin/overlay.rs @@ -353,7 +353,7 @@ impl PinWarp<'_> { fn run_pointer(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, pins: &[Pin]) { for i in 0..pins.len() { let Some(result) = cx.part_if_declared(PIN.at(i as u64)) else { continue }; - let (press, hovered, hover_pos) = (result.press, result.hovered, result.hover_pos); + let (press, hovered, hover_pos) = (result.press, result.hovered, cx.hover_pos(PIN.at(i as u64))); if hovered { self.report.hovered = Some(i); self.report.pointer = hover_pos.map(|at| space.view.to_doc(at)); @@ -370,7 +370,7 @@ impl PinWarp<'_> { } } let Some(result) = cx.part_if_declared(MESH) else { return }; - let (press, hovered, hover_pos) = (result.press, result.hovered, result.hover_pos); + let (press, hovered, hover_pos) = (result.press, result.hovered, cx.hover_pos(MESH)); if hovered && self.report.pointer.is_none() { self.report.pointer = hover_pos.map(|at| space.view.to_doc(at)); } diff --git a/crates/imaging/tests/it/curve.rs b/crates/imaging/tests/it/curve.rs index 4d2c977a0e..0bbe116b6e 100644 --- a/crates/imaging/tests/it/curve.rs +++ b/crates/imaging/tests/it/curve.rs @@ -6,18 +6,20 @@ use craft_imaging::ui::ChannelColor; use craft_imaging::ui::curve::{Curve, CurveChannel, CurveEditor}; use craft_theme::{Contrast, Mode}; use craft_ui::contract::Bind; -use craft_ui::testing::pointer::{moved, press, release}; +use craft_ui::testing::pointer::{moved, press, release, secondary}; use craft_ui::testing::{Fixture, Room, style, trial}; use egui::{Pos2, Vec2, pos2, vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; -struct Rig { - fixture: Fixture, +pub(crate) struct Rig { + pub(crate) fixture: Fixture, curve: Rc>, - selected: Rc>>, + pub(crate) selected: Rc>>, /// The kind of each edit event, in order. kinds: Rc>>, + /// The key presses left in egui's input after the editor, which the app reads, in order. + pub(crate) app_keys: Rc>>, origin: Pos2, scale: Vec2, } @@ -34,24 +36,42 @@ fn kind(event: &EditEvent) -> &'static str { } fn rig(points: &[[f32; 2]]) -> Rig { + rig_with(points, false) +} + +/// [`rig`] with `tab_steps` and `end_delete_deselects` when `point_keys`. +pub(crate) fn rig_with(points: &[[f32; 2]], point_keys: bool) -> Rig { let curve = Curve::smooth(points.to_vec()); let shared = Rc::new(RefCell::new(curve.clone())); let selected = Rc::new(Cell::new(None)); let kinds = Rc::new(RefCell::new(Vec::new())); - let (c, s, k) = (shared.clone(), selected.clone(), kinds.clone()); + let app_keys = Rc::new(RefCell::new(Vec::new())); + let (c, s, k, a) = (shared.clone(), selected.clone(), kinds.clone(), app_keys.clone()); let channels = [CurveChannel::new("RGB", ChannelColor::Neutral), CurveChannel::new("Red", ChannelColor::Red)]; let mut fixture = Fixture::new(move |ui| { let mut value = c.borrow().clone(); - let out = CurveEditor::new("Curve", Bind::bound(&mut value)).channels(&channels).channel(0).selection(s.get()).show(ui); + let mut editor = CurveEditor::new("Curve", Bind::bound(&mut value)).channels(&channels).channel(0).selection(s.get()); + if point_keys { + editor = editor.tab_steps().end_delete_deselects(); + } + let out = editor.show(ui); for event in &out.edit.events { k.borrow_mut().push(kind(event)); } s.set(out.selected); *c.borrow_mut() = value; + let pressed = ui.input(|input| { + input + .events + .iter() + .filter_map(|event| if let egui::Event::Key { key, pressed: true, .. } = event { Some(*key) } else { None }) + .collect::>() + }); + a.borrow_mut().extend(pressed); }); fixture.room(room()); fixture.settle(); - let mut rig = Rig { fixture, curve: shared, selected, kinds, origin: Pos2::ZERO, scale: Vec2::ZERO }; + let mut rig = Rig { fixture, curve: shared, selected, kinds, app_keys, origin: Pos2::ZERO, scale: Vec2::ZERO }; rig.calibrate(&curve); rig } @@ -72,7 +92,7 @@ impl Rig { pos2(self.origin.x + q[0] * self.scale.x, self.origin.y + q[1] * self.scale.y) } - fn points(&self) -> Vec<[f32; 2]> { + pub(crate) fn points(&self) -> Vec<[f32; 2]> { self.curve.borrow().points().map(<[_]>::to_vec).unwrap_or_default() } @@ -80,7 +100,7 @@ impl Rig { self.kinds.borrow().clone() } - fn press_at(&mut self, q: [f32; 2]) { + pub(crate) fn press_at(&mut self, q: [f32; 2]) { let pos = self.at(q); self.fixture.frame(vec![moved(pos)]); self.fixture.frame(vec![press(pos)]); @@ -102,10 +122,18 @@ impl Rig { self.fixture.frame(vec![moved(self.at(q))]); } - fn release_at(&mut self, q: [f32; 2]) { + pub(crate) fn release_at(&mut self, q: [f32; 2]) { self.fixture.frame(vec![release(self.at(q))]); self.fixture.idle(1); } + + fn right_click_at(&mut self, q: [f32; 2]) { + let pos = self.at(q); + self.fixture.frame(vec![moved(pos)]); + self.fixture.frame(vec![secondary(pos, true)]); + self.fixture.frame(vec![secondary(pos, false)]); + self.fixture.idle(1); + } } /// The room is this many plot widths wide and tall: the editor at its greatest size and the rows under it. @@ -173,6 +201,20 @@ fn a_press_near_a_point_grabs_it_and_a_press_far_from_it_adds_one() { assert_eq!(rig.points().len(), 4, "a press 30 px away adds a point"); } +/// A right-click on the empty graph drops the selection and adds no point; a right-click on an inner point removes it. +#[trial] +fn a_right_click_on_the_empty_graph_deselects_and_on_a_point_removes_it() { + let mut rig = rig(&THREE); + rig.press_at([100.0, 100.0]); + rig.release_at([100.0, 100.0]); + assert_eq!(rig.selected.get(), Some(1)); + rig.right_click_at([180.0, 20.0]); + assert_eq!(rig.selected.get(), None, "a right-click on the empty graph deselects"); + assert_eq!(rig.points(), THREE.to_vec(), "and adds no point"); + rig.right_click_at([100.0, 100.0]); + assert_eq!(rig.points(), vec![[0.0, 0.0], [255.0, 255.0]], "a right-click on a point removes it"); +} + /// Where two points are closer than the grab radius, a press nearer the second grabs the second. #[trial] fn where_grab_areas_overlap_the_nearest_point_is_grabbed() { diff --git a/crates/imaging/tests/it/curve_point_keys.rs b/crates/imaging/tests/it/curve_point_keys.rs new file mode 100644 index 0000000000..29dd91b651 --- /dev/null +++ b/crates/imaging/tests/it/curve_point_keys.rs @@ -0,0 +1,81 @@ +//! The curve editor's opt-in point keys: Ctrl+Tab and Ctrl+Shift+Tab step through the points with `tab_steps`, and +//! Delete on an end point deselects it with `end_delete_deselects`. + +use super::curve::{Rig, rig_with}; +use craft_ui::testing::input::key_press; +use craft_ui::testing::trial; +use egui::{Key, Modifiers}; + +const FOUR: [[f32; 2]; 4] = [[0.0, 0.0], [64.0, 64.0], [192.0, 192.0], [255.0, 255.0]]; + +/// Selects the point at `q` with a click on it, which also focuses the graph. +fn click_point(rig: &mut Rig, q: [f32; 2]) { + rig.press_at(q); + rig.release_at(q); +} + +/// Ctrl+Tab steps right through the points and wraps; Ctrl+Shift+Tab steps left. The curve stays as it is. +#[trial] +fn tab_steps_selects_the_next_and_previous_point_round_the_curve() { + let mut rig = rig_with(&FOUR, true); + click_point(&mut rig, [64.0, 64.0]); + assert_eq!(rig.selected.get(), Some(1)); + let mut seen = Vec::new(); + for _ in 0..3 { + rig.fixture.key(egui::Key::Tab, egui::Modifiers::CTRL).idle(1); + seen.push(rig.selected.get()); + } + assert_eq!(seen, [Some(2), Some(3), Some(0)], "right, then round to the first"); + seen.clear(); + for _ in 0..3 { + rig.fixture.key(egui::Key::Tab, egui::Modifiers::CTRL | egui::Modifiers::SHIFT).idle(1); + seen.push(rig.selected.get()); + } + assert_eq!(seen, [Some(3), Some(2), Some(1)], "round to the last, then left"); + assert_eq!(rig.points(), FOUR.to_vec(), "no point moved"); +} + +/// Without the option Ctrl+Tab leaves the selection. +#[trial] +fn without_tab_steps_ctrl_tab_leaves_the_selection() { + let mut rig = rig_with(&FOUR, false); + click_point(&mut rig, [64.0, 64.0]); + rig.fixture.key(egui::Key::Tab, egui::Modifiers::CTRL).idle(1); + assert_eq!(rig.selected.get(), Some(1)); +} + +/// Delete on an end point keeps the point; with the option it deselects it, without it the point stays selected. +/// Delete on an inner point removes it either way. +#[trial] +fn end_delete_deselects_an_end_point_and_inner_points_still_go() { + for (point_keys, after) in [(false, Some(0)), (true, None)] { + let mut rig = rig_with(&FOUR, point_keys); + click_point(&mut rig, [0.0, 0.0]); + assert_eq!(rig.selected.get(), Some(0)); + rig.fixture.key(egui::Key::Delete, egui::Modifiers::NONE).idle(1); + assert_eq!(rig.points(), FOUR.to_vec(), "an end point stays"); + assert_eq!(rig.selected.get(), after, "end_delete_deselects: {point_keys}"); + click_point(&mut rig, [192.0, 192.0]); + rig.fixture.key(egui::Key::Delete, egui::Modifiers::NONE).idle(1); + assert_eq!(rig.points(), vec![[0.0, 0.0], [64.0, 64.0], [255.0, 255.0]], "an inner point goes"); + } +} + +/// Delete and then Ctrl+Tab in one frame act in the order they were pressed: on an inner point the selected point goes, +/// not the next one, and on an end point Delete only deselects, so the Ctrl+Tab after it has no point to step from. A +/// shortcut the graph doesn't claim, pressed in the same frame, still reaches the app. +#[trial] +fn delete_then_ctrl_tab_in_one_frame_act_in_order_and_other_shortcuts_reach_the_app() { + let inner_gone = vec![[0.0, 0.0], [192.0, 192.0], [255.0, 255.0]]; + for (at, after) in [([64.0, 64.0], inner_gone), ([0.0, 0.0], FOUR.to_vec())] { + let mut rig = rig_with(&FOUR, true); + click_point(&mut rig, at); + rig.app_keys.borrow_mut().clear(); + let keys = [(Key::Delete, Modifiers::NONE), (Key::Tab, Modifiers::CTRL), (Key::S, Modifiers::CTRL)]; + rig.fixture.frame_through(keys.iter().map(|(key, mods)| key_press(*key, *mods)).collect()).idle(1); + assert_eq!(rig.points(), after, "Delete acts on the point selected at {at:?}"); + assert_eq!(rig.selected.get(), None, "nothing is selected after the Delete"); + let app = rig.app_keys.borrow(); + assert!(app.contains(&Key::S) && !app.contains(&Key::Delete) && !app.contains(&Key::Tab), "the app gets only Ctrl+S: {app:?}"); + } +} diff --git a/crates/imaging/tests/it/filter_gallery.rs b/crates/imaging/tests/it/filter_gallery.rs index 6824f7586c..a58b4a783f 100644 --- a/crates/imaging/tests/it/filter_gallery.rs +++ b/crates/imaging/tests/it/filter_gallery.rs @@ -146,9 +146,7 @@ impl FilterGallerySource for Flat { Job::new(|_, _| Ok(PreviewDone::new(Duration::from_millis(12)))) } else { Job::new(|_, cancel| { - while !cancel.is_cancelled() { - std::thread::sleep(Duration::from_millis(10)); - } + cancel.wait(); Err(String::new()) }) } diff --git a/crates/imaging/tests/it/main.rs b/crates/imaging/tests/it/main.rs index 2509982365..02844e5f72 100644 --- a/crates/imaging/tests/it/main.rs +++ b/crates/imaging/tests/it/main.rs @@ -8,6 +8,7 @@ pub(crate) mod channels_memo; pub(crate) mod color_range; pub(crate) mod contour_field; pub(crate) mod curve; +pub(crate) mod curve_point_keys; pub(crate) mod fill; pub(crate) mod filter_gallery; pub(crate) mod histogram; diff --git a/crates/keymap/README.md b/crates/keymap/README.md index 8fd2b48ab0..21691ac881 100644 --- a/crates/keymap/README.md +++ b/crates/keymap/README.md @@ -305,6 +305,9 @@ assert_eq!((report.unmatched[0].item.as_str(), report.unmatched[0].line), ("File are applied in file order; the earlier key is listed in `skipped`), and an entry without keys can clear its command. It clears it only when no entry matched to the same command has keys, whatever the order of the entries. +- Conflicts removed from one command are saved as one final binding list. An intermediate + list that cannot be stored does not block an import whose final list fits. If that final + list cannot be saved, the entries taking those keys fail and keep their previous bindings. - Keys read approximately (a numeric keypad key bound as the main key) are listed in `approximated`. - With `ImportOptions.suggest`, unmatched entries get fuzzy candidates (`import::namematch`); diff --git a/crates/keymap/src/editor.rs b/crates/keymap/src/editor.rs index af8a2929f3..fbb2acafc9 100644 --- a/crates/keymap/src/editor.rs +++ b/crates/keymap/src/editor.rs @@ -104,8 +104,8 @@ impl EditSession { new: Binding, policy: Policy, ) -> Result { - let list: Vec = keymap.bindings(command).into_iter().map(|b| if b == *old { new.clone() } else { b }).collect(); - self.edit(keymap, |km| km.set_bindings(command, list, policy)) + let bindings = replacing(keymap, command, old, &new); + self.edit(keymap, |km| km.set_bindings(command, bindings, policy)) } /// Removes one binding of a command as one undo step. @@ -180,6 +180,16 @@ impl EditSession { } } +/// Checks whether the replacement that [`EditSession::replace`] would make can be saved under `policy`. +/// This leaves the keymap and its undo history untouched. +pub fn check_replace(keymap: &Keymap, command: &CommandRef, old: &Binding, new: &Binding, policy: Policy) -> Result<(), AssignError> { + keymap.check_set_bindings(command, replacing(keymap, command, old, new), policy) +} + +fn replacing(keymap: &Keymap, command: &CommandRef, old: &Binding, new: &Binding) -> Vec { + keymap.bindings(command).into_iter().map(|binding| if binding == *old { new.clone() } else { binding }).collect() +} + /// The other commands whose bindings clash with `binding` given to `command`: what /// [`Policy::Steal`] would take and [`Policy::Keep`] would leave clashing. Tools of the command's /// group and twins sharing a default key are not listed. A dialog shows these while the user diff --git a/crates/keymap/src/import.rs b/crates/keymap/src/import.rs index 55347f4e5f..11eb1fcc96 100644 --- a/crates/keymap/src/import.rs +++ b/crates/keymap/src/import.rs @@ -745,6 +745,8 @@ impl ImportPlan { /// earlier entry stays with that entry. That includes taking a chord from another command, /// or from a command whose own change failed: both commands keep the bindings they had. With /// [`Start::Defaults`] that cannot happen. + /// All conflicts removed from one command are saved together, so only its final binding + /// list must fit in the overrides, rather than each intermediate list. pub fn apply(&self, keymap: &mut Keymap) -> ImportReport { let before: Vec> = self.commands.iter().map(|p| keymap.bindings(&p.command)).collect(); // Dropping every entry leaves room for all of them: each catalog command takes at most one @@ -802,7 +804,9 @@ impl ImportPlan { // A command that cannot take a chord from another command is dropped, so both keep // the bindings they had. That includes a command whose own change failed: freeing an // entry later must not take its chord away. - let mut unbind_failed = false; + let mut removals: Vec<(CommandRef, Vec, Vec)> = Vec::new(); + let mut removal_index = HashMap::new(); + let mut cleared = Vec::new(); for (c, (p, list)) in self.commands.iter().zip(&accepted).enumerate() { if list.is_empty() || !decided.contains(&p.command.key()) { continue; @@ -811,12 +815,27 @@ impl ImportPlan { if decided.contains(&h.command.key()) { continue; } - let home = home_of(keymap, &h.command); - let label = label_of(keymap, &h.command); - let shortcut = h.binding.text(&home); - if !failed_here.contains(&h.command.key()) && keymap.remove(&h.command, &h.binding) { - report.conflicts_cleared.push(Cleared { command: h.command, label, shortcut }); - } else { + let index = *removal_index.entry(h.command.key()).or_insert_with(|| { + removals.push((h.command.clone(), Vec::new(), Vec::new())); + removals.len() - 1 + }); + let Some((_, bindings, claimants)) = removals.get_mut(index) else { continue }; + if !claimants.contains(&c) { + claimants.push(c); + } + if !bindings.contains(&h.binding) { + bindings.push(h.binding.clone()); + cleared.push(h); + } + } + } + let mut unbind_failed = false; + for (command, bindings, claimants) in removals { + let remaining = keymap.bindings(&command).into_iter().filter(|binding| !bindings.contains(binding)).collect(); + if failed_here.contains(&command.key()) || keymap.set_bindings(&command, remaining, Policy::Keep).is_err() { + for c in claimants { + let Some(p) = self.commands.get(c) else { continue }; + let Some(list) = accepted.get(c) else { continue }; let home = home_of(keymap, &p.command); let list = in_default_order(keymap, &p.command, list); let shortcuts = list.iter().map(|b| b.text(&home)).collect(); @@ -824,15 +843,21 @@ impl ImportPlan { c, Failed { command: p.command.clone(), label: label_of(keymap, &p.command), change: FailedChange::Bind, shortcuts }, ); - unbind_failed = true; - break; } + unbind_failed = true; + break; } } if unbind_failed { *keymap = start.clone(); continue 'attempt; } + for h in cleared { + let home = home_of(keymap, &h.command); + let label = label_of(keymap, &h.command); + let shortcut = h.binding.text(&home); + report.conflicts_cleared.push(Cleared { command: h.command, label, shortcut }); + } for (p, from) in self.commands.iter().zip(&before) { if !decided.contains(&p.command.key()) { diff --git a/crates/keymap/src/keymap.rs b/crates/keymap/src/keymap.rs index 31ed74a36d..025cd2c391 100644 --- a/crates/keymap/src/keymap.rs +++ b/crates/keymap/src/keymap.rs @@ -27,7 +27,7 @@ mod binding; mod command; pub use binding::{Binding, BindingError}; -pub use command::{CommandDef, CommandKind, DeleteKeys, ModalRule, TypingRule}; +pub use command::{CommandDef, CommandKind, DeleteKeys, Dispatch, ModalRule, TypingRule}; mod editing; pub use editing::text_editing_chords; @@ -229,6 +229,8 @@ pub struct Conflict { /// A binding with its scope resolved. type Bound = (Trigger, Scope); +type BindingWrites = Vec<(usize, Vec)>; +type StoredBindingWrites = Vec<(usize, Vec, Option>)>; /// Whether `trigger` can start a command: any press can; a hold needs a chord that types a character, alone or with /// Shift, since the others are taken by the system and by text fields. @@ -398,7 +400,9 @@ impl Keymap { self.find(command).map(|i| &self.catalog[i]) } - /// The effective bindings of a command; empty for an unknown one. + /// The effective bindings of a command; empty for an unknown one. A command the app runs itself + /// ([`Dispatch::App`]) lists its bindings too, as the shortcut editor shows and edits them, though nothing here + /// matches them. pub fn bindings(&self, command: &CommandRef) -> Vec { self.find(command).map(|i| self.current[i].iter().filter(|b| self.counts(b)).map(|b| self.public(i, b)).collect()).unwrap_or_default() } @@ -453,7 +457,8 @@ impl Keymap { } } - /// The command `chord` (pressed twice when `double`) runs with `active` focus. + /// The command `chord` (pressed twice when `double`) runs with `active` focus. A command the app runs itself + /// ([`Dispatch::App`]) is none of them: its chords belong to the app's own key handling. pub fn lookup(&self, chord: &Chord, double: bool, active: &Active) -> Lookup { self.lookup_nested(chord, double, active, &[]) } @@ -520,6 +525,9 @@ impl Keymap { /// applies (an application binding with no panel focused, a panel binding with its panel focused, a context /// binding with its context active), gives the command or a cycle that holds it. `None` when every binding is /// shadowed or the command has none. Read from a table the keymap builds when its bindings change. + /// + /// A command the app runs itself ([`Dispatch::App`]) shows its first single-press binding wherever it is, home + /// scope first: nothing here matches its chords, so nothing here can shadow them. pub fn shown_chord(&self, command: &CommandRef) -> Option { self.find(command).and_then(|i| self.shown[i]) } @@ -535,6 +543,15 @@ impl Keymap { fn shown_of(&self, i: usize) -> Option { let home = &self.catalog[i].scope; let single = || self.current[i].iter().filter(|(trigger, _)| trigger.press == PressKind::Single); + // The app runs a command marked `Dispatch::App` on its own, so the keymap cannot tell whether a chord it also + // binds takes the key first: it shows the command's first binding rather than dropping it as shadowed. + if self.catalog[i].dispatch == Dispatch::App { + return single() + .filter(|(_, scope)| scope == home) + .chain(single().filter(|(_, scope)| scope != home)) + .map(|(trigger, _)| trigger.chord) + .next(); + } let runs = |(trigger, scope): &&Bound| { let name = [scope.as_str()]; let active = match self.scopes.kind(scope) { @@ -592,11 +609,24 @@ impl Keymap { } let mut list = self.current[i].clone(); list.push(new.clone()); - self.apply(i, list, &[new], policy) + let (assigned, writes) = self.plan_writes(i, list, &[new], policy)?; + self.commit(writes)?; + Ok(assigned) } /// Replaces all bindings of a command. pub fn set_bindings(&mut self, command: &CommandRef, bindings: Vec, policy: Policy) -> Result { + let (assigned, writes) = self.plan_set_bindings(command, bindings, policy)?; + self.commit(writes)?; + Ok(assigned) + } + + pub(crate) fn check_set_bindings(&self, command: &CommandRef, bindings: Vec, policy: Policy) -> Result<(), AssignError> { + let (_, writes) = self.plan_set_bindings(command, bindings, policy)?; + self.prepare_writes(writes).map(|_| ()) + } + + fn plan_set_bindings(&self, command: &CommandRef, bindings: Vec, policy: Policy) -> Result<(Assigned, BindingWrites), AssignError> { let i = self.find(command).ok_or(AssignError::UnknownCommand)?; if bindings.len() > MAX_BINDINGS { return Err(AssignError::TooMany); @@ -606,7 +636,7 @@ impl Keymap { let kept: Vec = self.hidden(i).into_iter().filter(|h| !list.iter().any(|b| self.same(b, h))).collect(); list.extend(kept); let new: Vec = list.iter().filter(|b| !self.current[i].iter().any(|c| self.same(c, b))).cloned().collect(); - self.apply(i, list, &new, policy) + self.plan_writes(i, list, &new, policy) } /// Removes one binding (matched by effective trigger and scope). `false` when the command does @@ -898,7 +928,7 @@ impl Keymap { out.len() < MAX_CONFLICTS } - fn apply(&mut self, i: usize, list: Vec, new: &[Bound], policy: Policy) -> Result { + fn plan_writes(&self, i: usize, list: Vec, new: &[Bound], policy: Policy) -> Result<(Assigned, BindingWrites), AssignError> { if list.len() > MAX_BINDINGS { return Err(AssignError::TooMany); } @@ -916,7 +946,7 @@ impl Keymap { let holders: Vec = clashes.iter().map(|(j, b)| Holder { command: self.catalog[*j].command.clone(), binding: self.public(*j, b) }).collect(); let mut done = Assigned::default(); - let mut writes: Vec<(usize, Vec)> = Vec::new(); + let mut writes = Vec::new(); match policy { Policy::Refuse if !holders.is_empty() => return Err(AssignError::Taken(holders)), Policy::Refuse => {} @@ -940,12 +970,11 @@ impl Keymap { } } writes.push((i, list)); - self.commit(writes)?; - Ok(done) + Ok((done, writes)) } /// Prepares all entries before replacing live or stored bindings, including commands whose bindings were taken. - fn commit(&mut self, writes: Vec<(usize, Vec)>) -> Result<(), AssignError> { + fn prepare_writes(&self, writes: BindingWrites) -> Result { let mut prepared = Vec::with_capacity(writes.len()); for (i, list) in writes { let texts = self.store_texts(i, &list)?; @@ -955,7 +984,11 @@ impl Keymap { if self.overrides.len() + needed > MAX_COMMANDS { return Err(AssignError::Full); } - for (i, list, texts) in prepared { + Ok(prepared) + } + + fn commit(&mut self, writes: BindingWrites) -> Result<(), AssignError> { + for (i, list, texts) in self.prepare_writes(writes)? { self.remove_entries(i); if let Some(texts) = texts { self.overrides.insert(self.keys[i].clone(), texts); @@ -1043,6 +1076,11 @@ impl Keymap { fn index_command(&mut self, i: usize) { let Some(list) = self.current.get(i) else { return }; + // A command the app runs itself matches nothing here: its chords stay in the app's hands, as the raw input + // holds them. + if self.catalog[i].dispatch == Dispatch::App { + return; + } let holds = self.holds; for (k, (t, _)) in list.iter().enumerate().filter(|(_, (t, _))| holds || !t.is_hold()) { self.by_trigger.entry(t.effective(self.platform)).or_default().insert((i, k)); diff --git a/crates/keymap/src/keymap/command.rs b/crates/keymap/src/keymap/command.rs index e29300cdd7..b97c7c6d6f 100644 --- a/crates/keymap/src/keymap/command.rs +++ b/crates/keymap/src/keymap/command.rs @@ -28,6 +28,27 @@ pub enum CommandKind { Momentary, } +/// Who runs a command's keys. +/// +/// A command the app runs itself keeps its place in the catalog and its bindings: menus, tooltips, rails and buttons +/// show its chords ([`Keymap::shown_chord`](crate::Keymap::shown_chord)) and the shortcut editor lists them, and the +/// keymap matches none of them, so the press goes to the app as it would for a command with no binding here. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub enum Dispatch { + /// This keymap runs the command on its chords ([`Keymap::lookup`](crate::Keymap::lookup)). + #[default] + Keymap, + /// The app runs the command from its own key handling (a canvas editor with its own keymap). + App, +} + +/// Whether a command's keys are the keymap's, which written catalogs leave out as the default. +fn is_keymap(dispatch: &Dispatch) -> bool { + *dispatch == Dispatch::Keymap +} + /// Whether a command fires while a dialog is open. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -82,6 +103,10 @@ pub struct CommandDef { /// Whether the command fires while a dialog is open. #[serde(default)] pub modal: ModalRule, + /// Who runs the command's keys: this keymap, or the app, which shows them and matches none of them + /// ([`Dispatch`]). + #[serde(default, skip_serializing_if = "is_keymap")] + pub dispatch: Dispatch, } impl CommandDef { @@ -99,6 +124,7 @@ impl CommandDef { defaults: Vec::new(), icon: None, modal: ModalRule::default(), + dispatch: Dispatch::Keymap, } } @@ -137,6 +163,12 @@ impl CommandDef { self } + /// Sets the [`dispatch`](CommandDef::dispatch). + pub fn with_dispatch(mut self, dispatch: Dispatch) -> CommandDef { + self.dispatch = dispatch; + self + } + /// Adds a default binding. pub fn with_default(mut self, binding: Binding) -> CommandDef { self.defaults.push(binding); diff --git a/crates/keymap/src/lib.rs b/crates/keymap/src/lib.rs index 02a8abc3e2..df067d7cea 100644 --- a/crates/keymap/src/lib.rs +++ b/crates/keymap/src/lib.rs @@ -62,6 +62,10 @@ //! assert_eq!(press("M", &editing), Lookup::None, "plain keys go to the text field"); //! ``` //! +//! A command whose keys the app runs itself keeps its bindings and shows their chords, and the keymap matches none of +//! them: `CommandDef::new(..).with_dispatch(Dispatch::App)` tells the surfaces what to show for a command whose keys +//! the app's own key handling takes (a canvas's tool keys), so the menus and the shortcut editor still read the catalog. +//! //! # Storing overrides //! //! [`Overrides`] is a field of the app's craft-settings type, marked @@ -158,8 +162,8 @@ pub use import::{ ContextRule, DecodedCode, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, ImportPlan, ImportReport, NoneDefined, NotRead, Start, plan, }; pub use keymap::{ - AssignError, Assigned, Binding, BindingError, CommandDef, CommandKind, Conflict, ConflictKind, DeleteKeys, DropReason, Holder, Keymap, Lookup, - MAX_BINDING_TEXT, MAX_BINDINGS, MAX_COMMANDS, MAX_CONFLICTS, ModalRule, Overrides, Policy, Problem, TypingRule, text_editing_chords, + AssignError, Assigned, Binding, BindingError, CommandDef, CommandKind, Conflict, ConflictKind, DeleteKeys, Dispatch, DropReason, Holder, Keymap, + Lookup, MAX_BINDING_TEXT, MAX_BINDINGS, MAX_COMMANDS, MAX_CONFLICTS, ModalRule, Overrides, Policy, Problem, TypingRule, text_editing_chords, }; pub use layout::{COMMON_SYMBOLS, KeyInput, Layout, SYMBOL_TABLE, SymbolLayout}; pub use matcher::{Hit, Matcher, Press}; diff --git a/crates/keymap/tests/editor.rs b/crates/keymap/tests/editor.rs index 3de26a98d5..4cda2cb526 100644 --- a/crates/keymap/tests/editor.rs +++ b/crates/keymap/tests/editor.rs @@ -1,6 +1,7 @@ //! Integration tests of craft-keymap: editor. -use craft_keymap::{Binding, CommandDef, CommandRef, EditSession, Keymap, Platform, Policy, Scope, Scopes}; +use craft_keymap::editor::check_replace; +use craft_keymap::{AssignError, Binding, CommandDef, CommandRef, EditSession, Keymap, Platform, Policy, Scope, Scopes}; fn b(text: &str) -> Binding { Binding::parse(text).unwrap_or_else(|e| panic!("{text}: {e}")) @@ -20,6 +21,19 @@ fn keys(km: &Keymap, id: &str) -> Vec { km.bindings(&CommandRef::new(id)).iter().map(|b| b.to_string()).collect() } +#[test] +fn checking_a_replacement_does_not_take_the_other_commands_shortcut() { + let km = keymap(Platform::Mac); + let save = CommandRef::new("file.save"); + let old = b("Cmd+S"); + let new = b("Cmd+C"); + assert!(matches!(check_replace(&km, &save, &old, &new, Policy::Refuse), Err(AssignError::Taken(_)))); + assert!(check_replace(&km, &save, &old, &new, Policy::Steal).is_ok()); + assert_eq!(keys(&km, "file.save"), ["Cmd+S"]); + assert_eq!(keys(&km, "edit.copy"), ["Cmd+C"]); + assert!(km.overrides().is_empty()); +} + #[test] fn edits_undo_redo_and_cancel() { let mut km = keymap(Platform::Windows); diff --git a/crates/keymap/tests/import.rs b/crates/keymap/tests/import.rs index a48cd968c8..667385a3ba 100644 --- a/crates/keymap/tests/import.rs +++ b/crates/keymap/tests/import.rs @@ -203,6 +203,88 @@ fn a_failed_change_keeps_its_shortcut_when_a_later_change_frees_room() { assert_eq!(r.imported, 1); } +#[test] +fn an_import_removes_conflicts_using_each_commands_final_binding_list() { + let a = "A".repeat(64); + let b = "B".repeat(64); + let scopes = || Scopes::new().with_context(&a).with_context(&b); + let scope_a = Scope::new(&a).unwrap(); + let scope_b = Scope::new(&b).unwrap(); + let trigger = craft_keymap::Trigger::parse("Cmd+Ctrl+Alt+Shift+IntlBackslash Cmd+Ctrl+Alt+Shift+IntlBackslash").unwrap(); + let other = craft_keymap::Trigger::parse("Cmd+K").unwrap(); + let old = CommandRef::new("old.command"); + let first = CommandRef::new("new.first"); + let second = CommandRef::new("new.second"); + let catalog = || { + vec![ + CommandDef::new(old.clone(), "Old", Scope::app()) + .with_default(Binding::in_scope(trigger, scope_a.clone())) + .with_default(Binding::in_scope(other, scope_b.clone())), + CommandDef::new(first.clone(), "First", scope_a.clone()), + CommandDef::new(second.clone(), "Second", scope_b.clone()), + ] + }; + let mut km = Keymap::new(catalog(), scopes(), Platform::Mac); + assert_eq!(km.bindings(&old).len(), 2); + assert!(km.bindings(&old).iter().any(|binding| binding.text(&Scope::app()).len() > craft_keymap::MAX_BINDING_TEXT)); + // A reader can supply an already parsed sequence through the public import API. + let key = |trigger: craft_keymap::Trigger| ForeignKey { context: None, text: trigger.to_string(), trigger: Ok(trigger), notes: Vec::new() }; + let set = ForeignSet::new(vec![ + ForeignEntry::new(None, ["Second"]).with_id("new.second").with_key(key(other)), + ForeignEntry::new(None, ["First"]).with_id("new.first").with_key(key(trigger)), + ]); + let report = plan(&set, &km, &ImportOptions::default()).apply(&mut km); + assert!(report.failed.is_empty(), "the final cleared list is savable: {report:?}"); + assert_eq!(report.imported, 2); + assert_eq!(report.conflicts_cleared.len(), 2); + assert!(km.bindings(&old).is_empty()); + assert_eq!(km.bindings(&first), [Binding::new(trigger)]); + assert_eq!(km.bindings(&second), [Binding::new(other)]); + let reopened = Keymap::new(catalog(), scopes(), Platform::Mac).with_overrides(km.overrides().clone()); + for command in [&old, &first, &second] { + assert_eq!(reopened.bindings(command), km.bindings(command), "the imported bindings persist in the same contexts"); + } +} + +#[test] +fn an_unsavable_final_conflict_list_keeps_all_claimants_and_applies_other_entries() { + let context = "A".repeat(64); + let scope = Scope::new(&context).unwrap(); + let long = craft_keymap::Trigger::parse("Cmd+Ctrl+Alt+Shift+IntlBackslash Cmd+Ctrl+Alt+Shift+IntlBackslash").unwrap(); + let old = CommandRef::new("old.command"); + let catalog = vec![ + CommandDef::new(old.clone(), "Old", Scope::app()) + .with_default(Binding::in_scope(long, scope.clone())) + .with_default(b("Cmd+K")) + .with_default(b("Cmd+L")), + command("new.first", "First", &[], &["Cmd+1"]), + command("new.second", "Second", &[], &["Cmd+2"]), + command("new.other", "Other", &[], &[]), + command("old.other", "Old Other", &[], &["Cmd+J"]), + ]; + let mut overrides = Overrides::new(); + for n in 0..MAX_COMMANDS - 3 { + overrides.insert(format!("junk.{n}"), vec!["Cmd+9".into()]); + } + let mut km = Keymap::new(catalog, Scopes::new().with_context(&context), Platform::Mac).with_overrides(overrides); + let before = km.bindings(&old); + let set = ForeignSet::new(vec![ + ForeignEntry::new(None, ["First"]).with_id("new.first").with_key(ForeignKey::read(None, "Cmd+K", Flavor::Mac)), + ForeignEntry::new(None, ["Second"]).with_id("new.second").with_key(ForeignKey::read(None, "Cmd+L", Flavor::Mac)), + ForeignEntry::new(None, ["Other"]).with_id("new.other").with_key(ForeignKey::read(None, "Cmd+J", Flavor::Mac)), + ]); + let report = plan(&set, &km, &ImportOptions::default()).apply(&mut km); + assert_eq!(report.failed.iter().map(|failed| failed.command.id.as_str()).collect::>(), ["new.first", "new.second"]); + assert_eq!(report.imported, 1); + assert_eq!(report.conflicts_cleared.len(), 1); + assert_eq!(report.conflicts_cleared[0].command.id, "old.other"); + assert_eq!(km.bindings(&old), before); + has(&km, "new.first", &["Cmd+1"]); + has(&km, "new.second", &["Cmd+2"]); + has(&km, "new.other", &["Cmd+J"]); + has(&km, "old.other", &[]); +} + /// A Mac keymap of `catalog` with no reserved chords, for sets read with [`kys::read`]. fn mac_keymap(catalog: Vec) -> Keymap { Keymap::new(catalog, Scopes::new(), Platform::Mac) diff --git a/crates/keymap/tests/keymap.rs b/crates/keymap/tests/keymap.rs index 215668bdd7..64ceb0f7e2 100644 --- a/crates/keymap/tests/keymap.rs +++ b/crates/keymap/tests/keymap.rs @@ -1,8 +1,8 @@ //! Integration tests of craft-keymap: keymap. use craft_keymap::{ - Active, Binding, Chord, CommandDef, CommandRef, DeleteKeys, DropReason, Key, KeyInput, Keymap, Layout, Lookup, MAX_COMMANDS, Matcher, Mods, - Overrides, Platform, Policy, Press, Problem, Scope, Scopes, Trigger, + Active, Binding, Chord, CommandDef, CommandRef, DeleteKeys, Dispatch, DropReason, Key, KeyInput, Keymap, Layout, Lookup, MAX_COMMANDS, Matcher, + Mods, Overrides, Platform, Policy, Press, Problem, Scope, Scopes, Trigger, }; use serde_json::json; @@ -152,6 +152,35 @@ fn a_command_shows_only_the_chords_the_lookup_runs_it_for() { assert_eq!(alone.shown_chord(&cmd("edit.settings")), None, "every key shadowed"); } +/// A command the app runs itself keeps its bindings and the chord they show, and matching passes over it: the lookup +/// finds nothing for its chords, the command holds none, another command on a chord it binds still shows it, and an +/// assignment takes nothing from it. +#[test] +fn a_command_the_app_runs_itself_shows_its_chords_and_matches_none() { + let own = |id: &str, keys: &[&str]| app(id, keys).with_dispatch(Dispatch::App); + let km = Keymap::new(vec![own("tool.brush", &["J", "B"])], Scopes::new(), Platform::Mac); + assert_eq!(km.shown_chord(&cmd("tool.brush")), Some(chord("J")), "its first binding shows"); + assert_eq!(km.bindings(&cmd("tool.brush")), [b("J"), b("B")], "and the shortcut editor lists them"); + assert_eq!(press(&km, "J", &Active::NONE), Lookup::None, "the lookup passes over its chords"); + assert_eq!(press(&km, "B", &Active::NONE), Lookup::None); + assert_eq!(km.holder(&chord("J")), None, "it holds no chord"); + assert!(km.holders(&chord("J")).is_empty()); + + // Another command on a chord it binds runs, and it still shows its own chord: nothing here shadows it. + let shared = Keymap::new(vec![own("tool.brush", &["J"]), app("view.grid", &["J"])], Scopes::new(), Platform::Mac); + assert_eq!(press(&shared, "J", &Active::NONE), run("view.grid"), "the chord is the other command's"); + assert_eq!(shared.shown_chord(&cmd("tool.brush")), Some(chord("J"))); + assert_eq!(shared.shown_chord(&cmd("view.grid")), Some(chord("J"))); + assert!(shared.conflicts().is_empty(), "a chord the app runs clashes with nothing here"); + + // Assigning a chord it binds to another command takes nothing from it. + let mut stealer = Keymap::new(vec![own("tool.brush", &["B"]), app("view.grid", &["J"])], Scopes::new(), Platform::Mac); + let done = stealer.assign(&cmd("view.grid"), b("B"), Policy::Steal).expect("the assignment is taken"); + assert!(done.taken_from.is_empty(), "the command the app runs keeps its binding"); + assert_eq!(stealer.bindings(&cmd("tool.brush")), [b("B")]); + assert_eq!(press(&stealer, "B", &Active::NONE), run("view.grid")); +} + /// The shown chords are worked out when the bindings change, not per call, and follow every change: a key freed by one /// command shows on the command it no longer shadows, and a stolen key leaves the command it was taken from. #[test] diff --git a/crates/latex/src/parser.rs b/crates/latex/src/parser.rs index 12971f1d05..d502e73976 100644 --- a/crates/latex/src/parser.rs +++ b/crates/latex/src/parser.rs @@ -5,6 +5,12 @@ use super::units::{length_pt, parse_color, size_of}; use super::{Align, Document, FBlock, Flow, Fmt, Inline, Kind, ListInfo, Para, model}; use craft_math::latex_text::latex_to_linear; +// Each visit in the two backward bookmark scans, not the number of source bytes. +#[cfg(test)] +std::thread_local! { + static LABEL_SCAN_STEPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + // ============================================================================================= // Import @@ -184,7 +190,18 @@ impl<'a> Parser<'a> { /// [`MAX_ANCHOR_RUN`] in a row further ones are left out (thousands of labels with no text /// between them made reading a file take time quadratic in its size). fn anchor(&mut self, name: String) { - let run = self.para.inlines.iter().rev().take(MAX_ANCHOR_RUN).take_while(|i| matches!(i, Inline::Anchor(_))).count(); + let run = self + .para + .inlines + .iter() + .rev() + .take(MAX_ANCHOR_RUN) + .take_while(|i| { + #[cfg(test)] + LABEL_SCAN_STEPS.with(|steps| steps.set(steps.get().saturating_add(1))); + matches!(i, Inline::Anchor(_)) + }) + .count(); if run < MAX_ANCHOR_RUN { self.para.inlines.push(Inline::Anchor(name)); } @@ -192,7 +209,11 @@ impl<'a> Parser<'a> { fn text(&mut self, s: &str) { // Spaces collapse, and none start a paragraph (as in TeX). - let after_space = match self.para.inlines.iter().rev().find(|i| !matches!(i, Inline::Anchor(_))) { + let after_space = match self.para.inlines.iter().rev().find(|i| { + #[cfg(test)] + LABEL_SCAN_STEPS.with(|steps| steps.set(steps.get().saturating_add(1))); + !matches!(i, Inline::Anchor(_)) + }) { Some(Inline::Text(t, _)) => t.is_empty() || t.ends_with([' ', '\n']), Some(_) => false, None => true, @@ -988,3 +1009,43 @@ pub fn parse(src: &str) -> Flow { fn squash(s: &str) -> String { s.split_whitespace().collect::>().join(" ") } + +#[cfg(test)] +mod tests { + use super::*; + + /// The backward bookmark scans grow linearly with a run of labels. + /// Count the actual scan visits so machine speed cannot decide whether this test passes. + #[test] + fn latex_labels_in_a_row_are_read_in_linear_time() -> Result<(), &'static str> { + let counted = |src: &str| { + LABEL_SCAN_STEPS.with(|steps| steps.set(0)); + assert!(import(src.as_bytes()).body.len() <= 2); + LABEL_SCAN_STEPS.with(std::cell::Cell::get) + }; + let cases: [fn(usize) -> String; 3] = + [|n| "\\label{a} ".repeat(n) + "x", |n| "\\label{a}".repeat(n) + "x", |n| "\\hypertarget{a}{} ".repeat(n)]; + let counts: Vec<_> = cases + .into_iter() + .map(|make| { + let n = 128; + (counted(&make(n)), counted(&make(n * 8))) + }) + .collect(); + let d = import("\\label{one}First \\label{two}second \\label{three}third.".as_bytes()); + let p = d.para_at(&craft_wordmodel::Pos::body(0, 0)).ok_or("the imported paragraph is missing")?; + let names: Vec<&str> = p + .objects + .iter() + .filter_map(|o| if let craft_wordmodel::InlineObject::BookmarkStart { name } = o { Some(name.as_str()) } else { None }) + .collect(); + assert_eq!(names, ["one", "two", "three"]); + assert_eq!(d.plain_text(craft_wordmodel::StoryRef::Body).replace('\u{FFFC}', ""), "First second third."); + for (shape, (small, large)) in counts.into_iter().enumerate() { + // Eight times the labels may double the linear ratio while the bounded scans + // reach their steady state; a quadratic rescan instead approaches 64 times. + assert!(small > 0 && large > small && large <= small * 16, "label shape {shape}: {small} scan visits at n, {large} at 8n"); + } + Ok(()) + } +} diff --git a/crates/latex/tests/hostile.rs b/crates/latex/tests/hostile.rs index 40755bc285..fe31be9eef 100644 --- a/crates/latex/tests/hostile.rs +++ b/crates/latex/tests/hostile.rs @@ -66,28 +66,6 @@ fn fastest(src: &str) -> Duration { .unwrap_or_default() } -/// Labels in a row are read in linear time: four times as many take well under the sixteen times -/// as long a quadratic read would (a ratio, so a busy machine does not fail it). -#[test] -fn latex_labels_in_a_row_are_read_in_linear_time() { - let cases: [fn(usize) -> String; 3] = [|n| "\\label{a} ".repeat(n) + "x", |n| "\\label{a}".repeat(n) + "x", |n| "\\hypertarget{a}{} ".repeat(n)]; - // The gate reads half the labels; nightly the full counts. - let size = |n: usize| n / craft_testkit::hostile::divisor().min(2); - for make in cases { - let (small, large) = (fastest(&make(size(25_000))), fastest(&make(size(100_000)))); - assert!(large < small * 8 + Duration::from_millis(50), "{small:?} for 25,000, {large:?} for 100,000"); - } - let d = import("\\label{one}First \\label{two}second \\label{three}third.".as_bytes()); - let p = d.para_at(&craft_wordmodel::Pos::body(0, 0)).unwrap(); - let names: Vec<&str> = p - .objects - .iter() - .filter_map(|o| if let craft_wordmodel::InlineObject::BookmarkStart { name } = o { Some(name.as_str()) } else { None }) - .collect(); - assert_eq!(names, ["one", "two", "three"]); - assert_eq!(d.plain_text(craft_wordmodel::StoryRef::Body).replace('\u{FFFC}', ""), "First second third."); -} - /// Empty optional arguments in a row after a definition are skipped in linear time: the text after /// each `]` is read where it lies in the token, not copied, and a run of no-break spaces at the /// token's end is not read again for each argument. diff --git a/crates/layers/src/ui/panel/mod.rs b/crates/layers/src/ui/panel/mod.rs index 02a8cf1574..d5491ae469 100644 --- a/crates/layers/src/ui/panel/mod.rs +++ b/crates/layers/src/ui/panel/mod.rs @@ -237,6 +237,10 @@ pub struct LayersOutput { pub hovered: Option, /// Key focus is in the rows this pass. pub focused: bool, + /// The pass's real run applied its one-time requests ([`start_rename`](LayersPanel::start_rename), + /// [`reveal`](LayersPanel::reveal), [`focus_filter_name`](LayersPanel::focus_filter_name)). A measuring run or a + /// replay applies none, so the host keeps them and passes them again until this is set. + pub requests_taken: bool, /// The panel. pub response: Response, } @@ -457,7 +461,7 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> { let current = RefCell::new(LayerFilter::default()); let unlock_label = words.unlock_layer.clone(); - let shown = Stack::new() + let mut shown = Stack::new() .fill() .command_scope(LayersPanelKeys::SCOPE) .header(|ui, stack| { @@ -536,11 +540,12 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> { } (reported, body.drop_preview, body.hovered, focused) }); + let requests_taken = shown.settle(|_, _| ()).is_some(); // Only the real run's result comes back, so the reveal's opens and the list's events are reported once. let mut events = events.into_inner(); let (body, drop_preview, hovered, focused) = shown.inner.unwrap_or_default(); events.extend(body); - LayersOutput { events, drop_preview, hovered, focused, response: shown.output } + LayersOutput { events, drop_preview, hovered, focused, requests_taken, response: shown.output } } } diff --git a/crates/layers/tests/it/panel_memo.rs b/crates/layers/tests/it/panel_memo.rs index 0de36e2fd3..e733658654 100644 --- a/crates/layers/tests/it/panel_memo.rs +++ b/crates/layers/tests/it/panel_memo.rs @@ -4,7 +4,7 @@ use craft_layers::ui::filter::{FilterBy, LayerFilter}; use craft_layers::ui::mock::FakeLayers; use craft_layers::ui::panel::{LayersEvent, LayersPanel}; use craft_ui::contract::{Bind, MemoProps, MemoView, Outbox, Tracked}; -use craft_ui::testing::{Fixture, MemoRun, last_frame_derived_builds, last_frame_memo_runs, pointer, trial}; +use craft_ui::testing::{Fixture, MemoRun, last_frame_derived_builds, last_frame_memo_runs, last_pass_memo_runs, pointer, trial}; use egui::{Ui, Vec2}; use std::cell::RefCell; use std::rc::Rc; @@ -73,6 +73,11 @@ impl Rig { (count(MemoRun::Ran), count(MemoRun::Replayed)) } + /// The real runs in the last pass of the memoized views whose type name holds `name`. + fn real_runs(&self, name: &str) -> u32 { + last_pass_memo_runs(self.fixture.ctx()).iter().filter(|(ty, _, run)| ty.contains(name) && *run == MemoRun::Ran).count() as u32 + } + /// One frame with no input, after the edit of the trial. fn frame(&mut self) -> &mut Self { self.fixture.frame(Vec::new()); @@ -184,7 +189,9 @@ fn a_pointer_over_the_rows_replays_the_blend_rows() { } } -/// A new blend mode on the active layer runs the blend rows, so they never show a stale value. +/// A new blend mode on the active layer runs the blend rows, so they never show a stale value. The edit is a new +/// version of the panel's view, so the header measures its content afresh in the frame's one pass: the blend rows run +/// in that measuring run and once more in the real run. #[trial] fn the_active_layers_blend_mode_runs_the_blend_rows() { let mut rig = rig(FakeLayers::fifty()); @@ -195,7 +202,9 @@ fn the_active_layers_blend_mode_runs_the_blend_rows() { layer.info.blend_key = String::from("multiply"); } rig.frame(); - assert_eq!(rig.view_runs("BlendProps").0, 1, "the edit runs the blend rows"); + assert_eq!(rig.fixture.passes(), 1, "the edit runs one pass"); + assert_eq!(rig.real_runs("BlendProps"), 1, "the edit runs the blend rows in the real run"); + assert!(rig.view_runs("BlendProps").0 <= 2, "and at most once more, in the header's measuring run"); rig.frame(); assert_eq!(rig.host_runs(), (0, 1), "and the panel replays after it"); } diff --git a/crates/lottie/src/zip.rs b/crates/lottie/src/zip.rs index 05ebe0b70a..cb3dc3509a 100644 --- a/crates/lottie/src/zip.rs +++ b/crates/lottie/src/zip.rs @@ -116,8 +116,15 @@ mod tests { fn deflated_entries_are_read_and_path_traversal_is_skipped() { let mut writer = Writer::new(); writer.add("animations/main.json", br#"{"w":1,"h":1}"#, Compression::Deflated).unwrap(); - writer.add("../outside.json", b"{}", Compression::Deflated).unwrap(); - let bytes = writer.finish().unwrap(); + writer.add("xx/outside.json", b"{}", Compression::Deflated).unwrap(); + let mut bytes = writer.finish().unwrap(); + let target = b"xx/outside.json"; + let replacement = b"../outside.json"; + for i in 0..bytes.len().saturating_sub(target.len()) { + if &bytes[i..i + target.len()] == target { + bytes[i..i + target.len()].copy_from_slice(replacement); + } + } assert_eq!(read_entries(&bytes).unwrap(), [("animations/main.json".into(), br#"{"w":1,"h":1}"#.to_vec())]); assert!(read_entries_with_limits(&bytes, Limits { max_entries: 10, max_total_bytes: 4 }).is_err()); } diff --git a/crates/markdown/src/inlines.rs b/crates/markdown/src/inlines.rs index 99c3972463..f8facbf3f9 100644 --- a/crates/markdown/src/inlines.rs +++ b/crates/markdown/src/inlines.rs @@ -377,7 +377,20 @@ fn tokenize(s: &str, base: &Fmt, depth: usize, refs: &Refs) -> Vec { } b'&' => { let rest = s.get(i..).unwrap_or(""); - match within(rest, 33).find(';').and_then(|k| decode_entity(rest.get(1..k)?).map(|ch| (ch, k))) { + match within(rest, 33).find(';').and_then(|k| { + let name = rest.get(1..k)?; + // CommonMark limits numeric references to seven decimal or six hexadecimal digits. + if let Some(num) = name.strip_prefix('#') { + let (digits, max) = match num.strip_prefix(['x', 'X']) { + Some(hex) => (hex, 6), + None => (num, 7), + }; + if digits.len() > max { + return None; + } + } + decode_entity(name).map(|ch| (ch, k)) + }) { Some((ch, k)) => { flush!(); push_text(&mut nodes, &ch, base); @@ -415,7 +428,7 @@ fn angle_inlines(s: &str, start: usize, base: &Fmt) -> Option<(usize, Vec) } else if matches!(lower.trim_end_matches('/').trim(), "br") { push_text(&mut nodes, "\n", base); Some((end, nodes)) - } else if lower.starts_with("a ") && rest.get(inner.len() + 1..).is_some_and(|tail| tail.to_ascii_lowercase().starts_with("")) { + } else if lower.starts_with("a ") && rest.get(inner.len() + 1..).and_then(|tail| tail.get(..4)).is_some_and(|p| p.eq_ignore_ascii_case("")) { if let Some(name) = tag_attr(inner, "id").or_else(|| tag_attr(inner, "name")) { nodes.push(Node::Inl(Inline::Anchor(name))); } diff --git a/crates/markdown/src/tests.rs b/crates/markdown/src/tests.rs index 309fda157f..427ef35c1a 100644 --- a/crates/markdown/src/tests.rs +++ b/crates/markdown/src/tests.rs @@ -21,6 +21,29 @@ fn emphasis() { assert!(matches!(&s[0], Inline::Text(t, f) if t == "gone" && f.strike)); } +/// An empty `` or `` is an anchor whatever the case of its `` (wordcraft#3715). +#[test] +fn empty_html_anchor() { + let anchors = |s: &str| inl(s).into_iter().filter_map(|i| if let Inline::Anchor(a) = i { Some(a) } else { None }).collect::>(); + assert_eq!(anchors(r#"x y"#), vec!["n"]); + assert_eq!(anchors(r#"x y"#), vec!["m"]); + assert_eq!(anchors(r#""#), vec!["p"]); + assert!(anchors(r#"text"#).is_empty()); + assert!(anchors(r#"` tag lower-cased a copy of the rest of its paragraph to look for `` +/// (wordcraft#3715): quadratic on a paragraph of tags. +#[test] +fn a_paragraph_of_anchor_tags_parses_in_linear_time() { + let src = "".repeat(1_000_000); + let t = std::time::Instant::now(); + inl(&src); + // Well under a second now; the per-tag copy took 40 s in a release build. + assert!(t.elapsed() < std::time::Duration::from_secs(10), "{:?}", t.elapsed()); +} + #[test] fn links_code_escapes() { let s = inl("see [the *site*](http://x.org \"T\") and `a*b*` \\*lit\\* & "); @@ -36,6 +59,28 @@ fn links_code_escapes() { assert!(text.contains("*lit* & "), "{text}"); } +#[test] +fn numeric_references_respect_commonmark_digit_limits() { + for (input, expected) in [ + ("�", "�"), + ("�", "�"), + ("�", "�"), + ("�", "�"), + ("A", "A"), + ("A", "A"), + ("A", "A"), + ("A", "A"), + ("A", "A"), + ("�", "\u{FFFD}"), + ("􏿿", "\u{10FFFF}"), + ("�", "\u{FFFD}"), + ("�", "\u{FFFD}"), + ("&", "&"), + ] { + assert_eq!(spans(input), vec![(expected.into(), false, false)], "{input}"); + } +} + /// Reference links: `[text][label]`, `[text][]` and `[text]` take their destination from a /// definition line, and the definition itself leaves the document. Before, none of the three /// was a link and the definition stayed as a paragraph of its own (#3238). diff --git a/crates/materialx/src/lib.rs b/crates/materialx/src/lib.rs index 99701366f9..e9c98a51c8 100644 --- a/crates/materialx/src/lib.rs +++ b/crates/materialx/src/lib.rs @@ -7,7 +7,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use craft_xml::{Doctype, El, Error as XmlError, Limits, Options, UnknownEntity}; @@ -65,6 +65,31 @@ pub enum Value { Image(String), } +/// The value connected to a shader input, as [`Document::read_material_strict`] resolves it. +#[derive(Clone, Debug, PartialEq)] +pub enum Resolved { + /// One to four finite numbers, kept in the source color space. The numbers may be separated + /// by commas, spaces or both, a `boolean` input's `true` and `false` are 1 and 0, and an + /// `integer` input holds one whole number. A `convert` node's output holds the converted channels. `colorspace` is the color + /// space in effect where the value is written: the input's own `colorspace`, else that of the + /// nearest enclosing element (the node, then its nodegraph), else the document's. A value + /// written on an input with a boolean, integer, float or vector type, on such a `constant` + /// node, or with no type on a `convert` node's input, is in the document's working color + /// space (the root element's `colorspace`). A `convert` node, and a `constant` node whose + /// value is connected, keep the color space of their input. + Constant { values: Vec, colorspace: Option }, + /// A file from an image node, with the file prefix in effect applied: the `file` input's + /// `fileprefix`, else the node's, its nodegraph's or the document's. `colorspace` is the + /// color space in effect on the node's `file` input, found the same way as for a constant, + /// and `uv_tiling` is the node's `uvtiling` as written. A `uvtiling` value that is not two + /// finite numbers is [`Error::Malformed`]. An image node with a boolean, integer, float or + /// vector type is in the document's working color space. + Image { file: String, colorspace: Option, uv_tiling: Option<[f32; 2]> }, + /// This variant stores an encoded tangent-space image connected through a `normalmap` node. + /// The fields have the same meaning as [`Self::Image`]. + NormalMap { file: String, colorspace: Option, uv_tiling: Option<[f32; 2]> }, +} + /// A surface material resolved from a MaterialX document. #[derive(Clone, Debug, PartialEq)] pub struct Material { @@ -82,12 +107,41 @@ pub struct Material { pub warnings: Vec, } +/// A surface material resolved by [`Document::read_material_strict`]. +#[derive(Clone, Debug, PartialEq)] +pub struct StrictMaterial { + /// Material name, or `Material` when omitted. + pub name: String, + /// Shader dialect represented by the material. + pub shader: Shader, + /// Resolved inputs in the shader table's deterministic order. + pub inputs: Vec<(String, Resolved)>, + /// Resolved scalar displacement input, if present. Vector displacement is reported as unsupported. + pub displacement: Option, + /// First image tiling of two positive numbers, kept in `0.001..=1000`, or `[1, 1]`. + pub uv_tiling: [f32; 2], + /// Unsupported or ignored constructs encountered while resolving values, and shader inputs + /// that are not in the shader's table and so are not read. + pub warnings: Vec, +} + #[derive(Clone, Debug)] struct Found { value: Value, tiling: Option<[f32; 2]>, } +/// The material, its surface shader and the document's nodes, found for a read. +struct Located<'a> { + mat: &'a El, + shader: &'a El, + scope: Option, + kind: Shader, + nodes: HashMap, + graphs: HashMap<&'a str, &'a El>, + outputs: Vec<(String, String)>, +} + const OPEN_PBR_INPUTS: &[&str] = &[ "base_color", "base_metalness", @@ -138,6 +192,76 @@ const GLTF_INPUTS: &[&str] = &[ "transmission", ]; +const OPEN_PBR_STRICT_INPUTS: &[&str] = &[ + "base_color", + "base_metalness", + "specular_roughness", + "geometry_normal", + "geometry_opacity", + "emission_color", + "coat_weight", + "coat_roughness", + "geometry_coat_normal", + "fuzz_weight", + "fuzz_color", + "fuzz_roughness", + "specular_roughness_anisotropy", + "transmission_weight", + "subsurface_weight", + "base_weight", + "specular_weight", + "specular_color", + "specular_ior", + "coat_color", + "coat_ior", + "emission_luminance", +]; +const STANDARD_STRICT_INPUTS: &[&str] = &[ + "base_color", + "metalness", + "specular_roughness", + "normal", + "opacity", + "emission_color", + "coat", + "coat_roughness", + "coat_normal", + "sheen", + "sheen_color", + "sheen_roughness", + "specular_anisotropy", + "transmission", + "subsurface", + "base", + "specular", + "specular_color", + "specular_IOR", + "coat_color", + "coat_IOR", + "emission", +]; +const GLTF_STRICT_INPUTS: &[&str] = &[ + "base_color", + "metallic", + "roughness", + "normal", + "alpha", + "emissive", + "occlusion", + "clearcoat", + "clearcoat_roughness", + "clearcoat_normal", + "sheen_color", + "sheen_roughness", + "transmission", + "emissive_strength", + "ior", + "specular", + "specular_color", + "alpha_mode", + "alpha_cutoff", +]; + /// OpenPBR input kind accepted by [`write_open_pbr`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum InputKind { @@ -253,49 +377,13 @@ impl Document { /// Resolves a surface material into shader inputs, image paths and warnings. pub fn read_material(&self, material: Option<&str>) -> Result { - let materials: Vec<&El> = self.root.children("surfacematerial").collect(); - let mat = match material { - Some(name) => materials.iter().copied().find(|m| m.attr("name") == Some(name)).ok_or_else(|| Error::MissingMaterial(name.to_owned()))?, - None => materials.first().copied().ok_or_else(|| Error::Unsupported("document has no surfacematerial".into()))?, + let Located { mat, shader, kind, nodes, outputs, .. } = self.locate(material, false)?; + let inputs = match kind { + Shader::OpenPbr => OPEN_PBR_INPUTS, + Shader::StandardSurface => STANDARD_INPUTS, + Shader::GltfPbr => GLTF_INPUTS, }; - let mut nodes = HashMap::new(); - let mut outputs = Vec::new(); - for child in self.root.elements() { - if child.name == "nodegraph" { - let Some(graph) = child.attr("name") else { continue }; - for node in child.elements() { - let Some(name) = node.attr("name") else { continue }; - if node.name == "output" { - if let Some(from) = node.attr("nodename") { - outputs.push((format!("{graph}/{name}"), format!("{graph}/{from}"))); - } - } else { - nodes.insert(format!("{graph}/{name}"), node); - } - } - } else if let Some(name) = child.attr("name") { - nodes.insert(name.to_owned(), child); - } - } - let shader_name = mat.children("input").find(|i| i.attr("name") == Some("surfaceshader")).and_then(|i| i.attr("nodename")); - let shader = shader_name.and_then(|n| nodes.get(n).copied()).ok_or_else(|| Error::Malformed("material has no surface shader".into()))?; - let (kind, inputs) = match shader.name.as_str() { - "open_pbr_surface" => (Shader::OpenPbr, OPEN_PBR_INPUTS), - "standard_surface" => (Shader::StandardSurface, STANDARD_INPUTS), - "gltf_pbr" => (Shader::GltfPbr, GLTF_INPUTS), - other => return Err(Error::Unsupported(format!("surface shader is {other}"))), - }; - let emission_gate = match kind { - Shader::OpenPbr => Some(("emission_luminance", true)), - Shader::StandardSurface => Some(("emission", true)), - Shader::GltfPbr => None, - }; - let emission_enabled = emission_gate.is_none_or(|(name, _)| { - shader - .children("input") - .find(|i| i.attr("name") == Some(name)) - .is_some_and(|i| i.attr("value").is_none_or(|v| parse_numbers(v).and_then(|n| n.first().copied()).is_some_and(|v| v > 0.0))) - }); + let emission_enabled = emission_enabled(kind, shader, parse_numbers); let mut warnings = Vec::new(); let base_weight_name = match kind { Shader::OpenPbr => Some("base_weight"), @@ -343,6 +431,166 @@ impl Document { warnings, }) } + + /// Resolves a surface material like [`Document::read_material`], with a wider input table, the + /// color space in effect and the UV tiling of each image, and stricter checks. + /// + /// The tables add each shader's weight, specular, IOR and coat color inputs, OpenPBR's + /// `emission_luminance`, and glTF PBR's `emissive_strength` and alpha mode inputs; glTF PBR's + /// emission color is read from `emissive`, the name its node definition gives it. Values may + /// be separated by commas, spaces or both, `convert` nodes follow the Standard Nodes rules, + /// and an image inside a nodegraph takes the nodegraph's `fileprefix`. A repeated shader + /// input, a value that is not one to four finite numbers or does not fit its type, and a + /// `uvtiling` that is not two finite numbers are [`Error::Malformed`]. A shader input that is + /// not in the table gives the warning `input is not read`; the base weight warning of + /// [`Document::read_material`] is not given, since the weight is read. A `normalmap` node's + /// `scale` other than 1 and authored `normal`, `tangent`, and `bitangent` inputs are not applied + /// and give warnings. Image inputs of `normalmap` nodes resolve as [`Resolved::NormalMap`]. + /// Three-component literal normal-map inputs are unsupported and give warnings. Other literal + /// sizes return [`Error::Malformed`]. + /// Surface shaders may connect through graph outputs. A graph with several outputs needs a + /// named selection; a graph with one output uses it regardless of the selection attribute. + /// Missing node and graph-output references are errors. Supported numeric `constant` nodes + /// use their typed zero values when `value` is omitted. Emission colors remain resolved when + /// their strength is zero. Nonzero image `uvoffset`, nonidentity displacement `scale`, and + /// vector displacement are reported as unsupported. + pub fn read_material_strict(&self, material: Option<&str>) -> Result { + let Located { mat, shader, scope, kind, nodes, graphs, outputs } = self.locate(material, true)?; + let inputs = match kind { + Shader::OpenPbr => OPEN_PBR_STRICT_INPUTS, + Shader::StandardSurface => STANDARD_STRICT_INPUTS, + Shader::GltfPbr => GLTF_STRICT_INPUTS, + }; + let mut warnings = Vec::new(); + let mut seen = HashSet::new(); + for name in shader.children("input").filter_map(|i| i.attr("name")) { + if !seen.insert(name) { + return Err(Error::Malformed(format!("the shader has more than one {name} input"))); + } + if !inputs.contains(&name) { + warnings.push(format!("input {name} is not read")); + } + } + let resolver = Resolver { root: &self.root, nodes: &nodes, graphs: &graphs, outputs: &outputs }; + let shader_space = resolver.space_of(shader, scope.as_deref()); + let mut resolved = Vec::new(); + let mut tiling = None; + for name in inputs { + let Some(input) = shader.children("input").find(|i| i.attr("name") == Some(*name)) else { continue }; + if let Some(value) = resolver.value(input, scope.as_deref(), shader_space, 0, &mut warnings)? { + if tiling.is_none() { + tiling = image_tiling(&value); + } + resolved.push(((*name).to_owned(), value)); + } + } + let mut displacement = None; + if let Some(connection) = mat.children("input").find(|i| i.attr("name") == Some("displacementshader")) { + let target = resolver.target(connection, None)?; + if let Some(node) = target.as_ref().and_then(|name| nodes.get(name).copied()) { + let node_scope = target.as_deref().and_then(|name| name.split_once('/')).map(|(graph, _)| graph); + let space = resolver.space_of(node, node_scope); + if let Some(input) = node.children("input").find(|i| i.attr("name") == Some("displacement")) { + let value = resolver.value(input, node_scope, space, 0, &mut warnings)?; + if resolver.value_type(input, node_scope)? == Some("vector3") + || matches!(&value, Some(Resolved::Constant { values, .. }) if values.len() == 3) + { + warnings.push("vector displacement is not supported; its input was skipped".into()); + } else { + displacement = value; + } + } + if let Some(scale) = node.children("input").find(|i| i.attr("name") == Some("scale")).filter(|i| has_authored_value(i)) { + let value = resolver.value(scale, node_scope, space, 0, &mut warnings)?; + match value { + Some(Resolved::Constant { values, .. }) if values.len() != 1 => { + return Err(Error::Malformed("displacement scale is not one finite number".into())); + } + Some(Resolved::Constant { values, .. }) if values == [1.0] => {} + _ => warnings.push("the scale of the displacement node is not read".into()), + } + } + if tiling.is_none() { + tiling = displacement.as_ref().and_then(image_tiling); + } + } + } + Ok(StrictMaterial { + name: mat.attr("name").unwrap_or("Material").to_owned(), + shader: kind, + inputs: resolved, + displacement, + uv_tiling: tiling.unwrap_or([1.0, 1.0]), + warnings, + }) + } + + /// The surface material named `material` (or the first one), its surface shader, and the + /// document's nodes, nodegraphs and graph outputs. + fn locate(&self, material: Option<&str>, strict: bool) -> Result, Error> { + let materials: Vec<&El> = self.root.children("surfacematerial").collect(); + let mat = match material { + Some(name) => materials.iter().copied().find(|m| m.attr("name") == Some(name)).ok_or_else(|| Error::MissingMaterial(name.to_owned()))?, + None => materials.first().copied().ok_or_else(|| Error::Unsupported("document has no surfacematerial".into()))?, + }; + let mut nodes = HashMap::new(); + let mut graphs = HashMap::new(); + let mut outputs = Vec::new(); + for child in self.root.elements() { + if child.name == "nodegraph" { + let Some(graph) = child.attr("name") else { continue }; + graphs.insert(graph, child); + for node in child.elements() { + let Some(name) = node.attr("name") else { continue }; + if node.name == "output" { + if let Some(from) = node.attr("nodename") { + outputs.push((format!("{graph}/{name}"), format!("{graph}/{from}"))); + } else if strict { + outputs.push((format!("{graph}/{name}"), String::new())); + } + } else { + nodes.insert(format!("{graph}/{name}"), node); + } + } + } else if let Some(name) = child.attr("name") { + nodes.insert(name.to_owned(), child); + } + } + let connection = mat.children("input").find(|i| i.attr("name") == Some("surfaceshader")); + let shader_name = if strict { + let resolver = Resolver { root: &self.root, nodes: &nodes, graphs: &graphs, outputs: &outputs }; + connection.map(|input| resolver.target(input, None)).transpose()?.flatten() + } else { + connection.and_then(|input| input.attr("nodename")).map(str::to_owned) + }; + let shader = + shader_name.as_ref().and_then(|n| nodes.get(n).copied()).ok_or_else(|| Error::Malformed("material has no surface shader".into()))?; + let scope = shader_name.as_deref().and_then(|name| name.split_once('/')).map(|(graph, _)| graph.to_owned()); + let kind = match shader.name.as_str() { + "open_pbr_surface" => Shader::OpenPbr, + "standard_surface" => Shader::StandardSurface, + "gltf_pbr" => Shader::GltfPbr, + other => return Err(Error::Unsupported(format!("surface shader is {other}"))), + }; + Ok(Located { mat, shader, scope, kind, nodes, graphs, outputs }) + } +} + +/// Whether the shader's emission is on: its strength input (`emission_luminance` or +/// `emission`) is connected or holds a value above 0, read with `parse`. glTF PBR has no such +/// input, so its emission is always on. +fn emission_enabled(kind: Shader, shader: &El, parse: fn(&str) -> Option>) -> bool { + let gate = match kind { + Shader::OpenPbr => Some("emission_luminance"), + Shader::StandardSurface => Some("emission"), + Shader::GltfPbr => None, + }; + gate.is_none_or(|name| { + shader + .children("input") + .find(|i| i.attr("name") == Some(name)) + .is_some_and(|i| i.attr("value").is_none_or(|v| parse(v).and_then(|n| n.first().copied()).is_some_and(|v| v > 0.0))) + }) } fn numeric_input(shader: &El, name: &str) -> Option { @@ -424,6 +672,373 @@ fn resolve_value( } } +fn image_tiling(value: &Resolved) -> Option<[f32; 2]> { + match value { + Resolved::Image { uv_tiling, .. } | Resolved::NormalMap { uv_tiling, .. } => { + uv_tiling.filter(|n| n.iter().all(|v| *v > 0.0)).map(|n| [n[0].clamp(0.001, 1000.0), n[1].clamp(0.001, 1000.0)]) + } + Resolved::Constant { .. } => None, + } +} + +fn has_authored_value(input: &El) -> bool { + ["value", "nodename", "nodegraph", "interfacename"].iter().any(|name| input.attr(name).is_some()) +} + +/// One to four finite numbers separated by commas, spaces or both, as MaterialX's own value +/// reader splits vector and color values. +fn parse_values(text: &str) -> Option> { + let nums: Option> = text + .split(|c: char| c == ',' || c.is_whitespace()) + .filter(|part| !part.is_empty()) + .map(|part| part.parse::().ok().filter(|v| v.is_finite())) + .collect(); + nums.filter(|v| !v.is_empty() && v.len() <= 4) +} + +/// The value of the input `input`, read as a `boolean` (`true` or `false`, as 1 or 0) or an +/// `integer` (one whole number) when its type says so, and as numbers otherwise. A `float`, +/// vector or color type needs as many numbers as it has channels. +fn input_numbers(input: &El, text: &str) -> Option> { + match input.attr("type") { + Some("boolean") => match text.trim() { + "true" => Some(vec![1.0]), + "false" => Some(vec![0.0]), + _ => None, + }, + Some("integer") => text.trim().parse::().ok().map(|v| vec![v as f32]), + ty => parse_values(text).filter(|v| ty.and_then(channels).is_none_or(|n| v.len() == n)), + } +} + +/// The number of channels of a MaterialX numeric type. +fn channels(ty: &str) -> Option { + match ty { + "float" | "integer" | "boolean" => Some(1), + "vector2" => Some(2), + "color3" | "vector3" => Some(3), + "color4" | "vector4" => Some(4), + _ => None, + } +} + +/// Whether `ty` is a numeric MaterialX type that is not a color: a boolean, integer, float or +/// vector. A `colorspace` does not apply to values of these types. +fn is_numeric_non_color(ty: Option<&str>) -> bool { + ty.is_some_and(|ty| channels(ty).is_some() && !matches!(ty, "color3" | "color4")) +} + +/// The type of `count` numbers whose type is not written: a float, or a vector. +fn untyped(count: usize) -> &'static str { + match count { + 1 => "float", + 2 => "vector2", + 3 => "vector3", + _ => "vector4", + } +} + +/// `values` of type `from` converted to type `to` by the `convert` node's rules in the MaterialX +/// Standard Nodes: a boolean becomes a float or integer of 0 or 1, an integer becomes a float or +/// a boolean (1 for any value that is not 0), a boolean, float or integer is copied to every +/// channel of a color or vector, and a color or vector keeps its first channels and fills +/// missing ones with 0 (1 in the fourth). `None` for a pair the node does not define, such as a +/// float to an integer or a color to a float, and for values that do not fit `from`. +fn converted(values: &[f32], from: &str, to: &str) -> Option> { + if channels(from)? != values.len() { + return None; + } + let out = channels(to)?; + match (from, to) { + _ if from == to => Some(values.to_vec()), + ("boolean", "float" | "integer") | ("integer", "float") => Some(values.to_vec()), + ("integer", "boolean") => Some(vec![if values[0] != 0.0 { 1.0 } else { 0.0 }]), + ("boolean" | "float" | "integer", _) if out > 1 => Some(vec![values[0]; out]), + _ if values.len() > 1 && out > 1 => Some((0..out).map(|c| values.get(c).copied().unwrap_or(if c == 3 { 1.0 } else { 0.0 })).collect()), + _ => None, + } +} + +/// The document's nodes, nodegraphs and graph outputs, for following input connections. +struct Resolver<'a> { + root: &'a El, + nodes: &'a HashMap, + graphs: &'a HashMap<&'a str, &'a El>, + outputs: &'a [(String, String)], +} + +impl<'a> Resolver<'a> { + /// The color space in effect on `element`: its own, else its nodegraph's when `scope` names + /// one, else the document's. + fn space_of(&self, element: &'a El, scope: Option<&str>) -> Option<&'a str> { + element + .attr("colorspace") + .or_else(|| scope.and_then(|g| self.graphs.get(g)).and_then(|g| g.attr("colorspace"))) + .or_else(|| self.root.attr("colorspace")) + } + + /// The document's working color space, the root element's `colorspace`. + fn working(&self) -> Option<&'a str> { + self.root.attr("colorspace") + } + + /// The value of `input`, an input of an element in nodegraph `scope` (or at the top level) + /// whose color space in effect is `space`. A `value` that is not one to four finite numbers, + /// or that does not fit a `boolean` or `integer` type, is [`Error::Malformed`]; an + /// unsupported connection is skipped with a warning. + fn value( + &self, + input: &'a El, + scope: Option<&str>, + space: Option<&'a str>, + hops: usize, + warnings: &mut Vec, + ) -> Result, Error> { + if hops > 16 { + warnings.push("a node chain is longer than 16 nodes (or loops); skipped".into()); + return Ok(None); + } + if let Some(interface) = input.attr("interfacename") { + warnings.push(format!("interface input {interface:?} is not supported; its value was skipped")); + return Ok(None); + } + if let Some(value) = input.attr("value") { + let Some(values) = input_numbers(input, value) else { + let name = input.attr("name").unwrap_or(""); + return Err(Error::Malformed(format!("input {name} has a value that is not one to four finite numbers or does not fit its type"))); + }; + let colorspace = if is_numeric_non_color(input.attr("type")) { self.working() } else { input.attr("colorspace").or(space) }; + return Ok(Some(Resolved::Constant { values, colorspace: colorspace.map(str::to_owned) })); + } + let target = self.target(input, scope)?; + let Some(node) = target.as_ref().and_then(|t| self.nodes.get(t).copied()) else { return Ok(None) }; + let node_scope = target.as_deref().and_then(|t| t.split_once('/')).map(|(g, _)| g); + let node_space = self.space_of(node, node_scope); + let child = |name: &str| node.children("input").find(|i| i.attr("name") == Some(name)); + let node_name = node.attr("name").unwrap_or(""); + match node.name.as_str() { + "image" | "tiledimage" => { + let file = child("file").and_then(|input| input.attr("value").filter(|file| !file.is_empty()).map(|file| (input, file))); + let Some((file_input, file)) = file else { + warnings.push(format!("image node {node_name:?} has no nonempty literal file value; its image was skipped")); + return Ok(None); + }; + let prefix = file_input + .attr("fileprefix") + .or_else(|| node.attr("fileprefix")) + .or_else(|| node_scope.and_then(|g| self.graphs.get(g)).and_then(|g| g.attr("fileprefix"))) + .or_else(|| self.root.attr("fileprefix")) + .unwrap_or(""); + let uv_tiling = match child("uvtiling").filter(|input| has_authored_value(input)) { + None => None, + Some(input) => match self.value(input, node_scope, node_space, hops + 1, warnings)? { + Some(Resolved::Constant { values, .. }) if values.len() == 2 => Some([values[0], values[1]]), + Some(Resolved::Constant { .. }) => { + return Err(Error::Malformed(format!("the uvtiling of image {node_name:?} is not two finite numbers"))); + } + _ => { + warnings.push(format!("the uvtiling of image {node_name:?} is not read")); + None + } + }, + }; + if let Some(offset) = child("uvoffset").filter(|input| has_authored_value(input)) { + match self.value(offset, node_scope, node_space, hops + 1, warnings)? { + Some(Resolved::Constant { values, .. }) if values.len() != 2 => { + return Err(Error::Malformed(format!("the uvoffset of image {node_name:?} is not two finite numbers"))); + } + Some(Resolved::Constant { values, .. }) if values == [0.0, 0.0] => {} + _ => warnings.push(format!("the uvoffset of image {node_name:?} is not read")), + } + } + for mode in ["uaddressmode", "vaddressmode"] { + if let Some(input) = child(mode).filter(|input| has_authored_value(input)) { + match input.attr("value") { + Some("periodic") => {} + Some("constant" | "clamp" | "mirror") | None => warnings.push(format!("the {mode} of image {node_name:?} is not read")), + Some(_) => return Err(Error::Malformed(format!("the {mode} of image {node_name:?} is not a supported addressing mode"))), + } + } + } + let colorspace = if is_numeric_non_color(node.attr("type")) { self.working() } else { file_input.attr("colorspace").or(node_space) } + .map(str::to_owned); + Ok(Some(Resolved::Image { file: format!("{prefix}{file}"), colorspace, uv_tiling })) + } + "normalmap" => { + for name in ["normal", "tangent", "bitangent"] { + if child(name).is_some_and(has_authored_value) { + warnings.push(format!("the {name} of normalmap node {node_name:?} is not read")); + } + } + // The normal is passed on without the node's scale, so a scale other than 1 is + // reported. + if let Some(scale) = child("scale").filter(|input| has_authored_value(input)) { + let resolved = self.value(scale, node_scope, node_space, hops + 1, &mut Vec::new())?; + if !matches!(resolved, Some(Resolved::Constant { ref values, .. }) if values.iter().all(|s| *s == 1.0)) { + warnings.push(format!("the scale of normalmap node {node_name:?} is not read")); + } + } + match child("in") { + Some(i) => Ok(match self.value(i, node_scope, node_space, hops + 1, warnings)? { + Some(Resolved::Image { file, colorspace, uv_tiling }) => Some(Resolved::NormalMap { file, colorspace, uv_tiling }), + Some(Resolved::Constant { values, .. }) if values.len() != 3 => { + return Err(Error::Malformed(format!("the input of normalmap node {node_name:?} is not three finite numbers"))); + } + Some(Resolved::Constant { .. }) => { + warnings.push(format!("the literal input of normalmap node {node_name:?} is not supported; its value was skipped")); + None + } + Some(Resolved::NormalMap { .. }) => { + warnings.push(format!("the nested normalmap input of node {node_name:?} is not supported; its value was skipped")); + None + } + value => value, + }), + None => Ok(None), + } + } + "convert" => { + let Some(i) = child("in").filter(|input| has_authored_value(input)) else { + let definition = node.attr("nodedef").and_then(|name| name.strip_prefix("ND_convert_")).and_then(|name| name.split_once('_')); + if let Some((from, to)) = definition + && from != to + && node.attr("type").is_none_or(|ty| ty == to) + && let Some(count) = channels(from) + && let Some(values) = converted(&vec![0.0; count], from, to) + { + return Ok(Some(Resolved::Constant { values, colorspace: self.working().map(str::to_owned) })); + } + warnings.push(format!("the input default of convert node {node_name:?} cannot be identified; its value was skipped")); + return Ok(None); + }; + let Some(value) = self.value(i, node_scope, node_space, hops + 1, warnings)? else { return Ok(None) }; + let to = node.attr("type").unwrap_or(""); + let from = self.value_type(i, node_scope)?; + match value { + Resolved::Constant { values, colorspace } => { + // A value with no type is a float or a vector, so it is in the working + // color space like a typed one. + let colorspace = if from.is_none() && i.attr("value").is_some() { self.working().map(str::to_owned) } else { colorspace }; + let from = from.unwrap_or_else(|| untyped(values.len())); + match converted(&values, from, to) { + Some(values) => Ok(Some(Resolved::Constant { values, colorspace })), + None => { + warnings.push(format!( + "a convert node ({node_name:?}) from type {from:?} to type {to:?} is not supported; its input was skipped" + )); + Ok(None) + } + } + } + // An image keeps its own channels, so only a convert that copies every + // channel as it is passes it on. + image @ (Resolved::Image { .. } | Resolved::NormalMap { .. }) => { + let copies = from.is_some_and(|from| from == to || channels(from).is_some_and(|n| n > 1 && channels(to) == Some(n))); + if copies { + Ok(Some(image)) + } else { + warnings.push(format!( + "a convert node ({node_name:?}) changes an image's channels to type {to:?}, which is not supported; its input was skipped" + )); + Ok(None) + } + } + } + } + "constant" => { + let value = child("value").filter(|input| has_authored_value(input)); + match value { + // A connected value keeps the color space it resolved; only a written value takes + // the working color space. + Some(i) => match self.constant_value(i, node, node_scope, node_space, hops + 1, warnings)? { + Some(Resolved::Constant { values, .. }) if is_numeric_non_color(node.attr("type")) && i.attr("value").is_some() => { + Ok(Some(Resolved::Constant { values, colorspace: self.working().map(str::to_owned) })) + } + value => Ok(value), + }, + None => match node.attr("type").and_then(channels) { + Some(count) => { + let space = if is_numeric_non_color(node.attr("type")) { self.working() } else { node_space }; + Ok(Some(Resolved::Constant { values: vec![0.0; count], colorspace: space.map(str::to_owned) })) + } + None => { + warnings.push(format!("the default of constant node {node_name:?} has an unsupported type")); + Ok(None) + } + }, + } + } + other => { + warnings.push(format!("a {other} node ({node_name:?}) is not supported; its input was skipped")); + Ok(None) + } + } + } + + fn constant_value( + &self, + input: &'a El, + node: &'a El, + scope: Option<&str>, + space: Option<&'a str>, + hops: usize, + warnings: &mut Vec, + ) -> Result, Error> { + if input.attr("type").is_none() + && input.attr("interfacename").is_none() + && let Some(text) = input.attr("value") + && let Some(ty) = node.attr("type") + { + let typed = El::new("input").with_attr("type", ty); + let values = input_numbers(&typed, text) + .ok_or_else(|| Error::Malformed(format!("constant {:?} has a value that does not fit {ty}", node.attr("name").unwrap_or(""))))?; + let colorspace = if is_numeric_non_color(Some(ty)) { self.working() } else { input.attr("colorspace").or(space) }; + return Ok(Some(Resolved::Constant { values, colorspace: colorspace.map(str::to_owned) })); + } + self.value(input, scope, space, hops, warnings) + } + + /// The key in `nodes` of the node that `input`, an input of an element in nodegraph `scope` + /// (or at the top level), connects to. + fn target(&self, input: &El, scope: Option<&str>) -> Result, Error> { + let target = if let Some(graph) = input.attr("nodegraph") { + let prefix = format!("{graph}/"); + let outputs: Vec<_> = self.outputs.iter().filter(|(name, _)| name.starts_with(&prefix)).collect(); + let selected = if outputs.len() == 1 { + outputs.first().copied() + } else { + input.attr("output").and_then(|output| outputs.iter().rev().copied().find(|(name, _)| name == &format!("{graph}/{output}"))) + }; + Some( + selected + .ok_or_else(|| { + Error::Malformed(format!("input {:?} has no selected output in nodegraph {graph:?}", input.attr("name").unwrap_or(""))) + })? + .1 + .clone(), + ) + } else if let Some(name) = input.attr("nodename") { + let qualified = scope.map(|g| format!("{g}/{name}")); + Some(qualified.unwrap_or_else(|| name.to_owned())) + } else { + None + }; + if let Some(name) = target.as_ref() + && !self.nodes.contains_key(name) + { + return Err(Error::Malformed(format!("input {:?} references missing node {name:?}", input.attr("name").unwrap_or("")))); + } + Ok(target) + } + + fn value_type(&self, input: &'a El, scope: Option<&str>) -> Result, Error> { + if input.attr("type").is_some() || input.attr("value").is_some() { + return Ok(input.attr("type")); + } + Ok(self.target(input, scope)?.as_ref().and_then(|name| self.nodes.get(name).copied()).and_then(|node| node.attr("type"))) + } +} + /// Writes an OpenPBR MaterialX document for the supplied textures. /// /// Unknown inputs and duplicate inputs are skipped; the first texture for an input wins. Color @@ -566,9 +1181,13 @@ mod tests { "#; - let material = Document::parse(xml).unwrap().read_material(None).unwrap(); + let doc = Document::parse(xml).unwrap(); + let material = doc.read_material(None).unwrap(); assert_eq!(material.displacement, Some(Value::Image("height.png".into()))); assert_eq!(material.uv_tiling, [4.0, 2.0]); + let strict = doc.read_material_strict(None).unwrap(); + assert_eq!(strict.displacement, Some(Resolved::Image { file: "height.png".into(), colorspace: None, uv_tiling: Some([4.0, 2.0]) })); + assert_eq!(strict.uv_tiling, [4.0, 2.0]); } #[test] @@ -594,6 +1213,22 @@ mod tests { assert_eq!(material.inputs[2].1, Value::Constant { values: vec![1.0, 0.5, 0.25], colorspace: None }); assert_eq!(material.displacement, Some(Value::Constant { values: vec![0.25], colorspace: None })); assert_eq!(material.uv_tiling, [2.0, 4.0]); + assert!(matches!(doc.read_material_strict(None), Err(Error::Malformed(_)))); + let mut explicit = doc.clone(); + let normalmap = explicit.root.elements_mut().find(|node| node.attr("name") == Some("N")).unwrap(); + normalmap.child_mut("input").unwrap().set_attr("output", "first"); + let strict = explicit.read_material_strict(None).unwrap(); + assert_eq!( + strict.inputs[0], + ("base_color".into(), Resolved::Image { file: "tex/albedo.png".into(), colorspace: None, uv_tiling: Some([2.0, 4.0]) }) + ); + assert_eq!( + strict.inputs[1], + ("geometry_normal".into(), Resolved::NormalMap { file: "tex/normal.png".into(), colorspace: None, uv_tiling: None }) + ); + assert_eq!(strict.inputs[2].1, Resolved::Constant { values: vec![1.0, 0.5, 0.25], colorspace: None }); + assert_eq!(strict.displacement, Some(Resolved::Constant { values: vec![0.25], colorspace: None })); + assert_eq!(strict.uv_tiling, [2.0, 4.0]); } #[test] @@ -612,8 +1247,423 @@ mod tests { assert_eq!(material.inputs[1], ("specular_roughness".into(), Value::Image("rough.png".into()))); assert_eq!(material.inputs[2], ("geometry_normal".into(), Value::Image("normal.png".into()))); assert_eq!(material.displacement, Some(Value::Image("height.png".into()))); + let strict = doc.read_material_strict(None).unwrap(); + let image = |file: &str, space: &str| Resolved::Image { file: file.into(), colorspace: Some(space.into()), uv_tiling: None }; + assert_eq!(strict.inputs[0], ("base_color".into(), image("albedo<&.png", "srgb_texture"))); + assert_eq!(strict.inputs[1], ("specular_roughness".into(), image("rough.png", "lin_rec709"))); + assert_eq!( + strict.inputs[2], + ("geometry_normal".into(), Resolved::NormalMap { file: "normal.png".into(), colorspace: Some("lin_rec709".into()), uv_tiling: None }) + ); + assert_eq!(strict.displacement, Some(image("height.png", "lin_rec709"))); assert!(xml.contains("colorspace=\"srgb_texture\"")); assert!(xml.contains("doc=\"Tiles every 100 x 50 cm\"")); assert!(!xml.contains("colorspace=\"ignored\"")); } + + #[test] + fn read_material_keeps_its_input_table_values_and_lenient_checks() { + // `read_material` reads glTF PBR's `emission`, keeps the base weight warning, skips + // repeated inputs, bad values and bad `uvtiling` instead of failing, and gives a + // constant only its own `colorspace`; `read_material_strict` is the stricter read. + let xml = r#" + + + + + + + "#; + let doc = Document::parse(xml.as_bytes()).unwrap(); + let gltf = doc.read_material(Some("M")).unwrap(); + assert_eq!( + gltf.inputs, + vec![ + ("base_color".into(), Value::Image("a.png".into())), + ("roughness".into(), Value::Constant { values: vec![0.25], colorspace: None }), + ("alpha".into(), Value::Constant { values: vec![0.5], colorspace: None }), + ("emission".into(), Value::Constant { values: vec![1.0, 0.5, 0.0], colorspace: None }), + ] + ); + assert_eq!(gltf.uv_tiling, [1.0, 1.0]); + assert!(gltf.warnings.is_empty(), "{:?}", gltf.warnings); + assert!(matches!(doc.read_material_strict(Some("M")), Err(Error::Malformed(_)))); + let open = doc.read_material(Some("N")).unwrap(); + assert_eq!(open.warnings, vec!["the base weight isn't 1; it was ignored".to_owned()]); + assert!(open.inputs.is_empty(), "{:?}", open.inputs); + let strict = doc.read_material_strict(Some("N")).unwrap(); + assert!(strict.warnings.is_empty(), "{:?}", strict.warnings); + assert_eq!(input(&strict, "base_weight"), Some(&constant(&[0.5], Some("srgb_texture")))); + assert_eq!(input(&strict, "base_color"), Some(&constant(&[0.5; 3], Some("srgb_texture")))); + } + + fn read(xml: &str) -> Result { + Document::parse(xml.as_bytes())?.read_material_strict(None) + } + + fn input<'m>(material: &'m StrictMaterial, name: &str) -> Option<&'m Resolved> { + material.inputs.iter().find(|(n, _)| n == name).map(|(_, v)| v) + } + + fn constant(values: &[f32], space: Option<&str>) -> Resolved { + Resolved::Constant { values: values.to_vec(), colorspace: space.map(str::to_owned) } + } + + #[test] + fn gltf_pbr_reads_the_emissive_input_its_definition_names() { + // The gltf_pbr node definition calls its emission color `emissive` + // (https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/bxdf/gltf_pbr.mtlx). + let m = read( + r#" + "#, + ) + .unwrap(); + assert_eq!(input(&m, "emissive"), Some(&constant(&[0.5, 0.25, 0.0], None))); + assert_eq!(input(&m, "emissive_strength"), Some(&constant(&[2.0], None))); + assert!(m.warnings.is_empty(), "{:?}", m.warnings); + } + + #[test] + fn weights_ior_and_alpha_inputs_are_read_for_each_shader() { + let open = read( + r#" + + + "#, + ) + .unwrap(); + for (name, values) in [ + ("base_weight", &[0.5][..]), + ("specular_weight", &[2.0]), + ("specular_color", &[1.0, 0.5, 0.5]), + ("specular_ior", &[1.33]), + ("coat_color", &[0.9, 0.9, 1.0]), + ("coat_ior", &[1.4]), + ("emission_luminance", &[10.0]), + ] { + assert_eq!(input(&open, name), Some(&constant(values, None)), "{name}"); + } + assert!(open.warnings.is_empty(), "{:?}", open.warnings); + let standard = read( + r#" + + "#, + ) + .unwrap(); + for (name, value) in [("base", 0.8), ("specular", 0.5), ("specular_IOR", 1.6), ("coat_IOR", 1.3), ("emission", 0.0)] { + assert_eq!(input(&standard, name), Some(&constant(&[value], None)), "{name}"); + } + let gltf = read( + r#" + + "#, + ) + .unwrap(); + for (name, values) in + [("alpha_mode", &[1.0][..]), ("alpha_cutoff", &[0.25]), ("ior", &[1.7]), ("specular", &[0.5]), ("specular_color", &[1.0, 1.0, 0.0])] + { + assert_eq!(input(&gltf, name), Some(&constant(values, None)), "{name}"); + } + } + + #[test] + fn constants_and_images_carry_the_color_space_in_effect_where_they_are_written() { + // An untagged value takes the nearest enclosing element's color space, then the + // document's (MaterialX specification, Color Spaces and Color Management Systems). + let m = read( + r#" + + + + + + + + + + "#, + ) + .unwrap(); + assert_eq!(input(&m, "base_color"), Some(&constant(&[0.5; 3], Some("srgb_texture")))); + assert_eq!(input(&m, "specular_color"), Some(&constant(&[0.5; 3], Some("lin_rec709")))); + assert_eq!(input(&m, "coat_color"), Some(&constant(&[0.1, 0.2, 0.3], Some("g22_rec709")))); + assert_eq!( + input(&m, "fuzz_color"), + Some(&Resolved::Image { file: "fuzz.png".into(), colorspace: Some("lin_rec709".into()), uv_tiling: None }) + ); + let doc = Document::parse( + br#" + "#, + ) + .unwrap(); + let tagged = doc.read_material_strict(Some("N")).unwrap(); + assert_eq!(input(&tagged, "base_color"), Some(&constant(&[0.2; 3], Some("acescg")))); + } + + #[test] + fn duplicate_inputs_and_values_that_are_not_finite_numbers_are_malformed() { + let shader = |inputs: &str| { + format!( + r#"{inputs}"# + ) + }; + let dup = read(&shader(r#""#)); + assert!(matches!(dup, Err(Error::Malformed(ref m)) if m.contains("base_metalness")), "{dup:?}"); + for bad in ["nan", "inf", "-inf", "1e40", "0.5,x", "", "1,2,3,4,5"] { + let r = read(&shader(&format!(r#""#))); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("specular_roughness")), "{bad}: {r:?}"); + } + } + + #[test] + fn a_normalmap_scale_other_than_1_gives_a_warning() { + let with_scale = |scale: &str| { + read(&open_pbr( + r#""#, + &format!(r#"{scale}"#), + )) + .unwrap() + }; + let scaled = with_scale(r#""#); + assert_eq!(scaled.warnings, vec![r#"the scale of normalmap node "N" is not read"#.to_owned()]); + assert!(matches!(input(&scaled, "geometry_normal"), Some(Resolved::NormalMap { .. }))); + for plain in ["", r#""#, r#""#] { + assert!(with_scale(plain).warnings.is_empty(), "{plain}"); + } + // A scale connected to a constant node is read through it. + let connected = |value: &str| { + read(&open_pbr( + r#""#, + &format!( + r#""# + ), + )) + .unwrap() + }; + assert!(connected("1").warnings.is_empty(), "{:?}", connected("1").warnings); + assert_eq!(connected("2").warnings.len(), 1, "{:?}", connected("2").warnings); + } + + #[test] + fn shader_inputs_that_are_not_read_give_a_warning() { + let m = read( + r#" + "#, + ) + .unwrap(); + assert_eq!(m.warnings, vec!["input thin_film_weight is not read".to_owned()]); + assert_eq!(input(&m, "base_metalness"), Some(&constant(&[1.0], None))); + } + + fn open_pbr(inputs: &str, rest: &str) -> String { + format!( + r#"{inputs}{rest}"# + ) + } + + #[test] + fn vector_values_may_be_separated_by_commas_spaces_or_both() { + // MaterialX's value reader splits vector and color values on commas and spaces + // (ARRAY_VALID_SEPARATORS, ", ", in source/MaterialXCore/Types.cpp). + for text in ["0.5 0.25 0.125", "0.5, 0.25, 0.125", "0.5,0.25,0.125", " 0.5 0.25 ,0.125 "] { + let m = read(&open_pbr(&format!(r#""#), "")).unwrap(); + assert_eq!(input(&m, "base_color"), Some(&constant(&[0.5, 0.25, 0.125], None)), "{text:?}"); + } + // A color3 holds three numbers. + for bad in ["0.5 x 1", "0.5 0.25 0.125 1 2", " ", "0.5", "0.5, 0.25", "0.5 0.25 0.125 1"] { + let r = read(&open_pbr(&format!(r#""#), "")); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("base_color")), "{bad:?}: {r:?}"); + } + } + + #[test] + fn a_nodegraph_file_prefix_applies_to_the_images_inside_it() { + // The nearest enclosing fileprefix applies (MaterialX specification, File Prefixes). + let m = read(&open_pbr( + r#""#, + r#" + + + + + "#, + ) + .replacen("", r#""#, 1)) + .unwrap(); + let file = |name: &str| match input(&m, name) { + Some(Resolved::Image { file, .. }) => file.clone(), + other => panic!("{name}: {other:?}"), + }; + assert_eq!( + (file("base_color"), file("specular_roughness"), file("base_metalness")), + ("stone/albedo.png".into(), "own/rough.png".into(), "shared/metal.png".into()) + ); + } + + #[test] + fn uv_tiling_is_kept_as_written_and_malformed_tiling_is_an_error() { + let tiled = |tiling: &str| { + read(&open_pbr( + r#""#, + &format!( + r#""# + ), + )) + }; + let tiling_of = |m: &StrictMaterial| match input(m, "base_color") { + Some(Resolved::Image { uv_tiling, .. }) => *uv_tiling, + other => panic!("{other:?}"), + }; + let wide = tiled("2000, 2").unwrap(); + assert_eq!((tiling_of(&wide), wide.uv_tiling), (Some([2000.0, 2.0]), [1000.0, 2.0])); + let flat = tiled("0 2").unwrap(); + assert_eq!((tiling_of(&flat), flat.uv_tiling), (Some([0.0, 2.0]), [1.0, 1.0])); + for bad in ["x", "1", "1,2,3", "nan,1"] { + let r = tiled(bad); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("uvtiling")), "{bad:?}: {r:?}"); + } + } + + #[test] + fn convert_nodes_change_the_number_of_channels() { + // The convert node's rules in the MaterialX Standard Nodes: a float is copied to every + // channel, a shorter color or vector is filled with 0 (1 in the fourth channel), a + // longer one keeps its first channels, and a boolean is 0 or 1. + let via = |ty: &str, in_ty: &str, value: &str| { + read(&open_pbr( + r#""#, + &format!(r#""#), + )) + .unwrap() + }; + assert_eq!(input(&via("color3", "float", "0.25"), "base_color"), Some(&constant(&[0.25; 3], None))); + assert_eq!(input(&via("color4", "color3", "0.1,0.2,0.3"), "base_color"), Some(&constant(&[0.1, 0.2, 0.3, 1.0], None))); + assert_eq!(input(&via("color3", "color4", "0.1,0.2,0.3,0.4"), "base_color"), Some(&constant(&[0.1, 0.2, 0.3], None))); + assert_eq!(input(&via("vector3", "vector2", "0.1,0.2"), "base_color"), Some(&constant(&[0.1, 0.2, 0.0], None))); + assert_eq!(input(&via("float", "boolean", "true"), "base_color"), Some(&constant(&[1.0], None))); + assert_eq!(input(&via("float", "integer", "3"), "base_color"), Some(&constant(&[3.0], None))); + assert_eq!(input(&via("boolean", "integer", "2"), "base_color"), Some(&constant(&[1.0], None))); + // An input with no type is a float or a vector by its count. + let untyped = read(&open_pbr( + r#""#, + r#""#, + )) + .unwrap(); + assert_eq!(input(&untyped, "base_color"), Some(&constant(&[0.5; 3], None))); + // A color to a float and a float to an integer are not conversions the node defines. + for (ty, in_ty, value) in [("float", "color3", "0.1,0.2,0.3"), ("integer", "float", "0.5"), ("boolean", "float", "1")] { + let unsupported = via(ty, in_ty, value); + assert_eq!(input(&unsupported, "base_color"), None, "{in_ty} to {ty}"); + assert!(unsupported.warnings.iter().any(|w| w.contains("convert node")), "{:?}", unsupported.warnings); + } + // An integer is one whole number. + for bad in ["1.5", "1.00000001", "1 2"] { + let r = read(&open_pbr( + r#""#, + &format!(r#""#), + )); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("input in ")), "{bad:?}: {r:?}"); + } + let image = |ty: &str, image_ty: &str| { + read(&open_pbr( + r#""#, + &format!( + r#""# + ), + )) + .unwrap() + }; + let g = Resolved::Image { file: "g.png".into(), colorspace: None, uv_tiling: None }; + assert_eq!(input(&image("float", "float"), "base_color"), Some(&g)); + assert_eq!(input(&image("vector3", "color3"), "base_color"), Some(&g)); + for (ty, image_ty) in [("color3", "float"), ("color3", "color4")] { + let changed = image(ty, image_ty); + assert_eq!(input(&changed, "base_color"), None, "{image_ty} to {ty}"); + assert!(changed.warnings.iter().any(|w| w.contains("convert node")), "{:?}", changed.warnings); + } + } + + #[test] + fn a_color_converted_from_another_type_is_in_the_working_color_space() { + // A colorspace applies to color values and color image files (MaterialX specification, + // Color Spaces and Color Management Systems), so a float or vector copied into a color + // by a convert node holds working-space channels; a color keeps its own color space. + let m = read( + r#" + + + + + + + + + + + + + + + + + "#, + ) + .unwrap(); + let image = |file: &str, space: &str| Resolved::Image { file: file.into(), colorspace: Some(space.into()), uv_tiling: None }; + assert_eq!(input(&m, "base_color"), Some(&constant(&[0.5; 3], Some("lin_rec709")))); + assert_eq!(input(&m, "specular_color"), Some(&constant(&[0.1, 0.2, 0.3], Some("lin_rec709")))); + assert_eq!(input(&m, "coat_color"), Some(&constant(&[0.1, 0.2, 0.3], Some("srgb_texture")))); + assert_eq!(input(&m, "fuzz_color"), Some(&image("v.png", "lin_rec709"))); + assert_eq!(input(&m, "emission_color"), Some(&image("c.png", "srgb_texture"))); + assert!(m.warnings.is_empty(), "{:?}", m.warnings); + // A color passed through a vector, also by way of a vector constant node, keeps its color + // space, and a float constant node or an untyped value is in the working color space. + let chain = read( + r#" + + + + + + + + + + + + + + + + "#, + ) + .unwrap(); + assert_eq!(input(&chain, "base_color"), Some(&constant(&[0.5; 3], Some("srgb_texture")))); + assert_eq!(input(&chain, "specular_color"), Some(&constant(&[0.25; 3], Some("lin_rec709")))); + assert_eq!(input(&chain, "coat_color"), Some(&constant(&[0.75; 3], Some("lin_rec709")))); + assert_eq!(input(&chain, "fuzz_color"), Some(&constant(&[0.4; 3], Some("srgb_texture")))); + assert!(chain.warnings.is_empty(), "{:?}", chain.warnings); + // A document without a working color space leaves the converted color untagged. + let plain = read(&open_pbr( + r#""#, + r#""#, + )) + .unwrap(); + assert_eq!(input(&plain, "base_color"), Some(&constant(&[0.5; 3], None))); + } + + #[test] + fn an_emission_color_is_checked_while_the_emission_is_0() { + let standard = |color: &str| { + read(&format!( + r#" + "# + )) + }; + let r = standard("0.5,x,1"); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("emission_color")), "{r:?}"); + let m = standard("0.5,0.5,1").unwrap(); + assert_eq!(input(&m, "emission_color"), Some(&constant(&[0.5, 0.5, 1.0], None))); + assert!(m.warnings.is_empty()); + } } diff --git a/crates/mcmat/src/lib.rs b/crates/mcmat/src/lib.rs index ca3fa7641b..56ca52a7ee 100644 --- a/crates/mcmat/src/lib.rs +++ b/crates/mcmat/src/lib.rs @@ -248,11 +248,31 @@ mod tests { fn rejects_ambiguous_or_nonlocal_resource_members() { for name in ["resources/../../x", "resources/a\\x", "/x", "maps/color.png", "resources/C:/x", "preview.png"] { assert!(write(b"x", [(name, &b"x"[..])]).is_err()); - let mut zip = Writer::new(); - zip.add(MANIFEST_ENTRY, MARKER, Compression::Stored).unwrap(); - zip.add(SOURCE_ENTRY, b"x", Compression::Deflated).unwrap(); - zip.add(name, b"x", Compression::Stored).unwrap(); - assert!(Material::open(&zip.finish().unwrap(), Limits::default()).is_err()); + let placeholder = "x".repeat(name.len()); + let bytes = { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, MARKER, Compression::Stored).unwrap(); + zip.add(SOURCE_ENTRY, b"x", Compression::Deflated).unwrap(); + match zip.add(name, b"x", Compression::Stored) { + Ok(()) => zip.finish().unwrap(), + Err(_) => { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, MARKER, Compression::Stored).unwrap(); + zip.add(SOURCE_ENTRY, b"x", Compression::Deflated).unwrap(); + zip.add(&placeholder, b"x", Compression::Stored).unwrap(); + let mut b = zip.finish().unwrap(); + let p = placeholder.as_bytes(); + let n = name.as_bytes(); + for i in 0..b.len().saturating_sub(p.len()) { + if &b[i..i + p.len()] == p { + b[i..i + p.len()].copy_from_slice(n); + } + } + b + } + } + }; + assert!(Material::open(&bytes, Limits::default()).is_err()); } assert!(write(b"x", [("resources/A", &b"a"[..]), ("resources/a", &b"b"[..])]).is_err()); } diff --git a/crates/mcp/README.md b/crates/mcp/README.md index 53e4c6550b..1fb8d2d7da 100644 --- a/crates/mcp/README.md +++ b/crates/mcp/README.md @@ -1,6 +1,8 @@ # craft-mcp -Transport-independent MCP 2025-03-26 server initialization and tool result helpers. +Transport-independent MCP server initialization and tool result helpers. +Transport-independent MCP 2025-03-26 server initialization and result helpers for tools, +resources, prompts and completion. Use one `Session` per client connection with `craft-jsonrpc` for message parsing and batch dispatch. The caller owns transport, tool definitions and execution, response size limits, and shutdown. Pass the outer envelope's batch status to `Session::request`. @@ -13,9 +15,18 @@ request IDs that MCP forbids. `process` does not check the message size. initialization, initialization can occur in a batch, and client information needs only to be an object. `Policy::Strict` requires initialization first (except ping), rejects batched or repeated initialization, and requires client name and version. -Both respond with the sole supported version, 2025-03-26, even if the client offered -a different version. Instructions set with `Session::set_instructions` are returned by -every initialize response, in either policy and with or without legacy initialization. +By default both respond with 2025-03-26, even if the client offered a different version. +`Session::with_versions` sets the accepted versions, in order of preference, from +`SUPPORTED_PROTOCOL_VERSIONS` (2025-06-18, 2025-03-26 and 2024-11-05). A client that +asks for one of them gets it back, and any other request gets the first. +`Session::negotiated_version` returns the version the session answered with, for +features that depend on it, such as the `MCP-Protocol-Version` HTTP header. Once +2025-06-18 is negotiated, `Policy::Strict` rejects every batched request and +`Session::accepts_batches` returns false. Reject a batch envelope with -32600 before +dispatching it when `accepts_batches` is false, because `Session::notification` cannot +tell a batched notification from a single one. Instructions set with +`Session::set_instructions` are returned by every initialize response, in either policy +and with or without legacy initialization. An initialized notification moves the session to `Ready`. This crate does not enforce every MCP lifecycle or capability rule; applications must validate any additional requirements they depend on. @@ -39,4 +50,27 @@ roots without both kinds. A path is checked before it is opened, so another program that replaces a folder with a link between the two steps can still reach outside the roots. -See the [MCP lifecycle specification](https://modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle). +See the [MCP lifecycle specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle) +and the [2025-06-18 changes](https://modelcontextprotocol.io/specification/2025-06-18/changelog). + +The crate also checks the parameters of the resource, prompt and completion methods and +builds their results, for a server that routes those methods itself: + +- `page` takes one page of a list from the request's `cursor`, and `resource_list`, + `resource_template_list` and `prompt_list` wrap the page with its `nextCursor`. A + cursor must be a canonical positive decimal offset divisible by the page size; + malformed cursors are rejected with -32602. The helper returns an empty last page + for a cursor past the list's end, including after the list shrinks. +- `resource_read` returns the requested URI. `text_contents`, `blob_contents` and + `read_result` build the `resources/read` result, and `resource_not_found` is the + -32002 error with the URI in its data. +- `prompt_get` returns the prompt name and its string arguments. `prompt_result` and + `text_message` build the `prompts/get` result. +- `completion_request` returns the prompt or resource reference and the argument being + completed. `completion_result` keeps the first 100 values and sets `total` and `hasMore`. + +See the [pagination](https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/pagination), +[resources](https://modelcontextprotocol.io/specification/2025-03-26/server/resources), +[prompts](https://modelcontextprotocol.io/specification/2025-03-26/server/prompts) and +[completion](https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/completion) +specifications. diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index 43685c9b56..c13cab4d78 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -1,17 +1,28 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -//! MCP 2025-03-26 server initialization and tool envelopes, independent of transport and tools. +//! MCP server initialization and the envelopes of tools, resources, prompts and completion, +//! independent of transport and of what the server serves. Sessions answer 2025-03-26 by default +//! and can negotiate any of `SUPPORTED_PROTOCOL_VERSIONS`. //! The caller owns routing, transport and JSON-RPC batching. Compatibility mode preserves servers //! that accepted calls before initialization and initialize in a batch; strict mode enforces the //! initialization ordering and batch prohibition. Create one session per connection. +use std::collections::BTreeMap; + use craft_jsonrpc::{Limits, Request, RpcError}; use serde_json::{Value, json}; pub mod roots; +/// The version a session answers with unless `Session::with_versions` sets others. pub const PROTOCOL_VERSION: &str = "2025-03-26"; +/// Protocol versions whose initialization this crate implements, newest first. +pub const SUPPORTED_PROTOCOL_VERSIONS: [&str; 3] = ["2025-06-18", "2025-03-26", "2024-11-05"]; + +/// Versions that removed JSON-RPC batching. +const BATCHLESS_VERSIONS: [&str; 1] = ["2025-06-18"]; + /// JSON-RPC limits for an MCP connection. MCP requires a string or integer request ID, so /// `craft_jsonrpc::process` answers a null or fractional ID with an invalid-request error and does /// not call the request handler. The size bounds are `Limits::default()`'s; override them with @@ -48,6 +59,7 @@ pub struct Session { permissive_initialize: bool, server_info: Option, instructions: Option, + negotiated: Option, initialized: bool, } @@ -63,10 +75,30 @@ impl Session { permissive_initialize: false, server_info: None, instructions: None, + negotiated: None, initialized: false, } } + /// Set the protocol versions the session accepts, in order of preference. A client that asks + /// for one of them gets it back; any other request gets the first. Each version must be in + /// `SUPPORTED_PROTOCOL_VERSIONS`, and the list must be non-empty and free of repeats. + pub fn with_versions(mut self, versions: &[&str]) -> Result { + if versions.is_empty() { + return Err(RpcError::new(-32602, "Protocol versions must not be empty")); + } + for (i, version) in versions.iter().enumerate() { + if !SUPPORTED_PROTOCOL_VERSIONS.contains(version) { + return Err(RpcError::new(-32602, format!("Unsupported protocol version {version}"))); + } + if versions[..i].contains(version) { + return Err(RpcError::new(-32602, format!("Repeated protocol version {version}"))); + } + } + self.versions = versions.iter().map(|v| (*v).to_owned()).collect(); + Ok(self) + } + /// Set the server capabilities returned at initialization. The value must be an object. pub fn with_capabilities(mut self, capabilities: Value) -> Result { if !capabilities.is_object() { @@ -101,9 +133,32 @@ impl Session { self.state } + /// The protocol version the last successful initialize answered with. + pub fn negotiated_version(&self) -> Option<&str> { + self.negotiated.as_deref() + } + + fn answer_version(&self, asked: Option<&str>) -> String { + asked + .filter(|v| self.versions.iter().any(|supported| supported == v)) + .unwrap_or_else(|| self.versions.first().map(String::as_str).unwrap_or(PROTOCOL_VERSION)) + .to_owned() + } + + /// Whether the caller may dispatch a JSON-RPC batch. False in strict mode once a version + /// without batching (2025-06-18) is negotiated; reject such a batch envelope with + /// -32600 before dispatching it, since `notification` cannot tell a batched notification apart. + pub fn accepts_batches(&self) -> bool { + self.policy != Policy::Strict || !self.negotiated.as_deref().is_some_and(|v| BATCHLESS_VERSIONS.contains(&v)) + } + /// Handles `initialize` and `ping`. Returns `None` for a request the app should route. - /// `in_batch` must describe the outer JSON-RPC envelope. + /// `in_batch` must describe the outer JSON-RPC envelope. A batched request is rejected + /// when `accepts_batches` is false. pub fn request(&mut self, request: Request<'_>, in_batch: bool) -> Option> { + if in_batch && !self.accepts_batches() { + return Some(Err(RpcError::new(-32600, "Invalid Request"))); + } if request.method == "ping" { return Some(Ok(json!({}))); } @@ -113,27 +168,29 @@ impl Session { } if self.permissive_initialize { let asked = request.params.and_then(|p| p.get("protocolVersion")).and_then(Value::as_str); - let version = asked - .filter(|v| self.versions.iter().any(|supported| supported == v)) - .unwrap_or_else(|| self.versions.first().map(String::as_str).unwrap_or(PROTOCOL_VERSION)); + let version = self.answer_version(asked); let result = json!({"protocolVersion": version, "capabilities": self.capabilities, "serverInfo": self.server_info}); self.state = State::AwaitingInitialized; + self.negotiated = Some(version); return Some(Ok(self.with_instructions(result))); } let Some(params) = request.params.and_then(Value::as_object) else { return Some(Err(invalid_initialize())); }; - let valid = params.get("protocolVersion").and_then(Value::as_str).is_some() - && params.get("capabilities").is_some_and(Value::is_object) - && params.get("clientInfo").is_some_and(Value::is_object); + let asked = params.get("protocolVersion").and_then(Value::as_str); + let valid = + asked.is_some() && params.get("capabilities").is_some_and(Value::is_object) && params.get("clientInfo").is_some_and(Value::is_object); let identity = params.get("clientInfo").and_then(Value::as_object); let strict_identity = identity .is_some_and(|info| info.get("name").and_then(Value::as_str).is_some() && info.get("version").and_then(Value::as_str).is_some()); if !valid || (self.policy == Policy::Strict && !strict_identity) { return Some(Err(invalid_initialize())); } + let version = self.answer_version(asked); + let result = + json!({"protocolVersion": version, "capabilities": self.capabilities, "serverInfo": {"name": self.name, "version": self.version}}); self.state = State::AwaitingInitialized; - let result = json!({"protocolVersion": PROTOCOL_VERSION, "capabilities": self.capabilities, "serverInfo": {"name": self.name, "version": self.version}}); + self.negotiated = Some(version); return Some(Ok(self.with_instructions(result))); } if self.policy == Policy::Strict && self.state == State::New { @@ -184,6 +241,196 @@ pub fn text_tool_result(text: &str, is_error: bool) -> Value { json!({"content": [{"type": "text", "text": text}], "isError": is_error}) } +/// Most values one `completion/complete` result may carry. +pub const MAX_COMPLETIONS: usize = 100; + +/// One page of a `resources/list`, `resources/templates/list` or `prompts/list` result. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Page { + pub items: Vec, + /// The cursor a client sends to get the next page; `None` on the last page. + pub next_cursor: Option, +} + +impl Page { + /// Every item in one page, for a server that does not paginate. + pub fn all(items: Vec) -> Self { + Self { items, next_cursor: None } + } +} + +/// Take the page of `items` that starts at the `cursor` in a list request's parameters, with at most +/// `page_size` items (0 puts every item in one page). The helper accepts canonical positive +/// decimal offsets divisible by `page_size`. Parameters that are not an object, and malformed +/// cursors, are rejected with -32602. The helper returns an empty last page for a cursor past +/// the list's end, including after the list shrinks. +pub fn page(params: Option<&Value>, mut items: Vec, page_size: usize) -> Result { + if params.is_some_and(|p| !p.is_object()) { + return Err(RpcError::new(-32602, "List parameters must be an object")); + } + let start = match params.and_then(|p| p.get("cursor")) { + None => 0, + Some(Value::String(cursor)) => match cursor.parse::() { + Ok(offset) if page_size > 0 && offset > 0 && offset % page_size == 0 && offset.to_string() == *cursor => offset, + _ => return Err(invalid_cursor()), + }, + Some(_) => return Err(invalid_cursor()), + }; + let start = start.min(items.len()); + items.drain(..start); + let mut next_cursor = None; + if page_size > 0 && items.len() > page_size { + items.truncate(page_size); + next_cursor = Some((start + page_size).to_string()); + } + Ok(Page { items, next_cursor }) +} + +fn invalid_cursor() -> RpcError { + RpcError::new(-32602, "Invalid cursor") +} + +/// Wrap a page of MCP `Resource` objects in the `resources/list` result. +pub fn resource_list(page: Page) -> Value { + list_result("resources", page) +} + +/// Wrap a page of MCP `ResourceTemplate` objects in the `resources/templates/list` result. +pub fn resource_template_list(page: Page) -> Value { + list_result("resourceTemplates", page) +} + +/// Wrap a page of MCP `Prompt` objects in the `prompts/list` result. +pub fn prompt_list(page: Page) -> Value { + list_result("prompts", page) +} + +fn list_result(key: &str, page: Page) -> Value { + let mut result = serde_json::Map::new(); + result.insert(key.to_owned(), Value::Array(page.items)); + if let Some(cursor) = page.next_cursor { + result.insert("nextCursor".to_owned(), Value::String(cursor)); + } + Value::Object(result) +} + +/// Validate `resources/read` parameters and return the requested URI. +pub fn resource_read(params: &Value) -> Result<&str, RpcError> { + params.get("uri").and_then(Value::as_str).ok_or_else(|| RpcError::new(-32602, "Missing resource URI")) +} + +/// The error MCP specifies for a `resources/read` of a URI the server does not have. +pub fn resource_not_found(uri: &str) -> RpcError { + RpcError { code: -32002, message: "Resource not found".into(), data: Some(json!({"uri": uri})) } +} + +/// Text contents of a resource, for [`read_result`]. +pub fn text_contents(uri: &str, mime_type: Option<&str>, text: &str) -> Value { + contents(uri, mime_type, "text", text) +} + +/// Binary contents of a resource, for [`read_result`]. `base64` is the data in standard base64. +pub fn blob_contents(uri: &str, mime_type: Option<&str>, base64: &str) -> Value { + contents(uri, mime_type, "blob", base64) +} + +fn contents(uri: &str, mime_type: Option<&str>, key: &str, value: &str) -> Value { + let mut result = serde_json::Map::new(); + result.insert("uri".to_owned(), json!(uri)); + if let Some(mime_type) = mime_type { + result.insert("mimeType".to_owned(), json!(mime_type)); + } + result.insert(key.to_owned(), json!(value)); + Value::Object(result) +} + +/// Wrap resource contents in the `resources/read` result. +pub fn read_result(contents: Vec) -> Value { + json!({"contents": contents}) +} + +/// Validate `prompts/get` parameters and return the prompt name and its arguments. MCP prompt +/// arguments are strings, so an argument of any other type is rejected with -32602. +pub fn prompt_get(params: &Value) -> Result<(&str, BTreeMap<&str, &str>), RpcError> { + let name = params.get("name").and_then(Value::as_str).ok_or_else(|| RpcError::new(-32602, "Missing prompt name"))?; + let arguments = match params.get("arguments") { + None => BTreeMap::new(), + Some(Value::Object(map)) => map + .iter() + .map(|(key, value)| value.as_str().map(|v| (key.as_str(), v))) + .collect::>>() + .ok_or_else(|| RpcError::new(-32602, "Prompt arguments must be strings"))?, + Some(_) => return Err(RpcError::new(-32602, "Prompt arguments must be an object")), + }; + Ok((name, arguments)) +} + +/// Wrap prompt messages (MCP `PromptMessage` objects) in the `prompts/get` result. +pub fn prompt_result(description: Option<&str>, messages: Vec) -> Value { + let mut result = json!({"messages": messages}); + if let Some(description) = description { + result["description"] = json!(description); + } + result +} + +/// A prompt message with one text block, from `"user"` or `"assistant"`. +pub fn text_message(role: &str, text: &str) -> Value { + json!({"role": role, "content": {"type": "text", "text": text}}) +} + +/// What a `completion/complete` request refers to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CompletionRef<'a> { + /// A prompt, by name (`ref/prompt`). + Prompt(&'a str), + /// A resource or resource template, by URI or URI template (`ref/resource`). + Resource(&'a str), +} + +/// The parameters of a `completion/complete` request. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Completion<'a> { + pub reference: CompletionRef<'a>, + /// The name of the argument being completed. + pub argument: &'a str, + /// What the user has typed for it so far. + pub value: &'a str, +} + +/// Validate `completion/complete` parameters. +pub fn completion_request(params: &Value) -> Result, RpcError> { + let invalid = |message: &str| RpcError::new(-32602, message); + let reference = params.get("ref").ok_or_else(|| invalid("Missing completion reference"))?; + let field = |key: &str| reference.get(key).and_then(Value::as_str); + let reference = match reference.get("type").and_then(Value::as_str) { + Some("ref/prompt") => CompletionRef::Prompt(field("name").ok_or_else(|| invalid("Missing prompt name"))?), + Some("ref/resource") => CompletionRef::Resource(field("uri").ok_or_else(|| invalid("Missing resource URI"))?), + _ => return Err(invalid("Unknown completion reference type")), + }; + let argument = params.get("argument"); + let text = |key: &str| argument.and_then(|a| a.get(key)).and_then(Value::as_str); + let (Some(name), Some(value)) = (text("name"), text("value")) else { + return Err(invalid("Completion argument needs a name and a value")); + }; + Ok(Completion { reference, argument: name, value }) +} + +/// Build the `completion/complete` result from every matching value. The result carries the first +/// [`MAX_COMPLETIONS`] values, the number of matches in `total`, and whether any were left out in +/// `hasMore`. +pub fn completion_result(values: impl IntoIterator) -> Value { + let mut kept = Vec::new(); + let mut total = 0usize; + for value in values { + if kept.len() < MAX_COMPLETIONS { + kept.push(value); + } + total += 1; + } + json!({"completion": {"values": kept, "total": total, "hasMore": total > MAX_COMPLETIONS}}) +} + #[cfg(test)] mod tests { use super::*; @@ -205,6 +452,7 @@ mod tests { assert_eq!(result["protocolVersion"], expected); assert_eq!(result["serverInfo"]["title"], "Title"); assert_eq!(result["instructions"], "help"); + assert_eq!(s.negotiated_version(), Some(expected)); } } @@ -266,6 +514,54 @@ mod tests { } } + #[test] + fn validated_initialize_negotiates_configured_versions() { + let mut s = Session::new("test", "1", Policy::Compatible).with_versions(&SUPPORTED_PROTOCOL_VERSIONS).unwrap(); + assert_eq!(s.negotiated_version(), None); + for (asked, expected) in [("2024-11-05", "2024-11-05"), ("2025-03-26", "2025-03-26"), ("2025-06-18", "2025-06-18"), ("1.0.0", "2025-06-18")] { + let p = json!({"protocolVersion": asked, "capabilities": {}, "clientInfo": {}}); + let r = s.request(call("initialize", Some(&p)), false).unwrap().unwrap(); + assert_eq!(r["protocolVersion"], expected); + assert_eq!(s.negotiated_version(), Some(expected)); + } + let mut old_first = Session::new("test", "1", Policy::Compatible).with_versions(&["2025-03-26", "2025-06-18"]).unwrap(); + let p = json!({"protocolVersion": "2099-01-01", "capabilities": {}, "clientInfo": {}}); + assert_eq!(old_first.request(call("initialize", Some(&p)), false).unwrap().unwrap()["protocolVersion"], "2025-03-26"); + } + + #[test] + fn version_lists_reject_empty_unknown_and_repeated_entries() { + let new = || Session::new("test", "1", Policy::Compatible); + assert!(new().with_versions(&[]).is_err()); + assert!(new().with_versions(&["2099-01-01"]).is_err()); + assert!(new().with_versions(&["2025-06-18", "2025-06-18"]).is_err()); + let mut s = new(); + let p = json!({"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {}}); + assert!(s.request(call("initialize", Some(&json!({}))), false).unwrap().is_err()); + assert_eq!(s.negotiated_version(), None); + assert_eq!(s.request(call("initialize", Some(&p)), false).unwrap().unwrap()["protocolVersion"], PROTOCOL_VERSION); + } + + #[test] + fn strict_rejects_batches_after_negotiating_a_version_without_them() { + let p = |v: &str| json!({"protocolVersion": v, "capabilities": {}, "clientInfo": {"name": "client", "version": "1"}}); + let mut s = Session::new("test", "1", Policy::Strict).with_versions(&SUPPORTED_PROTOCOL_VERSIONS).unwrap(); + assert!(s.accepts_batches()); + assert!(s.request(call("initialize", Some(&p("2025-06-18"))), false).unwrap().is_ok()); + assert!(!s.accepts_batches()); + assert_eq!(s.request(call("ping", None), true).unwrap().unwrap_err().code, -32600); + assert_eq!(s.request(call("tools/list", None), true).unwrap().unwrap_err().code, -32600); + assert!(s.request(call("tools/list", None), false).is_none()); + let mut older = Session::new("test", "1", Policy::Strict).with_versions(&SUPPORTED_PROTOCOL_VERSIONS).unwrap(); + assert!(older.request(call("initialize", Some(&p("2025-03-26"))), false).unwrap().is_ok()); + assert!(older.accepts_batches()); + assert!(older.request(call("tools/list", None), true).is_none()); + let mut compatible = Session::new("test", "1", Policy::Compatible).with_versions(&SUPPORTED_PROTOCOL_VERSIONS).unwrap(); + assert!(compatible.request(call("initialize", Some(&p("2025-06-18"))), false).unwrap().is_ok()); + assert!(compatible.accepts_batches()); + assert!(compatible.request(call("tools/list", None), true).is_none()); + } + #[test] fn tool_envelopes_validate_arguments_and_preserve_results() { let p = json!({"name":"open"}); @@ -320,4 +616,89 @@ mod tests { assert_eq!(reply[1]["result"]["tools"], json!([])); assert_eq!(session.borrow().state(), State::Ready); } + + #[test] + fn list_pages_follow_their_cursors_to_the_end() { + let items: Vec = (0..5).map(|i| json!({"name": i})).collect(); + let mut params = None; + let mut names = Vec::new(); + let mut pages = 0; + loop { + let page = page(params.as_ref(), items.clone(), 2).unwrap(); + let result = prompt_list(page); + pages += 1; + names.extend(result["prompts"].as_array().unwrap().iter().map(|p| p["name"].clone())); + match result.get("nextCursor") { + Some(cursor) => params = Some(json!({"cursor": cursor})), + None => break, + } + } + assert_eq!((pages, names), (3, (0..5).map(|i| json!(i)).collect::>())); + assert_eq!(resource_list(page(None, items.clone(), 0).unwrap()), json!({"resources": items})); + let past_the_end = page(Some(&json!({"cursor": "8"})), items, 2).unwrap(); + assert_eq!(resource_template_list(past_the_end), json!({"resourceTemplates": []})); + } + + #[test] + fn list_cursors_that_were_not_handed_out_are_invalid_params() { + for cursor in [json!(""), json!("-1"), json!("+1"), json!("1.0"), json!("abc"), json!(2), json!(null), json!("99999999999999999999999")] { + let error = page(Some(&json!({"cursor": cursor})), vec![json!(1)], 1).unwrap_err(); + assert_eq!(error.code, -32602, "{cursor}"); + } + for cursor in ["1", "02", "0"] { + assert_eq!(page(Some(&json!({"cursor": cursor})), vec![json!(1); 5], 2).unwrap_err().code, -32602, "{cursor}"); + } + assert_eq!(page(Some(&json!({"cursor": "2"})), vec![json!(1); 5], 0).unwrap_err().code, -32602); + for params in [json!(null), json!([]), json!("0")] { + assert_eq!(page(Some(¶ms), vec![json!(1)], 1).unwrap_err().code, -32602, "{params}"); + } + } + + #[test] + fn resource_reads_validate_the_uri_and_build_contents() { + assert_eq!(resource_read(&json!({"uri": "x://a"})).unwrap(), "x://a"); + assert_eq!(resource_read(&json!({"uri": 1})).unwrap_err().code, -32602); + let missing = resource_not_found("x://b"); + assert_eq!((missing.code, missing.data), (-32002, Some(json!({"uri": "x://b"})))); + let result = read_result(vec![text_contents("x://a", Some("text/markdown"), "# A"), blob_contents("x://c", None, "AAE=")]); + assert_eq!(result, json!({"contents": [{"uri": "x://a", "mimeType": "text/markdown", "text": "# A"}, {"uri": "x://c", "blob": "AAE="}]})); + } + + #[test] + fn prompt_arguments_must_be_strings() { + let params = json!({"name": "describe", "arguments": {"part": "bracket"}}); + let (name, args) = prompt_get(¶ms).unwrap(); + assert_eq!((name, args.get("part").copied()), ("describe", Some("bracket"))); + assert!(prompt_get(&json!({"name": "describe"})).unwrap().1.is_empty()); + for params in [json!({}), json!({"name": "d", "arguments": {"n": 1}}), json!({"name": "d", "arguments": ["x"]})] { + assert_eq!(prompt_get(¶ms).unwrap_err().code, -32602, "{params}"); + } + let result = prompt_result(Some("Describe a part"), vec![text_message("user", "Describe bracket")]); + assert_eq!(result["messages"][0]["content"], json!({"type": "text", "text": "Describe bracket"})); + assert_eq!(result["description"], "Describe a part"); + } + + #[test] + fn completion_requests_name_a_prompt_or_a_resource() { + let prompt = json!({"ref": {"type": "ref/prompt", "name": "describe"}, "argument": {"name": "part", "value": "br"}}); + assert_eq!(completion_request(&prompt).unwrap(), Completion { reference: CompletionRef::Prompt("describe"), argument: "part", value: "br" }); + let resource = json!({"ref": {"type": "ref/resource", "uri": "lib://parts/{part}"}, "argument": {"name": "part", "value": ""}}); + assert_eq!(completion_request(&resource).unwrap().reference, CompletionRef::Resource("lib://parts/{part}")); + for params in [ + json!({"ref": {"type": "ref/tool", "name": "x"}, "argument": {"name": "a", "value": ""}}), + json!({"ref": {"type": "ref/prompt"}, "argument": {"name": "a", "value": ""}}), + json!({"ref": {"type": "ref/prompt", "name": "x"}, "argument": {"name": "a"}}), + json!({"argument": {"name": "a", "value": ""}}), + ] { + assert_eq!(completion_request(¶ms).unwrap_err().code, -32602, "{params}"); + } + } + + #[test] + fn completion_results_carry_at_most_a_hundred_values() { + let result = completion_result((0..150).map(|i| i.to_string())); + assert_eq!(result["completion"]["values"].as_array().map(Vec::len), Some(MAX_COMPLETIONS)); + assert_eq!((&result["completion"]["total"], &result["completion"]["hasMore"]), (&json!(150), &json!(true))); + assert_eq!(completion_result(["a".to_owned()]), json!({"completion": {"values": ["a"], "total": 1, "hasMore": false}})); + } } diff --git a/crates/media/README.md b/crates/media/README.md index 38c0ced3f7..bbbe121a5a 100644 --- a/crates/media/README.md +++ b/crates/media/README.md @@ -467,6 +467,10 @@ not apply to it; damage is skipped with the same budget and warnings as `open`. in `streams()`, where a later link of a chained file appears as a new stream when its pages are reached. `OggFile::read_packet_into` reads a packet into a reused buffer. `OpusTiming` gives each Opus packet's start, the pre-skip and the end trimming of the final page. +`VorbisTiming` gives each Vorbis packet's start and duration (from the block sizes of the modes that +`VorbisModes` reads from the setup header), the samples to discard before a negative starting +position, the offset of a stream that starts after 0, and the end trimming of the final page +(Vorbis I §4.3.8 and §A.2). The muxer side is `PageWriter`, from FilmCraft's `filmcraft-oggmux` by @JordyUSA (storytold/filmcraft#4481): it laces the packets of one logical stream into pages (continued @@ -625,9 +629,10 @@ let au: Vec = file.read_unit(&bytes, v, 0)?; // the first access unit - **Program streams**: MPEG-2 and MPEG-1 packs, system headers, the program stream map (stream types for elementary stream ids), padding, private stream 2 (DVD navigation) skipped, private stream 1 split by sub-stream id. Garbage resynchronises on the next pack or PES start code. -- **Streams**: MPEG-1/2 video, H.264, HEVC, MPEG audio, AAC (ADTS, LATM/LOAS), AC-3, E-AC-3, - DTS, TrueHD, Blu-ray LPCM, DVD LPCM (format from the sub-stream header), PGS / DVB / teletext - subtitles; ISO 639 language from the PMT. +- **Streams**: MPEG-1/2 video, H.264, HEVC, MPEG-4 Part 2 (stream type 0x10), AV1 and Opus + (stream type 0x06 with the `AV01` or `Opus` registration descriptor), MPEG audio, AAC (ADTS, + LATM/LOAS), AC-3, E-AC-3, DTS, TrueHD, Blu-ray LPCM, DVD LPCM (format from the sub-stream + header), PGS / DVB / teletext subtitles; ISO 639 language from the PMT. - **Access units**, found while the file is scanned (one pass, streaming; only a few bytes of each stream are buffered): - MPEG-1/2 video: a coded frame — a frame picture, or two field pictures (paired by @@ -639,6 +644,17 @@ let au: Vec = file.read_unit(&bytes, v, 0)?; // the first access unit - Audio: one frame per unit from the frame headers (sync re-hunted after garbage; a header found while hunting is confirmed by the next one); a PTS belongs to the first frame starting in the PES. + - MPEG-4 Part 2: PES packets with a timestamp, as for H.264; the first VOP's coding type + gives the key (I-VOP) and disposable (B-VOP) flags. + - Opus: one access unit per unit, cut by its control header's payload size; `read_unit` + returns the Opus packet without the header, and the start and end trims are in + `Stream::opus` (`OpusConfig::trims`). An access unit without a control header runs to the + end of its PES packet; one whose size runs past its PES packet is dropped and counted in + `skipped_bytes`. + - AV1: one PES packet per unit, a key unit when the TS packet that starts it sets the random + access indicator. `read_unit` returns the OBUs in the low overhead bitstream format (start + codes, emulation prevention bytes and temporal delimiters removed, `obu_size` added where it + is missing), as Matroska and ISOBMFF store them. - LPCM and everything else: one PES packet per unit. - **Timestamps**: 33-bit PTS/DTS unwrapped across the wrap (and back, for B pictures shown before a wrap that came earlier); PCR / SCR range. @@ -652,8 +668,12 @@ MPEG audio or AC-3 frames in chunks that do not follow them (AVI) find the frame `Codec::codec_id()` and `Stream::codec_params()` give the crate-wide `CodecId` / `CodecParams`. MPEG-1 video reports `Mpeg2Video`; MPEG audio reports `Mp2` whatever its layer (the layer is in each frame header: `frame_info(..).variant`); ADTS and LATM AAC both report `Aac`; DTS, TrueHD and -subtitles have no identifier (`Unknown`). The streams carry their configuration in band, so -`extradata` is empty; DVD LPCM fills `sample_rate`, `channels` and `pcm`. +subtitles have no identifier (`Unknown`). Opus fills `sample_rate` (48 kHz), `channels` and an +`OpusHead` header in `extradata`, built from the PMT's Opus audio descriptor (`Stream::opus`) with +the start trims of the units that open the stream as its pre-skip. AV1 puts the first four bytes of an `av1C` record, +from the PMT's AV1 video descriptor (`Stream::av1c`), in `extradata`. The other streams carry +their configuration in band, so `extradata` is empty; DVD LPCM fills `sample_rate`, `channels` +and `pcm`. Limits, each with a test: 2²³ access units per stream (the rest are not indexed, with a warning), 128 MiB per unit read (`MAX_UNIT_BYTES`), a PES header given up after 1024 bytes, 16 stuffing bytes @@ -670,6 +690,9 @@ at least 8 bytes. | DVD-Video private stream 1 sub-stream layout (AC-3 / DTS 0x80-0x8F with a 3-byte header, LPCM 0xA0-0xAF with a 6-byte header, sub-pictures 0x20-0x3F) | public descriptions | `.vob` | | ETSI EN 300 468 (descriptors 0x56, 0x59, 0x6A, 0x7A, 0x7B), ATSC A/52 Annex A (AC-3 in TS) | — | identifying private PES streams | | ISO/IEC 11172-3, 13818-3 (frame headers), ISO/IEC 13818-7 (ADTS), 14496-3 (LOAS), ATSC A/52 (syncinfo, E-AC-3 frmsiz) | — | audio frame lengths for splitting | +| ISO/IEC 14496-2 | any edition | MPEG-4 Part 2 VOP coding types | +| Opus Interactive Audio Codec Transport Multiplexing Standard | draft TS V0.1.3 (2015-10) | Opus control headers, the Opus audio descriptor and its channel configurations; RFC 7845 for the `OpusHead` header and the channel mapping families | +| Carriage of AV1 in MPEG-2 TS (Alliance for Open Media) | working draft | the AV1 video descriptor, start codes and emulation prevention; the AV1 Bitstream & Decoding Process Specification for OBU headers and `obu_size` | ### Gaps @@ -688,9 +711,10 @@ Differences from `filmcraft-mpegts`: `ByteSource` is `craft_media::ByteSource`; Tests: a small TS muxer and PS writer (every access unit reads back byte-identical with its PTS, key and disposable flags), 33-bit unwrap, truncation and mutation, streams of every codec filled with random start codes and sync words, damaged PSI sections with valid CRCs, and the frame-header -helpers on arbitrary bytes. `tests/oracle_mpegts.rs` compares ten ffmpeg-made files (MPEG-2, H.264 -and HEVC video; MP2, ADTS and LATM AAC, AC-3, E-AC-3, Blu-ray and DVD LPCM; TS, M2TS, VOB and -MPEG-1 system streams) with ffprobe's packets: unit counts, sizes, timestamps and key flags. +helpers on arbitrary bytes. `tests/oracle_mpegts.rs` compares eleven ffmpeg-made files (MPEG-2, +H.264, HEVC and MPEG-4 Part 2 video; MP2, ADTS and LATM AAC, AC-3, E-AC-3, Opus, Blu-ray and DVD +LPCM; TS, M2TS, VOB and MPEG-1 system streams) with ffprobe's packets: unit counts, sizes, +timestamps and key flags. ### Transport stream writer @@ -783,9 +807,7 @@ the first stream) every 40 ms and 700 ms behind the DTS, the PAT and PMT every 1 keyframes, and writes of 7 packets. Gaps: one program per stream; no null packets (no constant bit rate); not written: LPCM (H.222.0 -defines no LPCM stream type for transport streams), AAC in LATM, DTS, subtitles and teletext. The -demuxer reads Opus and AV1 streams as `Unknown(6)` and MPEG-4 Part 2 as `Unknown(0x10)`, one unit -per PES packet. +defines no LPCM stream type for transport streams), AAC in LATM, DTS, subtitles and teletext. Specifications: the ones above, and Opus Interactive Audio Codec Transport Multiplexing Standard, draft TS V0.1.3 (2015-10), for the Opus control header and descriptors; RFC 6716 for Opus packet @@ -796,7 +818,8 @@ descriptors. Tests: `tests/mpegts_mux_readback.rs` reads the output back with the demuxer: streams, codecs, languages, every frame's bytes, PTS and DTS, keyframes and the PCR range, with no continuity or -CRC warnings, including AV1 units, Opus with an explicit mapping and a start trim, both sides of a +CRC warnings, including AV1 units as OBUs with their `av1C` fields, Opus packets with fixed +and explicit channel configurations and their start and end trims, MPEG-4 Part 2, both sides of a discontinuity, and the output that follows an I/O error. `tests/mpegts_mux_fuzz.rs` muxes random programs and timelines with idle gaps and output swaps and reads them back, and feeds random bytes to every codec. Unit tests check every PES header's fixed bits, the sections' CRC, and that every diff --git a/crates/media/src/mpegts/es.rs b/crates/media/src/mpegts/es.rs index 8568c7cba2..c17f086484 100644 --- a/crates/media/src/mpegts/es.rs +++ b/crates/media/src/mpegts/es.rs @@ -7,7 +7,7 @@ use std::collections::VecDeque; -use super::{Codec, PictureInfo, Unit}; +use super::{Codec, OpusTrim, PictureInfo, Unit}; /// How a stream is cut into units. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -19,6 +19,16 @@ enum Mode { Nal { hevc: bool }, /// Framed audio with self-describing frame headers. Audio(AudioSync), + /// Opus: one access unit per unit, cut by its control header's payload size and starting + /// after the header; an access unit without a control header runs to the end of its PES + /// packet (Opus transport draft §6). + Opus, + /// MPEG-4 Part 2 video: a PES packet with a timestamp starts a unit; the first VOP's coding + /// type gives the flags. + Mpeg4, + /// AV1: one PES packet per unit (Carriage of AV1 in MPEG-2 TS §3.4), a key unit where the + /// packet that starts it sets the random access indicator. + Av1, /// One PES packet per unit. Pes, } @@ -41,6 +51,9 @@ impl Mode { Codec::AacAdts => Mode::Audio(AudioSync::Adts), Codec::AacLatm => Mode::Audio(AudioSync::Loas), Codec::Ac3 | Codec::Eac3 => Mode::Audio(AudioSync::Ac3), + Codec::Opus => Mode::Opus, + Codec::Mpeg4Part2 => Mode::Mpeg4, + Codec::Av1 => Mode::Av1, _ => Mode::Pes, } } @@ -101,8 +114,16 @@ pub(crate) struct Splitter { gop: Option<(bool, bool)>, pending: Option, open_field: Option, - // audio state + // audio state; for Opus, where the next access unit's control header starts (None: the + // rest of the PES packet belongs to the open unit) or, once one is read, where its payload + // ends next_frame: Option, + /// Opus: how far the payload size of a control header cut off by the end of a chunk was read. + opus_scan: OpusSizeScan, + /// Opus: the open unit's start and end trims. + open_trim: (u16, u16), + /// Opus: the trims of the units so far. + pub trims: Vec, } /// AC-3 frame sizes in 16-bit words for 48 / 44.1 / 32 kHz (A/52 Table 5.18), by @@ -331,6 +352,158 @@ pub(crate) const MAX_UNITS: usize = 1 << 23; /// Full-bandwidth channels per AC-3 audio coding mode (A/52 Table 5.8). const AC3_CHANNELS: [u32; 8] = [2, 1, 2, 3, 3, 4, 4, 5]; +/// What starts an Opus access unit. +#[derive(Debug, PartialEq, Eq)] +enum OpusHeader { + /// More bytes are needed to tell. + Incomplete, + /// No control header: the access unit is the rest of the PES packet. + Absent, + /// A control header whose payload size is past [`super::MAX_UNIT_BYTES`]. + Invalid, + /// A control header of `len` bytes, then `size` bytes of payload with these start and end + /// trims. + Found { len: usize, size: u64, trim: (u16, u16) }, +} + +/// How far the payload size of the control header at ES offset `at` was read: `next` is the +/// header index of the next size byte to read, and `size` is the sum of the bytes before it. +#[derive(Debug, Default)] +struct OpusSizeScan { + at: u64, + next: usize, + size: u64, + /// Size bytes read, by every header. + #[cfg(test)] + reads: u64, +} + +/// The opus_control_header at the start of `b`, which is ES offset `at` (Opus transport draft +/// §6.2): the 11-bit prefix 0x3FF, the start trim, end trim and extension flags, the payload size +/// as bytes of 0xFF and a last byte, then the 13-bit trims and the extension. When `b` ends +/// before the header does, `scan` keeps the size read so far, and a call with more bytes of the +/// same header goes on from there, so each size byte is read once. +fn opus_control_header(b: &[u8], at: u64, scan: &mut OpusSizeScan) -> OpusHeader { + match b { + [] => return OpusHeader::Incomplete, + [0x7F] => return OpusHeader::Incomplete, + [0x7F, b1, ..] if b1 & 0xE0 == 0xE0 => {} + _ => return OpusHeader::Absent, + } + let flags = b[1]; + if scan.at != at || scan.next < 2 { + scan.at = at; + scan.next = 2; + scan.size = 0; + } + let mut i = scan.next; + let mut size = scan.size; + loop { + let Some(&x) = b.get(i) else { + scan.next = i; + scan.size = size; + return OpusHeader::Incomplete; + }; + #[cfg(test)] + { + scan.reads += 1; + } + if size + u64::from(x) > u64::from(super::MAX_UNIT_BYTES) { + return OpusHeader::Invalid; + } + if x != 0xFF { + // the trims or the extension may still be cut off: a later call reads this last + // size byte again + scan.next = i; + scan.size = size; + size += u64::from(x); + i += 1; + break; + } + size += u64::from(x); + i += 1; + } + let mut trim = [0u16; 2]; + for (k, bit) in [0x10u8, 0x08].into_iter().enumerate() { + if flags & bit != 0 { + let Some(v) = b.get(i..i + 2) else { return OpusHeader::Incomplete }; + trim[k] = u16::from_be_bytes([v[0], v[1]]) & 0x1FFF; + i += 2; + } + } + if flags & 0x04 != 0 { + let Some(&n) = b.get(i) else { return OpusHeader::Incomplete }; + i += 1 + usize::from(n); + if i > b.len() { + return OpusHeader::Incomplete; + } + } + OpusHeader::Found { len: i, size, trim: (trim[0], trim[1]) } +} + +/// Rewrites an AV1 access unit from the start code form of Carriage of AV1 in MPEG-2 TS §3.2 to +/// the low overhead bitstream format: each OBU follows a start code 0x000001, and the 0x03 of +/// every 0x000003 in it is an emulation prevention byte. Temporal delimiters and bytes before the +/// first start code are left out, as Matroska and ISOBMFF store AV1. An OBU that carries +/// obu_size ends there; one without gets an obu_size for the bytes up to the next start code. +pub(crate) fn av1_obus(es: &mut Vec) { + let mut out = Vec::with_capacity(es.len() + 16); + let mut obu = Vec::new(); + let start_code = |i: usize| es.get(i..i + 3) == Some(&[0, 0, 1][..]); + let mut i = (0..es.len()).find(|&i| start_code(i)).unwrap_or(es.len()); + while i < es.len() { + // `i` is at a start code + i += 3; + obu.clear(); + let mut zeros = 0; + while i < es.len() && !start_code(i) { + let b = es[i]; + i += 1; + if zeros >= 2 && b == 3 { + zeros = 0; + continue; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + obu.push(b); + } + let Some(&h) = obu.first() else { continue }; + let header = 1 + usize::from(h & 0x04 != 0); + if obu.len() < header || (h >> 3) & 0x0F == 2 { + continue; + } + if h & 0x02 != 0 { + // obu_size, leb128 (AV1 §4.10.5) + let mut size = 0u64; + let mut at = header; + for k in 0..8 { + let Some(&b) = obu.get(at) else { break }; + at += 1; + size |= u64::from(b & 0x7F) << (7 * k); + if b & 0x80 == 0 { + break; + } + } + let end = usize::try_from(size).ok().and_then(|s| at.checked_add(s)).filter(|&e| e <= obu.len()).unwrap_or(obu.len()); + out.extend_from_slice(&obu[..end]); + } else { + out.push(h | 0x02); + out.extend_from_slice(&obu[1..header]); + let mut size = obu.len() - header; + loop { + let b = (size & 0x7F) as u8; + size >>= 7; + if size == 0 { + out.push(b); + break; + } + out.push(b | 0x80); + } + out.extend_from_slice(&obu[header..]); + } + } + *es = out; +} + /// Frame length at the start of `b` for the given sync type (`None`: no valid header; `Some(0)` /// is never returned). fn frame_len(sync: AudioSync, b: &[u8]) -> Option { @@ -388,6 +561,9 @@ impl Splitter { pending: None, open_field: None, next_frame: None, + opus_scan: OpusSizeScan::default(), + open_trim: (0, 0), + trims: Vec::new(), } } @@ -398,12 +574,48 @@ impl Splitter { self.pes.pop_front(); } match self.mode { - Mode::Pes => self.begin_pes_unit(true), - Mode::Nal { .. } => self.begin_pes_unit(pts.is_some() || dts.is_some()), + Mode::Pes | Mode::Av1 => self.begin_pes_unit(true), + Mode::Nal { .. } | Mode::Mpeg4 => self.begin_pes_unit(pts.is_some() || dts.is_some()), + Mode::Opus => { + // a PES packet holds whole access units: the next one starts here + self.close_opus(self.es_pos); + self.next_frame = Some(self.es_pos); + } _ => {} } } + /// The packet that started the PES packet set the random access indicator: an AV1 unit + /// that the packet starts is a key unit. + pub fn random_access(&mut self) { + if self.mode == Mode::Av1 + && let Some(o) = self.open.as_mut() + && o.start == self.es_pos + { + o.key = true; + } + } + + /// Opus: end the open unit before ES byte `limit` (the end of its PES packet). A unit whose + /// payload size runs past `limit` is dropped, and so are the bytes of a control header that + /// the PES packet cuts off. + fn close_opus(&mut self, limit: u64) { + match self.next_frame { + Some(end) if end > limit => { + if let Some(o) = self.open.take() { + self.skipped += limit.saturating_sub(o.start); + } + self.open_trim = (0, 0); + } + Some(end) => { + self.close(end); + self.skipped += limit - end; + } + None => self.close(limit), + } + self.next_frame = None; + } + /// PES-delimited units: a packet with a timestamp (or any packet in plain PES mode) starts a /// new unit; one without continues the previous unit. fn begin_pes_unit(&mut self, new: bool) { @@ -443,6 +655,7 @@ impl Splitter { /// End the open unit at `end`. fn close(&mut self, end: u64) { let Some(o) = self.open.take() else { return }; + let (start_trim, end_trim) = std::mem::take(&mut self.open_trim); if end <= o.start || o.pos == u64::MAX { return; } @@ -450,6 +663,9 @@ impl Splitter { self.truncated = true; return; } + if (start_trim, end_trim) != (0, 0) { + self.trims.push(OpusTrim { unit: self.units.len(), start: start_trim, end: end_trim }); + } let size = (end - o.start).min(u32::MAX as u64) as u32; self.units.push(Unit { pts: o.pts, @@ -469,9 +685,9 @@ impl Splitter { return; } // PES-delimited modes resolve a unit's position from `pos` right here and never look a - // chunk up again, so remembering chunks there would only grow without bound (NAL streams - // keep theirs: an access unit can start inside a PES; `keep_from` prunes them) - if matches!(self.mode, Mode::MpegVideo | Mode::Audio(_) | Mode::Nal { .. }) { + // chunk up again, so remembering chunks there would only grow without bound (NAL and Opus + // streams keep theirs: an access unit can start inside a PES; `keep_from` prunes them) + if matches!(self.mode, Mode::MpegVideo | Mode::Audio(_) | Mode::Nal { .. } | Mode::Opus) { self.chunks.push_back((pos, self.es_pos)); } if let Some(o) = self.open.as_mut() @@ -484,10 +700,12 @@ impl Splitter { let start = self.es_pos; self.es_pos += data.len() as u64; match self.mode { - Mode::Pes => {} + Mode::Pes | Mode::Av1 => {} Mode::Nal { hevc } => self.scan_nal(start, data, hevc), Mode::MpegVideo => self.scan_mpeg(start, data), + Mode::Mpeg4 => self.scan_mpeg4(start, data), Mode::Audio(sync) => self.scan_audio(start, data, sync), + Mode::Opus => self.scan_opus(start, data), } // forget chunks no pending position can refer to let keep_from = self.buf_start.min(self.pending.map_or(u64::MAX, |p| p.unit_start.min(p.at))).min(self.header_start.unwrap_or(u64::MAX)); @@ -789,8 +1007,115 @@ impl Splitter { frame_len(sync, &self.buf[j..]).is_some() } + /// Opus access units: each control header gives the payload size, so the unit starts after + /// the header and ends where the next header starts. + fn scan_opus(&mut self, start: u64, data: &[u8]) { + let end = start + data.len() as u64; + let Some(next) = self.next_frame else { + // the rest of the PES packet belongs to the open unit, or is not Opus at all + if self.open.is_none() { + self.skipped += data.len() as u64; + } + // no later header can refer back to these bytes: `feed` may forget their chunks + self.buf.clear(); + self.buf_start = end; + return; + }; + if next >= end { + // inside the open unit's payload + self.buf.clear(); + self.buf_start = end; + return; + } + self.window(start, data); + while let Some(at) = self.next_frame { + if at < self.buf_start { + self.next_frame = None; + break; + } + let i = (at - self.buf_start) as usize; + if i >= self.buf.len() { + break; + } + match opus_control_header(&self.buf[i..], at, &mut self.opus_scan) { + OpusHeader::Incomplete => { + self.trim(self.buf.len() - i); + return; + } + OpusHeader::Absent => { + // no control header: the access unit runs to the end of the PES packet + self.close(at); + self.open_opus(at, at, (0, 0)); + self.next_frame = None; + } + OpusHeader::Invalid => { + self.close(at); + self.skipped += end - at; + self.next_frame = None; + } + OpusHeader::Found { len, size, trim } => { + self.close(at); + let payload = at + len as u64; + self.open_opus(at, payload, trim); + self.next_frame = Some(payload + size); + } + } + } + self.buf.clear(); + self.buf_start = end; + } + + /// Open an Opus unit at `start` for the access unit whose header (if any) starts at `at`. + fn open_opus(&mut self, at: u64, start: u64, trim: (u16, u16)) { + // a payload that starts with the next chunk is placed when that chunk arrives + let (pos, offset) = if start < self.es_pos { self.locate(start).unwrap_or((u64::MAX, 0)) } else { (u64::MAX, 0) }; + let mut o = Open { start, pos, offset, pts: None, dts: None, key: true, disposable: false, vcl: false, picture: None }; + if let Some((pts, dts)) = self.timestamps_at(at) { + o.pts = pts; + o.dts = dts; + } + self.open = Some(o); + self.open_trim = trim; + } + + /// MPEG-4 Part 2 video: the unit's first VOP header gives its coding type (ISO/IEC 14496-2 + /// §6.2.5: 0 I, 1 P, 2 B, 3 S). + fn scan_mpeg4(&mut self, start: u64, data: &[u8]) { + self.window(start, data); + if self.open.is_some_and(|o| o.vcl) { + // the unit's flags are known: keep only where a start code may begin + self.trim(3); + return; + } + let mut i = 0; + let mut blocked = None; + while let Some(k) = self.next_start_code(i) { + if k + 5 > self.buf.len() { + blocked = Some(k); + break; + } + let at = self.buf_start + k as u64; + if self.buf[k + 3] == 0xB6 + && let Some(o) = self.open.as_mut() + && !o.vcl + && at >= o.start + { + let coding_type = self.buf[k + 4] >> 6; + o.key = coding_type == 0; + o.disposable = coding_type == 2; + o.vcl = true; + } + i = k + 3; + } + self.keep_tail(i, blocked); + } + /// End of stream: close the open unit. pub fn finish(&mut self) { + if self.mode == Mode::Opus { + self.close_opus(self.es_pos); + return; + } self.settle_pending(); let end = match (self.mode, self.next_frame) { (Mode::Audio(_), Some(n)) => n.min(self.es_pos), @@ -884,6 +1209,48 @@ mod tests { } } + #[test] + fn a_long_opus_control_header_is_read_once() { + // a payload size of 100,000 bytes of 0xFF, cut into transport stream payloads + let mut s = Splitter::new(&Codec::Opus); + s.pes_start(Some(0), None); + let mut es = vec![0x7F, 0xE0]; + es.extend(std::iter::repeat_n(0xFF, 100_000)); + es.push(0); + for (k, c) in es.chunks(184).enumerate() { + s.feed(k as u64 * 188, c); + } + assert!(s.opus_scan.reads <= es.len() as u64, "{} size bytes read for a {}-byte header", s.opus_scan.reads, es.len()); + assert_eq!(s.next_frame, Some(es.len() as u64 + 255 * 100_000)); + } + + #[test] + fn opus_chunks_are_forgotten_inside_a_unit_and_after_a_headerless_one() { + // an access unit whose payload spans 500 chunks, then a PES packet without a control + // header + let mut s = Splitter::new(&Codec::Opus); + s.pes_start(Some(0), None); + let size = 184 * 500; + let mut es = vec![0x7F, 0xE0]; + es.extend(std::iter::repeat_n(0xFF, size / 255)); + es.push((size % 255) as u8); + es.resize(es.len() + size, 0x11); + let mut pos = 0; + for (k, c) in es.chunks(184).enumerate() { + s.feed(pos, c); + pos += 188; + assert!(k < 3 || s.chunks.len() <= 2, "chunk {k}: {} chunks retained", s.chunks.len()); + } + s.pes_start(Some(1800), None); + for k in 0..500 { + s.feed(pos, &[0xFC; 184]); + pos += 188; + assert!(s.chunks.len() <= 2, "headerless chunk {k}: {} chunks retained", s.chunks.len()); + } + s.finish(); + assert_eq!(s.units.iter().map(|u| u.size as usize).collect::>(), [size, 184 * 500]); + } + #[test] fn unit_table_is_capped() { let frame = |k: u8| { diff --git a/crates/media/src/mpegts/mod.rs b/crates/media/src/mpegts/mod.rs index 32356be02d..3e0570fa29 100644 --- a/crates/media/src/mpegts/mod.rs +++ b/crates/media/src/mpegts/mod.rs @@ -9,10 +9,11 @@ //! LPCM). //! - **Elementary streams** are split into access units on open — coded frames for MPEG-1/2 //! video (picture start codes, field pairs), H.264 and HEVC (access unit delimiters / first -//! slice of a picture), audio frames for MPEG audio, ADTS / LATM AAC, AC-3 and E-AC-3, PES -//! packets for LPCM — each with its PTS/DTS (a PES timestamp belongs to the first access unit -//! that starts in the packet), random-access flag and, for MPEG video, picture type, temporal -//! reference and field structure. That index is the seeking table. +//! slice of a picture), audio frames for MPEG audio, ADTS / LATM AAC, AC-3 and E-AC-3, Opus +//! access units (by their control headers), PES packets for LPCM, AV1 and MPEG-4 Part 2 video. +//! Each unit has its PTS/DTS (a PES timestamp belongs to the first access unit that starts in +//! the packet), random-access flag and, for MPEG video, picture type, temporal reference and field +//! structure. That index is the seeking table. //! - Units are read back on demand by re-reading the file from the unit's first packet, so the //! index costs a few dozen bytes per access unit. //! - [`mux`] writes one program as a transport stream to any `io::Write`, frame by frame. @@ -162,6 +163,13 @@ pub enum Codec { H264, /// H.265 / HEVC, Annex B. Hevc, + /// MPEG-4 Part 2 visual (ISO/IEC 14496-2), stream type 0x10. + Mpeg4Part2, + /// AV1 (stream type 0x06 with the registration descriptor "AV01"). [`File::read_unit`] + /// returns each access unit in the low overhead bitstream format, without start codes, + /// emulation prevention bytes or temporal delimiters; the AV1 video descriptor is in + /// [`Stream::av1c`]. + Av1, /// MPEG-1/2 audio (layers I-III; the layer is in each frame header). MpegAudio, /// AAC in ADTS frames. @@ -174,6 +182,10 @@ pub enum Codec { Eac3, /// DTS. Dts, + /// Opus (stream type 0x06 with the registration descriptor "Opus"). Each unit is one Opus + /// access unit without its control header; the channel configuration and the trims are in + /// [`Stream::opus`]. + Opus, /// Dolby TrueHD. TrueHd, /// Blu-ray / AVCHD LPCM (a 4-byte header per PES packet, big-endian samples). @@ -194,12 +206,15 @@ impl Codec { Codec::Mpeg2Video => "MPEG-2 Video".into(), Codec::H264 => "H.264".into(), Codec::Hevc => "HEVC".into(), + Codec::Mpeg4Part2 => "MPEG-4 Part 2".into(), + Codec::Av1 => "AV1".into(), Codec::MpegAudio => "MPEG Audio".into(), Codec::AacAdts => "AAC (ADTS)".into(), Codec::AacLatm => "AAC (LATM)".into(), Codec::Ac3 => "AC-3".into(), Codec::Eac3 => "E-AC-3".into(), Codec::Dts => "DTS".into(), + Codec::Opus => "Opus".into(), Codec::TrueHd => "Dolby TrueHD".into(), Codec::LpcmBluray => "LPCM (Blu-ray)".into(), Codec::LpcmDvd => "LPCM (DVD)".into(), @@ -220,10 +235,13 @@ impl Codec { Codec::Mpeg1Video | Codec::Mpeg2Video => Id::Mpeg2Video, Codec::H264 => Id::H264, Codec::Hevc => Id::Hevc, + Codec::Mpeg4Part2 => Id::Mpeg4Video, + Codec::Av1 => Id::Av1, Codec::MpegAudio => Id::Mp2, Codec::AacAdts | Codec::AacLatm => Id::Aac, Codec::Ac3 => Id::Ac3, Codec::Eac3 => Id::Eac3, + Codec::Opus => Id::Opus, Codec::LpcmBluray | Codec::LpcmDvd => Id::Pcm, Codec::Dts | Codec::TrueHd | Codec::Subtitle(_) | Codec::Unknown(_) => Id::Unknown, } @@ -232,13 +250,14 @@ impl Codec { /// The kind of media. pub fn kind(&self) -> Kind { match self { - Codec::Mpeg1Video | Codec::Mpeg2Video | Codec::H264 | Codec::Hevc => Kind::Video, + Codec::Mpeg1Video | Codec::Mpeg2Video | Codec::H264 | Codec::Hevc | Codec::Mpeg4Part2 | Codec::Av1 => Kind::Video, Codec::MpegAudio | Codec::AacAdts | Codec::AacLatm | Codec::Ac3 | Codec::Eac3 | Codec::Dts + | Codec::Opus | Codec::TrueHd | Codec::LpcmBluray | Codec::LpcmDvd => Kind::Audio, @@ -280,11 +299,14 @@ pub struct Unit { pub pts: Option, /// See `pts`. pub dts: Option, - /// Decoding can start here (I / IDR / IRAP pictures; every audio frame). + /// Decoding can start here (I / IDR / IRAP pictures, MPEG-4 Part 2 I-VOPs, AV1 units whose + /// packet sets the random access indicator; every audio frame). pub key: bool, - /// No other unit depends on it (B pictures of MPEG-1/2 video, non-reference H.264/HEVC). + /// No other unit depends on it (B pictures of MPEG-1/2 video, MPEG-4 Part 2 B-VOPs, + /// non-reference H.264/HEVC). pub disposable: bool, - /// Bytes of elementary stream. + /// Bytes of elementary stream (for AV1, with its start codes and emulation prevention + /// bytes). pub size: u32, /// TS: byte offset of the packet holding the first byte; PS: byte offset of its PES packet. pub(crate) pos: u64, @@ -305,6 +327,59 @@ pub struct LpcmFormat { pub bits: u32, } +/// An Opus stream's channel configuration (the Opus audio descriptor of the Opus transport +/// draft, with the fixed configurations of its table 4-3 written out) and its trims. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OpusConfig { + /// Output channels. + pub channels: u8, + /// Channel mapping family (RFC 7845 §5.1.1): 0, 1 or 255. + pub family: u8, + /// Opus streams in each access unit. + pub streams: u8, + /// Streams that decode to two channels. + pub coupled: u8, + /// For each output channel, the coded channel it is taken from, or 255 for silence. + pub mapping: Vec, + /// The units whose control header carries a start or end trim, in unit order. + pub trims: Vec, +} + +/// Samples at 48 kHz that a unit's control header says to discard. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct OpusTrim { + /// Index of the unit in [`Stream::units`]. + pub unit: usize, + /// Samples to discard from the start of the unit. + pub start: u16, + /// Samples to discard from the end of the unit. + pub end: u16, +} + +impl OpusConfig { + /// The `OpusHead` identification header (RFC 7845 §5.1) for this configuration. Its pre-skip + /// is the sum of the start trims of the units that open the stream (units 0, 1, 2 and so on, + /// as long as each one has a start trim), at most 65 535; a start trim later in the stream, + /// after a discontinuity, stays in [`OpusConfig::trims`] only. Its input sample rate is 48 kHz + /// and its output gain 0. + pub fn opus_head(&self) -> Vec { + let pre_skip = + self.trims.iter().enumerate().take_while(|&(k, t)| t.unit == k && t.start > 0).fold(0u16, |a, (_, t)| a.saturating_add(t.start)); + let mut v = b"OpusHead".to_vec(); + v.push(1); + v.push(self.channels); + v.extend_from_slice(&pre_skip.to_le_bytes()); + v.extend_from_slice(&48_000u32.to_le_bytes()); + v.extend_from_slice(&0i16.to_le_bytes()); + v.push(self.family); + if self.family != 0 { + v.extend_from_slice(&[self.streams, self.coupled]); + v.extend_from_slice(&self.mapping); + } + v + } +} + /// Where a stream's PES packets come from. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum StreamId { @@ -334,6 +409,13 @@ pub struct Stream { pub units: Vec, /// DVD LPCM: the sample format. pub lpcm: Option, + /// Opus: the channel configuration from the PMT's Opus audio descriptor, and the trims of the + /// units' control headers. `None` when the descriptor is missing or not valid. + pub opus: Option, + /// AV1: the first four bytes of an ISOBMFF `av1C` record, from the PMT's AV1 video + /// descriptor (marker and version, profile and level, tier and color format, initial + /// presentation delay). `None` without a valid descriptor. + pub av1c: Option<[u8; 4]>, /// PES packets seen. pub pes_packets: u64, /// Bytes of payload ignored because the stream could not be split (e.g. before the first @@ -347,16 +429,24 @@ impl Stream { self.codec.kind() } /// What a decoder needs for this stream, in the container-neutral form the codec crates take: - /// the codec ([`Codec::codec_id`]) and, for DVD LPCM, the sample format (big-endian). These - /// streams carry their configuration in band, so `extradata` is empty: H.264 and HEVC are - /// Annex B with their parameter sets, AAC is ADTS or LATM frames, and a Blu-ray LPCM packet - /// starts with its own 4-byte format header. + /// the codec ([`Codec::codec_id`]) and, for DVD LPCM, the sample format (big-endian). Opus + /// gets its `OpusHead` header ([`OpusConfig::opus_head`]), 48 kHz and its channel count, and + /// AV1 the four bytes of [`Stream::av1c`]. The other streams carry their configuration in + /// band, so `extradata` is empty: H.264 and HEVC are Annex B with their parameter sets, + /// MPEG-4 Part 2 has its configuration headers before its keyframes, AAC is ADTS or LATM + /// frames, and a Blu-ray LPCM packet starts with its own 4-byte format header. pub fn codec_params(&self) -> crate::CodecParams { let mut p = crate::CodecParams::new(self.codec.codec_id()); if let Some(f) = self.lpcm { let n = |v: u32| u16::try_from(v).unwrap_or(0); p = p.with_sample_rate(f.sample_rate).with_channels(n(f.channels)).with_pcm(crate::PcmFormat::int(n(f.bits), true, true)); } + if let (Codec::Opus, Some(o)) = (&self.codec, &self.opus) { + p = p.with_sample_rate(48_000).with_channels(u16::from(o.channels)).with_extradata(o.opus_head()); + } + if let (Codec::Av1, Some(c)) = (&self.codec, self.av1c) { + p = p.with_extradata(c.to_vec()); + } p } /// First and last presentation timestamps (90 kHz) of the stream's units. @@ -397,7 +487,8 @@ impl File { self.streams.iter().position(|s| s.kind() == kind && !s.units.is_empty() && f(&s.codec)) } - /// Read access unit `i` of stream `s`. + /// Read access unit `i` of stream `s`. An AV1 unit comes back in the low overhead bitstream + /// format ([`Codec::Av1`]), so it can be shorter than [`Unit::size`]. pub fn read_unit(&self, src: &S, s: usize, i: usize) -> Result> { let st = self.streams.get(s).ok_or_else(|| Error::Invalid("no such stream".into()))?; let u = st.units.get(i).ok_or_else(|| Error::Invalid("no such unit".into()))?; @@ -413,6 +504,9 @@ impl File { if out.len() < u.size as usize { return Err(Error::Invalid(format!("unit {i} truncated ({} of {} bytes)", out.len(), u.size))); } + if st.codec == Codec::Av1 { + es::av1_obus(&mut out); + } Ok(out) } } diff --git a/crates/media/src/mpegts/mux/mod.rs b/crates/media/src/mpegts/mux/mod.rs index 7e7ced7918..89f5ba8fd8 100644 --- a/crates/media/src/mpegts/mux/mod.rs +++ b/crates/media/src/mpegts/mux/mod.rs @@ -51,6 +51,8 @@ mod av1; mod pes; mod psi; +pub(crate) use psi::OPUS_DESCRIPTOR_EXTENSION; + use std::fmt; use std::io::{self, Write}; diff --git a/crates/media/src/mpegts/ps.rs b/crates/media/src/mpegts/ps.rs index d044c01f45..effc7b92c0 100644 --- a/crates/media/src/mpegts/ps.rs +++ b/crates/media/src/mpegts/ps.rs @@ -247,6 +247,8 @@ pub(crate) fn scan(src: &S, mpeg1: bool) -> Result language: None, units: Vec::new(), lpcm, + opus: None, + av1c: None, pes_packets: 0, skipped_bytes: 0, }; diff --git a/crates/media/src/mpegts/tests.rs b/crates/media/src/mpegts/tests.rs index b9cb1af3b7..842dc43625 100644 --- a/crates/media/src/mpegts/tests.rs +++ b/crates/media/src/mpegts/tests.rs @@ -5,6 +5,7 @@ use super::*; mod hostile; +mod opus_av1_mpeg4; fn ts_bytes(prefix: u8, v: i64) -> [u8; 5] { let v = v & ((1 << 33) - 1); @@ -1035,6 +1036,8 @@ fn oversized_unit_is_refused_without_reserving_it() { language: None, units: vec![Unit { pts: None, dts: None, key: true, disposable: false, size: u32::MAX, pos: 0, offset: 0, picture: None }], lpcm: None, + opus: None, + av1c: None, pes_packets: 0, skipped_bytes: 0, }], diff --git a/crates/media/src/mpegts/tests/hostile.rs b/crates/media/src/mpegts/tests/hostile.rs index a0503fc0c1..5f4d09b4b5 100644 --- a/crates/media/src/mpegts/tests/hostile.rs +++ b/crates/media/src/mpegts/tests/hostile.rs @@ -57,13 +57,13 @@ fn ps_seed() -> Vec { #[test] fn hostile_input_never_panics() { - let mut seeds = vec![ts_seed(false), ts_seed(true), ps_seed()]; + let mut seeds = vec![ts_seed(false), ts_seed(true), ps_seed(), super::opus_av1_mpeg4::seed()]; seeds.push(work_tests::big_program_stream(false, 8).0); seeds.push(work_tests::big_program_stream(true, 8).0); // fewer rounds than FilmCraft's 40 000: tests here build without optimisation, and the two // large program streams cost a megabyte of window refill per unit read for (i, s) in seeds.iter().enumerate() { - craft_media_testkit::hostile::hammer(&format!("mpegts seed {i}"), s, if i < 3 { 4_000 } else { 150 }, exercise); + craft_media_testkit::hostile::hammer(&format!("mpegts seed {i}"), s, if i < 4 { 4_000 } else { 150 }, exercise); } } @@ -83,6 +83,9 @@ fn elementary_stream_frame_parsers_never_panic() { Codec::TrueHd, Codec::LpcmBluray, Codec::LpcmDvd, + Codec::Mpeg4Part2, + Codec::Av1, + Codec::Opus, Codec::Unknown(0x55), ]; let mut ac3 = vec![0x0B, 0x77, 0, 0, 30, 0x40]; diff --git a/crates/media/src/mpegts/tests/opus_av1_mpeg4.rs b/crates/media/src/mpegts/tests/opus_av1_mpeg4.rs new file mode 100644 index 0000000000..6375fb3981 --- /dev/null +++ b/crates/media/src/mpegts/tests/opus_av1_mpeg4.rs @@ -0,0 +1,279 @@ +//! Opus, AV1 and MPEG-4 Part 2 streams built by hand from the carriage rules: the Opus transport +//! draft (control headers, the Opus audio descriptor), Carriage of AV1 in MPEG-2 TS (start codes, +//! emulation prevention, the AV1 video descriptor) and stream type 0x10. + +use super::super::ts::opus_config; +use super::*; + +const OPUS_PID: u16 = 0x1100; +const AV1_PID: u16 = 0x1200; +const MPEG4_PID: u16 = 0x1300; + +/// The registration descriptor "Opus" and an Opus audio descriptor with this channel_config_code +/// and the bytes after it. +fn opus_desc(code: &[u8]) -> Vec { + let mut d = vec![0x05, 4, b'O', b'p', b'u', b's', 0x7F, 1 + code.len() as u8, 0x80]; + d.extend_from_slice(code); + d +} + +/// An opus_control_header for `size` payload bytes. +fn control(size: usize, start: Option, end: Option, ext: Option<&[u8]>) -> Vec { + let flags = 0xE0 | if start.is_some() { 0x10 } else { 0 } | if end.is_some() { 0x08 } else { 0 } | if ext.is_some() { 0x04 } else { 0 }; + let mut v = vec![0x7F, flags]; + v.extend(std::iter::repeat_n(0xFF, size / 255)); + v.push((size % 255) as u8); + for t in [start, end].into_iter().flatten() { + v.extend_from_slice(&t.to_be_bytes()); + } + if let Some(e) = ext { + v.push(e.len() as u8); + v.extend_from_slice(e); + } + v +} + +/// `n` bytes of an Opus packet: a TOC byte, then filler. +fn opus_packet(n: usize, seed: u8) -> Vec { + let mut v = vec![0xFC]; + v.extend((1..n).map(|i| (i as u8).wrapping_mul(7) ^ seed)); + v +} + +fn opus_mux(code: &[u8]) -> TsMux { + let mut mux = TsMux::new(false); + mux.psi_full(&[(0x06, OPUS_PID, opus_desc(code))], OPUS_PID); + mux +} + +/// A transport stream packet on `pid` that starts a PES packet and sets the random access +/// indicator; `payload` is at most 182 bytes. +fn random_access_packet(mux: &mut TsMux, pid: u16, payload: &[u8]) { + let cc = mux.cc.entry(pid).or_insert(0); + let al = 183 - payload.len(); + let mut p = vec![0x47, 0x40 | (pid >> 8) as u8, pid as u8, 0x30 | *cc, al as u8, 0x40]; + p.extend(std::iter::repeat_n(0xFF, al - 1)); + p.extend_from_slice(payload); + *cc = (*cc + 1) & 15; + mux.out.extend(p); +} + +/// A transport stream packet on `pid` that sets the unit start indicator and carries only an +/// adaptation field, with the random access indicator set when `random_access` is. +fn adaptation_only_start(mux: &mut TsMux, pid: u16, random_access: bool) { + let cc = *mux.cc.entry(pid).or_insert(0); + let mut p = vec![0x47, 0x40 | (pid >> 8) as u8, pid as u8, 0x20 | cc, 183, if random_access { 0x40 } else { 0 }]; + p.extend(std::iter::repeat_n(0xFF, 182)); + mux.out.extend(p); +} + +/// Opus, AV1 and MPEG-4 Part 2 streams in one program, for the hostile-input sweep. +pub(super) fn seed() -> Vec { + let mut mux = TsMux::new(false); + let av1 = vec![0x05, 4, b'A', b'V', b'0', b'1', 0x80, 4, 0x81, 0x08, 0x0C, 0xC0]; + mux.psi_full(&[(0x06, OPUS_PID, opus_desc(&[0x02])), (0x06, AV1_PID, av1), (0x10, MPEG4_PID, Vec::new())], OPUS_PID); + for k in 0..6i64 { + let mut au = control(40, (k == 0).then_some(312), None, Some(&[1, 2])); + au.extend(opus_packet(40, k as u8)); + au.extend(control(3, None, None, None)); + au.extend(opus_packet(3, k as u8)); + mux.pes(OPUS_PID, &pes(0xBD, Some(1800 * k), None, &au, true)); + let tu = [0, 0, 1, 0x12, 0x00, 0, 0, 1, 0x0A, 0x04, 0, 0, 3, 0, 0x7F, 0, 0, 1, 0x30, 0x10, 0x20]; + mux.pes(AV1_PID, &pes(0xBD, Some(3600 * k), None, &tu, true)); + let vop = [0, 0, 1, 0xB6, if k == 0 { 0x10 } else { 0x50 }, 1, 2, 3]; + mux.pes(MPEG4_PID, &pes(0xE0, Some(3600 * k), None, &vop, true)); + } + mux.out +} + +#[test] +fn opus_access_units_are_cut_by_their_control_headers() { + let mut mux = opus_mux(&[0x02]); + let (a, b, c, d) = (opus_packet(600, 1), opus_packet(5, 2), opus_packet(7, 3), opus_packet(10, 4)); + // one PES packet: an access unit with a start trim and a control extension, a plain one, and + // one without a control header that runs to the end of the packet + let mut first = control(a.len(), Some(312), None, Some(&[9, 9, 9])); + first.extend(&a); + first.extend(control(b.len(), None, None, None)); + first.extend(&b); + first.extend(&c); + mux.pes(OPUS_PID, &pes(0xBD, Some(90_000), None, &first, true)); + let mut second = control(d.len(), None, Some(100), None); + second.extend(&d); + mux.pes(OPUS_PID, &pes(0xBD, Some(91_800), None, &second, true)); + let f = open(&mux.out).unwrap(); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + let s = &f.streams[0]; + assert_eq!((s.codec.clone(), s.kind(), s.skipped_bytes), (Codec::Opus, Kind::Audio, 0)); + let units: Vec> = (0..s.units.len()).map(|n| f.read_unit(&mux.out, 0, n).unwrap()).collect(); + assert_eq!(units, [a, b, c, d]); + // the PES timestamps belong to the first access unit of each packet + assert_eq!(s.units.iter().map(|u| u.pts).collect::>(), [Some(90_000), None, None, Some(91_800)]); + assert!(s.units.iter().all(|u| u.key)); + let o = s.opus.as_ref().unwrap(); + assert_eq!(o.trims, [OpusTrim { unit: 0, start: 312, end: 0 }, OpusTrim { unit: 3, start: 0, end: 100 }]); +} + +#[test] +fn an_opus_control_header_may_cross_packet_boundaries() { + // the second header starts at every offset around the end of the first TS packet's payload + for len in 150..200 { + let mut mux = opus_mux(&[0x01]); + let (a, b) = (opus_packet(len, 5), opus_packet(300, 6)); + let mut au = control(a.len(), None, None, None); + au.extend(&a); + au.extend(control(b.len(), Some(80), Some(20), None)); + au.extend(&b); + mux.pes(OPUS_PID, &pes(0xBD, Some(1000), None, &au, true)); + let f = open(&mux.out).unwrap(); + let s = &f.streams[0]; + assert_eq!(s.units.len(), 2, "len {len}"); + assert_eq!((f.read_unit(&mux.out, 0, 0).unwrap(), f.read_unit(&mux.out, 0, 1).unwrap()), (a, b), "len {len}"); + assert_eq!(s.opus.as_ref().unwrap().trims, [OpusTrim { unit: 1, start: 80, end: 20 }], "len {len}"); + } +} + +#[test] +fn opus_access_units_past_their_packet_are_dropped() { + let mut mux = opus_mux(&[0x02]); + // a payload size of 1000 in a packet that holds 50 bytes of it + let mut cut = control(1000, None, None, None); + cut.extend(opus_packet(50, 1)); + mux.pes(OPUS_PID, &pes(0xBD, Some(0), None, &cut, true)); + // a payload size past the largest unit: 0xFF bytes for 130 MiB, then the packet ends + let mut huge = vec![0x7F, 0xE0]; + huge.extend(std::iter::repeat_n(0xFF, 535_000)); + mux.pes(OPUS_PID, &pes(0xBD, Some(1800), None, &huge, false)); + let good = opus_packet(20, 2); + let mut au = control(good.len(), None, None, None); + au.extend(&good); + mux.pes(OPUS_PID, &pes(0xBD, Some(3600), None, &au, true)); + let f = open(&mux.out).unwrap(); + let s = &f.streams[0]; + assert_eq!(s.units.len(), 1); + assert_eq!(s.units[0].pts, Some(3600)); + assert_eq!(f.read_unit(&mux.out, 0, 0).unwrap(), good); + assert!(s.skipped_bytes >= 50 + 535_000, "{} bytes skipped", s.skipped_bytes); +} + +#[test] +fn opus_channel_configurations_follow_the_draft_table() { + let config = |code: &[u8]| opus_config(&opus_desc(code)).map(|o| (o.channels, o.family, o.streams, o.coupled, o.mapping)); + // dual mono as one coupled stream and as two mono streams + assert_eq!(config(&[0x00]), Some((2, 255, 1, 1, vec![0, 1]))); + assert_eq!(config(&[0x80]), Some((2, 255, 2, 0, vec![0, 1]))); + assert_eq!(config(&[0x03]), Some((3, 1, 2, 1, vec![0, 2, 1]))); + assert_eq!(config(&[0x07]), Some((7, 1, 4, 3, vec![0, 4, 1, 2, 3, 5, 6]))); + // the same orders with a mono stream per channel + assert_eq!(config(&[0x82]), Some((2, 1, 2, 0, vec![0, 1]))); + assert_eq!(config(&[0x88]), Some((8, 1, 8, 0, vec![0, 1, 2, 3, 4, 5, 6, 7]))); + for reserved in [0x09, 0x7F, 0x89, 0xFF] { + assert_eq!(config(&[reserved]), None, "{reserved:#x}"); + } + // explicit: 3 channels, family 1, 2 streams (01), 1 coupled (01), mapping 0 2 1 (00 10 01) + assert_eq!(config(&[0x81, 3, 1, 0b0101_0010, 0b0100_0000]), Some((3, 1, 2, 1, vec![0, 2, 1]))); + // a silent channel is the all-ones mapping value: 2 streams (1), none coupled (00), mapping + // silence 0 (11 00) + assert_eq!(config(&[0x81, 2, 255, 0b1001_1000]), Some((2, 255, 2, 0, vec![255, 0]))); + // no channels, a reserved family, more streams than channels, a mapping past the coded + // channels, too few bytes + assert_eq!(config(&[0x81, 0, 0]), None); + assert_eq!(config(&[0x81, 2, 2, 0]), None); + assert_eq!(config(&[0x81, 3, 1, 0xFF, 0xFF]), None); + // two streams, none coupled: mapping values take 2 bits, and 2 names no coded channel + // (1, 00, then 10 00) + assert_eq!(config(&[0x81, 2, 255, 0b1001_0000]), None); + assert_eq!(config(&[0x81, 3, 1]), None); + // family 1 stops at 8 channels; family 0 at 2 + assert_eq!(config(&[0x81, 9, 1, 0, 0, 0, 0, 0]), None); + assert_eq!(config(&[0x81, 3, 0]), None); +} + +#[test] +fn the_pre_skip_counts_only_the_start_trims_that_open_the_stream() { + let pre_skip = |trims: &[(usize, u16, u16)]| { + let mut o = opus_config(&opus_desc(&[0x02])).unwrap(); + o.trims = trims.iter().map(|&(unit, start, end)| OpusTrim { unit, start, end }).collect(); + let head = o.opus_head(); + u16::from_le_bytes([head[10], head[11]]) + }; + assert_eq!(pre_skip(&[]), 0); + // a lead-in longer than one access unit, then a start trim after a discontinuity + assert_eq!(pre_skip(&[(0, 960, 0), (1, 960, 0), (2, 312, 0), (40, 500, 0)]), 2232); + // an end trim on the first unit stops the lead-in + assert_eq!(pre_skip(&[(0, 0, 100), (1, 312, 0)]), 0); + assert_eq!(pre_skip(&[(3, 312, 0)]), 0); + assert_eq!(pre_skip(&[(0, 60_000, 0), (1, 60_000, 0)]), u16::MAX); +} + +#[test] +fn av1_units_come_back_as_obus() { + let mut mux = TsMux::new(false); + // hdr_wcg_idc 3 (11), a reserved bit (0), initial_presentation_delay_present (1), delay 3 + // (0011) + let desc = vec![0x05, 4, b'A', b'V', b'0', b'1', 0x80, 4, 0x81, 0x08, 0x0C, 0b1101_0011]; + mux.psi_full(&[(0x06, AV1_PID, desc)], AV1_PID); + // a temporal delimiter; a sequence header with obu_size 4 whose payload 00 00 00 7F carries + // an emulation prevention byte, and a stray byte after it; a frame OBU without obu_size + let key = [0, 0, 1, 0x12, 0x00, 0, 0, 1, 0x0A, 0x04, 0, 0, 3, 0, 0x7F, 0x55, 0, 0, 1, 0x30, 0x10, 0x20, 0x30]; + random_access_packet(&mut mux, AV1_PID, &pes(0xBD, Some(3600), None, &key, true)); + let next = [0, 0, 1, 0x32, 0x02, 0xAA, 0xBB]; + mux.pes(AV1_PID, &pes(0xBD, Some(7200), None, &next, true)); + // null packets, so the file holds the five packets the probe looks for + mux.pes(0x1FFF, &[0xFF; 184 * 2]); + let f = open(&mux.out).unwrap(); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + let s = &f.streams[0]; + assert_eq!((s.codec.clone(), s.kind(), s.codec.codec_id()), (Codec::Av1, Kind::Video, crate::CodecId::Av1)); + assert_eq!(s.av1c, Some([0x81, 0x08, 0x0C, 0b0001_0011])); + assert_eq!(s.codec_params().extradata, [0x81, 0x08, 0x0C, 0b0001_0011]); + assert_eq!(s.units.iter().map(|u| u.key).collect::>(), [true, false]); + assert_eq!(f.read_unit(&mux.out, 0, 0).unwrap(), [0x0A, 0x04, 0, 0, 0, 0x7F, 0x32, 0x03, 0x10, 0x20, 0x30]); + assert_eq!(f.read_unit(&mux.out, 0, 1).unwrap(), [0x32, 0x02, 0xAA, 0xBB]); +} + +#[test] +fn an_adaptation_field_only_unit_start_keeps_the_random_access_indicator_of_the_pes_packet() { + let tu = [0, 0, 1, 0x12, 0x00, 0, 0, 1, 0x32, 0x02, 0xAA, 0xBB]; + for first_is_key in [true, false] { + let mut mux = TsMux::new(false); + let desc = vec![0x05, 4, b'A', b'V', b'0', b'1', 0x80, 4, 0x81, 0x08, 0x0C, 0xC0]; + mux.psi_full(&[(0x06, AV1_PID, desc)], AV1_PID); + // the PES header ends in the next packet; an adaptation-field-only unit start with the + // other indicator comes between the two + let first = pes(0xBD, Some(3600), None, &tu, true); + if first_is_key { + random_access_packet(&mut mux, AV1_PID, &first[..5]); + } else { + mux.packet(AV1_PID, true, &first[..5]); + } + adaptation_only_start(&mut mux, AV1_PID, !first_is_key); + mux.packet(AV1_PID, false, &first[5..]); + mux.pes(AV1_PID, &pes(0xBD, Some(7200), None, &tu, true)); + mux.pes(0x1FFF, &[0xFF; 184 * 2]); + let f = open(&mux.out).unwrap(); + let s = &f.streams[0]; + assert_eq!(s.units.iter().map(|u| u.key).collect::>(), [first_is_key, false], "first is key: {first_is_key}"); + } +} + +#[test] +fn mpeg4_part2_units_take_their_flags_from_the_first_vop() { + let mut mux = TsMux::new(false); + mux.psi(&[(0x10, MPEG4_PID)]); + // visual object sequence and VOL headers, then an I-VOP; a P-VOP whose data goes on in a PES + // packet without a timestamp; a B-VOP + let i_vop = [0, 0, 1, 0xB0, 0x01, 0, 0, 1, 0x00, 0, 0, 1, 0x20, 0x00, 0x84, 0, 0, 1, 0xB6, 0x10, 1, 2]; + let p_vop = [0, 0, 1, 0xB6, 0x50, 3, 4]; + let more = [5u8; 300]; + let b_vop = [0, 0, 1, 0xB6, 0x90, 6, 7]; + mux.pes(MPEG4_PID, &pes(0xE0, Some(3600), None, &i_vop, true)); + mux.pes(MPEG4_PID, &pes(0xE0, Some(7200), None, &p_vop, true)); + mux.pes(MPEG4_PID, &pes(0xE0, None, None, &more, true)); + mux.pes(MPEG4_PID, &pes(0xE0, Some(10_800), None, &b_vop, true)); + let f = open(&mux.out).unwrap(); + let s = &f.streams[0]; + assert_eq!((s.codec.clone(), s.kind(), s.codec.codec_id()), (Codec::Mpeg4Part2, Kind::Video, crate::CodecId::Mpeg4Video)); + assert_eq!(s.units.iter().map(|u| (u.key, u.disposable)).collect::>(), [(true, false), (false, false), (false, true)]); + assert_eq!(f.read_unit(&mux.out, 0, 1).unwrap(), [&p_vop[..], &more].concat()); +} diff --git a/crates/media/src/mpegts/ts.rs b/crates/media/src/mpegts/ts.rs index 1d28bb736a..7c9ea716ef 100644 --- a/crates/media/src/mpegts/ts.rs +++ b/crates/media/src/mpegts/ts.rs @@ -4,7 +4,7 @@ use std::collections::HashMap; use super::es::Splitter; use super::pes::{self, PesHeader}; -use super::{ByteSource, ClockRange, Codec, Error, File, Format, Result, Stream, StreamId, Unit, Unwrap, read_some}; +use super::{ByteSource, ClockRange, Codec, Error, File, Format, OpusConfig, Result, Stream, StreamId, Unit, Unwrap, read_some}; /// Byte-wise table for the MSB-first CRC-32 (polynomial 0x04C11DB7): entry `i` is the CRC register /// after shifting the byte `i` through eight bit steps. @@ -40,6 +40,8 @@ struct Packet<'a> { cc: u8, has_payload: bool, discontinuity: bool, + /// random_access_indicator of the adaptation field. + random_access: bool, pcr: Option, payload: &'a [u8], } @@ -65,6 +67,7 @@ fn packet(p: &[u8]) -> std::result::Result, Bad> { let mut start = 4; let mut pcr = None; let mut discontinuity = false; + let mut random_access = false; if afc & 2 != 0 { let al = p[4] as usize; start = 5 + al; @@ -74,6 +77,7 @@ fn packet(p: &[u8]) -> std::result::Result, Bad> { if al > 0 { let flags = p[5]; discontinuity = flags & 0x80 != 0; + random_access = flags & 0x40 != 0; if flags & 0x10 != 0 && al >= 7 { let base = ((p[6] as i64) << 25) | ((p[7] as i64) << 17) | ((p[8] as i64) << 9) | ((p[9] as i64) << 1) | (p[10] as i64 >> 7); let ext = (((p[10] & 1) as i64) << 8) | p[11] as i64; @@ -82,7 +86,7 @@ fn packet(p: &[u8]) -> std::result::Result, Bad> { } } let has_payload = afc & 1 != 0; - Ok(Packet { pusi, pid, cc, has_payload, discontinuity, pcr, payload: if has_payload { &p[start..188] } else { &[] } }) + Ok(Packet { pusi, pid, cc, has_payload, discontinuity, random_access, pcr, payload: if has_payload { &p[start..188] } else { &[] } }) } /// `(transport_error_indicator, scrambled)` of a packet whose first byte is the sync byte (H.222.0 @@ -230,6 +234,31 @@ struct EsState { asm: PesAsm, cc: Option, dup: DupGuard, + /// The packet that started the PES packet being assembled set random_access_indicator. + random_access: bool, +} + +impl EsState { + /// Reassemble PES packets from packet `pk` (at file offset `pos`) and pass their payload to + /// the splitter. + fn feed(&mut self, pk: &Packet<'_>, pos: u64, unwrap: &mut Unwrap) { + // `PesAsm` passes over an adaptation-field-only unit start, so its indicator does not + // belong to the PES packet being assembled + if pk.pusi && !pk.payload.is_empty() { + self.random_access = pk.random_access; + } + let (hdr, bytes) = self.asm.packet(pk.pusi, pk.payload); + if let Some(h) = hdr { + self.stream.pes_packets += 1; + let pts = h.pts.map(|t| unwrap.unwrap(t)); + let dts = h.dts.map(|t| unwrap.unwrap(t)); + self.split.pes_start(pts, dts); + if std::mem::take(&mut self.random_access) { + self.split.random_access(); + } + } + self.split.feed(pos, bytes); + } } /// Map a PMT stream_type (and the ES descriptors) to a codec. `hdmv`: a Blu-ray / AVCHD stream @@ -253,6 +282,7 @@ pub(crate) fn codec_of(stream_type: u8, desc: &[u8], hdmv: bool) -> Codec { 0x03 | 0x04 => Codec::MpegAudio, 0x0F => Codec::AacAdts, 0x11 => Codec::AacLatm, + 0x10 => Codec::Mpeg4Part2, 0x1B => Codec::H264, 0x24 => Codec::Hevc, 0x80 if hdmv => Codec::LpcmBluray, @@ -264,6 +294,10 @@ pub(crate) fn codec_of(stream_type: u8, desc: &[u8], hdmv: bool) -> Codec { 0x87 => Codec::Eac3, 0x90 if hdmv => Codec::Subtitle("PGS subtitles"), 0x92 if hdmv => Codec::Subtitle("Text subtitles"), + // the registration descriptors of the Opus transport draft (§4.3) and of Carriage of + // AV1 in MPEG-2 TS (§2.1) + 0x06 if reg == Some(*b"Opus") => Codec::Opus, + 0x06 if reg == Some(*b"AV01") => Codec::Av1, 0x06 => { if tags.contains(&0x6A) || reg == Some(*b"AC-3") { Codec::Ac3 @@ -283,6 +317,131 @@ pub(crate) fn codec_of(stream_type: u8, desc: &[u8], hdmv: bool) -> Codec { } } +/// The body of the first descriptor with this tag (and, for tag 0x7F, this extension tag, which +/// the returned body leaves out). +fn descriptor(desc: &[u8], tag: u8, extension: Option) -> Option<&[u8]> { + let mut i = 0; + while i + 2 <= desc.len() { + let (t, len) = (desc[i], desc[i + 1] as usize); + let body = desc.get(i + 2..i + 2 + len)?; + match extension { + None if t == tag => return Some(body), + Some(e) if t == tag && body.first() == Some(&e) => return Some(&body[1..]), + _ => {} + } + i += 2 + len; + } + None +} + +/// Bits needed for the values 0 to `n - 1`: ceil(log2(n)). +fn bits_for(n: u32) -> u32 { + if n <= 1 { 0 } else { 32 - (n - 1).leading_zeros() } +} + +/// The channel configuration of the Opus audio descriptor (Opus transport draft §5.3: tag 0x7F, +/// extension tag 0x80, the value the writer uses): a fixed configuration of table 4-3, or one +/// coded in full (channel_config_code 0x81). `None` for a reserved code or fields out of range. +pub(crate) fn opus_config(desc: &[u8]) -> Option { + let body = descriptor(desc, 0x7F, Some(super::mux::OPUS_DESCRIPTOR_EXTENSION))?; + let code = *body.first()?; + let fixed = |channels: u8, family: u8, streams: u8, coupled: u8, mapping: &[u8]| OpusConfig { + channels, + family, + streams, + coupled, + mapping: mapping.to_vec(), + trims: Vec::new(), + }; + let c = match code { + // two channels as one coupled stream, or as two mono streams, in no speaker order + 0x00 => fixed(2, 255, 1, 1, &[0, 1]), + 0x80 => fixed(2, 255, 2, 0, &[0, 1]), + 0x01 => fixed(1, 0, 1, 0, &[0]), + 0x02 => fixed(2, 0, 1, 1, &[0, 1]), + // the RFC 7845 §5.1.1.2 surround orders, with as many coupled streams as fit + 0x03 => fixed(3, 1, 2, 1, &[0, 2, 1]), + 0x04 => fixed(4, 1, 2, 2, &[0, 1, 2, 3]), + 0x05 => fixed(5, 1, 3, 2, &[0, 4, 1, 2, 3]), + 0x06 => fixed(6, 1, 4, 2, &[0, 4, 1, 2, 3, 5]), + 0x07 => fixed(7, 1, 4, 3, &[0, 4, 1, 2, 3, 5, 6]), + 0x08 => fixed(8, 1, 5, 3, &[0, 6, 1, 2, 3, 4, 5, 7]), + // the same orders with every channel in a mono stream + 0x82..=0x88 => { + let ch = code - 0x80; + fixed(ch, 1, ch, 0, &(0..ch).collect::>()) + } + 0x81 => opus_explicit(body.get(1..)?)?, + _ => return None, + }; + Some(c) +} + +/// An explicit Opus channel configuration: channel_count, mapping_family and, for a family above +/// 0, stream_count_minus_one, coupled_stream_count and the channel mapping in as few bits as the +/// draft gives each. +fn opus_explicit(b: &[u8]) -> Option { + let (&channels, &family) = (b.first()?, b.get(1)?); + if channels == 0 { + return None; + } + if family == 0 { + // one mono or stereo stream in coded order + return (channels <= 2).then(|| OpusConfig { + channels, + family, + streams: 1, + coupled: channels - 1, + mapping: (0..channels).collect(), + trims: Vec::new(), + }); + } + // family 1 is defined for 1 to 8 channels (RFC 7845 §5.1.1.2) + if !(family == 255 || family == 1 && channels <= 8) { + return None; + } + let bits = &b[2..]; + let mut at = 0u32; + let mut take = |n: u32| -> Option { + let mut v = 0u32; + for _ in 0..n { + let byte = *bits.get((at / 8) as usize)?; + v = v << 1 | u32::from(byte >> (7 - at % 8) & 1); + at += 1; + } + Some(v) + }; + let ch = u32::from(channels); + let streams = take(bits_for(ch))? + 1; + let coupled = take(bits_for(streams + 1))?; + // a mapping entry is one byte, 255 meaning silence (RFC 7845 §5.1.1) + if streams > ch || coupled > streams || streams + coupled > 255 { + return None; + } + let width = bits_for(streams + coupled + 1); + let silence = (1u32 << width) - 1; + let mut mapping = Vec::with_capacity(usize::from(channels)); + for _ in 0..channels { + let m = take(width)?; + match m { + m if m == silence => mapping.push(255), + m if m < streams + coupled => mapping.push(m as u8), + _ => return None, + } + } + Some(OpusConfig { channels, family, streams: streams as u8, coupled: coupled as u8, mapping, trims: Vec::new() }) +} + +/// The AV1 video descriptor (Carriage of AV1 in MPEG-2 TS §2.2: tag 0x80, marker and version 1) +/// as the first four bytes of an `av1C` record: the descriptor's fourth byte holds hdr_wcg_idc +/// and a reserved bit where `av1C` has reserved zeros. +pub(crate) fn av1c(desc: &[u8]) -> Option<[u8; 4]> { + match descriptor(desc, 0x80, None)? { + &[0x81, b1, b2, b3, ..] => Some([0x81, b1, b2, b3 & 0x1F]), + _ => None, + } +} + fn language(desc: &[u8]) -> Option { let mut i = 0; while i + 2 <= desc.len() { @@ -369,10 +528,15 @@ fn add_pmt_streams(sec: &[u8], packet_size: usize, later: bool, es: &mut HashMap language: language(desc), units: Vec::new(), lpcm: None, + opus: if codec == Codec::Opus { opus_config(desc) } else { None }, + av1c: if codec == Codec::Av1 { av1c(desc) } else { None }, pes_packets: 0, skipped_bytes: 0, }; - es.insert(pid, EsState { stream, split: Splitter::new(&codec), asm: PesAsm::default(), cc: None, dup: DupGuard::default() }); + es.insert( + pid, + EsState { stream, split: Splitter::new(&codec), asm: PesAsm::default(), cc: None, dup: DupGuard::default(), random_access: false }, + ); order.push(pid); } changed || (later && es.keys().any(|p| !listed.contains(p))) @@ -595,14 +759,7 @@ pub(crate) fn scan(src: &S, packet_size: usize, sync_off } e.cc = Some(pk.cc); } - let (hdr, bytes) = e.asm.packet(pk.pusi, pk.payload); - if let Some(h) = hdr { - e.stream.pes_packets += 1; - let pts = h.pts.map(|t| unwrap.unwrap(t)); - let dts = h.dts.map(|t| unwrap.unwrap(t)); - e.split.pes_start(pts, dts); - } - e.split.feed(pos, bytes); + e.feed(&pk, pos, &mut unwrap); } // `p >= 1` here (the loop ran at least once or `resync` moved past the failed packet) off += p.max(1) as u64; @@ -640,6 +797,9 @@ pub(crate) fn scan(src: &S, packet_size: usize, sync_off e.split.finish(); e.stream.units = std::mem::take(&mut e.split.units); e.stream.skipped_bytes = e.split.skipped; + if let Some(o) = e.stream.opus.as_mut() { + o.trims = std::mem::take(&mut e.split.trims); + } if e.split.truncated { warnings.push(format!("PID {pid}: more than {} access units, the rest are not indexed", super::es::MAX_UNITS)); } @@ -729,7 +889,16 @@ mod dup_tests { #[test] fn a_discontinuity_packet_is_never_a_duplicate() { let payload = [7u8; 20]; - let pk = |discontinuity| Packet { pusi: true, pid: 0x100, cc: 3, has_payload: true, discontinuity, pcr: None, payload: &payload }; + let pk = |discontinuity| Packet { + pusi: true, + pid: 0x100, + cc: 3, + has_payload: true, + discontinuity, + random_access: false, + pcr: None, + payload: &payload, + }; let mut g = DupGuard::default(); assert!(!g.is_dup(&pk(false))); assert!(!g.is_dup(&pk(true)), "same counter and payload, but the stream restarts here"); @@ -745,6 +914,7 @@ mod dup_tests { cc: 3, has_payload, discontinuity, + random_access: false, pcr: None, payload: if has_payload { &payload } else { &[] }, }; diff --git a/crates/media/src/mpegts/work_tests.rs b/crates/media/src/mpegts/work_tests.rs index d92aca42af..07dfc69e42 100644 --- a/crates/media/src/mpegts/work_tests.rs +++ b/crates/media/src/mpegts/work_tests.rs @@ -94,9 +94,22 @@ fn program_stream_with_large_pes_packets_gives_back_every_frame() { assert_eq!(f.streams.len(), 2); for (s, frames) in f.streams.iter().zip([&a, &b]) { assert_eq!(s.units.len(), frames.len()); - // a read refills a 1 MiB window: every seventh unit and the last ones keep a debug build quick - for (i, fr) in frames.iter().enumerate().filter(|(i, _)| i % 7 == 0 || i + 4 > frames.len()) { - assert_eq!(&f.read_unit(&data, f.streams.iter().position(|x| std::ptr::eq(x, s)).unwrap(), i).unwrap(), fr, "mpeg1 {mpeg1} unit {i}"); + // Sparse reads keep the debug build quick; also force PES-boundary and end reads. + let mut read_unit = frames.iter().enumerate().map(|(i, _)| i % 7 == 0 || i + 4 > frames.len()).collect::>(); + for boundary in (60_000..frames.len() * 576).step_by(60_000) { + read_unit[(boundary - 1) / 576] = true; + if boundary % 576 == 0 { + read_unit[boundary / 576] = true; + } + } + for (i, (fr, should_read)) in frames.iter().zip(read_unit).enumerate() { + if should_read { + assert_eq!( + &f.read_unit(&data, f.streams.iter().position(|x| std::ptr::eq(x, s)).unwrap(), i).unwrap(), + fr, + "mpeg1 {mpeg1} unit {i}" + ); + } } } // cut inside the last packets: never panics, and the units before the cut are intact diff --git a/crates/media/src/ogg/mod.rs b/crates/media/src/ogg/mod.rs index 850240f453..54ffc045eb 100644 --- a/crates/media/src/ogg/mod.rs +++ b/crates/media/src/ogg/mod.rs @@ -16,6 +16,10 @@ //! TOC-derived durations, the pre-skip, and end trimming of the final page, so a player can seek //! to any 48 kHz sample. //! +//! [`VorbisTiming`] does the same for Vorbis (Vorbis I §4.3.8 and §A.2): packet durations from the +//! block sizes of the modes in the setup header ([`VorbisModes`]), a nonzero starting position, +//! and end trimming of the final page. +//! //! [`PageWriter`] writes the pages of a logical bitstream, and [`opus_tags`] and //! [`vorbis_comment`] build the comment headers of Ogg Opus and Ogg Vorbis. //! @@ -32,8 +36,10 @@ use std::fmt; use std::io; pub use crate::source::{ByteSource, ReadSeekSource}; +pub use vorbis::{VorbisModes, VorbisTiming}; pub use write::{PAGE_TARGET_BYTES, PAGE_TARGET_PACKETS, PageWriter, opus_tags, vorbis_comment}; +mod vorbis; mod write; /// Errors from reading an Ogg file. @@ -1046,4 +1052,6 @@ pub use timing::{MAX_OPUS_GRANULE, OpusTiming, VorbisInfo, opus_packet_samples}; #[cfg(test)] mod tests; #[cfg(test)] +mod vorbis_tests; +#[cfg(test)] mod write_tests; diff --git a/crates/media/src/ogg/timing.rs b/crates/media/src/ogg/timing.rs index e01f39b4c3..e5485f507b 100644 --- a/crates/media/src/ogg/timing.rs +++ b/crates/media/src/ogg/timing.rs @@ -126,6 +126,10 @@ pub struct VorbisInfo { pub sample_rate: u32, /// Nominal bit rate in bits per second (0 or negative when not set). pub bitrate_nominal: i32, + /// The short block size in samples, as the header states it (Vorbis I allows 64 to 8192). + pub blocksize_0: u32, + /// The long block size in samples, as the header states it. + pub blocksize_1: u32, } impl VorbisInfo { @@ -138,6 +142,9 @@ impl VorbisInfo { channels: h[11], sample_rate: u32::from_le_bytes([h[12], h[13], h[14], h[15]]), bitrate_nominal: i32::from_le_bytes([h[20], h[21], h[22], h[23]]), + // two 4-bit exponents, the short block's in the low bits + blocksize_0: 1 << (h[28] & 0x0F), + blocksize_1: 1 << (h[28] >> 4), }) } } diff --git a/crates/media/src/ogg/vorbis.rs b/crates/media/src/ogg/vorbis.rs new file mode 100644 index 0000000000..c80d4ceb56 --- /dev/null +++ b/crates/media/src/ogg/vorbis.rs @@ -0,0 +1,447 @@ +//! Vorbis packet durations and stream timing, from the Vorbis I specification: the block sizes of +//! the identification header (§4.2.2), the modes at the end of the setup header (§4.2.4), the +//! samples a packet returns (§4.3.8) and the Ogg granule positions (§A.2). + +use super::{MAX_OPUS_GRANULE, Stream, VorbisInfo}; + +/// The most modes a setup header can declare (a 6-bit count plus one). +const MAX_MODES: usize = 64; + +/// What a Vorbis stream's packets need for their durations: the two block sizes and the block flag +/// of each mode. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VorbisModes { + /// The short and the long block size, in samples. + pub blocksizes: [u32; 2], + /// The block flag of each mode: `true` for the long block. + pub long: Vec, +} + +impl VorbisModes { + /// Reads the block sizes from the identification header and the modes from the setup header; + /// `None` when either is not a valid Vorbis I header. + /// + /// The setup header is walked from its start (codebooks, time-domain transforms, floors, + /// residues and mappings) to reach the modes, without building any decoder tables, so the cost + /// is one pass over the header's bits. + pub fn parse(identification: &[u8], setup: &[u8]) -> Option { + let info = VorbisInfo::parse(identification)?; + let [b0, b1] = [info.blocksize_0, info.blocksize_1]; + // Vorbis I is version 0, with channels and a sample rate (§4.2.2) + let version = u32::from_le_bytes([identification[7], identification[8], identification[9], identification[10]]); + if version != 0 + || info.channels == 0 + || info.sample_rate == 0 + || !(64..=8192).contains(&b0) + || !(64..=8192).contains(&b1) + || b0 > b1 + || identification[29] & 1 == 0 + { + return None; + } + let long = setup_modes(setup, info.channels)?; + Some(VorbisModes { blocksizes: [b0, b1], long }) + } + + /// The block size of an audio packet from its first byte (§4.3.1: a packet-type bit of 0, then + /// the mode number in `ilog(modes - 1)` bits); `None` for a packet that is not audio or names a + /// mode the setup header does not have. + pub fn blocksize(&self, first: u8) -> Option { + self.mode(first).map(|(_, long)| self.blocksizes[usize::from(long)]) + } + + /// The block size of an audio packet of `size` bytes starting with `prefix`; `None` also when + /// the packet ends inside its header, whose long blocks carry the previous and next window + /// flags after the mode number (§4.3.1), since a decoder drops such a packet. + fn packet_blocksize(&self, prefix: [u8; 2], size: u32) -> Option { + let (bits, long) = self.mode(prefix[0])?; + let header = 1 + bits + if long { 2 } else { 0 }; + (u64::from(size) * 8 >= u64::from(header)).then(|| self.blocksizes[usize::from(long)]) + } + + /// The width of the mode number and the block flag of the mode an audio packet's first byte + /// names. + fn mode(&self, first: u8) -> Option<(u32, bool)> { + if first & 1 != 0 { + return None; + } + let bits = ilog(self.long.len().saturating_sub(1) as u32); + let mode = usize::from(first >> 1) & ((1usize << bits) - 1); + self.long.get(mode).map(|&l| (bits, l)) + } +} + +/// Vorbis I §A.2 timing of a Vorbis stream, in samples at the stream's sample rate. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VorbisTiming { + /// Granule position of the first sample each packet returns. A packet's samples run from its + /// start for its duration; positions before 0 are samples to discard. + pub starts: Vec, + /// Samples each packet returns (§4.3.8): 0 for the first audio packet, which only primes the + /// decoder, and for packets that are not audio; otherwise a quarter of the previous audio + /// packet's block size plus a quarter of its own. + pub durations: Vec, + /// Samples to discard at the start: the first page's granule position states fewer samples + /// than its packets return (a negative starting position, at most the first two audio + /// packets' overlap). + pub skip: u32, + /// Granule position of the first sample to play: 0, or the positive start offset of a stream + /// that does not begin at time zero. + pub first: i64, + /// Playable samples from `first`, with the final page's end trimming applied. + pub total: i64, +} + +impl VorbisTiming { + /// Timing of the Vorbis stream `stream`, from its identification and setup headers and the + /// granule positions of its pages; `None` when the stream has no valid Vorbis headers. + /// + /// A granule position outside `0..=MAX_OPUS_GRANULE` is treated like a missing one, as + /// [`OpusTiming::of`](super::OpusTiming::of) does. + pub fn of(stream: &Stream) -> Option { + let modes = VorbisModes::parse(stream.headers.first()?, stream.headers.get(2)?)?; + Some(VorbisTiming::with_modes(stream, &modes)) + } + + /// Timing of `stream` with modes already read, for example from a stream whose headers came + /// from elsewhere. + pub fn with_modes(stream: &Stream, modes: &VorbisModes) -> VorbisTiming { + // Granule positions come straight from the file, so the arithmetic saturates. + let mut previous: Option = None; + // samples the first two audio packets return, the most a negative start can discard + let mut overlap = 0i64; + let mut audio = 0u8; + let durations: Vec = stream + .packets + .iter() + .map(|p| { + let Some(size) = modes.packet_blocksize(p.prefix, p.size) else { return 0 }; + let n = previous.map_or(0, |prev| prev / 4 + size / 4); + previous = Some(size); + if audio < 2 { + audio += 1; + overlap = overlap.saturating_add(i64::from(n)); + } + n + }) + .collect(); + let n = durations.len(); + let granule_of = |k: usize| stream.packets.get(k).and_then(|p| p.granule).filter(|g| (0..=MAX_OPUS_GRANULE).contains(g)); + let mut ends: Vec = vec![0; n]; + let mut cursor: Option = None; + let mut trimmed_end: Option = None; + let mut start: Option = None; + let mut i = 0; + while i < n { + // packets completing on the same page: i..=j, the last carries the page's granule + let mut j = i; + while j < n && granule_of(j).is_none() { + j += 1; + } + let sum = durations[i..j.min(n - 1) + 1].iter().fold(0i64, |a, &d| a.saturating_add(i64::from(d))); + let end = match (granule_of(j), cursor) { + // trailing packets without a granule (a truncated file): continue from the cursor + (None, c) => c.unwrap_or(0).saturating_add(sum), + // end trimming on the final page: keep the positions the packets would have + (Some(g), Some(c)) if stream.packets[j].eos && g < c.saturating_add(sum) => { + trimmed_end = Some(g); + c.saturating_add(sum) + } + // a page that returns no samples (only the priming packet) does not place the stream + (Some(g), None) if sum == 0 && !stream.packets[j].eos => { + ends[i..=j].fill(g); + i = j + 1; + continue; + } + // the first page with audio: its granule places the stream, which may start before + // or after 0 (§A.2) + (Some(g), None) => { + let s = g.saturating_sub(sum); + start = Some(s); + if stream.packets[j].eos && s < 0 { + // one page holds the whole stream: a granule below the samples it returns + // trims the end, not the start + trimmed_end = Some(g); + start = Some(0); + sum + } else { + g + } + } + // a discontinuity: trust the granule + (Some(g), Some(_)) => g, + }; + let mut e = end; + for k in (i..=j.min(n - 1)).rev() { + ends[k] = e; + e = e.saturating_sub(i64::from(durations[k])); + } + cursor = Some(end); + i = j + 1; + } + let starts: Vec = ends.iter().zip(&durations).map(|(e, &d)| e.saturating_sub(i64::from(d))).collect(); + let origin = start.unwrap_or(0); + // a negative start discards samples, never more than the first two audio packets overlap + let skip = origin.saturating_neg().clamp(0, overlap); + let first = origin.saturating_add(skip).max(0); + let end = trimmed_end.or(cursor).unwrap_or(0); + let total = end.saturating_sub(first).max(0); + VorbisTiming { starts, durations, skip: u32::try_from(skip).unwrap_or(u32::MAX), first, total } + } +} + +/// Number of bits needed to hold `x` (§9.2.1). +fn ilog(x: u32) -> u32 { + 32 - x.leading_zeros() +} + +/// Bits read least significant first (§2.1.4). +struct Bits<'a> { + data: &'a [u8], + pos: u64, +} + +impl Bits<'_> { + fn left(&self) -> u64 { + (self.data.len() as u64 * 8).saturating_sub(self.pos) + } + fn read(&mut self, n: u32) -> Option { + if u64::from(n) > self.left() { + return None; + } + let mut v = 0u32; + for k in 0..n { + let at = self.pos + u64::from(k); + let bit = (self.data[(at / 8) as usize] >> (at % 8)) & 1; + v |= u32::from(bit) << k; + } + self.pos += u64::from(n); + Some(v) + } + fn skip(&mut self, n: u64) -> Option<()> { + (n <= self.left()).then(|| self.pos += n) + } + fn zero(&mut self, n: u32) -> Option<()> { + (self.read(n)? == 0).then_some(()) + } +} + +/// The largest `r` with `r^dims <= entries` (§9.2.3). +pub(super) fn lookup1_values(entries: u32, dims: u32) -> u64 { + let fits = |r: u64| { + let mut p = 1u64; + for _ in 0..dims { + p = p.saturating_mul(r); + if p > u64::from(entries) { + return false; + } + } + true + }; + let (mut lo, mut hi) = (0u64, u64::from(entries)); + while lo < hi { + let mid = lo + (hi - lo).div_ceil(2); + if fits(mid) { lo = mid } else { hi = mid - 1 } + } + lo +} + +/// The block flag of each mode of a setup header (§4.2.4), passing over everything before them. +fn setup_modes(h: &[u8], channels: u8) -> Option> { + if !h.starts_with(b"\x05vorbis") { + return None; + } + let mut b = Bits { data: &h[7..], pos: 0 }; + let codebooks = b.read(8)? + 1; + for _ in 0..codebooks { + codebook(&mut b)?; + } + for _ in 0..b.read(6)? + 1 { + b.zero(16)?; + } + let floors = b.read(6)? + 1; + for _ in 0..floors { + floor(&mut b, codebooks)?; + } + let residues = b.read(6)? + 1; + for _ in 0..residues { + residue(&mut b, codebooks)?; + } + let mappings = b.read(6)? + 1; + for _ in 0..mappings { + mapping(&mut b, channels, floors, residues)?; + } + let count = b.read(6)? as usize + 1; + let mut long = Vec::with_capacity(count.min(MAX_MODES)); + for _ in 0..count { + let flag = b.read(1)? == 1; + b.zero(16)?; + b.zero(16)?; + if b.read(8)? >= mappings { + return None; + } + long.push(flag); + } + (b.read(1)? == 1).then_some(long) +} + +/// Passes over one codebook (§3.2.1). +fn codebook(b: &mut Bits<'_>) -> Option<()> { + if b.read(24)? != 0x56_4342 { + return None; + } + // a codebook of no dimensions is allowed and has no lookup values, as in the reference decoder + let dims = b.read(16)?; + let entries = b.read(24)?; + if b.read(1)? == 1 { + // ordered: runs of entries per length, each count in ilog(entries left) bits + let mut length = b.read(5)? + 1; + let mut entry = 0u32; + while entry < entries { + if length > 32 { + return None; + } + entry = entry.checked_add(b.read(ilog(entries - entry))?).filter(|&e| e <= entries)?; + length += 1; + } + } else { + let sparse = b.read(1)? == 1; + for _ in 0..entries { + if !sparse || b.read(1)? == 1 { + b.skip(5)?; + } + } + } + match b.read(4)? { + 0 => {} + kind @ (1 | 2) => { + // minimum value and delta, then the value width and the sequence flag + b.skip(32 + 32)?; + let width = u64::from(b.read(4)? + 1); + b.skip(1)?; + let values = match (kind, dims) { + (_, 0) => 0, + (1, _) => lookup1_values(entries, dims), + _ => u64::from(entries) * u64::from(dims), + }; + b.skip(values.checked_mul(width)?)?; + } + _ => return None, + } + Some(()) +} + +/// Passes over one floor configuration (§6.2.1, §7.2.2), whose books are among `codebooks`. +fn floor(b: &mut Bits<'_>, codebooks: u32) -> Option<()> { + match b.read(16)? { + 0 => { + // order, rate, bark map size, amplitude bits, amplitude offset, then the books + b.skip(8 + 16 + 16 + 6 + 8)?; + let books = b.read(4)? + 1; + for _ in 0..books { + if b.read(8)? >= codebooks { + return None; + } + } + Some(()) + } + 1 => floor1(b, codebooks), + _ => None, + } +} + +/// Passes over one residue configuration (§8.6.1), whose books are among `codebooks`. +fn residue(b: &mut Bits<'_>, codebooks: u32) -> Option<()> { + if b.read(16)? > 2 { + return None; + } + // begin, end, partition size, then the classifications and the classbook + b.skip(24 + 24 + 24)?; + let classifications = b.read(6)? + 1; + if b.read(8)? >= codebooks { + return None; + } + let mut books = 0u64; + for _ in 0..classifications { + let low = b.read(3)?; + let high = if b.read(1)? == 1 { b.read(5)? } else { 0 }; + books += u64::from((high << 3 | low).count_ones()); + } + for _ in 0..books { + if b.read(8)? >= codebooks { + return None; + } + } + Some(()) +} + +/// Passes over one mapping configuration (§4.2.4, mappings), whose submaps name one of `floors` +/// floors and one of `residues` residues. +fn mapping(b: &mut Bits<'_>, channels: u8, floors: u32, residues: u32) -> Option<()> { + b.zero(16)?; + let submaps = if b.read(1)? == 1 { b.read(4)? + 1 } else { 1 }; + if b.read(1)? == 1 { + let channel_bits = ilog(u32::from(channels) - 1); + for _ in 0..b.read(8)? + 1 { + let (magnitude, angle) = (b.read(channel_bits)?, b.read(channel_bits)?); + if magnitude == angle || magnitude >= u32::from(channels) || angle >= u32::from(channels) { + return None; + } + } + } + b.zero(2)?; + if submaps > 1 { + for _ in 0..channels { + if b.read(4)? >= submaps { + return None; + } + } + } + // per submap: an unused time configuration, the floor and the residue + for _ in 0..submaps { + b.skip(8)?; + if b.read(8)? >= floors || b.read(8)? >= residues { + return None; + } + } + Some(()) +} + +/// Passes over a floor 1 configuration (§7.2.2), whose books are among `codebooks`. The X list, +/// with its two implicit end points, holds at most 65 distinct values. +fn floor1(b: &mut Bits<'_>, codebooks: u32) -> Option<()> { + let partitions = b.read(5)?; + let mut classes = Vec::with_capacity(partitions as usize); + for _ in 0..partitions { + classes.push(b.read(4)? as usize); + } + let count = classes.iter().max().map_or(0, |&m| m + 1); + let mut dims = [0u32; 16]; + for d in dims.iter_mut().take(count) { + *d = b.read(3)? + 1; + let subclasses = b.read(2)?; + if subclasses != 0 && b.read(8)? >= codebooks { + return None; + } + // a subclass book is its number plus one, and 0 means none + for _ in 0..1u32 << subclasses { + if b.read(8)? > codebooks { + return None; + } + } + } + b.skip(2)?; + let range = b.read(4)?; + let points: u64 = classes.iter().map(|&c| u64::from(dims[c])).sum(); + if points + 2 > 65 { + return None; + } + let mut xs = vec![0u32, 1u32 << range]; + for _ in 0..points { + xs.push(b.read(range)?); + } + xs.sort_unstable(); + xs.windows(2).all(|w| w[0] != w[1]).then_some(()) +} diff --git a/crates/media/src/ogg/vorbis_tests.rs b/crates/media/src/ogg/vorbis_tests.rs new file mode 100644 index 0000000000..e84322099e --- /dev/null +++ b/crates/media/src/ogg/vorbis_tests.rs @@ -0,0 +1,359 @@ +//! Vorbis modes and timing on synthetic headers and packets. + +use super::vorbis::*; +use super::*; + +/// Bits written least significant first, as Vorbis reads them. +#[derive(Default)] +struct BitWriter { + bytes: Vec, + bits: u64, +} + +impl BitWriter { + fn put(&mut self, value: u32, n: u32) -> &mut Self { + for k in 0..n { + if self.bits.is_multiple_of(8) { + self.bytes.push(0); + } + let bit = ((value >> k) & 1) as u8; + let last = self.bytes.len() - 1; + self.bytes[last] |= bit << (self.bits % 8); + self.bits += 1; + } + self + } +} + +/// An identification header: one channel at 44.1 kHz, blocks of 256 and 2048 samples. +fn identification() -> Vec { + let mut h = b"\x01vorbis".to_vec(); + h.extend_from_slice(&0u32.to_le_bytes()); + h.push(1); + h.extend_from_slice(&44_100u32.to_le_bytes()); + h.extend_from_slice(&[0; 12]); + h.push(0xB8); + h.push(1); + h +} + +/// The smallest setup header: one codebook, floor 1, residue 0 and mapping, then `modes` with the +/// given block flags. +fn setup(modes: &[bool]) -> Vec { + setup_with(modes, Codebook { dims: 1, lookup: 0 }, 0, 0) +} + +/// The codebook of [`setup_with`]: 2 entries of length 1 with `dims` dimensions and lookup type +/// `lookup` (0, or 1 with 1-bit values). +#[derive(Clone, Copy)] +struct Codebook { + dims: u32, + lookup: u32, +} + +/// [`setup`] with the given codebook and the floor and residue its one mapping's submap names. +fn setup_with(modes: &[bool], book: Codebook, floor: u32, residue: u32) -> Vec { + let plain_floor = |w: &mut BitWriter| { + // one floor 1 with no partitions: multiplier and range bits + w.put(0, 6).put(1, 16).put(0, 5).put(0, 2).put(0, 4); + }; + let plain_residue = |w: &mut BitWriter| { + // one residue 0 with one classification, classbook 0 and no books + w.put(0, 6).put(0, 16).put(0, 24).put(0, 24).put(0, 24).put(0, 6).put(0, 8).put(0, 3).put(0, 1); + }; + setup_parts(modes, book, floor, residue, &plain_floor, &plain_residue) +} + +/// [`setup_with`] with the floor and residue configurations written by the given closures, each +/// starting with its count of 0 (one entry). +fn setup_parts( + modes: &[bool], + book: Codebook, + floor: u32, + residue: u32, + write_floor: &dyn Fn(&mut BitWriter), + write_residue: &dyn Fn(&mut BitWriter), +) -> Vec { + let mut w = BitWriter::default(); + // one codebook: 2 entries of length 1 + w.put(0, 8).put(0x56_4342, 24).put(book.dims, 16).put(2, 24).put(0, 1).put(0, 1).put(0, 5).put(0, 5).put(book.lookup, 4); + if book.lookup == 1 { + // minimum value, delta, 1-bit values, no sequence flag, then the values themselves + w.put(0, 32).put(0, 32).put(0, 4).put(0, 1); + let values = if book.dims == 0 { 0 } else { lookup1_values(2, book.dims) }; + for _ in 0..values { + w.put(0, 1); + } + } + // one time-domain transform + w.put(0, 6).put(0, 16); + write_floor(&mut w); + write_residue(&mut w); + // one mapping: one submap, no coupling, reserved bits, the submap's time, floor and residue + w.put(0, 6).put(0, 16).put(0, 1).put(0, 1).put(0, 2).put(0, 8).put(floor, 8).put(residue, 8); + w.put(modes.len() as u32 - 1, 6); + for &long in modes { + w.put(u32::from(long), 1).put(0, 16).put(0, 16).put(0, 8); + } + w.put(1, 1); + let mut h = b"\x05vorbis".to_vec(); + h.extend_from_slice(&w.bytes); + h +} + +const SHORT: u8 = 0b00; +const LONG: u8 = 0b10; + +/// A Vorbis stream whose packets are laid out in `pages`: each page is its packets' first bytes and +/// the page's granule position; the last page is the end of the stream. +fn stream(pages: &[(&[u8], i64)]) -> Stream { + let mut packets = Vec::new(); + for (k, &(firsts, granule)) in pages.iter().enumerate() { + for (i, &first) in firsts.iter().enumerate() { + let last = i + 1 == firsts.len(); + packets.push(Packet { + parts: Vec::new(), + size: 10, + granule: last.then_some(granule), + page: k as u32, + eos: k + 1 == pages.len(), + prefix: [first, 0], + }); + } + } + Stream { + serial: 1, + codec: Codec::Vorbis, + // three modes, so mode 3 is one the header does not have + headers: vec![identification(), b"\x03vorbis".to_vec(), setup(&[false, true, true])], + packets, + pages: pages.len() as u32, + last_granule: pages.last().map(|p| p.1), + saw_eos: true, + header_count: 3, + header_bytes: 0, + next_seq: None, + started: true, + } +} + +#[test] +fn modes_come_from_the_end_of_the_setup_header() { + let modes = VorbisModes::parse(&identification(), &setup(&[false, true, true])).unwrap(); + assert_eq!(modes.blocksizes, [256, 2048]); + assert_eq!(modes.long, [false, true, true]); + // two bits of mode number after the packet-type bit + assert_eq!(modes.blocksize(0b000), Some(256)); + assert_eq!(modes.blocksize(0b100), Some(2048)); + assert_eq!(modes.blocksize(0b110), None, "a mode the header does not have"); + assert_eq!(modes.blocksize(0b001), None, "not an audio packet"); +} + +#[test] +fn damaged_headers_give_no_modes() { + let id = identification(); + let full = setup(&[false, true]); + for cut in 7..full.len() { + assert_eq!(VorbisModes::parse(&id, &full[..cut]), None, "setup cut to {cut} bytes"); + } + let mut no_framing = full.clone(); + *no_framing.last_mut().unwrap() = 0; + assert_eq!(VorbisModes::parse(&id, &no_framing), None); + let mut long_first = id.clone(); + long_first[28] = 0x8B; + assert_eq!(VorbisModes::parse(&long_first, &full), None, "short block larger than the long one"); + let mut version_1 = id.clone(); + version_1[7] = 1; + assert_eq!(VorbisModes::parse(&version_1, &full), None, "not Vorbis I"); +} + +#[test] +fn a_zero_sample_rate_gives_no_modes() { + let full = setup(&[false, true]); + assert!(VorbisModes::parse(&identification(), &full).is_some()); + let mut no_rate = identification(); + no_rate[12..16].copy_from_slice(&0u32.to_le_bytes()); + assert_eq!(VorbisModes::parse(&no_rate, &full), None); +} + +#[test] +fn a_mapping_names_only_configured_floors_and_residues() { + let id = identification(); + let plain = Codebook { dims: 1, lookup: 0 }; + assert!(VorbisModes::parse(&id, &setup_with(&[false, true], plain, 0, 0)).is_some()); + assert_eq!(VorbisModes::parse(&id, &setup_with(&[false, true], plain, 1, 0)), None, "floor 1 of one floor"); + assert_eq!(VorbisModes::parse(&id, &setup_with(&[false, true], plain, 0, 1)), None, "residue 1 of one residue"); +} + +/// The setup of [`setup_with`] with one floor 1 (partition list, then classes) and one residue. +fn books_setup(floor: &dyn Fn(&mut BitWriter), residue: &dyn Fn(&mut BitWriter)) -> Option { + let plain = Codebook { dims: 1, lookup: 0 }; + VorbisModes::parse(&identification(), &setup_parts(&[false, true], plain, 0, 0, floor, residue)) +} + +#[test] +fn residue_books_name_configured_codebooks() { + let residue = |classbook: u32, book: u32| { + move |w: &mut BitWriter| { + // one classification with the first cascade bit set, which names one book + w.put(0, 6).put(0, 16).put(0, 24).put(0, 24).put(0, 24).put(0, 6).put(classbook, 8).put(1, 3).put(0, 1); + w.put(book, 8); + } + }; + let floor = |w: &mut BitWriter| { + w.put(0, 6).put(1, 16).put(0, 5).put(0, 2).put(0, 4); + }; + assert!(books_setup(&floor, &residue(0, 0)).is_some()); + assert_eq!(books_setup(&floor, &residue(1, 0)), None, "classbook 1 of one codebook"); + assert_eq!(books_setup(&floor, &residue(0, 1)), None, "book 1 of one codebook"); +} + +#[test] +fn floor_books_name_configured_codebooks() { + let residue = |w: &mut BitWriter| { + w.put(0, 6).put(0, 16).put(0, 24).put(0, 24).put(0, 24).put(0, 6).put(0, 8).put(0, 3).put(0, 1); + }; + // floor 0: order, rate, bark map size, amplitude bits and offset, one book + let floor0 = |book: u32| { + move |w: &mut BitWriter| { + w.put(0, 6).put(0, 16).put(0, 8).put(0, 16).put(0, 16).put(0, 6).put(0, 8).put(0, 4).put(book, 8); + } + }; + assert!(books_setup(&floor0(0), &residue).is_some()); + assert_eq!(books_setup(&floor0(1), &residue), None); + // floor 1: one partition of class 0 with one dimension and 1 subclass bit, a master book and + // two subclass books (number plus one), then 2 range bits and one X value + let floor1 = |master: u32, sub: u32, x: u32| { + move |w: &mut BitWriter| { + w.put(0, 6).put(1, 16).put(1, 5).put(0, 4).put(0, 3).put(1, 2).put(master, 8).put(sub, 8).put(0, 8); + w.put(0, 2).put(2, 4).put(x, 2); + } + }; + assert!(books_setup(&floor1(0, 1, 1), &residue).is_some()); + assert!(books_setup(&floor1(0, 0, 1), &residue).is_some(), "no subclass book"); + assert_eq!(books_setup(&floor1(1, 1, 1), &residue), None, "master book 1"); + assert_eq!(books_setup(&floor1(0, 2, 1), &residue), None, "subclass book 1"); + assert_eq!(books_setup(&floor1(0, 1, 0), &residue), None, "X value equal to the implicit 0"); + assert_eq!(books_setup(&floor1(0, 1, 1), &residue).map(|m| m.long), Some(vec![false, true])); +} + +#[test] +fn floor_one_x_values_are_distinct() { + let residue = |w: &mut BitWriter| { + w.put(0, 6).put(0, 16).put(0, 24).put(0, 24).put(0, 24).put(0, 6).put(0, 8).put(0, 3).put(0, 1); + }; + // one partition of class 0 with two dimensions and no subclasses, 3 range bits, two X values + let floor1 = |a: u32, b: u32| { + move |w: &mut BitWriter| { + w.put(0, 6).put(1, 16).put(1, 5).put(0, 4).put(1, 3).put(0, 2).put(0, 8); + w.put(0, 2).put(3, 4).put(a, 3).put(b, 3); + } + }; + assert!(books_setup(&floor1(3, 5), &residue).is_some()); + assert_eq!(books_setup(&floor1(3, 3), &residue), None, "repeated X value"); + assert_eq!(books_setup(&floor1(0, 5), &residue), None, "X value equal to the implicit 0"); +} + +#[test] +fn a_codebook_of_no_dimensions_has_no_lookup_values() { + let id = identification(); + for lookup in [0, 1] { + let modes = VorbisModes::parse(&id, &setup_with(&[false, true], Codebook { dims: 0, lookup }, 0, 0)); + assert_eq!(modes.map(|m| m.long), Some(vec![false, true]), "lookup type {lookup}"); + let one = VorbisModes::parse(&id, &setup_with(&[false, true], Codebook { dims: 1, lookup }, 0, 0)); + assert_eq!(one.map(|m| m.long), Some(vec![false, true]), "lookup type {lookup}, one dimension"); + } +} + +#[test] +fn the_first_packet_primes_and_the_rest_overlap_by_quarter_blocks() { + let t = VorbisTiming::of(&stream(&[(&[SHORT, LONG], 576), (&[LONG, LONG, SHORT], 3200)])).unwrap(); + assert_eq!(t.durations, [0, 64 + 512, 1024, 1024, 512 + 64]); + assert_eq!(t.starts, [0, 0, 576, 1600, 2624]); + assert_eq!((t.skip, t.first, t.total), (0, 0, 3200)); +} + +#[test] +fn a_negative_start_discards_leading_samples() { + let t = VorbisTiming::of(&stream(&[(&[SHORT, LONG], 476), (&[LONG, SHORT], 2076)])).unwrap(); + assert_eq!(t.starts[1], -100); + assert_eq!((t.skip, t.first), (100, 0)); + assert_eq!(t.total, 2076); +} + +#[test] +fn packets_that_are_not_audio_do_not_shrink_the_leading_discard() { + let t = VorbisTiming::of(&stream(&[(&[0xFF, SHORT, LONG], 476), (&[LONG, SHORT], 2076)])).unwrap(); + assert_eq!(&t.durations[..3], [0, 0, 576]); + assert_eq!(t.starts[2], -100); + assert_eq!((t.skip, t.first, t.total), (100, 0, 2076)); +} + +#[test] +fn a_packet_too_short_for_its_window_flags_returns_nothing() { + // 64 modes: six bits of mode number, so a long block's two window flags reach the second byte + let mut modes = vec![false; 64]; + modes[1] = true; + let mut s = stream(&[(&[SHORT, LONG, SHORT], 1000)]); + s.headers[2] = setup(&modes); + s.packets[1].size = 1; + let t = VorbisTiming::of(&s).unwrap(); + assert_eq!(t.durations, [0, 0, 128], "the cut long packet is skipped and the next one follows the first"); + s.packets[1].size = 2; + let t = VorbisTiming::of(&s).unwrap(); + assert_eq!(t.durations, [0, 64 + 512, 512 + 64]); +} + +#[test] +fn a_positive_start_is_a_time_offset() { + let t = VorbisTiming::of(&stream(&[(&[SHORT, LONG], 44_676), (&[LONG, SHORT], 46_276)])).unwrap(); + assert_eq!((t.skip, t.first), (0, 44_100)); + assert_eq!(t.starts[1], 44_100); + assert_eq!(t.total, 46_276 - 44_100); +} + +#[test] +fn a_page_with_only_the_priming_packet_does_not_place_the_stream() { + let negative = VorbisTiming::of(&stream(&[(&[SHORT], 0), (&[LONG], 476), (&[LONG, SHORT], 2076)])).unwrap(); + assert_eq!(negative.starts[1], -100); + assert_eq!((negative.skip, negative.first, negative.total), (100, 0, 2076)); + let offset = VorbisTiming::of(&stream(&[(&[SHORT], 0), (&[LONG], 44_676), (&[LONG, SHORT], 46_276)])).unwrap(); + assert_eq!(offset.starts[1], 44_100); + assert_eq!((offset.skip, offset.first, offset.total), (0, 44_100, 2176)); +} + +#[test] +fn the_final_page_trims_the_end() { + let full = VorbisTiming::of(&stream(&[(&[SHORT, LONG], 576), (&[LONG, SHORT], 2176)])).unwrap(); + let trimmed = VorbisTiming::of(&stream(&[(&[SHORT, LONG], 576), (&[LONG, SHORT], 2000)])).unwrap(); + assert_eq!(trimmed.starts, full.starts, "trimming moves no packet"); + assert_eq!(trimmed.total, full.total - 176); +} + +#[test] +fn one_page_shorter_than_its_packets_trims_the_end() { + let t = VorbisTiming::of(&stream(&[(&[SHORT, LONG, SHORT], 1000)])).unwrap(); + assert_eq!((t.skip, t.first, t.total), (0, 0, 1000)); + assert_eq!(t.starts[1], 0); +} + +#[test] +fn hostile_granules_and_packets_do_not_overflow() { + for g in [i64::MIN, -2, i64::MAX, MAX_OPUS_GRANULE] { + let t = VorbisTiming::of(&stream(&[(&[SHORT, LONG], g), (&[0xFF, 0b110, LONG], g)])).unwrap(); + assert_eq!(t.starts.len(), 5); + assert_eq!(&t.durations[2..4], [0, 0], "a non-audio packet and an unknown mode return nothing"); + assert!(t.total >= 0); + } + let mut no_setup = stream(&[(&[SHORT], 0)]); + no_setup.headers.truncate(2); + assert_eq!(VorbisTiming::of(&no_setup), None); +} + +#[test] +fn lookup_values_are_the_integer_root_of_the_entries() { + assert_eq!(lookup1_values(81, 4), 3); + assert_eq!(lookup1_values(80, 4), 2); + assert_eq!(lookup1_values(1 << 24, 1), 1 << 24); + assert_eq!(lookup1_values(1 << 24, 65_535), 1); +} diff --git a/crates/media/tests/mpegts_mux/mod.rs b/crates/media/tests/mpegts_mux/mod.rs index 4a3e6f2d11..0287a8ce9c 100644 --- a/crates/media/tests/mpegts_mux/mod.rs +++ b/crates/media/tests/mpegts_mux/mod.rs @@ -195,13 +195,24 @@ pub fn av1_unescape(es: &[u8]) -> Vec { out } -/// The Opus control header and packet the demuxer gives back for an Opus frame. -pub fn opus_unit(packet: &[u8]) -> Vec { - let mut v = vec![0x7F, 0xE0]; - v.extend(std::iter::repeat_n(0xFF, packet.len() / 255)); - v.push((packet.len() % 255) as u8); - v.extend_from_slice(packet); - v +/// The payload of every PES packet on `pid`, as the muxer wrote it (the PES header left out). +pub fn pes_payloads(ts: &[u8], pid: u16) -> Vec> { + let mut out: Vec> = Vec::new(); + for p in ts.chunks(PACKET_SIZE) { + if ((p[1] & 0x1F) as u16) << 8 | p[2] as u16 != pid || p[3] & 0x10 == 0 { + continue; + } + let start = if p[3] & 0x20 != 0 { 5 + p[4] as usize } else { 4 }; + let mut payload = &p[start..]; + if p[1] & 0x40 != 0 { + payload = &payload[9 + payload[8] as usize..]; + out.push(Vec::new()); + } + if let Some(last) = out.last_mut() { + last.extend_from_slice(payload); + } + } + out } /// What the demuxer gives back for a video frame: an access unit delimiter first. diff --git a/crates/media/tests/mpegts_mux_fuzz.rs b/crates/media/tests/mpegts_mux_fuzz.rs index 0067e5a17c..662105ae8e 100644 --- a/crates/media/tests/mpegts_mux_fuzz.rs +++ b/crates/media/tests/mpegts_mux_fuzz.rs @@ -66,8 +66,7 @@ fn frame(s: usize, size: usize, key: bool, n: usize) -> (Vec, Vec) { 1 => { let mut d = vec![0xFC]; fill(&mut d, size.min(1500), seed); - let e = opus_unit(&d); - (d, e) + (d.clone(), d) } 2 => { let mut d = Vec::new(); diff --git a/crates/media/tests/mpegts_mux_readback.rs b/crates/media/tests/mpegts_mux_readback.rs index 7d8471525c..733a6f2d75 100644 --- a/crates/media/tests/mpegts_mux_readback.rs +++ b/crates/media/tests/mpegts_mux_readback.rs @@ -90,7 +90,7 @@ fn every_codec_in_one_program() { for k in 0..150i64 { let mut p = vec![0xFC]; fill(&mut p, 1 + (k as usize * 41) % 700, k as u8); - items.push(Item { stream: 2, expect: opus_unit(&p), data: p, pts: t0 + k * 1800, dts: t0 + k * 1800, key: true }); + items.push(Item { stream: 2, expect: p.clone(), data: p, pts: t0 + k * 1800, dts: t0 + k * 1800, key: true }); } for k in 0..90i64 { let f = ac3(k as u8); @@ -100,7 +100,7 @@ fn every_codec_in_one_program() { let f = mp3(false, k as u8); items.push(Item { stream: 4, expect: f.clone(), data: f, pts: t0 + k * 2160, dts: t0 + k * 2160, key: true }); } - let want = [Demuxed::H264, Demuxed::AacAdts, Demuxed::Unknown(6), Demuxed::Ac3, Demuxed::MpegAudio]; + let want = [Demuxed::H264, Demuxed::AacAdts, Demuxed::Opus, Demuxed::Ac3, Demuxed::MpegAudio]; let (ts, pcrs) = round_trip(Config::default(), &streams, &mut items, &want); let file = mpegts::open(&ts).unwrap(); assert_eq!(file.pcr_range, Some((pcrs[0], *pcrs.last().unwrap()))); @@ -108,6 +108,10 @@ fn every_codec_in_one_program() { // the frames' own headers read back with the demuxer's frame parser let aac = file.read_unit(&ts, 1, 0).unwrap(); assert_eq!(mpegts::frame_info(&Demuxed::AacAdts, &aac).map(|i| (i.sample_rate, i.channels)), Some((48_000, 2))); + // a stereo Opus stream (channel_config_code 2): one coupled stream, no start trim + let opus = file.streams[2].codec_params(); + assert_eq!((opus.codec, opus.sample_rate, opus.channels), (craft_media::CodecId::Opus, Some(48_000), Some(2))); + assert_eq!(opus.extradata, [b"OpusHead".as_slice(), &[1, 2, 0, 0, 0x80, 0xBB, 0, 0, 0, 0, 0]].concat()); } #[test] @@ -162,9 +166,9 @@ fn timestamps_run_past_the_33_bit_wrap() { for k in 0..140i64 { let p = vec![0x08, k as u8 | 1, 0x55]; let t = start + k * 1800; - items.push(Item { stream: 1, expect: opus_unit(&p), data: p, pts: t, dts: t, key: true }); + items.push(Item { stream: 1, expect: p.clone(), data: p, pts: t, dts: t, key: true }); } - round_trip(Config::default(), &streams, &mut items, &[Demuxed::H264, Demuxed::Unknown(6)]); + round_trip(Config::default(), &streams, &mut items, &[Demuxed::H264, Demuxed::Opus]); } #[test] @@ -185,7 +189,7 @@ fn eac3_mpeg1_video_and_mpeg4_part2() { let t = 100_000 + k * 2880; items.push(Item { stream: 1, expect: f.clone(), data: f, pts: t, dts: t, key: true }); } - round_trip(Config::default(), &streams, &mut items, &[Demuxed::Mpeg1Video, Demuxed::Eac3, Demuxed::Unknown(0x10)]); + round_trip(Config::default(), &streams, &mut items, &[Demuxed::Mpeg1Video, Demuxed::Eac3, Demuxed::Mpeg4Part2]); } #[test] @@ -200,20 +204,61 @@ fn av1_reads_back_as_its_obus() { let t = 90_000 + k * 3000; m.write_frame(0, &Frame { data: &tu, pts: t, dts: None, key }).unwrap(); m.write_frame(1, &Frame { data: &[0xFC, k as u8 | 1], pts: t, dts: None, key: true }).unwrap(); - tus.push((tu, t)); + tus.push((tu, t, key)); } let ts = m.finish().unwrap(); check_packets(&ts, 0x100, 3600 * 300); let file = mpegts::open(&ts).unwrap(); assert!(file.warnings.is_empty(), "{:?}", file.warnings); - assert_eq!(file.streams[0].codec, Demuxed::Unknown(6)); + assert_eq!(file.streams[0].codec, Demuxed::Av1); assert_eq!(file.streams[0].stream_type, 0x06); + assert_eq!(file.streams[1].codec, Demuxed::Opus); + // the descriptor's fields come back as the av1C record they were taken from + let params = file.streams[0].codec_params(); + assert_eq!(params.codec, craft_media::CodecId::Av1); + assert_eq!(Av1Config::from_av1c(¶ms.extradata).unwrap(), config); let units = &file.streams[0].units; assert_eq!(units.len(), tus.len()); - for (n, (u, (tu, t))) in units.iter().zip(&tus).enumerate() { + let written = pes_payloads(&ts, 0x100); + assert_eq!(written.len(), tus.len()); + for (n, (u, (tu, t, key))) in units.iter().zip(&tus).enumerate() { assert_eq!(u.pts, Some(*t)); - let es = file.read_unit(&ts, 0, n).unwrap(); - assert_eq!(av1_unescape(&es), av1_without_delimiters(tu), "unit {n}"); + assert_eq!(u.key, *key, "unit {n}"); + // the writer's start code form, and the demuxer's OBUs + assert_eq!(av1_unescape(&written[n]), av1_without_delimiters(tu), "unit {n}"); + assert_eq!(file.read_unit(&ts, 0, n).unwrap(), av1_without_delimiters(tu), "unit {n}"); + } +} + +#[test] +fn opus_channel_configurations_read_back() { + let opened = |codec: Codec| { + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, codec)]).unwrap(); + for k in 0..10i64 { + m.write_frame(0, &Frame { data: &[0xFC, 1, 0x55], pts: 90_000 + k * 1800, dts: None, key: true }).unwrap(); + } + let ts = m.finish().unwrap(); + let s = mpegts::open(&ts).unwrap().streams.remove(0); + assert_eq!(s.codec, Demuxed::Opus); + let o = s.opus.unwrap(); + (o.channels, o.family, o.streams, o.coupled, o.mapping) + }; + // the fixed configurations: family 0 for one or two channels, the RFC 7845 surround orders + // for more + assert_eq!(opened(Codec::Opus { channels: 1 }), (1, 0, 1, 0, vec![0])); + assert_eq!(opened(Codec::Opus { channels: 2 }), (2, 0, 1, 1, vec![0, 1])); + assert_eq!(opened(Codec::Opus { channels: 6 }), (6, 1, 4, 2, vec![0, 4, 1, 2, 3, 5])); + assert_eq!(opened(Codec::Opus { channels: 8 }), (8, 1, 5, 3, vec![0, 6, 1, 2, 3, 4, 5, 7])); + // explicit configurations come back field for field, silent channels included + for m in [ + OpusMapping { channels: 6, family: 1, streams: 4, coupled: 2, mapping: [0, 4, 1, 2, 3, 5, 0, 0] }, + OpusMapping { channels: 3, family: 255, streams: 3, coupled: 0, mapping: [2, 255, 0, 0, 0, 0, 0, 0] }, + OpusMapping { channels: 8, family: 255, streams: 8, coupled: 0, mapping: [7, 6, 5, 4, 3, 2, 1, 0] }, + OpusMapping { channels: 2, family: 0, streams: 1, coupled: 1, mapping: [0, 1, 0, 0, 0, 0, 0, 0] }, + OpusMapping { channels: 1, family: 1, streams: 1, coupled: 0, mapping: [0, 0, 0, 0, 0, 0, 0, 0] }, + ] { + let ch = usize::from(m.channels); + assert_eq!(opened(Codec::OpusMapped(m)), (m.channels, m.family, m.streams, m.coupled, m.mapping[..ch].to_vec()), "{m:?}"); } } @@ -226,23 +271,32 @@ fn opus_with_an_explicit_mapping_and_trims() { for k in 0..20i64 { // three streams of 20 ms: two self-delimited packets, then the last one let au = [0xFC, 1, 0x55, 0xFC, 1, 0x66, 0xFC, 0x77]; - let trim = if k == 0 { craft_media::mpegts::mux::OpusTrim { start: 312, end: 0 } } else { Default::default() }; + let trim = match k { + 0 => craft_media::mpegts::mux::OpusTrim { start: 312, end: 0 }, + 19 => craft_media::mpegts::mux::OpusTrim { start: 0, end: 100 }, + _ => Default::default(), + }; let t = 90_000 + k * 1800; m.write_frame_with_trim(0, &Frame { data: &au, pts: t, dts: None, key: true }, trim).unwrap(); - let mut unit = if k == 0 { vec![0x7F, 0xF0, 8] } else { vec![0x7F, 0xE0, 8] }; - if k == 0 { - unit.extend_from_slice(&312u16.to_be_bytes()); - } - unit.extend_from_slice(&au); - want.push(unit); + want.push(au.to_vec()); } let ts = m.finish().unwrap(); let file = mpegts::open(&ts).unwrap(); assert!(file.warnings.is_empty(), "{:?}", file.warnings); - assert_eq!(file.streams[0].units.len(), want.len()); + let s = &file.streams[0]; + assert_eq!(s.codec, Demuxed::Opus); + assert_eq!(s.units.len(), want.len()); for (n, w) in want.iter().enumerate() { assert_eq!(&file.read_unit(&ts, 0, n).unwrap(), w); } + let opus = s.opus.as_ref().unwrap(); + assert_eq!((opus.channels, opus.family, opus.streams, opus.coupled, &opus.mapping[..]), (3, 255, 3, 0, &[0, 1, 2][..])); + assert_eq!(opus.trims, [mpegts::OpusTrim { unit: 0, start: 312, end: 0 }, mpegts::OpusTrim { unit: 19, start: 0, end: 100 }]); + // the OpusHead header (RFC 7845 §5.1) carries the start trim as its pre-skip + let head = s.codec_params().extradata; + assert_eq!(&head[..8], b"OpusHead"); + assert_eq!(u16::from_le_bytes([head[10], head[11]]), 312); + assert_eq!(&head[18..], &[255, 3, 0, 0, 1, 2]); } #[test] diff --git a/crates/media/tests/oracle_mpegts.rs b/crates/media/tests/oracle_mpegts.rs index d395c09ff1..28e5904fdb 100644 --- a/crates/media/tests/oracle_mpegts.rs +++ b/crates/media/tests/oracle_mpegts.rs @@ -22,6 +22,7 @@ const ALL: &[&str] = &[ "m2ts_h264_ac3.mts", "ts_hevc_latm.ts", "ts_h264_eac3.ts", + "ts_mpeg4_opus.ts", "ps_mpeg2_mp2.vob", "ps_mpeg2_lpcm.vob", "ps_mpeg2_ac3.vob", @@ -72,6 +73,10 @@ fn spec(name: &str) -> Vec<&'static str> { &["-c:a", "aac", "-b:a", "96k", "-f", "mpegts", "-mpegts_flags", "latm"], ]), "ts_h264_eac3.ts" => cat(&[PIC, NOISE, &["-t", "1"], x264, &["-c:a", "eac3", "-b:a", "192k", "-f", "mpegts"]]), + // stream type 0x10, and Opus with its registration and audio descriptors and control headers + "ts_mpeg4_opus.ts" => { + cat(&[PIC, NOISE, &["-t", "1.2", "-c:v", "mpeg4", "-bf", "2", "-g", "12", "-c:a", "libopus", "-b:a", "96k", "-f", "mpegts"]]) + } // DVD-style program streams "ps_mpeg2_mp2.vob" => cat(&[ &["-f", "lavfi", "-i", "testsrc2=size=720x480:rate=30000/1001"], @@ -112,7 +117,9 @@ fn expected_codec(name: &str, format: Format) -> Codec { "mpeg2video" => Codec::Mpeg2Video, "h264" => Codec::H264, "hevc" => Codec::Hevc, + "mpeg4" => Codec::Mpeg4Part2, "mp2" | "mp3" => Codec::MpegAudio, + "opus" => Codec::Opus, "aac" => Codec::AacAdts, "aac_latm" => Codec::AacLatm, "ac3" => Codec::Ac3, @@ -184,7 +191,7 @@ fn check(name: &str) -> Option { #[test] fn transport_streams_match_ffprobe() { - for name in ["ts_mpeg2_mp2.ts", "ts_h264_aac.ts", "ts_hevc_latm.ts", "ts_h264_eac3.ts"] { + for name in ["ts_mpeg2_mp2.ts", "ts_h264_aac.ts", "ts_hevc_latm.ts", "ts_h264_eac3.ts", "ts_mpeg4_opus.ts"] { let Some(f) = check(name) else { return }; assert_eq!(f.format, Format::Ts { packet_size: 188, sync_offset: 0 }, "{name}"); assert_eq!(f.program, Some(1), "{name}"); @@ -195,9 +202,17 @@ fn transport_streams_match_ffprobe() { "ts_mpeg2_mp2.ts" => [CodecId::Mpeg2Video, CodecId::Mp2], "ts_h264_aac.ts" => [CodecId::H264, CodecId::Aac], "ts_hevc_latm.ts" => [CodecId::Hevc, CodecId::Aac], + "ts_mpeg4_opus.ts" => [CodecId::Mpeg4Video, CodecId::Opus], _ => [CodecId::H264, CodecId::Eac3], }; assert_eq!(ids, want, "{name}"); + if name == "ts_mpeg4_opus.ts" { + // stereo from the Opus audio descriptor, and libopus's 312-sample start trim as the + // pre-skip + let p = f.streams[1].codec_params(); + assert_eq!((p.sample_rate, p.channels), (Some(48_000), Some(2))); + assert_eq!(&p.extradata[..12], &[b"OpusHead".as_slice(), &[1, 2], &312u16.to_le_bytes()].concat()[..]); + } } } diff --git a/crates/media/tests/oracle_ogg.rs b/crates/media/tests/oracle_ogg.rs index 4e14a651e0..d81dba1f35 100644 --- a/crates/media/tests/oracle_ogg.rs +++ b/crates/media/tests/oracle_ogg.rs @@ -1,9 +1,9 @@ -//! Oracle tests: compare the Ogg demuxer's streams, packet bytes and Opus timing with ffprobe on -//! ffmpeg-generated fixtures (skipped when ffmpeg/ffprobe are not installed). +//! Oracle tests: compare the Ogg demuxer's streams, packet bytes and Opus and Vorbis timing with +//! ffprobe on ffmpeg-generated fixtures (skipped when ffmpeg/ffprobe are not installed). use super::common; -use craft_media::ogg::{self, Codec, OggFile, OpusTiming}; +use craft_media::ogg::{self, Codec, OggFile, OpusTiming, VorbisTiming}; use serde_json::Value; use std::path::{Path, PathBuf}; use std::process::Command; @@ -184,6 +184,27 @@ fn assert_opus_timing_matches(name: &str, file: &OggFile, s: usize, json: &Value eprintln!("{context}: timing of {} packets matches, {} samples", theirs.len(), timing.total); } +/// `VorbisTiming` against ffmpeg: from the second packet on, the starts are its pts and the +/// durations its packet durations (the last one trimmed by the discard padding), and the total is +/// the sum of those durations. ffmpeg gives the first packet, which returns no samples, a pts and +/// duration of its own, so it is compared only for returning nothing. +fn assert_vorbis_timing_matches(name: &str, file: &OggFile, s: usize, json: &Value, ff: usize) { + let timing = VorbisTiming::of(&file.streams[s]).unwrap_or_else(|| panic!("{name}: Vorbis headers")); + let theirs = ff_packets(json, ff); + let context = format!("{name}: Vorbis stream {ff}"); + assert_eq!(timing.starts.len(), theirs.len(), "{context}: packet count"); + assert_eq!(timing.durations[0], 0, "{context}: the first packet returns nothing"); + let last = theirs.len() - 1; + for (k, p) in theirs.iter().enumerate().skip(1) { + assert_eq!(p.pts, Some(timing.starts[k]), "{context}: start of packet {k}"); + let duration = p.duration.unwrap() + if k == last { p.discard } else { 0 }; + assert_eq!(duration, i64::from(timing.durations[k]), "{context}: duration of packet {k}"); + } + let playable: i64 = theirs.iter().skip(1).map(|p| p.duration.unwrap()).sum(); + assert_eq!((timing.skip, timing.first, timing.total), (0, 0, playable), "{context}: skip, first, total"); + eprintln!("{context}: timing of {} packets matches, {} samples", theirs.len(), timing.total); +} + /// Multiplexed streams: each is read on its own, in ffmpeg's order. #[test] fn grouped_streams() { @@ -197,6 +218,7 @@ fn grouped_streams() { for s in 0..2 { assert_opus_timing_matches("grouped.ogg", &file, s, &json, s); } + assert_vorbis_timing_matches("grouped.ogg", &file, 2, &json, 2); } /// A chained file: two links, each its own stream with its own headers. ffmpeg joins the links of diff --git a/crates/menu/README.md b/crates/menu/README.md index a9de1bfded..69947e7bae 100644 --- a/crates/menu/README.md +++ b/crates/menu/README.md @@ -135,6 +135,14 @@ The module documentation lists every `Outcome`, `Options` and the words (`Shortc app translates. The dialog never opens a file dialog or touches the file system. Enable `screen-testing` for the stories and the `it` trials. +Automation can select a command and set `replace` to `{"old":"Text: Cmd+B","new":"Cmd+K"}` +through `ShortcutsDialog::set_json_field`. The old text must identify exactly one current binding; +the new trigger keeps its scope and regular or Hold column. An equivalent trigger changes nothing, +and a changed replacement has one Undo step. Ask mode leaves the original binding until the user +answers the conflict bar; Steal and Keep follow the host's configured policy. A stale confirmation +cannot replace bindings that changed after its prompt opened. Unavailable edits and replacements +that cannot be stored return a refusal. + ## Windows, Linux and web: the in-window bar `MenuBarUi` draws a laid-out bar and returns the titles' rect and the width every title takes side by diff --git a/crates/menu/src/bar.rs b/crates/menu/src/bar.rs index 3d1204ce5e..a852119d72 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -202,7 +202,7 @@ fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput { .zip(&labels.menus) .map(|((menu, title), level)| { // The commands the title holds, for the palette's callout; a built-in has no command of the app. - let held = menu.children.iter().flat_map(node_commands).filter(|command| Builtin::of(command).is_none()).collect(); + let held = menu.children.iter().flat_map(node_commands).filter(|command| Builtin::of(command).is_none()).collect::>(); let row = MenuTitle::new(title.label.clone(), move |ui| shared.show(ui, &menu.children, level)).holds(held); match title.hidden { Some(letter) => row.mnemonic(letter), diff --git a/crates/menu/src/ribbon/gallery.rs b/crates/menu/src/ribbon/gallery.rs index 683fb76fb2..08f9683a10 100644 --- a/crates/menu/src/ribbon/gallery.rs +++ b/crates/menu/src/ribbon/gallery.rs @@ -226,6 +226,8 @@ pub enum GalleryFace<'a> { thumbnails: &'a Thumbnails, /// What renders the thumbnail. source: &'a dyn ThumbSource, + /// Whether the transparency grid shows behind transparent pixels. + checker: bool, }, /// A tile painted directly. Paint(&'a dyn Fn(&ContentPainterCx, Rect)), @@ -250,7 +252,17 @@ impl<'a> GalleryFace<'a> { /// A thumbnail under `key`, rendered by `source` into `thumbnails`. pub fn rendered(key: u64, thumbnails: &'a Thumbnails, source: &'a dyn ThumbSource) -> Self { - GalleryFace::Rendered { key, thumbnails, source } + GalleryFace::Rendered { key, thumbnails, source, checker: true } + } + + /// Whether a rendered thumbnail shows the transparency grid behind its transparent pixels (default on). Off for a + /// thumbnail that is a mask on the surface it sits on, such as an equation symbol. Other faces ignore it. + #[must_use] + pub fn checker(mut self, on: bool) -> Self { + if let GalleryFace::Rendered { checker, .. } = &mut self { + *checker = on; + } + self } /// The picture this face shows, `size` high and `aspect` times as wide. It is decoration: the tile that holds it @@ -258,7 +270,9 @@ impl<'a> GalleryFace<'a> { fn picture(&self, aspect: ThumbAspect, size: ThumbSize) -> Picture<'a> { let picture = match self { GalleryFace::Image { key, revision, image } => Picture::new(Label::default(), *key, *image).revision(*revision), - GalleryFace::Rendered { key, thumbnails, source } => Picture::rendered(Label::default(), *key, thumbnails, *source), + GalleryFace::Rendered { key, thumbnails, source, checker } => { + Picture::rendered(Label::default(), *key, thumbnails, *source).checker(*checker) + } GalleryFace::Paint(paint) => { let paint = *paint; Picture::painter(Label::default(), aspect, move |cx: &ContentPainterCx<'_>, rect: Rect| paint(cx, rect)) diff --git a/crates/menu/src/ribbon/gallery/stories.rs b/crates/menu/src/ribbon/gallery/stories.rs index 786f074e2b..2a80c79e78 100644 --- a/crates/menu/src/ribbon/gallery/stories.rs +++ b/crates/menu/src/ribbon/gallery/stories.rs @@ -172,8 +172,7 @@ fn gallery_rendered(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { let options = ThumbnailOptions::new(); let thumbnails = Thumbnails::::in_context(ui.ctx(), "craft_menu.gallery.story", options); let source = FakeThumbSource::::new().later(true); - let items: Vec> = (0..COUNT) - .map(|at| GalleryItem { key: at, label: name(at), face: GalleryFace::Rendered { key: at as u64, thumbnails: &thumbnails, source: &source } }) - .collect(); + let items: Vec> = + (0..COUNT).map(|at| GalleryItem { key: at, label: name(at), face: GalleryFace::rendered(at as u64, &thumbnails, &source) }).collect(); show(ui, &items) } diff --git a/crates/menu/src/shortcuts/keyboard.rs b/crates/menu/src/shortcuts/keyboard.rs index 9166e2533d..c1f35db0a2 100644 --- a/crates/menu/src/shortcuts/keyboard.rs +++ b/crates/menu/src/shortcuts/keyboard.rs @@ -4,19 +4,21 @@ use std::collections::HashMap; use std::sync::Arc; +use craft_behavior::ColumnWidth; use craft_behavior::nav::NavShape; use craft_behavior::{Metrics, PartKey, Roving, Sense}; use craft_keymap::{Binding, Chord, CommandRef, Holder, Key, Keymap, Mods, Overrides, Platform, Scope, Trigger}; -use craft_theme::variant::Tone; +use craft_theme::Variant; +use craft_theme::variant::{Emphasis, Tone}; use craft_ui::buttons::{Button, ToggleButton}; use craft_ui::contract::{ Access, Bind, BodyCx, Component, Cx, Input, MeasureCx, Name, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, Role, Show as _, - ShowContainer as _, clicked, + ShowContainer as _, Sizing, clicked, }; -use craft_ui::display::Text; -use craft_ui::layout_components::{Row, Stack}; +use craft_ui::display::{Badge, Text}; +use craft_ui::layout_components::{Grid, Row, Stack}; use craft_ui::primitives::{PaintShape, StrokeWidth, TextRun, Wrap}; -use craft_ui::style::{ComponentStyle, FocusLook, StyleColor, StyleCx, TextLook, TypeRole}; +use craft_ui::style::{ComponentStyle, FocusLook, StyleColor, StyleCx, SurfaceKind, TextLook, TypeRole}; use egui::{CornerRadius, Rect, Response, Ui, Vec2, vec2}; use super::state::{DialogState, Env}; @@ -31,6 +33,11 @@ const ROW_GAP: f32 = 0.25; /// Where the navigation cluster starts, in key units. const NAV_AT: f32 = 15.5; +/// The share of the pane's width the keys take beside the clicked key's shortcuts, and the share those take. +const CAPS_SHARE: f32 = 0.7; +const LIST_SHARE: f32 = 0.3; +const COLUMNS: [ColumnWidth; 2] = [ColumnWidth::fill(CAPS_SHARE), ColumnWidth::fill(LIST_SHARE)]; + const KEY: PartKey = PartKey::new("key"); const MODIFIER: PartKey = PartKey::new("modifier"); @@ -328,6 +335,8 @@ pub(crate) struct PaneStyle { /// Cap fills by class, and the ink that reads on each: free, application, panel or context, both. fills: [StyleColor; 4], inks: [StyleColor; 4], + /// The thin edge of every cap, so a cap whose fill is the dialog's own still reads as a key. + edge: StyleColor, /// A modifier cap that is on. on_fill: StyleColor, on_ink: StyleColor, @@ -379,22 +388,36 @@ impl Component for KeyCaps { fn style(cx: &StyleCx<'_>, _: Self::StyleKey) -> PaneStyle { let classes = [Class::Free, Class::App, Class::Scoped, Class::Both]; + // The solid look of a tone: its fill and the ink that reads on it. + let solid = |tone: Tone| { + let look = cx.with_variant(Variant::look(Emphasis::Solid, tone)).variant_look(); + (look.fill.off.rest, look.text.off.rest) + }; PaneStyle { metrics: Metrics::new(), focus: cx.focus_look(), text: TextLook::new(TypeRole::Caption, craft_theme::Stateful::new(cx.ink(craft_ui::style::Ink::OnPanel))), step: cx.control().height, radius: cx.surface(craft_ui::style::SurfaceKind::Raised).radius, - fills: classes.map(|c| cx.tone_fill(c.tone())), - inks: classes.map(|c| if c == Class::Free { cx.ink(craft_ui::style::Ink::OnPanel) } else { cx.tone(c.tone()) }), - on_fill: cx.tone_fill(Tone::Info), - on_ink: cx.tone(Tone::Info), + // A free key is a raised cap (the neutral tone's soft fill is the sunken surface, which a dialog may share); a + // held key is the solid fill of its tone, so the classes read at a glance. + fills: classes.map(|c| if c == Class::Free { StyleColor(cx.surface(SurfaceKind::Raised).fill) } else { solid(c.tone()).0 }), + inks: classes.map(|c| if c == Class::Free { cx.ink(craft_ui::style::Ink::OnPanel) } else { solid(c.tone()).1 }), + edge: cx.color(cx.tokens.color.line.border), + on_fill: solid(Tone::Info).0, + on_ink: solid(Tone::Info).1, } } fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { + // The caps keep their proportions: 18.5 units go across the pane and 6.25 down it, so the pane is as tall as + // the width it is given makes the keys, and a wider pane draws bigger keys rather than the same keys one + // control high. Measured at its least, the pane is 18.5 controls wide, so a key is one control; a pane given + // less room than that takes the room it is given (down to the plot's least height), so its keys can come out + // smaller than a control. A pane measured in a column that offers it no room still learns the height it shows + // at, as `picture_size` has the column sweep again with the width the pane settles on. let step = cx.style.step; - vec2(UNITS_W * step, UNITS_H * step) + cx.picture_size(UNITS_W * step, 2.0 * UNITS_W * step, |width| width / UNITS_W * UNITS_H) } fn sense(&self) -> Sense { @@ -448,13 +471,16 @@ impl Component for KeyCaps { }; let shape = PaintShape::Rect(cell, style.radius); draw.fill(&shape, fill); + draw.stroke(&shape, StrokeWidth::Thin, style.edge); if Self::interactive(view) && cx.part(Self::part(at, view)).hovered { draw.stroke(&shape, StrokeWidth::Medium, ink); } if view.marked && matches!(view.cap, Cap::Key(_)) { draw.stroke(&shape, StrokeWidth::Thick, ink); } - let (top, bottom) = cell.split_top_bottom_at_fraction(0.5); + // The names stand off the cap's edges, so a long one is cut before it touches the next key. + let pad = (unit * 0.1).clamp(2.0, 4.0); + let (top, bottom) = cell.shrink2(vec2(pad, pad * 0.5)).split_top_bottom_at_fraction(0.5); if let Some(title) = &view.title { draw.text(top, &TextRun::new(title.as_str()).role(style.text.role).color(ink).wrap(Wrap::Elide)); } @@ -621,7 +647,7 @@ pub(crate) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, env: &mut Env<'_>, state: let mut assign = false; let mods = state.keyboard.mods; let index = state.keyboard.index(env.keymap); - Stack::new().show(ui, |ui, _| { + Stack::new().fill_width().show(ui, |ui, _| { Row::new().show(ui, |ui, _| { let layout = if mac { &words.keyboard_us_macos } else { &words.keyboard_us }; Text::new(layout.clone()).show(ui); @@ -632,26 +658,30 @@ pub(crate) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, env: &mut Env<'_>, state: toggled = Some(m); } } + // The legend: each word on the solid fill its keys take. for (tone, word) in [ (Tone::Accent, &words.application), (Tone::Warn, &words.panel_or_context), (Tone::Bad, &words.both), (Tone::Info, &words.modifier_on), ] { - Text::new(word.clone()).tone(tone).show(ui); + Badge::new(word.clone()).variant(Variant::look(Emphasis::Solid, tone)).id_salt(("shortcuts.legend", word.as_str())).show(ui); } }); - Row::new().show(ui, |ui, _| { - let caps = KeyCaps { - common: craft_ui::contract::Common::new(), - caps: cap_views(env, &state.keyboard, &index.1, mods), - key: None, - toggled: None, - }; - let pane = caps.id_salt("shortcuts.keyboardCaps").show(ui); - picked_key = pane.key; - toggled = toggled.or(pane.toggled); - Stack::new().show(ui, |ui, _| key_list(ui, env, state, &index.1, mods, &mut go, &mut assign)); + // The keys take most of the width; the clicked key's shortcuts the rest, under the keys' own height. + Grid::new(&COLUMNS).fill_width().show(ui, |ui, _| { + Stack::new().fill_width().show(ui, |ui, _| { + let caps = KeyCaps { + common: craft_ui::contract::Common::new(), + caps: cap_views(env, &state.keyboard, &index.1, mods), + key: None, + toggled: None, + }; + let pane = caps.id_salt("shortcuts.keyboardCaps").sizing(Sizing::FillWidth).show(ui); + picked_key = pane.key; + toggled = toggled.or(pane.toggled); + }); + Stack::new().fill_width().show(ui, |ui, _| key_list(ui, env, state, &index.1, mods, &mut go, &mut assign)); }); }); if let Some(m) = toggled { @@ -680,7 +710,7 @@ fn key_list(ui: &mut Ui, env: &Env<'_>, state: &DialogState, index: &Index, mods let words = say.words(); let platform = env.keymap.platform(); let Some(key) = state.keyboard.key else { - Text::new(words.click_a_key_to_see_its.clone()).shade(craft_ui::display::Shade::Muted).show(ui); + Text::new(words.click_a_key_to_see_its.clone()).shade(craft_ui::display::Shade::Muted).sizing(Sizing::FillWidth).show(ui); return; }; Text::new(words.key_key.fill(&[("key", say.key_word(key, platform).as_str())])).show(ui); diff --git a/crates/menu/src/shortcuts/mod.rs b/crates/menu/src/shortcuts/mod.rs index 7a2bb5b536..2b2165d4f9 100644 --- a/crates/menu/src/shortcuts/mod.rs +++ b/crates/menu/src/shortcuts/mod.rs @@ -444,10 +444,14 @@ impl<'a> ShortcutsDialog<'a> { self } - /// Sets the value `field` names in `state`, as the user editing that control would - /// (`search`, `area`, `command`, `pressed`; `assign` true presses Assign; `remove` takes the text - /// of one of the command's keys, as [`DialogSnapshot::keys`] reports it), for automation. It builds the words `Env` that `DialogState::set_field` needs. `Err` says why - /// the field was refused. + /// Sets a dialog field for automation, as the user editing `search`, `area`, `command` or `pressed` would. + /// `assign` true presses Assign. + /// `remove` takes one of the selected command's keys as reported by [`DialogSnapshot::keys`]. `replace` takes + /// an object with `old` in the same form and `new` as [`Trigger`] text. It preserves the old scope and keeps + /// hold shortcuts in the Hold column. In [`ConflictMode::Ask`], a conflict leaves the old binding in place + /// until the user confirms. Hosts can use [`ConflictMode::Steal`] or [`ConflictMode::Keep`] for immediate + /// handling. Replacing a shortcut with an equivalent trigger leaves it alone. A replacement that changes + /// the shortcut can be undone in one step. `Err` says why the field was refused. pub fn set_json_field(self, ui: &Ui, state: &mut DialogState, field: &str, value: &serde_json::Value) -> Result<(), String> { use craft_ui::dialog::FieldRefusal; let rejects = || FieldRefusal::Rejects(value).message(field); @@ -490,6 +494,31 @@ impl<'a> ShortcutsDialog<'a> { state.remove(env, &command, &wanted); state.edit_result()?; } + "replace" => { + if !env.options.editable || !state.is_showing() || state.modal() || state.is_recording() || env.has_app_tab(state.tab) { + return Err(inactive()); + } + let command = state.selected.clone().ok_or_else(inactive)?; + let text = |key: &str| value.get(key).and_then(serde_json::Value::as_str).ok_or_else(rejects); + let old_text = text("old")?; + let bindings = env.keymap.bindings(&command); + let mut matches = bindings.iter().filter(|binding| binding.to_string() == old_text); + let old = matches.next().ok_or_else(rejects)?; + let trigger = Trigger::parse(text("new")?).map_err(|_| rejects())?; + if matches.next().is_some() || trigger.is_hold() != old.trigger.is_hold() { + return Err(rejects()); + } + let platform = env.keymap.platform(); + let effective = trigger.effective(platform); + if effective == old.trigger.effective(platform) { + return Ok(()); + } + if bindings.iter().any(|binding| binding.scope == old.scope && binding.trigger.effective(platform) == effective) { + return Err(rejects()); + } + let new = Binding { trigger, scope: old.scope.clone() }; + state.replace_for_automation(env, &command, old, new)?; + } _ => return Err(FieldRefusal::Unknown.message(field)), } Ok(()) diff --git a/crates/menu/src/shortcuts/pages.rs b/crates/menu/src/shortcuts/pages.rs index dee3c9589d..134cd86763 100644 --- a/crates/menu/src/shortcuts/pages.rs +++ b/crates/menu/src/shortcuts/pages.rs @@ -120,7 +120,7 @@ pub struct DialogSnapshot { pub selected: Option, /// Commands whose bindings differ from the defaults, with their binding texts. pub overrides: Vec<(CommandRef, Vec)>, - /// The conflict bar's chord and the commands holding it, while it shows. + /// The pending conflict's chord and the commands holding it. Another prompt or app tab can hide the conflict bar. pub conflict: Option<(String, Vec)>, /// Whether a chord is being recorded, and the command it is for. pub recording: Option, diff --git a/crates/menu/src/shortcuts/sets.rs b/crates/menu/src/shortcuts/sets.rs index 71d790ae37..a5408e3e8c 100644 --- a/crates/menu/src/shortcuts/sets.rs +++ b/crates/menu/src/shortcuts/sets.rs @@ -129,7 +129,7 @@ fn publish(cx: &mut BodyCx<'_>, env: &Env<'_>, idle: bool, builtin: bool, modifi /// The strip's items. An app that writes other formats gets its own Export menu in place of the Export item. fn items(env: &Env<'_>, formats: bool) -> Vec { - let item = |command: SetCommand| BarItem::new(command).display(ItemDisplay::Text); + let item = |command: SetCommand| BarItem::new(command).display(ItemDisplay::Button); let mut items = vec![item(SetCommand::New), item(SetCommand::Rename), item(SetCommand::Delete), item(SetCommand::Save), item(SetCommand::Revert)]; if !formats { items.push(item(SetCommand::Export)); diff --git a/crates/menu/src/shortcuts/state.rs b/crates/menu/src/shortcuts/state.rs index eb9bc606c8..9f67d256b8 100644 --- a/crates/menu/src/shortcuts/state.rs +++ b/crates/menu/src/shortcuts/state.rs @@ -7,13 +7,15 @@ use craft_keymap::editor::{self, DOUBLE_PRESS, EditSession, Recorded, Recorder}; use craft_keymap::import::{self, ForeignEntry, ForeignSet, ImportOptions, ImportPlan, ImportReport, Start}; use craft_keymap::profiles::{Builtins, ProfileError, Profiles, set_name}; use craft_keymap::{ - AssignError, Assigned, Binding, BindingError, Chord, CommandRef, Holder, Key, Keymap, MAX_BINDINGS, Overrides, ParseError, Policy, Scope, Trigger, + AssignError, Assigned, Binding, BindingError, Chord, CommandRef, Holder, Key, Keymap, MAX_BINDINGS, Overrides, ParseError, Platform, Policy, + Scope, Trigger, }; +use craft_ui::primitives::ChordText; use super::keyboard::KeyboardState; use super::pages::TabSet; use super::rows::{self, AreaEntry, AreaId, Built, Filter, RowCache, View}; -use super::words::Say; +use super::words::{Say, around_chord}; use super::{ConflictMode, HoldSetting, JSON_FORMAT, Layout, Options, Outcome, summary}; /// What the dialog edits this frame. @@ -28,6 +30,10 @@ pub(crate) struct Env<'e> { } impl Env<'_> { + pub(crate) fn has_app_tab(&self, id: Option<&str>) -> bool { + id.is_some_and(|id| self.tabs.as_ref().is_some_and(|tabs| (0..tabs.len()).any(|i| tabs.describe(i).is_some_and(|(tab, _)| tab == id)))) + } + fn chord_text(&self, t: &Trigger) -> String { self.text.trigger(t, self.keymap.platform()) } @@ -129,14 +135,43 @@ pub(crate) struct FieldChord { /// The conflict bar, for one pending chord. #[derive(Clone, Debug, PartialEq)] pub(crate) struct ConflictBar { + pub revision: u64, pub command: CommandRef, pub old: Option, pub binding: Binding, pub holders: Vec, + pub can_steal: bool, + pub can_keep: bool, + before: Option, /// "{chord} is used by {label}". pub text: String, } +impl ConflictBar { + pub(crate) fn notice_text(&self, env: &Env) -> String { + if self.before.is_some() { self.text.clone() } else { around_chord(env.text.rtl(), &self.text, &env.chord_text(&self.binding.trigger)) } + } +} + +/// The existing bindings and home scopes that an automation conflict was opened against. +#[derive(Clone, Debug, PartialEq)] +struct ConflictBasis { + bindings: Vec>, + scopes: Vec>, + platform: Platform, +} + +impl ConflictBasis { + fn of(keymap: &Keymap, command: &CommandRef, holders: &[Holder]) -> Self { + let scopes = std::iter::once(command) + .chain(holders.iter().map(|holder| &holder.command)) + .map(|command| keymap.bindable(command).map(|entry| entry.scope.clone())) + .collect(); + let bindings = std::iter::once(command).chain(holders.iter().map(|holder| &holder.command)).map(|command| keymap.bindings(command)).collect(); + Self { bindings, scopes, platform: keymap.platform() } + } +} + /// A line under the table after an action. #[derive(Clone, Debug, PartialEq)] pub(crate) struct Message { @@ -269,6 +304,7 @@ pub struct DialogState { pub(crate) recording: Option, pub(crate) field: Option, pub(crate) conflict: Option, + conflict_revision: u64, pub(crate) prompt: Option, pub(crate) message: Option, pub(crate) review: Option, @@ -320,6 +356,7 @@ impl DialogState { recording: None, field: None, conflict: None, + conflict_revision: 0, prompt: None, message: None, review: None, @@ -679,6 +716,49 @@ impl DialogState { self.commit_with(env, command, old, binding, mode); } + /// Checks that a replacement can be saved before offering conflict confirmation to an automation caller. + pub(crate) fn replace_for_automation(&mut self, env: &mut Env, command: &CommandRef, old: &Binding, binding: Binding) -> Result<(), String> { + let mut actions = None; + if env.options.conflicts == ConflictMode::Ask && !editor::holders(env.keymap, command, &binding).is_empty() { + let preview = |policy| editor::check_replace(env.keymap, command, old, &binding, policy); + let steal = preview(Policy::Steal); + let keep = preview(Policy::Keep).is_ok(); + if let Err(error) = &steal + && (!keep || !env.options.allow_keep) + { + let text = assign_error(env, error); + self.conflict = None; + self.refuse(text.clone()); + return Err(text); + } + actions = Some((steal.is_ok(), keep)); + } + self.commit(env, command, Some(old.clone()), binding); + if let (Some(conflict), Some((steal, keep))) = (&mut self.conflict, actions) { + conflict.can_steal = steal; + conflict.can_keep = keep; + conflict.before = Some(ConflictBasis::of(env.keymap, command, &conflict.holders)); + let chord = |trigger| { + let text = env.chord_text(trigger); + if env.text.rtl() { ChordText::new(text).isolated() } else { text } + }; + let label = env.label(command); + let target = match env.keymap.bindable(command) { + Some(entry) => fill!(env, label_scope, ("label", &label), ("scope", &env.text.scope_name(old.scope_or(&entry.scope)))), + None => label, + }; + conflict.text = fill!( + env, + replace_old_for_command_with_chord_used_by_label, + ("old", &chord(&old.trigger)), + ("command", &target), + ("chord", &chord(&conflict.binding.trigger)), + ("label", &env.holder_labels(&conflict.holders)) + ); + } + self.edit_result() + } + fn commit_with(&mut self, env: &mut Env, command: &CommandRef, old: Option, binding: Binding, mode: ConflictMode) { self.conflict = None; self.message = None; @@ -701,7 +781,18 @@ impl DialogState { match mode { ConflictMode::Ask => { let text = fill!(env, chord_is_used_by_label, ("chord", &chord), ("label", &env.holder_labels(&holders))); - self.conflict = Some(ConflictBar { command: command.clone(), old, binding, holders, text }); + self.conflict_revision = self.conflict_revision.wrapping_add(1); + self.conflict = Some(ConflictBar { + revision: self.conflict_revision, + command: command.clone(), + old, + binding, + holders, + can_steal: true, + can_keep: true, + before: None, + text, + }); } ConflictMode::Steal => { self.apply_and_say(env, command, old, binding, Policy::Steal); @@ -771,14 +862,14 @@ impl DialogState { /// Take It. pub(crate) fn take_it(&mut self, env: &mut Env) { - if let Some(c) = self.conflict.take() { + if let Some(c) = self.accept_conflict(env) { self.apply_and_say(env, &c.command, c.old, c.binding, Policy::Steal); } } /// Accept and Go to Conflict. pub(crate) fn take_it_and_go(&mut self, env: &mut Env) { - if let Some(c) = self.conflict.take() { + if let Some(c) = self.accept_conflict(env) { let first = c.holders.first().map(|h| h.command.clone()); if self.apply_and_say(env, &c.command, c.old, c.binding, Policy::Steal) && let Some(holder) = first @@ -793,11 +884,37 @@ impl DialogState { if !env.options.allow_keep { return; } - if let Some(c) = self.conflict.take() { + if let Some(c) = self.accept_conflict(env) { self.apply_and_say(env, &c.command, c.old, c.binding, Policy::Keep); } } + /// The pending conflict the user can currently answer. + pub(crate) fn visible_conflict(&self, env: &Env) -> Option<&ConflictBar> { + self.conflict.as_ref().filter(|conflict| { + conflict.before.is_none() || (env.options.editable && !self.modal() && !self.is_recording() && !env.has_app_tab(self.tab)) + }) + } + + fn accept_conflict(&mut self, env: &Env) -> Option { + self.visible_conflict(env)?; + let conflict = self.conflict.take()?; + if let Some(before) = &conflict.before { + let holders = editor::holders(env.keymap, &conflict.command, &conflict.binding); + if holders != conflict.holders || ConflictBasis::of(env.keymap, &conflict.command, &holders) != *before { + self.refuse(word!(env, the_shortcuts_changed_try_replacing_again)); + return None; + } + if let (Some(accept), Some(command)) = (&env.options.accept, env.keymap.bindable(&conflict.command)) + && let Err(text) = accept(command, &conflict.binding) + { + self.refuse(text); + return None; + } + } + Some(conflict) + } + /// ✕ on the conflict bar: nothing was applied, so nothing changes. pub(crate) fn dismiss_conflict(&mut self) { self.conflict = None; @@ -982,7 +1099,7 @@ impl DialogState { pub(crate) fn escape(&mut self, env: &mut Env) { if self.recording.is_some() { self.stop_recording(); - } else if self.conflict.is_some() { + } else if self.visible_conflict(env).is_some() { self.conflict = None; } else if self.prompt.is_some() { self.prompt = None; diff --git a/crates/menu/src/shortcuts/view/bars.rs b/crates/menu/src/shortcuts/view/bars.rs index 22326b7f55..10c0ca6e75 100644 --- a/crates/menu/src/shortcuts/view/bars.rs +++ b/crates/menu/src/shortcuts/view/bars.rs @@ -49,30 +49,40 @@ fn prompt(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) { } fn conflict_bar(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) { - let Some(conflict) = state.conflict.clone() else { return }; + enum Action { + Take, + TakeAndGo, + Keep, + Dismiss, + } + + let Some(conflict) = state.visible_conflict(env).cloned() else { return }; let words = env.text.words(); - let chord = env.text.trigger(&conflict.binding.trigger, env.keymap.platform()); - let text = around_chord(env.text.rtl(), &conflict.text, &chord); + let text = conflict.notice_text(env); + let keep = conflict.can_keep && env.options.allow_keep; let mut notice = Notice::new(Tone::Warn, text) - .id_salt("shortcuts.conflict") + .id_salt(("shortcuts.conflict", conflict.revision, keep)) .layout(NoticeLayout::Inline) - .announce(Politeness::Polite) - .action(NoticeAction::new(words.take_it.clone())) - .action(NoticeAction::new(words.accept_and_go_to_conflict.clone())); - let keep = env.options.allow_keep; - if keep { - notice = notice.action(NoticeAction::new(words.keep_both.clone())); + .announce(Politeness::Polite); + let mut actions = Vec::new(); + for (available, label, action) in [ + (conflict.can_steal, &words.take_it, Action::Take), + (conflict.can_steal, &words.accept_and_go_to_conflict, Action::TakeAndGo), + (keep, &words.keep_both, Action::Keep), + (true, &words.undo_changes, Action::Dismiss), + ] { + if available { + notice = notice.action(NoticeAction::new(label.clone())); + actions.push(action); + } } - // Photoshop's wording for turning the new shortcut down is "Undo Changes", the notice's last action. - let undo_at = if keep { 3 } else { 2 }; - notice = notice.action(NoticeAction::new(words.undo_changes.clone())); let out = notice.show(ui); - match out.action { - Some(0) => state.take_it(env), - Some(1) => state.take_it_and_go(env), - Some(2) if keep => state.keep_both(env), - Some(at) if at == undo_at => state.dismiss_conflict(), - _ => {} + match out.action.and_then(|at| actions.get(at)) { + Some(Action::Take) => state.take_it(env), + Some(Action::TakeAndGo) => state.take_it_and_go(env), + Some(Action::Keep) => state.keep_both(env), + Some(Action::Dismiss) => state.dismiss_conflict(), + None => {} } } diff --git a/crates/menu/src/shortcuts/view/lists.rs b/crates/menu/src/shortcuts/view/lists.rs index 00b35ce177..5bd47ed1a5 100644 --- a/crates/menu/src/shortcuts/view/lists.rs +++ b/crates/menu/src/shortcuts/view/lists.rs @@ -24,6 +24,8 @@ use crate::shortcuts::state::{DialogState, Env}; const LISTS_SHARE: f32 = 0.5; /// The detail column's share of the width beside the lists. const DETAIL_SHARE: f32 = 0.5; +/// The most Categories rows shown before the list scrolls. +const CATEGORY_ROWS: u16 = 6; const PANES: [ColumnWidth; 2] = [ColumnWidth::fill(LISTS_SHARE), ColumnWidth::fill(DETAIL_SHARE)]; /// One frame of the command-lists body: a search field, the Categories list beside the Commands @@ -62,6 +64,8 @@ fn categories(ui: &mut Ui, env: &Env<'_>, state: &mut DialogState) { let mut selection = Selection::new(at.into_iter().collect(), at, at); let out = List::::new(words.categories.clone()) .id_salt("categories") + // A short list, so the Commands list under it keeps room in a dialog of ordinary height. + .max_rows(CATEGORY_ROWS) .select(SelectMode::Single) .selection(Bind::bound(&mut selection)) .show_items(ui, &Titles(&labels), &mut |key, _| ListRow::new(labels[*key].clone())); diff --git a/crates/menu/src/shortcuts/view/table.rs b/crates/menu/src/shortcuts/view/table.rs index 1edfab4d0f..4d557de665 100644 --- a/crates/menu/src/shortcuts/view/table.rs +++ b/crates/menu/src/shortcuts/view/table.rs @@ -428,7 +428,10 @@ impl Component for CommandRow<'_> { Line::Row(line) => { let mut cell = self.measure_chips(cx, line, false); if line.chips.is_empty() { - cell += cx.child(("chip", "none"), &mut ChordChip::new(self.env.words.none.as_str().to_owned()), Proposal::Ideal).x + gap; + let none = self.env.words.none.as_str().to_owned(); + let width = cx.child(("chip", "none"), &mut ChordChip::new(none.clone()), Proposal::Ideal).x; + self.widths.insert((Shown::Chip, none), width); + cell += width + gap; } for text in &line.unparsed { let width = cx.child(("unparsed", text), &mut unparsed_note(text, String::new()), Proposal::Ideal).x; @@ -578,14 +581,15 @@ impl CommandRow<'_> { } } if cells.is_empty() && !hold { - let rect = band(&flow, cell, 0.0, chips_end.max(height)); let none = words.none.as_str(); + let width = width_of(Shown::Chip, none).min(chips_end.max(0.0)); + let rect = band(&flow, cell, 0.0, width); let name = words.label_chord.fill(&[("label", &line.label), ("chord", none)]); let chip = ChordChip::new(none.to_owned()).label(name).id_salt(("chip", line.key.as_str(), 0)).enabled(editable); if ui.child(("chip", line.key.as_str(), 0), rect, chip).pressed { act = Some(RowAct::Record(None)); } - at = chips_end.max(height) + gap; + at = width + gap; } let unparsed: &[String] = if hold { &[] } else { &line.unparsed }; for (n, text) in unparsed.iter().enumerate() { diff --git a/crates/menu/src/shortcuts/words.rs b/crates/menu/src/shortcuts/words.rs index 77c054e118..886b2a3df5 100644 --- a/crates/menu/src/shortcuts/words.rs +++ b/crates/menu/src/shortcuts/words.rs @@ -123,6 +123,8 @@ craft_ui::words! { keep_both: "keyboardShortcuts.keepBoth" = "Keep Both"; go_to_conflict: "keyboardShortcuts.goToConflict" = "Go to Conflict"; undo_changes: "keyboardShortcuts.undoChanges" = "Undo Changes"; + replace_old_for_command_with_chord_used_by_label: template "keyboardShortcuts.replaceOldForCommandWithChordUsedByLabel" = "Replace {old} for {command} with {chord}, which is used by {label}"; + the_shortcuts_changed_try_replacing_again: "keyboardShortcuts.theShortcutsChangedTryReplacingAgain" = "The shortcuts changed. Try the replacement again."; dismiss: "keyboardShortcuts.dismiss" = "Dismiss"; // Saved shortcuts that could not be used. key_no_command_has_this_name: template "keyboardShortcuts.keyNoCommandHasThisName" = "{key}: no command has this name"; diff --git a/crates/menu/tests/it/ribbon_gallery.rs b/crates/menu/tests/it/ribbon_gallery.rs index 44abf3d767..93e83d0e78 100644 --- a/crates/menu/tests/it/ribbon_gallery.rs +++ b/crates/menu/tests/it/ribbon_gallery.rs @@ -263,3 +263,26 @@ fn the_current_tile_paints_an_accent_fill_and_edge_even_when_focused() { assert!(shapes.iter().any(|p| p.fill == fill && near(p, current)), "{who}: the focused current tile keeps its fill"); } } + +/// How many shapes a gallery of one rendered tile of a transparent image paints, as built or with `checker(false)`. +fn shapes_of_rendered(opt_out: bool) -> usize { + use craft_ui::primitives::textures::{FakeThumbSource, ThumbnailOptions, Thumbnails}; + let mut fixture = Fixture::new(move |ui| { + let options = ThumbnailOptions::new().jobs(std::sync::Arc::new(craft_host::InlineJobs)); + let thumbnails = Thumbnails::::in_context(ui.ctx(), "gallery_checker_test", options); + let source = FakeThumbSource::::new(); + // The default case sets nothing, so a default that turned the grid off fails here. + let face = GalleryFace::rendered(1, &thumbnails, &source); + let face = if opt_out { face.checker(false) } else { face }; + let items = [GalleryItem { key: 0_usize, label: Label::from("Mask"), face }]; + Gallery::new("Symbols", &items, None).tiles(1, 1).show(ui); + }); + fixture.settle(); + fixture.frame_shapes().len() +} + +#[trial] +fn a_rendered_gallery_tile_paints_a_checker_unless_it_opts_out() { + let (with, without) = (shapes_of_rendered(false), shapes_of_rendered(true)); + assert!(with > without, "the default paints {with} shapes, the opt-out {without}: the grid is the difference"); +} diff --git a/crates/menu/tests/it/shortcuts/fixture.rs b/crates/menu/tests/it/shortcuts/fixture.rs index 1bc858139d..fbafc48bf1 100644 --- a/crates/menu/tests/it/shortcuts/fixture.rs +++ b/crates/menu/tests/it/shortcuts/fixture.rs @@ -258,6 +258,16 @@ impl Rig { self.shared.borrow().sets.as_ref().map(|(p, _)| p.active().to_string()) } + /// Sets an automation field in the next dialog pass. + pub(crate) fn set_json_field(&mut self, field: &'static str, value: serde_json::Value) -> Result<(), String> { + let result = Rc::new(RefCell::new(None)); + let out = result.clone(); + let job: Job = Box::new(move |dialog, ui, state| *out.borrow_mut() = Some(dialog.set_json_field(ui, state, field, &value))); + self.shared.borrow_mut().jobs.push(job); + self.fixture.idle(2); + result.take().expect("the automation job ran") + } + /// Runs `job` with the dialog in the next pass and returns what it returns. pub(crate) fn import_json(&mut self, json: &str) -> Result { let result = Rc::new(RefCell::new(None)); diff --git a/crates/menu/tests/it/shortcuts/keyboard.rs b/crates/menu/tests/it/shortcuts/keyboard.rs new file mode 100644 index 0000000000..f7faa47345 --- /dev/null +++ b/crates/menu/tests/it/shortcuts/keyboard.rs @@ -0,0 +1,130 @@ +//! The keyboard pane, the set row's buttons and the shortcut column keep the look the dialog had before the port: readable keys +//! beside the clicked key's shortcuts, filled keys and a legend in the same fills, framed set buttons, and the add button right +//! after the chips of every row. + +use craft_keymap::{Platform, Profiles}; +use craft_ui::contract::Role; +use craft_ui::testing::{Target, trial}; +use egui::Shape; + +use super::fixture::Rig; + +/// The pane as an app opens it: a size of its own in the rig's 1000 by 700 point window. The pane takes the height its +/// width gives the keys. +fn pane_like_an_app(options: &mut craft_menu::shortcuts::Options) { + options.keyboard = true; + options.size = Some(egui::vec2(900.0, 620.0)); +} + +/// The key named `name` on the pane (its node is a button of that name). +fn cap(rig: &Rig, name: &str) -> Target { + rig.named(name, Role::BUTTON) +} + +/// The pane `width` points wide, with the height of one control and a key's rect: the footer's OK is a control. +fn pane(width: f32) -> (f32, egui::Rect) { + let rig = Rig::tuned(Platform::Windows, |options| { + options.keyboard = true; + options.size = Some(egui::vec2(width, 620.0)); + }); + (rig.named("OK", Role::BUTTON).rect.height(), cap(&rig, "Q").rect) +} + +/// The rects of the painted rectangles that have a fill. +fn filled(shapes: &[Shape]) -> Vec<(egui::Rect, egui::Color32)> { + shapes + .iter() + .filter_map(|shape| match shape { + Shape::Rect(rect) if rect.fill.a() > 0 => Some((rect.visual_bounding_rect(), rect.fill)), + _ => None, + }) + .collect() +} + +/// With the keyboard pane on, a key is readable (at least a control tall and wide) and the clicked key's shortcuts stand +/// beside the whole block of keys, not between them. +#[trial] +fn the_keyboard_keeps_readable_keys_beside_the_key_list() { + let rig = Rig::tuned(Platform::Windows, pane_like_an_app); + let q = cap(&rig, "Q").rect; + assert!(q.width() >= 24.0 && q.height() >= 24.0, "a key stays readable: {q:?}"); + let hint = rig.fixture.texts().iter().find(|text| text.text.starts_with("Click a key")).expect("the hint").rect; + // Q starts 1.5 units in and the block is 18.5 units wide, so the block ends 17 key widths past Q's left edge. + assert!(hint.left() > q.left() + 17.0 * q.width(), "the hint stands beside the whole block of keys (a key is {q:?}): {hint:?}"); +} + +/// The keys keep their proportions in the room the app gives the pane: a wider pane is taller, so its keys stand above one +/// control's height rather than staying one control high however wide the dialog is. +/// +/// Both dialogs keep the pane's two columns beside each other, so the keys take the same share of the room in each and +/// the wider one draws the taller keys. A `Grid` stacks its columns only when their least widths do not fit: the caps +/// ask for 18.5 control heights (444 points at the compact preset's 24 point control) and the shortcut column for its +/// hint's readable least, which a 700 point dialog's 684 points of room (its two 8 point pads taken off) leaves well +/// inside. A stacked grid would give the caps the whole width instead, and they would come out wider, and so taller, +/// in the narrower dialog. +#[trial] +fn a_wider_pane_is_taller_and_its_keys_stand_above_a_control() { + let (control, narrow) = pane(700.0); + let (_, wide) = pane(950.0); + assert!(wide.height() > narrow.height(), "a wider pane draws taller keys: {:?} against {:?}", wide, narrow); + assert!(wide.height() > control, "the keys stand above one control's height: {:?} against {control}", wide); +} + +/// Keys are painted with a fill of their own, and the legend words stand on fills too. +#[trial] +fn keys_and_the_legend_are_filled() { + let mut rig = Rig::tuned(Platform::Windows, pane_like_an_app); + let q = cap(&rig, "Q").rect; + let legend = rig.fixture.texts().iter().find(|text| text.text == "Application").expect("the legend word Application").rect; + let fills = filled(&rig.fixture.frame_shapes()); + assert!(fills.iter().any(|(rect, _)| (rect.center() - q.center()).length() < 2.0 && rect.width() > 20.0), "the key Q has a fill: {q:?}"); + assert!(fills.iter().any(|(rect, _)| rect.contains_rect(legend)), "the legend word stands on a fill: {legend:?}"); +} + +/// The set row's actions are framed buttons. +#[trial] +fn the_set_row_buttons_are_framed() { + let mut rig = Rig::mac_with_sets(Profiles::default()); + let new = rig.find("New Set\u{2026}").rect; + let shapes = rig.fixture.frame_shapes(); + let framed = shapes.iter().any(|shape| match shape { + Shape::Rect(rect) => { + let r = rect.visual_bounding_rect(); + (r.center() - new.center()).length() < 3.0 && r.width() >= new.width() - 3.0 && (rect.fill.a() > 0 || !rect.stroke.is_empty()) + } + _ => false, + }); + assert!(framed, "New Set\u{2026} is drawn as a framed button: {new:?}"); +} + +/// A shortcut is one keycap per key (`Ctrl`, `S`), the framework's look for a chord. +#[trial] +fn a_shortcut_is_one_keycap_per_key() { + let rig = Rig::tuned(Platform::Windows, |_| {}); + let texts: Vec<&str> = rig.fixture.texts().iter().map(|text| text.text.as_str()).collect(); + assert!(texts.contains(&"Ctrl") && texts.contains(&"S"), "Save's shortcut shows a keycap for Ctrl and one for S: {texts:?}"); + assert!(!texts.contains(&"Ctrl+S"), "not one text for the chord: {texts:?}"); +} + +/// The add button stands right after the last text of its row's shortcut cell, whether the cell holds a chord or None. +#[trial] +fn the_add_button_follows_the_chips_of_every_row() { + let rig = Rig::tuned(Platform::Windows, |_| {}); + let adds: Vec = rig + .fixture + .by_role(Role::BUTTON) + .into_iter() + .filter(|node| rig.fixture.tree().name_of(node.node).is_some_and(|name| name.starts_with("Add a shortcut to"))) + .collect(); + assert!(adds.len() >= 3, "rows with an add button: {}", adds.len()); + for add in adds { + let before = rig + .fixture + .texts() + .iter() + .filter(|text| (text.rect.center().y - add.rect.center().y).abs() < 6.0 && text.rect.right() <= add.rect.left() + 1.0) + .map(|text| text.rect.right()) + .fold(f32::MIN, f32::max); + assert!(add.rect.left() - before < 24.0, "the add button {:?} follows its chips ({before})", add.rect); + } +} diff --git a/crates/menu/tests/it/shortcuts/lists.rs b/crates/menu/tests/it/shortcuts/lists.rs index 6322b27524..71131385c9 100644 --- a/crates/menu/tests/it/shortcuts/lists.rs +++ b/crates/menu/tests/it/shortcuts/lists.rs @@ -1,7 +1,7 @@ //! The Customize Keyboard layout: each change is applied at once and Escape closes without rolling back. use craft_keymap::{Binding, CommandDef, CommandRef, Keymap, Platform, Scope, Scopes, Trigger}; -use craft_menu::shortcuts::{Layout, Outcome}; +use craft_menu::shortcuts::{Area, Layout, Outcome}; use craft_ui::contract::Role; use craft_ui::testing::trial; use egui::{Key, Modifiers}; @@ -79,3 +79,29 @@ fn command_lists_assign_remove_and_close_apply_each_change_at_once() { assert_eq!(keys(&rig), left, "the keymap keeps the edits"); assert!(rig.bindings("file.export").is_empty(), "the taken chord is not given back"); } + +/// A long Categories list must not take the room the Commands list needs: in a dialog of ordinary height a command row +/// still shows above the footer. +#[trial] +fn commands_keep_room_beside_a_long_categories_list() { + let rig = Rig::tuned(Platform::Mac, |options| { + options.layout = Layout::CommandLists; + options.own_areas = true; + options.size = Some(egui::vec2(640.0, 460.0)); + options.areas = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"].map(|name| Area::new(name, name, |_| true)).to_vec(); + }); + let row = rig.find("Bring to Front").center(); + let footer = rig.find("Reset All…").center(); + assert!(row.y < footer.y, "the command row ({row:?}) sits above the footer ({footer:?})"); + // The capped list scrolls: the arrow keys still reach its last entry. + let mut rig = rig; + rig.click("A"); + for _ in 0..11 { + rig.press(Modifiers::NONE, Key::ArrowDown); + } + let area = { + let shared = rig.shared.borrow(); + shared.state.snapshot(&shared.km).expect("the dialog has shown").area + }; + assert_eq!(area, "L", "the last Categories entry is reachable"); +} diff --git a/crates/menu/tests/it/shortcuts/mod.rs b/crates/menu/tests/it/shortcuts/mod.rs index fc1ff547c8..c796c17854 100644 --- a/crates/menu/tests/it/shortcuts/mod.rs +++ b/crates/menu/tests/it/shortcuts/mod.rs @@ -2,6 +2,7 @@ mod fixture; pub(crate) mod hold; pub(crate) mod import_offer; +pub(crate) mod keyboard; pub(crate) mod lists; pub(crate) mod recorder; pub(crate) mod review; @@ -9,11 +10,307 @@ pub(crate) mod rows; pub(crate) mod sets; pub(crate) mod tabs; -use craft_keymap::Platform; +use std::cell::Cell; +use std::rc::Rc; + +use craft_keymap::{Binding, CommandDef, CommandRef, Keymap, Platform, Policy, Scope, Scopes, Trigger}; +use craft_menu::shortcuts::HoldSetting; +use craft_ui::contract::Role; use craft_ui::testing::trial; +use egui::{Key, Modifiers}; +use serde_json::json; use fixture::Rig; +#[trial] +fn automation_replaces_a_shortcut_in_its_scope_as_one_undo_step() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("type.bold")).unwrap(); + let original = rig.bindings("type.bold"); + let old = &original[0]; + + assert!(rig.set_json_field("replace", json!({"old": old, "new": "not a trigger"})).is_err()); + assert!(rig.set_json_field("replace", json!({"old": "Cmd+B", "new": "Cmd+K"})).is_err()); + assert!(rig.set_json_field("replace", json!({"old": old, "new": "Hold K"})).is_err()); + assert_eq!(rig.bindings("type.bold"), original); + + rig.set_json_field("replace", json!({"old": old, "new": "Cmd+K"})).unwrap(); + assert_eq!(rig.bindings("type.bold"), ["Text: Cmd+K"]); + rig.click("Undo"); + assert_eq!(rig.bindings("type.bold"), original); + let shared = rig.shared.borrow(); + assert!(!shared.state.snapshot(&shared.km).unwrap().can_undo); +} + +#[trial] +fn an_automation_replacement_waits_for_conflict_confirmation() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); + assert!([Role::STATUS, Role::ALERT].into_iter().any(|role| !rig.names_with(role, "for Save (Application) with").is_empty())); + + rig.click("Take It"); + assert_eq!(rig.bindings("file.save"), ["Cmd+E"]); + assert!(rig.bindings("file.export").is_empty()); + rig.click("Undo"); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); +} + +#[trial] +fn confirming_an_automation_replacement_preserves_shortcuts_that_changed_after_the_prompt() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + let third = CommandRef::from("object.front"); + rig.shared.borrow_mut().km.assign(&third, Binding::parse("Cmd+E").unwrap(), Policy::Keep).unwrap(); + rig.pass(); + rig.answer("Take It"); + + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); + assert_eq!(rig.bindings("object.front"), ["Cmd+E"]); + let shared = rig.shared.borrow(); + assert!(shared.state.snapshot(&shared.km).unwrap().conflict.is_none()); +} + +#[trial] +fn confirming_an_automation_replacement_cannot_change_shortcuts_in_a_new_scope() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + let mut catalog = rig.shared.borrow().km.catalog().to_vec(); + for command in &mut catalog { + if matches!(command.command.key().as_str(), "file.save" | "file.export") { + command.scope = Scope::new("Text").unwrap(); + } + } + rig.shared.borrow_mut().km = Keymap::new(catalog, Scopes::new().with_context("Text"), Platform::Mac); + rig.pass(); + rig.answer("Take It"); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); + let shared = rig.shared.borrow(); + assert!(shared.state.snapshot(&shared.km).unwrap().conflict.is_none()); +} + +#[trial] +fn a_holder_binding_change_retires_its_pending_replacement_confirmation() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + rig.shared.borrow_mut().km.assign(&CommandRef::from("file.export"), Binding::parse("Cmd+K").unwrap(), Policy::Keep).unwrap(); + rig.pass(); + rig.answer("Take It"); + + assert_eq!(rig.bindings("file.save"), ["Cmd+S"], "a stale confirmation cannot replace the original shortcut"); + assert_eq!(rig.bindings("file.export"), ["Cmd+E", "Cmd+K"], "the changed holder keeps all its current shortcuts"); + let shared = rig.shared.borrow(); + assert!(shared.state.snapshot(&shared.km).unwrap().conflict.is_none()); +} + +#[trial] +fn a_superseding_replacement_has_its_own_confirmation_actions() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + let old_action = rig.find("Take It").node; + rig.shared.borrow_mut().options.allow_keep = false; + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+Shift+S"})).unwrap(); + assert_ne!(rig.find("Take It").node, old_action); + assert!(!rig.has("Keep Both")); + let dismiss = rig.find("Undo Changes").node; + rig.shared.borrow_mut().options.allow_keep = true; + rig.pass(); + assert_ne!(rig.find("Keep Both").node, dismiss); +} + +#[trial] +fn escape_dismisses_a_visible_prompt_before_a_hidden_replacement() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+K"})).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+K", "new": "Cmd+E"})).unwrap(); + assert!(rig.has("Take It")); + rig.click("Reset All…"); + assert!(rig.has("Reset All")); + assert!(!rig.has("Take It")); + + rig.press(Modifiers::NONE, Key::Escape); + assert!(!rig.has("Reset All")); + assert!(rig.has("Take It")); + assert_eq!(rig.bindings("file.save"), ["Cmd+K"]); +} + +#[trial] +fn automation_offers_only_keep_both_when_taking_the_shortcut_cannot_be_saved() { + let scope = "Text".repeat(16); + let trigger = Trigger::parse("Cmd+Ctrl+Alt+Shift+IntlBackslash Cmd+Ctrl+Alt+Shift+IntlBackslash").unwrap(); + let retained = Binding::in_scope(trigger, Scope::new(&scope).unwrap()); + let save = CommandDef::new("file.save", "Save", Scope::app()).with_default(Binding::parse("Cmd+S").unwrap()); + let export = CommandDef::new("file.export", "Export", Scope::app()).with_default(retained.clone()).with_default(Binding::parse("Cmd+E").unwrap()); + let keymap = Keymap::new(vec![save, export], Scopes::new().with_context(&scope), Platform::Mac); + let mut rig = Rig::new(keymap, fixture::options(), None); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + assert!(!rig.has("Take It")); + assert!(!rig.has("Accept and Go to Conflict")); + rig.click("Keep Both"); + assert_eq!(rig.bindings("file.save"), ["Cmd+E"]); + assert_eq!(rig.bindings("file.export"), [retained.to_string(), "Cmd+E".into()]); +} + +#[trial] +fn automation_replacement_preserves_the_shortcut_when_the_app_rejects_it() { + let mut rig = Rig::tuned(Platform::Mac, |options| options.accept = Some(Box::new(|_, _| Err("That shortcut is unavailable".into())))); + rig.set_json_field("command", json!("file.save")).unwrap(); + let result = rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+K"})); + assert_eq!(result, Err("That shortcut is unavailable".into())); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); +} + +#[trial] +fn confirming_an_automation_replacement_checks_the_current_app_rule() { + let accepted = Rc::new(Cell::new(true)); + let rule = accepted.clone(); + let mut rig = Rig::tuned(Platform::Mac, |options| { + options.accept = Some(Box::new(move |_, _| if rule.get() { Ok(()) } else { Err("That shortcut is unavailable".into()) })); + }); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + accepted.set(false); + rig.answer("Take It"); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); + let shared = rig.shared.borrow(); + assert!(shared.state.snapshot(&shared.km).unwrap().conflict.is_none()); +} + +#[trial] +fn a_pending_automation_conflict_cannot_be_applied_from_a_read_only_dialog() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap(); + assert!(rig.has("Take It")); + + rig.shared.borrow_mut().options.editable = false; + rig.pass(); + assert!(!rig.has("Take It")); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); + rig.press(Modifiers::NONE, Key::Escape); + assert!(!rig.is_open()); +} + +#[trial] +fn automation_cannot_replace_a_shortcut_while_reset_confirmation_is_open() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+K"})).unwrap(); + rig.click("Reset All…"); + assert!(rig.set_json_field("replace", json!({"old": "Cmd+K", "new": "Cmd+B"})).is_err()); + assert_eq!(rig.bindings("file.save"), ["Cmd+K"]); +} + +#[trial] +fn an_automation_hold_replacement_is_dismissed_when_holds_are_disabled() { + let mut keymap = fixture::keymap(Platform::Mac); + keymap.set_holds(true); + for (command, binding) in [("file.save", "Hold K"), ("file.export", "Hold L")] { + keymap.assign(&CommandRef::from(command), Binding::parse(binding).unwrap(), Policy::Keep).unwrap(); + } + let mut rig = Rig::with_holds(keymap, fixture::options(), HoldSetting::new(true, 0.5, 0.2..=2.0)); + rig.set_json_field("command", json!("file.save")).unwrap(); + let original = rig.bindings("file.save"); + assert!(rig.set_json_field("replace", json!({"old": "Hold K", "new": "Cmd+E"})).is_err()); + rig.set_json_field("replace", json!({"old": "Hold K", "new": "Hold L"})).unwrap(); + assert!(rig.has("Take It")); + + rig.click("Hold Shortcuts"); + assert!(!rig.has("Take It")); + rig.click("Hold Shortcuts"); + assert_eq!(rig.bindings("file.save"), original); +} + +#[trial] +fn automation_does_not_replace_a_binding_while_the_recorder_owns_it() { + let mut rig = Rig::mac(); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.click("Save: ⌘S"); + assert!(rig.shared.borrow().state.is_recording()); + assert!(rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+K"})).is_err()); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + rig.press(Modifiers::COMMAND, Key::L); + assert_eq!(rig.bindings("file.save"), ["Cmd+L"]); + assert!(!rig.shared.borrow().state.is_recording()); +} + +#[trial] +fn automation_rejects_oversize_replacements_but_can_replace_an_oversize_default() { + let scope = "Text".repeat(16); + let original = Binding::in_scope(Trigger::parse("Cmd+S").unwrap(), Scope::new(&scope).unwrap()); + let trigger = "Cmd+Ctrl+Alt+Shift+IntlBackslash Cmd+Ctrl+Alt+Shift+IntlBackslash"; + let oversize = Binding::in_scope(Trigger::parse(trigger).unwrap(), Scope::new(&scope).unwrap()); + let command = CommandDef::new("text.save", "Save Text", Scope::app()).with_default(original.clone()); + let repair = CommandDef::new("text.fix", "Fix Text", Scope::app()).with_default(oversize.clone()).with_default(Binding::parse("Cmd+K").unwrap()); + let export = CommandDef::new("text.export", "Export Text", Scope::app()).with_default(Binding::parse("Cmd+L").unwrap()); + let keymap = Keymap::new(vec![command, repair, export], Scopes::new().with_context(&scope), Platform::Mac); + let mut rig = Rig::new(keymap, fixture::options(), None); + rig.set_json_field("command", json!("text.save")).unwrap(); + + assert!(rig.set_json_field("replace", json!({"old": original.to_string(), "new": trigger})).is_err()); + assert_eq!(rig.bindings("text.save"), [original.to_string()]); + rig.set_json_field("command", json!("text.fix")).unwrap(); + assert!(rig.set_json_field("replace", json!({"old": "Cmd+K", "new": "Cmd+L"})).is_err()); + assert!(!rig.has("Take It")); + assert_eq!(rig.bindings("text.fix"), [oversize.to_string(), "Cmd+K".into()]); + let adjusted = format!("{scope}: Cmd+J"); + rig.set_json_field("replace", json!({"old": oversize.to_string(), "new": "Cmd+J"})).unwrap(); + assert_eq!(rig.bindings("text.fix"), [adjusted.clone(), "Cmd+K".into()]); + rig.set_json_field("replace", json!({"old": adjusted, "new": trigger})).unwrap(); + assert_eq!(rig.bindings("text.fix"), [oversize.to_string(), "Cmd+K".into()]); + assert!(rig.shared.borrow().km.overrides().is_empty()); +} + +#[trial] +fn automation_rejects_a_shortcut_that_would_reload_in_a_different_scope() { + let scope = "Cmd+"; + let original = Binding::in_scope(Trigger::parse("K").unwrap(), Scope::new(scope).unwrap()); + let command = CommandDef::new("text.save", "Save Text", Scope::app()).with_default(original.clone()); + let keymap = Keymap::new(vec![command], Scopes::new().with_context(scope), Platform::Mac); + let mut rig = Rig::new(keymap, fixture::options(), None); + rig.set_json_field("command", json!("text.save")).unwrap(); + assert!(rig.set_json_field("replace", json!({"old": original.to_string(), "new": "Cmd+:"})).is_err()); + assert_eq!(rig.bindings("text.save"), [original.to_string()]); +} + +#[trial] +fn an_automation_replacement_with_the_same_effective_shortcut_is_a_noop() { + let mut rig = Rig::tuned(Platform::Windows, |_| {}); + rig.set_json_field("command", json!("file.save")).unwrap(); + rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Ctrl+S"})).unwrap(); + assert_eq!(rig.bindings("file.save"), ["Cmd+S"]); + let shared = rig.shared.borrow(); + assert!(!shared.state.snapshot(&shared.km).unwrap().can_undo); +} + +#[trial] +fn an_automation_replacement_does_not_offer_to_take_a_shortcut_the_command_already_has() { + let mut keymap = fixture::keymap(Platform::Mac); + let save = CommandRef::from("file.save"); + keymap.assign(&save, Binding::parse("Cmd+E").unwrap(), Policy::Keep).unwrap(); + let mut rig = Rig::new(keymap, fixture::options(), None); + rig.set_json_field("command", json!("file.save")).unwrap(); + let original = rig.bindings("file.save"); + + assert!(rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).is_err()); + assert!(!rig.has("Take It")); + assert_eq!(rig.bindings("file.save"), original); + assert_eq!(rig.bindings("file.export"), ["Cmd+E"]); +} + /// A read-only shortcuts reference does not stretch to the window's height: it opens at a moderate, fixed height and /// scrolls inside it. #[trial] diff --git a/crates/menu/tests/it/shortcuts/tabs.rs b/crates/menu/tests/it/shortcuts/tabs.rs index a1d8022351..2f3dcea838 100644 --- a/crates/menu/tests/it/shortcuts/tabs.rs +++ b/crates/menu/tests/it/shortcuts/tabs.rs @@ -1,5 +1,8 @@ //! The app's pages share the Keyboard Shortcuts dialog's width and navigation. +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + use craft_host::target::Os; use craft_keymap::{Platform, Profiles}; use craft_menu::shortcuts::{Area, DialogState, DialogTab, ShortcutsDialog}; @@ -8,9 +11,42 @@ use craft_ui::contract::Role; use craft_ui::runtime::egui::access::AccessTree; use craft_ui::runtime::env::RootEnv; use craft_ui::testing::{Fixture, Frames, pointer, trial}; +use serde_json::json; use super::fixture; +#[trial] +fn shortcut_replacement_is_unavailable_on_an_app_tab() { + for (tab, app_tab) in [("menus", true), ("unknown", false)] { + let result = Rc::new(RefCell::new(None)); + let observed = result.clone(); + let drawn = Rc::new(Cell::new(false)); + let app_page_drawn = drawn.clone(); + let mut keys = fixture::keymap(Platform::Mac); + let mut state = DialogState::new().with_tab(tab); + let mut fixture = Fixture::new(move |ui| { + let mut tabs = [DialogTab::new("menus", "Menus", |_| { + app_page_drawn.set(true); + false + })]; + if observed.borrow().is_none() { + ShortcutsDialog::new(&mut keys).tabs(&mut tabs).set_json_field(ui, &mut state, "command", &json!("file.save")).unwrap(); + let answer = ShortcutsDialog::new(&mut keys).tabs(&mut tabs).set_json_field( + ui, + &mut state, + "replace", + &json!({"old": "Cmd+S", "new": "Cmd+E"}), + ); + *observed.borrow_mut() = Some(answer); + } + ShortcutsDialog::new(&mut keys).tabs(&mut tabs).show(ui, &mut state); + }); + fixture.settle(); + assert_eq!(drawn.get(), app_tab); + assert_eq!(result.borrow().as_ref().unwrap().is_err(), app_tab); + } +} + fn dialog_at_125_percent(toolbar_label: &str) -> (Frames, impl FnMut(&mut egui::Ui) + '_) { // Use the Windows test context and a 1600 × 1000 physical-pixel window at 125%. let mut os = Fixture::new(|_| {}); diff --git a/crates/menu/tests/it/title_bar.rs b/crates/menu/tests/it/title_bar.rs index 15543e8d97..8c1260f038 100644 --- a/crates/menu/tests/it/title_bar.rs +++ b/crates/menu/tests/it/title_bar.rs @@ -47,19 +47,22 @@ fn window(width: f32, pixels_per_point: f32) -> Fixture { let mut fixture = Fixture::new(move |ui| { let bar = Rc::clone(&bar); AppShell::new(WindowKey::main()) - .title_bar(move |ui, _, _: &mut ()| { - let bar = Rc::clone(&bar); - let layout = craft_window::Layout { left: vec![], right: vec![Caption::Minimize, Caption::Maximize, Caption::Close] }; - TitleBar::new().frame(Frame::Integrated(Captions { family: CaptionFamily::Windows, layout })).show_titled( - ui, - Title::new(DOCUMENT), - move |ui, _| { - Picture::new("", 7, &brand).show(ui); - MenuBarUi::new(&bar).target(Target::Windows).mnemonics(&PREFERRED).help_search(true).show(ui); - }, - |_, _| {}, - ); - }) + .title_bar( + |_| None, + move |ui, _, _: &mut ()| { + let bar = Rc::clone(&bar); + let layout = craft_window::Layout { left: vec![], right: vec![Caption::Minimize, Caption::Maximize, Caption::Close] }; + TitleBar::new().frame(Frame::Integrated(Captions { family: CaptionFamily::Windows, layout })).show_titled( + ui, + Title::new(DOCUMENT), + move |ui, _| { + Picture::new("", 7, &brand).show(ui); + MenuBarUi::new(&bar).target(Target::Windows).mnemonics(&PREFERRED).help_search(true).show(ui); + }, + |_, _| {}, + ); + }, + ) .body(|ui, _, _| { ui.label("Document"); }) diff --git a/crates/mesh-ops/ATTRIBUTION.md b/crates/mesh-ops/ATTRIBUTION.md new file mode 100644 index 0000000000..6e592bafa0 --- /dev/null +++ b/crates/mesh-ops/ATTRIBUTION.md @@ -0,0 +1,32 @@ +# Attribution + +`craft-mesh-ops` generates tangents with the `mikktspace` crate. + +| Package | Authors | Source | License | +|---|---|---|---| +| `mikktspace` 0.3.0 | Benjamin Wasty, David Harvey-Macaulay, Layl Bongers | [crates.io](https://crates.io/crates/mikktspace/0.3.0), [gltf-rs/mikktspace](https://github.com/gltf-rs/mikktspace) | MIT OR Apache-2.0 (the package's `license` field) | + +The package's `src/generated.rs` is a translation of Morten S. Mikkelsen's C implementation of +the MikkTSpace algorithm and carries that implementation's notice, reproduced here unchanged: + +```text +Copyright (C) 2011 by Morten S. Mikkelsen + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not +claim that you wrote the original software. If you use this software +in a product, an acknowledgment in the product documentation would be +appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and must not be +misrepresented as being the original software. + +3. This notice may not be removed or altered from any source distribution. +``` diff --git a/crates/mesh-ops/Cargo.toml b/crates/mesh-ops/Cargo.toml new file mode 100644 index 0000000000..441abc88c1 --- /dev/null +++ b/crates/mesh-ops/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "craft-mesh-ops" +description = "Triangle mesh operations: smooth normals, MikkTSpace tangents, welding, UV unwrapping, a UV-space G-buffer, primitives with UVs, a BVH and an orbit camera" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +glam = { version = "0.30", features = ["serde"] } +# MIT OR Apache-2.0; its src/generated.rs also carries the zlib-style notice of the C original, +# reproduced in ATTRIBUTION.md. +mikktspace = { version = "0.3", default-features = false, features = ["glam"] } +rayon = { workspace = true } +serde = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md new file mode 100644 index 0000000000..db1c866efc --- /dev/null +++ b/crates/mesh-ops/README.md @@ -0,0 +1,54 @@ +# craft-mesh-ops + +Operations on triangle meshes, for apps that paint, bake or preview materials on 3D models. The +crate has no UI, does no file or network I/O and has no `unsafe` code. File formats stay in +[`craft-mesh`](../mesh/README.md). + +- **`Mesh`.** Positions, normals, tangents, UVs, vertex colors, indices, per-material submeshes + and polygon-diagonal flags, with `validate`, `append`, `subdivided`, `normalize_to`, wireframe + and UV-seam edges, and UV-tile helpers. +- **Normals and tangents.** Smooth normals are area weighted. Tangents come from MikkTSpace, which + glTF 2.0 recommends for meshes without tangents + (): `w` holds the bitangent sign. +- **UV unwrapping.** `unwrap::auto_unwrap` makes a non-overlapping layout per material, splitting + vertices where charts meet. It checks the mesh against its size limits and its attribute data + first and returns an error without changing the mesh when a check fails. Charts are projected + and packed in `f64`. Padding uses the + requested resolution, with a minimum resolution of 16. A layout that cannot fit returns an + error without changing the mesh. Missing normals use area-weighted `f64` accumulation and normalization. +- **UV G-buffer.** `UvGBuffer` records, for each texel of one material's UV space, the triangle + and barycentrics under the texel center; `surface_at` turns them into a position, normal and + tangent frame. `UvGBuffer::new` returns an error for a side of 0 or above `MAX_SIDE` (16,384), + for more than `MAX_TEXELS` texels (8,192 × 8,192), when the triangles touch more than + `MAX_BAND_ENTRIES` bands of 32 rows in all, and when the memory cannot be reserved. +- **Primitives.** Sphere, rounded box, cube, cylinder, torus and plane with UVs and tangents, and + the built-in scenes in `primitives::BUILTINS`. `primitives::cube` and `primitives::rounded_box` + return `Result`. They reject non-finite or nonpositive dimensions and dimensions whose + doubled half extents overflow. A box bevel must be finite and between zero and 95% of its + smallest half extent; an invalid bevel returns `GeomError::Invalid`. + Sphere and torus seam endpoints have identical positions and retain distinct UV endpoints. + Cylinder caps share exact rim positions with the side, and rounded-box faces share exact boundary positions. + Lathe profile lengths and direction normalization use `f64` before the UVs and normals are stored as `f32`. +- **BVH.** `Bvh` is a binned SAH tree on all three axes with a median split when no split beats a + leaf. It answers closest-hit, any-hit and filtered ray casts, nearest-point queries and box + queries. +- **Camera.** `OrbitCamera` and `Ray` give an orbit view and picking rays. + +`GeomError::Invalid` is the one error type. `rayon` parallelizes the UV G-buffer, and `serde` +serializes `OrbitCamera`; both are always on. + +## Origin + +| Part | Source | +|---|---| +| `mesh.rs`, `bvh.rs`, `primitives.rs`, `gbuffer.rs`, `unwrap.rs`, `camera.rs` and their tests | TextureCraft `crates/geom` at [386630e](https://github.com/storytold/texturecraft/commit/386630ee85cb22679295b24013575d1aecb39ad2) | +| `Mesh::subdivided` and `subdivision_shares_edge_midpoints` | MaterialCraft `crates/geom/src/mesh.rs` at [3133062](https://github.com/storytold/materialcraft/commit/3133062968b8a1566eda12a357cb06062db16687) | + +MikkTSpace comes from the `mikktspace` crate; its notice is in [ATTRIBUTION.md](ATTRIBUTION.md). + +## Migration + +| App | Status | +|---|---| +| TextureCraft | `texturecraft-geom` is the source. The app switches to this crate in its own pull request. | +| MaterialCraft | `materialcraft-geom` is the source of `subdivided`. The app switches in its own pull request. | diff --git a/crates/mesh-ops/src/bvh.rs b/crates/mesh-ops/src/bvh.rs new file mode 100644 index 0000000000..9b01c84155 --- /dev/null +++ b/crates/mesh-ops/src/bvh.rs @@ -0,0 +1,678 @@ +//! Bounding volume hierarchy over a mesh's triangles: closest-hit and any-hit ray casts, and +//! box queries (used by picking, baking and brush stamps). + +use glam::{Vec3, Vec3A}; + +use crate::Mesh; + +#[derive(Clone, Copy, Debug)] +struct Node { + lo: Vec3A, + hi: Vec3A, + /// Leaf: first triangle in `order`; inner: index of the left child (right = left + 1). + first: u32, + /// Triangles in a leaf; 0 for inner nodes. + count: u32, +} + +/// A ray hit: distance, triangle and barycentrics (weights of vertices 1 and 2). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Hit { + pub t: f32, + pub tri: u32, + pub u: f32, + pub v: f32, +} + +#[derive(Clone, Debug)] +pub struct Bvh { + nodes: Vec, + /// Triangle vertices in BVH order. + tris: Vec<[Vec3; 3]>, + /// Original triangle index of each entry in `tris`. + order: Vec, +} + +const LEAF: usize = 4; + +/// Traversal stack of (node, entry distance): inline for typical depths (no allocation per +/// ray), spilling to the heap for degenerate trees. +struct Stack { + inline: [(u32, f32); 64], + len: usize, + spill: Vec<(u32, f32)>, +} + +impl Default for Stack { + fn default() -> Self { + Stack { inline: [(0, 0.0); 64], len: 0, spill: Vec::new() } + } +} + +impl Stack { + fn push(&mut self, v: (u32, f32)) { + match self.inline.get_mut(self.len) { + Some(slot) if self.spill.is_empty() => { + *slot = v; + self.len += 1; + } + _ => self.spill.push(v), + } + } + + fn pop(&mut self) -> Option<(u32, f32)> { + self.spill.pop().or_else(|| { + self.len = self.len.checked_sub(1)?; + self.inline.get(self.len).copied() + }) + } +} +const BINS: usize = 12; + +fn grow(lo: &mut Vec3, hi: &mut Vec3, p: Vec3) { + *lo = lo.min(p); + *hi = hi.max(p); +} + +fn area(lo: Vec3, hi: Vec3) -> f32 { + let d = (hi - lo).max(Vec3::ZERO); + d.x * d.y + d.y * d.z + d.z * d.x +} + +impl Bvh { + pub fn new(mesh: &Mesh) -> Bvh { + let triangle_count = mesh.triangle_count(); + let mut tris = Vec::with_capacity(triangle_count); + + for triangle in 0..triangle_count { + let Some([a, b, c]) = mesh.tri(triangle) else { continue }; + let position = |i: usize| mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO); + tris.push([position(a), position(b), position(c)]); + } + + let mut order: Vec = (0..tris.len() as u32).collect(); + let centroids: Vec = tris.iter().map(|t| (t[0] + t[1] + t[2]) / 3.0).collect(); + + let mut nodes = vec![Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first: 0, count: tris.len() as u32 }]; + let mut stack = vec![0usize]; + + while let Some(node_index) = stack.pop() { + let Node { first, count, .. } = nodes[node_index]; + let (start, count) = (first as usize, count as usize); + let (mut bounds_min, mut bounds_max) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)); + let (mut centroid_min, mut centroid_max) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)); + + for &triangle in &order[start..start + count] { + for position in tris[triangle as usize] { + grow(&mut bounds_min, &mut bounds_max, position); + } + grow(&mut centroid_min, &mut centroid_max, centroids[triangle as usize]); + } + + nodes[node_index].lo = bounds_min.into(); + nodes[node_index].hi = bounds_max.into(); + + if count <= LEAF { + continue; + } + + let centroid_extent = centroid_max - centroid_min; + let bin_of = |triangle: u32, axis: usize| { + let offset = centroids[triangle as usize][axis] - centroid_min[axis]; + ((offset / centroid_extent[axis] * BINS as f32) as usize).min(BINS - 1) + }; + + // Reuse each triangle's bounds across all three axes + let mut axis_bins = [[(0u32, Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)); BINS]; 3]; + + for &triangle in &order[start..start + count] { + let [a, b, c] = tris[triangle as usize]; + let (triangle_min, triangle_max) = (a.min(b).min(c), a.max(b).max(c)); + + for axis in 0..3 { + if centroid_extent[axis] <= 1e-12 { + continue; + } + + let bin = &mut axis_bins[axis][bin_of(triangle, axis)]; + bin.0 += 1; + bin.1 = bin.1.min(triangle_min); + bin.2 = bin.2.max(triangle_max); + } + } + + let mut best_axis = 0; + let mut best_split = 0; + let mut best_cost = f32::MAX; + + for axis in 0..3 { + if centroid_extent[axis] <= 1e-12 { + continue; + } + + let bins = axis_bins[axis]; + + // Cache right bounds once and advance the left bounds per split + let mut suffix = bins; + for i in (0..BINS - 1).rev() { + suffix[i] = (suffix[i].0 + suffix[i + 1].0, suffix[i].1.min(suffix[i + 1].1), suffix[i].2.max(suffix[i + 1].2)); + } + + let (mut left_count, mut left_min, mut left_max) = (0u32, Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)); + + for split in 1..BINS { + let bin = bins[split - 1]; + left_count += bin.0; + left_min = left_min.min(bin.1); + left_max = left_max.max(bin.2); + + let (right_count, right_min, right_max) = suffix[split]; + if left_count == 0 || right_count == 0 { + continue; + } + + let cost = left_count as f32 * area(left_min, left_max) + right_count as f32 * area(right_min, right_max); + if cost < best_cost { + best_cost = cost; + best_axis = axis; + best_split = split; + } + } + } + + let node_order = &mut order[start..start + count]; + let left_count = if best_split == 0 || best_cost >= count as f32 * area(bounds_min, bounds_max) { + // Split by count when SAH cannot help, including tied centroids + let axis = if centroid_extent.x >= centroid_extent.y && centroid_extent.x >= centroid_extent.z { + 0 + } else if centroid_extent.y >= centroid_extent.z { + 1 + } else { + 2 + }; + + let mid = count / 2; + node_order.select_nth_unstable_by(mid, |&a, &b| centroids[a as usize][axis].total_cmp(¢roids[b as usize][axis])); + mid + } else { + let mut left_count = 0; + + for i in 0..node_order.len() { + if bin_of(node_order[i], best_axis) < best_split { + node_order.swap(left_count, i); + left_count += 1; + } + } + + left_count + }; + + if left_count == 0 || left_count == count { + continue; + } + + let left_child = nodes.len(); + nodes.push(Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first, count: left_count as u32 }); + nodes.push(Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first: first + left_count as u32, count: (count - left_count) as u32 }); + + nodes[node_index].first = left_child as u32; + nodes[node_index].count = 0; + + stack.push(left_child); + stack.push(left_child + 1); + } + + let tris = order.iter().map(|t| tris[*t as usize]).collect(); + Bvh { nodes, tris, order } + } + + pub fn is_empty(&self) -> bool { + self.tris.is_empty() + } + + /// The flattened tree (for GPU traversal), root first: bounds, then for a leaf the range + /// `first..first + count` of [`Bvh::triangles`], for an inner node (`count` 0) the children + /// `first` and `first + 1`. + pub fn nodes(&self) -> impl ExactSizeIterator + '_ { + self.nodes.iter().map(|n| (n.lo.into(), n.hi.into(), n.first, n.count)) + } + + /// Triangle vertices in BVH order, and the original triangle index of each. + pub fn triangles(&self) -> (&[[Vec3; 3]], &[u32]) { + (&self.tris, &self.order) + } + + fn slab(lo: Vec3A, hi: Vec3A, o: Vec3A, inv: Vec3A, tmax: f32) -> Option { + let t0 = (lo - o) * inv; + let t1 = (hi - o) * inv; + // A ray lying in a slab plane gives 0·∞ = NaN: it is inside that slab, so the axis does + // not bound the hit. + let open = t0.is_nan_mask() | t1.is_nan_mask(); + let tn = Vec3A::select(open, Vec3A::NEG_INFINITY, t0.min(t1)).max_element().max(0.0); + let tf = Vec3A::select(open, Vec3A::INFINITY, t0.max(t1)).min_element().min(tmax); + (tn <= tf).then_some(tn) + } + + /// Möller–Trumbore, double sided. + fn hit_tri(t: &[Vec3; 3], o: Vec3, d: Vec3) -> Option<(f32, f32, f32)> { + let e1 = t[1] - t[0]; + let e2 = t[2] - t[0]; + let p = d.cross(e2); + let det = e1.dot(p); + if det.abs() < 1e-12 { + return None; + } + let inv = 1.0 / det; + let s = o - t[0]; + // A little slack on the edges: rays through a shared edge must not slip between its + // two triangles to a surface behind. + const EDGE: f32 = 1e-5; + let u = s.dot(p) * inv; + if !(-EDGE..=1.0 + EDGE).contains(&u) { + return None; + } + let q = s.cross(e1); + let v = d.dot(q) * inv; + if v < -EDGE || u + v > 1.0 + EDGE { + return None; + } + let tt = e2.dot(q) * inv; + (tt > 0.0).then_some((tt, u, v)) + } + + fn traverse(&self, o: Vec3, d: Vec3, mut tmax: f32, any: bool, filter: &dyn Fn(u32) -> bool) -> Option { + let root = self.nodes.first().filter(|_| !self.tris.is_empty())?; + let (oa, inv) = (Vec3A::from(o), Vec3A::ONE / Vec3A::from(d)); + let mut best = None; + let mut stack = Stack::default(); + stack.push((0, Self::slab(root.lo, root.hi, oa, inv, tmax)?)); + // Entries carry their entry distance: nodes behind a closer hit are skipped unopened. + while let Some((ni, tn)) = stack.pop() { + let Some(n) = self.nodes.get(ni as usize).filter(|_| tn <= tmax) else { continue }; + if n.count > 0 { + let (f, c) = (n.first as usize, n.count as usize); + for i in f..(f + c).min(self.tris.len()) { + let (Some(tri), Some(&orig)) = (self.tris.get(i), self.order.get(i)) else { continue }; + if let Some((t, u, v)) = Self::hit_tri(tri, o, d) + && t < tmax + && filter(orig) + { + tmax = t; + best = Some(Hit { t, tri: orig, u, v }); + if any { + return best; + } + } + } + } else { + // Visit the nearer child first. + let (l, r) = (n.first, n.first + 1); + let dl = self.nodes.get(l as usize).and_then(|c| Self::slab(c.lo, c.hi, oa, inv, tmax)); + let dr = self.nodes.get(r as usize).and_then(|c| Self::slab(c.lo, c.hi, oa, inv, tmax)); + match (dl, dr) { + (Some(a), Some(b)) if a <= b => { + stack.push((r, b)); + stack.push((l, a)); + } + (Some(a), Some(b)) => { + stack.push((l, a)); + stack.push((r, b)); + } + (Some(a), None) => stack.push((l, a)), + (None, Some(b)) => stack.push((r, b)), + (None, None) => {} + } + } + } + best + } + + /// Closest hit along `o + t·d` for `t` in (0, tmax). + pub fn closest(&self, o: Vec3, d: Vec3, tmax: f32) -> Option { + self.traverse(o, d, tmax, false, &|_| true) + } + + /// Closest hit on triangles accepted by `filter` (original triangle index). + pub fn closest_filtered(&self, o: Vec3, d: Vec3, tmax: f32, filter: &dyn Fn(u32) -> bool) -> Option { + self.traverse(o, d, tmax, false, filter) + } + + /// Whether anything is hit before `tmax` (occlusion rays). + pub fn occluded(&self, o: Vec3, d: Vec3, tmax: f32) -> bool { + self.traverse(o, d, tmax, true, &|_| true).is_some() + } + + /// The point nearest to `p` within `max_dist` on a triangle accepted by `filter` (original + /// index): a [`Hit`] with the distance in `t` and the barycentrics of vertices 1 and 2. + pub fn nearest(&self, p: Vec3, max_dist: f32, filter: &dyn Fn(u32) -> bool) -> Option { + let root = self.nodes.first().filter(|_| !self.tris.is_empty() && p.is_finite())?; + let pa = Vec3A::from(p); + let box_d2 = |n: &Node| (n.lo - pa).max(pa - n.hi).max(Vec3A::ZERO).length_squared(); + let (mut best_d2, mut best) = (max_dist * max_dist, None); + let mut stack = Stack::default(); + stack.push((0, box_d2(root))); + while let Some((ni, d2)) = stack.pop() { + let Some(n) = self.nodes.get(ni as usize).filter(|_| d2 <= best_d2) else { continue }; + if n.count > 0 { + for i in n.first as usize..(n.first as usize + n.count as usize).min(self.tris.len()) { + let (Some(tri), Some(&orig)) = (self.tris.get(i), self.order.get(i)) else { continue }; + if !filter(orig) { + continue; + } + let (q, u, v) = closest_on_triangle(p, tri); + let dd = (q - p).length_squared(); + if dd < best_d2 { + best_d2 = dd; + best = Some(Hit { t: dd.sqrt(), tri: orig, u, v }); + } + } + } else { + // Push the farther child first so the nearer one is searched first. + let child = |c: u32| self.nodes.get(c as usize).map(|n| (c, box_d2(n))); + let (Some(l), Some(r)) = (child(n.first), child(n.first + 1)) else { continue }; + let (near, far) = if l.1 <= r.1 { (l, r) } else { (r, l) }; + stack.push(far); + stack.push(near); + } + } + best + } + + /// Call `f` with every triangle (original index) whose bounds overlap the box. + pub fn query_box(&self, lo: Vec3, hi: Vec3, mut f: impl FnMut(u32)) { + let mut stack = vec![0u32]; + while let Some(i) = stack.pop() { + let Some(n) = self.nodes.get(i as usize) else { continue }; + if self.tris.is_empty() || n.hi.cmplt(lo.into()).any() || n.lo.cmpgt(hi.into()).any() { + continue; + } + if n.count > 0 { + for k in n.first as usize..(n.first + n.count) as usize { + let (Some(t), Some(o)) = (self.tris.get(k), self.order.get(k)) else { continue }; + let tlo = t[0].min(t[1]).min(t[2]); + let thi = t[0].max(t[1]).max(t[2]); + if !(thi.cmplt(lo).any() || tlo.cmpgt(hi).any()) { + f(*o); + } + } + } else { + stack.push(n.first); + stack.push(n.first + 1); + } + } + } +} + +/// The point of triangle `t` nearest to `p` and its barycentrics (weights of vertices 1 and 2), +/// by Voronoi region (Ericson, Real-Time Collision Detection, 5.1.5). Degenerate triangles give +/// a non-finite distance and are never nearest. +fn closest_on_triangle(p: Vec3, t: &[Vec3; 3]) -> (Vec3, f32, f32) { + let [a, b, c] = *t; + let (ab, ac, ap) = (b - a, c - a, p - a); + let (d1, d2) = (ab.dot(ap), ac.dot(ap)); + if d1 <= 0.0 && d2 <= 0.0 { + return (a, 0.0, 0.0); + } + let bp = p - b; + let (d3, d4) = (ab.dot(bp), ac.dot(bp)); + if d3 >= 0.0 && d4 <= d3 { + return (b, 1.0, 0.0); + } + let vc = d1 * d4 - d3 * d2; + if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 { + let v = d1 / (d1 - d3); + return (a + ab * v, v, 0.0); + } + let cp = p - c; + let (d5, d6) = (ab.dot(cp), ac.dot(cp)); + if d6 >= 0.0 && d5 <= d6 { + return (c, 0.0, 1.0); + } + let vb = d5 * d2 - d1 * d6; + if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 { + let w = d2 / (d2 - d6); + return (a + ac * w, 0.0, w); + } + let va = d3 * d6 - d5 * d4; + if va <= 0.0 && d4 - d3 >= 0.0 && d5 - d6 >= 0.0 { + let w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); + return (b + (c - b) * w, 1.0 - w, w); + } + let denom = 1.0 / (va + vb + vc); + let (v, w) = (vb * denom, vc * denom); + (a + ab * v + ac * w, v, w) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::primitives; + + #[test] + fn nearest_point_matches_brute_force() { + let m = primitives::builtin("torus").unwrap(); + let bvh = Bvh::new(&m); + let mut seed = 7u32; + let mut rnd = move || { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 8) as f32 / (1u32 << 24) as f32 * 4.0 - 2.0 + }; + for _ in 0..200 { + let p = Vec3::new(rnd(), rnd(), rnd()); + let hit = bvh.nearest(p, f32::MAX, &|_| true).unwrap(); + let brute = (0..m.triangle_count()) + .map(|t| { + let [a, b, c] = m.tri(t).unwrap().map(|i| m.positions[i]); + (closest_on_triangle(p, &[a, b, c]).0 - p).length() + }) + .fold(f32::MAX, f32::min); + assert!((hit.t - brute).abs() < 1e-5, "{} vs {brute}", hit.t); + let [a, b, c] = m.tri(hit.tri as usize).unwrap().map(|i| m.positions[i]); + let q = a * (1.0 - hit.u - hit.v) + b * hit.u + c * hit.v; + assert!(((q - p).length() - hit.t).abs() < 1e-4); + } + assert!(bvh.nearest(Vec3::splat(100.0), 1.0, &|_| true).is_none(), "out of range"); + assert!(bvh.nearest(Vec3::ZERO, f32::MAX, &|_| false).is_none(), "filtered out"); + } + + #[test] + fn traversal_stack_spills_in_lifo_order() { + let mut st = Stack::default(); + for v in 0..200 { + st.push((v, v as f32)); + } + assert!((0..200).rev().all(|v| st.pop() == Some((v, v as f32)))); + assert_eq!(st.pop(), None); + } + + #[test] + fn ray_hits_sphere_at_expected_distance() { + let m = primitives::sphere(1.0, 64, 32); + let bvh = Bvh::new(&m); + let h = bvh.closest(Vec3::new(0.0, 0.0, 5.0), Vec3::NEG_Z, 100.0).unwrap(); + assert!((h.t - 4.0).abs() < 0.01, "{}", h.t); + assert!(bvh.closest(Vec3::new(0.0, 3.0, 5.0), Vec3::NEG_Z, 100.0).is_none()); + // Rays lying exactly in a node's bounding plane (y = 0 is the equator) hit the front. + // Axis-aligned rays lying in a node's bounding plane (y = 0) still find the front. + for x in [-0.5f32, -0.4, 0.3] { + let h = bvh.closest(Vec3::new(x, 0.0, 5.0), Vec3::NEG_Z, 100.0).unwrap(); + assert!(h.t < 5.0, "x {x}: hit the back at t {}", h.t); + } + // Rays through shared edges (the equator) hit the front, never slip through to the back. + let m = primitives::sphere(1.0, 48, 24); + let bvh = Bvh::new(&m); + for i in 0..200 { + let x = i as f32 / 100.0 - 1.0; + let o = Vec3::new(0.0, 0.0, 5.0); + let d = (Vec3::new(x * 0.9, 0.0, 0.0) - o).normalize(); + let h = bvh.closest(o, d, 100.0).unwrap(); + assert!(h.t < 5.0, "x {x}: hit the back at t {}", h.t); + } + assert!(bvh.occluded(Vec3::new(0.0, 0.0, 5.0), Vec3::NEG_Z, 10.0)); + assert!(!bvh.occluded(Vec3::new(0.0, 0.0, 5.0), Vec3::NEG_Z, 3.0)); + } + + #[test] + fn matches_brute_force() { + let m = primitives::material_ball(); + let bvh = Bvh::new(&m); + for i in 0..200 { + let a = i as f32 * 0.731; + let o = Vec3::new(a.cos() * 6.0, (i as f32 * 0.37).sin() * 3.0 + 1.0, a.sin() * 6.0); + let d = (Vec3::new(0.0, 1.0, 0.0) + Vec3::new((a * 3.1).sin(), (a * 1.7).cos(), (a * 2.3).sin()) * 0.6 - o).normalize(); + let fast = bvh.closest(o, d, 1e9).map(|h| h.t); + let mut slow: Option = None; + for t in 0..m.triangle_count() { + let [x, y, z] = m.tri(t).unwrap(); + if let Some((tt, _, _)) = Bvh::hit_tri(&[m.positions[x], m.positions[y], m.positions[z]], o, d) { + slow = Some(slow.map_or(tt, |s: f32| s.min(tt))); + } + } + match (fast, slow) { + (Some(a), Some(b)) => assert!((a - b).abs() < 1e-4, "{a} {b}"), + (None, None) => {} + other => panic!("mismatch {other:?}"), + } + } + } + + #[test] + fn box_query_finds_overlapping_triangles() { + let m = primitives::plane(2.0, 4); + let bvh = Bvh::new(&m); + let mut found = Vec::new(); + bvh.query_box(Vec3::new(-0.1, -0.1, -0.1), Vec3::new(0.1, 0.1, 0.1), |t| found.push(t)); + assert!(!found.is_empty() && found.len() <= 8, "{found:?}"); + let empty = Bvh::new(&Mesh::default()); + assert!(empty.closest(Vec3::ZERO, Vec3::X, 1.0).is_none()); + } + + #[test] + fn large_coplanar_plate_does_not_degrade_leaf_sizes() { + let mut positions = Vec::new(); + let mut indices = Vec::new(); + let w = 200.0f32; + let h = 100.0f32; + + // Large plate at z = 0 + let b = positions.len() as u32; + positions.extend_from_slice(&[Vec3::new(0.0, 0.0, 0.0), Vec3::new(w, 0.0, 0.0), Vec3::new(w, h, 0.0), Vec3::new(0.0, h, 0.0)]); + indices.extend_from_slice(&[b, b + 1, b + 2, b, b + 2, b + 3]); + + // 500 small triangles sitting at z = 0.5 + for i in 0..500 { + let x = 20.0 + (i % 160) as f32; + let y = 10.0 + ((i / 160) % 80) as f32; + let idx = positions.len() as u32; + positions.push(Vec3::new(x, y, 0.5)); + positions.push(Vec3::new(x + 0.5, y, 0.5)); + positions.push(Vec3::new(x, y + 0.5, 0.6)); + indices.extend_from_slice(&[idx, idx + 1, idx + 2]); + } + + let mesh = Mesh { + positions, + normals: Vec::new(), + uvs: Vec::new(), + indices, + tangents: Vec::new(), + colors: Vec::new(), + submeshes: Vec::new(), + materials: Vec::new(), + diagonals: Vec::new(), + }; + + let bvh = Bvh::new(&mesh); + + for (_, _, _, count) in bvh.nodes() { + if count > 0 { + assert!(count <= LEAF as u32, "leaf has too many triangles: {count}"); + } + } + + // The foreground triangle is the closest hit + let hit = bvh.closest(Vec3::new(20.1, 10.1, 10.0), Vec3::NEG_Z, 100.0).unwrap(); + assert!((hit.t - 9.5).abs() < 0.1, "hit t: {}", hit.t); + } + + #[test] + fn clustered_coplanar_fallback_partitions_nodes() { + let mut positions = Vec::new(); + let mut indices = Vec::new(); + let w = 200.0f32; + let h = 100.0f32; + + let b = positions.len() as u32; + positions.extend_from_slice(&[Vec3::new(0.0, 0.0, 0.0), Vec3::new(w, 0.0, 0.0), Vec3::new(w, h, 0.0), Vec3::new(0.0, h, 0.0)]); + indices.extend_from_slice(&[b, b + 1, b + 2, b, b + 2, b + 3]); + + // Shared bins keep every SAH split as costly as an unsplit leaf + for i in 0..500 { + let x = 130.0 + (i % 10) as f32 * 0.1; + let y = 64.0 + (i / 10) as f32 * 0.02; + let idx = positions.len() as u32; + positions.push(Vec3::new(x, y, 0.0)); + positions.push(Vec3::new(x + 0.01, y, 0.0)); + positions.push(Vec3::new(x, y + 0.01, 0.0)); + indices.extend_from_slice(&[idx, idx + 1, idx + 2]); + } + + let mesh = Mesh { + positions, + normals: Vec::new(), + uvs: Vec::new(), + indices, + tangents: Vec::new(), + colors: Vec::new(), + submeshes: Vec::new(), + materials: Vec::new(), + diagonals: Vec::new(), + }; + + let bvh = Bvh::new(&mesh); + + for (_, _, _, count) in bvh.nodes() { + if count > 0 { + assert!(count <= LEAF as u32, "leaf has too many triangles: {count}"); + } + } + } + + #[test] + fn coincident_centroids_still_partition_large_and_small_triangles() { + let mut mesh = Mesh::default(); + + // Different triangle sizes share an exact centroid + for i in 0..=500 { + let size = if i == 0 { 100.0 } else { 0.01 + i as f32 * 0.0001 }; + let first = mesh.positions.len() as u32; + mesh.positions.extend([Vec3::new(-size, -size, 0.0), Vec3::new(size, -size, 0.0), Vec3::new(0.0, 2.0 * size, 0.0)]); + mesh.indices.extend([first, first + 1, first + 2]); + } + + mesh.normals.resize(mesh.positions.len(), Vec3::Z); + mesh.uvs.resize(mesh.positions.len(), glam::Vec2::ZERO); + mesh.tangents.resize(mesh.positions.len(), glam::Vec4::new(1.0, 0.0, 0.0, 1.0)); + mesh.validate().unwrap(); + + let bvh = Bvh::new(&mesh); + + for (_, _, _, count) in bvh.nodes() { + assert!(count <= LEAF as u32, "leaf has too many triangles: {count}"); + } + + // The outer ray only hits the large triangle + let origin = Vec3::new(50.0, 0.0, 10.0); + let hit = bvh.closest(origin, Vec3::NEG_Z, 100.0).unwrap(); + assert_eq!(hit.tri, 0); + assert_eq!(hit.t, 10.0); + + assert!(bvh.occluded(origin, Vec3::NEG_Z, 100.0)); + assert!(!bvh.occluded(origin, Vec3::NEG_Z, 5.0)); + + // Median partitions preserve original triangle IDs + let hit = bvh.closest_filtered(Vec3::new(0.0, 0.0, 10.0), Vec3::NEG_Z, 100.0, &|t| t == 500).unwrap(); + assert_eq!(hit.tri, 500); + assert_eq!(hit.t, 10.0); + } +} diff --git a/crates/mesh-ops/src/camera.rs b/crates/mesh-ops/src/camera.rs new file mode 100644 index 0000000000..1f4156c93e --- /dev/null +++ b/crates/mesh-ops/src/camera.rs @@ -0,0 +1,140 @@ +//! Orbit camera (texture painting navigation) and picking rays. + +use glam::{Mat4, Vec2, Vec3, Vec4}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct OrbitCamera { + pub target: Vec3, + /// Radians around Y. + pub yaw: f32, + /// Radians above the horizon, clamped to ±89°. + pub pitch: f32, + pub distance: f32, + /// Vertical field of view, degrees. + pub fov: f32, + /// Scene radius (sets the clip planes). + pub scene_radius: f32, + /// Orthographic projection instead of perspective. + #[serde(default)] + pub ortho: bool, +} + +impl Default for OrbitCamera { + fn default() -> Self { + OrbitCamera { target: Vec3::ZERO, yaw: 0.0, pitch: 0.12, distance: 5.0, fov: 40.0, scene_radius: 1.0, ortho: false } + } +} + +/// A ray in world space. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Ray { + pub origin: Vec3, + pub dir: Vec3, +} + +impl OrbitCamera { + pub fn eye(&self) -> Vec3 { + let (sy, cy) = self.yaw.sin_cos(); + let (sp, cp) = self.pitch.sin_cos(); + self.target + Vec3::new(cp * sy, sp, cp * cy) * self.distance + } + + pub fn forward(&self) -> Vec3 { + (self.target - self.eye()).try_normalize().unwrap_or(Vec3::NEG_Z) + } + + pub fn view(&self) -> Mat4 { + Mat4::look_at_rh(self.eye(), self.target, Vec3::Y) + } + + pub fn proj(&self, aspect: f32) -> Mat4 { + let r = self.scene_radius.max(1e-3); + let near = (self.distance - r * 4.0).max(r * 0.01).max(1e-4); + let far = self.distance + r * 50.0; + let aspect = if aspect.is_finite() && aspect > 1e-4 { aspect } else { 1.0 }; + if self.ortho { + let h = self.distance * (self.fov.to_radians() * 0.5).tan(); + Mat4::orthographic_rh(-h * aspect, h * aspect, -h, h, near.min(0.01), far) + } else { + Mat4::perspective_rh(self.fov.clamp(5.0, 150.0).to_radians(), aspect, near, far) + } + } + + pub fn view_proj(&self, aspect: f32) -> Mat4 { + self.proj(aspect) * self.view() + } + + /// Frame a bounding box, keeping the current angles. + pub fn frame(&mut self, lo: Vec3, hi: Vec3) { + self.target = (lo + hi) * 0.5; + let r = ((hi - lo).length() * 0.5).max(1e-3); + self.scene_radius = r; + self.distance = r / (self.fov.clamp(5.0, 150.0).to_radians() * 0.5).sin() * 1.1; + } + + pub fn orbit(&mut self, dx: f32, dy: f32) { + self.yaw -= dx; + self.pitch = (self.pitch + dy).clamp(-89f32.to_radians(), 89f32.to_radians()); + } + + /// Pan by a screen fraction (dx, dy in viewport heights). + pub fn pan(&mut self, dx: f32, dy: f32) { + let f = self.forward(); + let right = f.cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X); + let up = right.cross(f); + let scale = self.distance * (self.fov.to_radians() * 0.5).tan() * 2.0; + self.target += (-right * dx + up * dy) * scale; + } + + /// Dolly by a factor exponent (positive zooms in). + pub fn zoom(&mut self, amount: f32) { + let r = self.scene_radius.max(1e-3); + self.distance = (self.distance * (-amount).exp()).clamp(r * 0.05, r * 200.0); + } + + /// Ray through a viewport point given in normalized device coordinates (-1..1, y up). + pub fn ray(&self, ndc: Vec2, aspect: f32) -> Ray { + let inv = self.view_proj(aspect).inverse(); + let a = inv * Vec4::new(ndc.x, ndc.y, 0.0, 1.0); + let b = inv * Vec4::new(ndc.x, ndc.y, 1.0, 1.0); + let (a, b) = (a.truncate() / a.w, b.truncate() / b.w); + Ray { origin: a, dir: (b - a).try_normalize().unwrap_or(self.forward()) } + } + + /// Project a world point to NDC (x, y in -1..1, y up; z depth). None behind the camera. + pub fn project(&self, p: Vec3, aspect: f32) -> Option { + let c = self.view_proj(aspect) * p.extend(1.0); + (c.w > 1e-6).then(|| c.truncate() / c.w) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn center_ray_points_at_target_and_projection_inverts() { + let mut c = OrbitCamera::default(); + c.frame(Vec3::splat(-1.0), Vec3::splat(1.0)); + let r = c.ray(Vec2::ZERO, 1.5); + assert!((r.dir - c.forward()).length() < 1e-4); + let p = Vec3::new(0.3, -0.2, 0.1); + let ndc = c.project(p, 1.5).unwrap(); + let r = c.ray(ndc.truncate(), 1.5); + let to_p = (p - r.origin).normalize(); + assert!(to_p.dot(r.dir) > 0.9999); + } + + #[test] + fn pitch_is_clamped_and_zoom_bounded() { + let mut c = OrbitCamera::default(); + c.orbit(0.0, 10.0); + assert!(c.pitch <= 89f32.to_radians() + 1e-6); + for _ in 0..1000 { + c.zoom(1.0); + } + assert!(c.distance > 0.0 && c.distance.is_finite()); + let _ = c.proj(f32::NAN); + } +} diff --git a/crates/mesh-ops/src/gbuffer.rs b/crates/mesh-ops/src/gbuffer.rs new file mode 100644 index 0000000000..59757f0462 --- /dev/null +++ b/crates/mesh-ops/src/gbuffer.rs @@ -0,0 +1,309 @@ +//! The UV-space G-buffer: which triangle (and where on it) each texel of a texture set maps +//! to. Painting, compositing, baking and padding all work from this one buffer, so they agree +//! on which texel is which surface point. + +use glam::{Vec2, Vec3, Vec4}; +use rayon::prelude::*; + +use crate::{GeomError, Mesh, Result}; + +/// Texel not covered by any triangle. +pub const NO_TRI: u32 = u32::MAX; + +const BAND: u32 = 32; + +/// Largest width or height of a G-buffer, in texels. +pub const MAX_SIDE: u32 = 16_384; + +/// Largest texel count of a G-buffer (8,192 × 8,192). Each texel takes 12 bytes, so a full +/// buffer takes 768 MiB and its largest vector (`bary`) 512 MiB, which fits a 32-bit address +/// space. +pub const MAX_TEXELS: usize = 1 << 26; + +/// Largest number of (triangle, band of 32 rows) pairs a G-buffer bins before rasterizing: a +/// triangle counts once for every band it touches. The bins take 4 bytes per entry, 512 MiB at +/// most. +pub const MAX_BAND_ENTRIES: usize = 1 << 27; + +#[derive(Clone, Debug, PartialEq)] +pub struct UvGBuffer { + pub width: u32, + pub height: u32, + /// Triangle under each texel center, [`NO_TRI`] when uncovered. + pub tri: Vec, + /// Barycentric weights of the triangle's second and third vertices. + pub bary: Vec<[f32; 2]>, + /// Texels written by more than one triangle (overlapping UVs). + pub overlaps: u32, +} + +/// Interpolated surface attributes at a texel. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Surface { + pub pos: Vec3, + /// Interpolated shading normal (normalized). + pub nrm: Vec3, + /// Flat triangle normal (for ray offsets). + pub geo_nrm: Vec3, + pub tangent: Vec4, + pub uv: Vec2, + pub tri: u32, +} + +/// Checks a requested G-buffer size against [`MAX_SIDE`] and [`MAX_TEXELS`] and returns its +/// texel count. +fn checked_texels(width: u32, height: u32) -> Result { + for (name, side) in [("width", width), ("height", height)] { + if side == 0 || side > MAX_SIDE { + return Err(GeomError::Invalid(format!("G-buffer {name} {side} is outside 1..={MAX_SIDE}"))); + } + } + // Both sides are at most MAX_SIDE, so the product fits in usize on 32-bit targets too. + let n = width as usize * height as usize; + if n > MAX_TEXELS { + return Err(GeomError::Invalid(format!("G-buffer {width}×{height} has more than {MAX_TEXELS} texels"))); + } + Ok(n) +} + +/// A vector of `n` copies of `value`, or an error when the memory cannot be reserved. +fn filled(n: usize, value: T) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(n).map_err(|e| GeomError::Invalid(format!("G-buffer of {n} texels: {e}")))?; + v.resize(n, value); + Ok(v) +} + +fn edge(a: Vec2, b: Vec2, p: Vec2) -> f32 { + (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x) +} + +impl UvGBuffer { + /// Rasterize the triangles of material `material` at `width × height`. + /// + /// Returns an error when `width` or `height` is 0 or above [`MAX_SIDE`], when + /// `width × height` is above [`MAX_TEXELS`], when the triangles touch more than + /// [`MAX_BAND_ENTRIES`] bands of 32 rows in all, or when the memory cannot be reserved. + pub fn new(mesh: &Mesh, material: usize, width: u32, height: u32) -> Result { + let n = checked_texels(width, height)?; + let (w, h) = (width, height); + let size = Vec2::new(w as f32, h as f32); + let bands = h.div_ceil(BAND) as usize; + let span = |t: usize| -> Option<(usize, usize)> { + let [a, b, c] = mesh.tri(t)?; + let (ua, ub, uc) = (mesh.uvs.get(a)?, mesh.uvs.get(b)?, mesh.uvs.get(c)?); + let y0 = (ua.y.min(ub.y).min(uc.y) * size.y).floor().max(0.0) as i64; + let y1 = (ua.y.max(ub.y).max(uc.y) * size.y).ceil().min(size.y) as i64; + if y1 <= y0 || !ua.is_finite() || !ub.is_finite() || !uc.is_finite() { + return None; + } + Some(((y0 / BAND as i64) as usize, ((y1 - 1).max(0) / BAND as i64) as usize)) + }; + // The triangles of each band, in mesh order, as one list: band `i` holds + // `bins[start[i]..start[i + 1]]`. A counting pass sizes the list before it is reserved. + let mut start = vec![0usize; bands + 1]; + for t in mesh.triangles_of(material) { + let Some((b0, b1)) = span(t) else { continue }; + for s in start.iter_mut().skip(b0 + 1).take(b1 + 1 - b0) { + *s += 1; + } + } + for i in 1..start.len() { + start[i] = start[i].saturating_add(start[i - 1]); + } + let entries = start.last().copied().unwrap_or(0); + if entries > MAX_BAND_ENTRIES { + return Err(GeomError::Invalid(format!("G-buffer triangles touch {entries} bands in all, more than {MAX_BAND_ENTRIES}"))); + } + let mut bins = filled(entries, 0u32)?; + let mut next = start.clone(); + for t in mesh.triangles_of(material) { + let Some((b0, b1)) = span(t) else { continue }; + for k in next.iter_mut().take(b1 + 1).skip(b0) { + if let Some(slot) = bins.get_mut(*k) { + *slot = t as u32; + } + *k += 1; + } + } + let mut tri = filled(n, NO_TRI)?; + let mut bary = filled(n, [0.0f32; 2])?; + let band_len = BAND as usize * w as usize; + let overlaps: u32 = tri + .par_chunks_mut(band_len) + .zip(bary.par_chunks_mut(band_len)) + .enumerate() + .map(|(bi, (tri, bary))| { + let mut overlaps = 0u32; + let row0 = bi as u32 * BAND; + let rows = (tri.len() as u32) / w; + let band = match (start.get(bi), start.get(bi + 1)) { + (Some(&s), Some(&e)) => bins.get(s..e).unwrap_or(&[]), + _ => &[], + }; + for &t in band { + let Some([a, b, c]) = mesh.tri(t as usize) else { continue }; + let (Some(&ua), Some(&ub), Some(&uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue }; + let (pa, pb, pc) = (ua * size, ub * size, uc * size); + let area = edge(pa, pb, pc); + if area.abs() < 1e-12 { + continue; + } + let eps = -1e-6 * area.abs(); + let x0 = pa.x.min(pb.x).min(pc.x).floor().max(0.0) as u32; + let x1 = (pa.x.max(pb.x).max(pc.x).ceil().min(w as f32) as u32).min(w); + let y0 = (pa.y.min(pb.y).min(pc.y).floor().max(row0 as f32) as u32).max(row0); + let y1 = (pa.y.max(pb.y).max(pc.y).ceil() as u32).min(row0 + rows); + for y in y0..y1 { + for x in x0..x1 { + let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); + let (w0, w1, w2) = (edge(pb, pc, p) * area.signum(), edge(pc, pa, p) * area.signum(), edge(pa, pb, p) * area.signum()); + if w0 < eps || w1 < eps || w2 < eps { + continue; + } + let i = (y - row0) as usize * w as usize + x as usize; + if let (Some(slot), Some(bw)) = (tri.get_mut(i), bary.get_mut(i)) { + if *slot != NO_TRI { + overlaps += 1; + } + *slot = t; + let inv = 1.0 / area.abs(); + *bw = [w1 * inv, w2 * inv]; + } + } + } + } + overlaps + }) + .sum(); + Ok(UvGBuffer { width: w, height: h, tri, bary, overlaps }) + } + + pub fn covered(&self, i: usize) -> bool { + self.tri.get(i).is_some_and(|t| *t != NO_TRI) + } + + pub fn coverage_mask(&self) -> Vec { + self.tri.iter().map(|t| *t != NO_TRI).collect() + } + + pub fn covered_count(&self) -> usize { + self.tri.iter().filter(|t| **t != NO_TRI).count() + } + + /// Surface attributes at texel index `i` (None when uncovered). + pub fn surface(&self, mesh: &Mesh, i: usize) -> Option { + let t = *self.tri.get(i)?; + if t == NO_TRI { + return None; + } + let [b1, b2] = *self.bary.get(i)?; + surface_at(mesh, t, b1, b2) + } +} + +/// Interpolate triangle `t` at barycentrics (weights of vertices 1 and 2). +pub fn surface_at(mesh: &Mesh, t: u32, b1: f32, b2: f32) -> Option { + let [a, b, c] = mesh.tri(t as usize)?; + let b0 = 1.0 - b1 - b2; + let p = |v: &[Vec3]| -> Option { Some(*v.get(a)? * b0 + *v.get(b)? * b1 + *v.get(c)? * b2) }; + let pos = p(&mesh.positions)?; + let nrm = p(&mesh.normals)?.try_normalize().unwrap_or(Vec3::Y); + let (pa, pb, pc) = (*mesh.positions.get(a)?, *mesh.positions.get(b)?, *mesh.positions.get(c)?); + let geo_nrm = (pb - pa).cross(pc - pa).try_normalize().unwrap_or(nrm); + let tan = *mesh.tangents.get(a)? * b0 + *mesh.tangents.get(b)? * b1 + *mesh.tangents.get(c)? * b2; + let uv = *mesh.uvs.get(a)? * b0 + *mesh.uvs.get(b)? * b1 + *mesh.uvs.get(c)? * b2; + let tdir = tan.truncate().try_normalize().unwrap_or_else(|| nrm.any_orthonormal_vector()); + let w = mesh.tangents.get(a).map(|t| if t.w < 0.0 { -1.0 } else { 1.0 }).unwrap_or(1.0); + Some(Surface { pos, nrm, geo_nrm, tangent: tdir.extend(w), uv, tri: t }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::primitives; + + #[test] + fn half_triangle_covers_texels_with_centers_inside() { + // One triangle covering the lower-left half of UV space (v down: y = v·H). + let m = Mesh::from_parts( + vec![Vec3::ZERO, Vec3::X, Vec3::Y], + None, + vec![Vec2::new(0.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0)], + vec![0, 1, 2], + "m", + ) + .unwrap(); + let g = UvGBuffer::new(&m, 0, 8, 8).unwrap(); + for y in 0..8u32 { + for x in 0..8u32 { + let inside = (x as f32 + 0.5) <= (y as f32 + 0.5); + assert_eq!(g.covered((y * 8 + x) as usize), inside, "({x},{y})"); + } + } + assert_eq!(g.overlaps, 0); + } + + #[test] + fn overlapping_and_degenerate_triangles() { + let uv = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(0.5, 0.5)]; + let m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z], None, uv, vec![0, 1, 2, 0, 1, 2, 0, 3, 3], "m").unwrap(); + let g = UvGBuffer::new(&m, 0, 16, 16).unwrap(); + assert!(g.overlaps > 0); + assert!(g.covered_count() > 0); + } + + #[test] + fn sizes_outside_the_limits_are_rejected() { + // 2^27 + 1 texels wide: 32 rows of it overflow u32. + assert!(checked_texels((1 << 27) + 1, 1).is_err()); + assert!(checked_texels(u32::MAX, u32::MAX).is_err()); + assert!(checked_texels(0, 8).is_err()); + assert!(checked_texels(8, 0).is_err()); + assert!(checked_texels(MAX_SIDE + 1, 1).is_err()); + assert!(checked_texels(1, MAX_SIDE + 1).is_err()); + // Both sides in range, but more than MAX_TEXELS texels. + assert!(checked_texels(MAX_SIDE, MAX_SIDE).is_err()); + assert!(checked_texels(MAX_SIDE, 4_097).is_err()); + assert_eq!(checked_texels(MAX_SIDE, 4_096), Ok(MAX_TEXELS)); + assert_eq!(checked_texels(MAX_SIDE, 1), Ok(MAX_SIDE as usize)); + + let m = primitives::sphere(1.0, 8, 4); + assert!(UvGBuffer::new(&m, 0, MAX_SIDE + 1, 1).is_err()); + assert!(UvGBuffer::new(&m, 0, 0, 1).is_err()); + let g = UvGBuffer::new(&m, 0, 64, 32).unwrap(); + assert_eq!((g.width, g.height, g.tri.len(), g.bary.len()), (64, 32, 2_048, 2_048)); + } + + #[test] + fn too_many_band_entries_are_rejected() { + // 2^27 / 512 + 1 triangles, each spanning all 512 bands of a 1 × 16,384 buffer. + let tall = (MAX_BAND_ENTRIES / 512 + 1) as u32; + let mut m = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y], + uvs: vec![Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)], + ..Mesh::default() + }; + m.indices = (0..tall).flat_map(|_| [0, 1, 2]).collect(); + m.submeshes = vec![crate::SubMesh { name: "m".into(), material: 0, start: 0, count: tall * 3 }]; + assert!(UvGBuffer::new(&m, 0, 1, MAX_SIDE).is_err()); + m.indices.truncate(3); + m.submeshes[0].count = 3; + let g = UvGBuffer::new(&m, 0, 1, MAX_SIDE).unwrap(); + // The texel centers at u = 0.5 lie inside the triangle down to v = 0.5. + assert_eq!(g.covered_count(), MAX_SIDE as usize / 2); + } + + #[test] + fn sphere_surface_lies_on_the_sphere() { + let m = primitives::sphere(2.0, 64, 32); + let g = UvGBuffer::new(&m, 0, 128, 128).unwrap(); + assert!(g.covered_count() > 128 * 128 * 9 / 10, "{}", g.covered_count()); + for i in (0..g.tri.len()).step_by(97) { + if let Some(s) = g.surface(&m, i) { + assert!((s.pos.length() - 2.0).abs() < 0.02); + assert!(s.nrm.dot(s.pos.normalize()) > 0.99); + } + } + } +} diff --git a/crates/mesh-ops/src/lib.rs b/crates/mesh-ops/src/lib.rs new file mode 100644 index 0000000000..a30a6ef681 --- /dev/null +++ b/crates/mesh-ops/src/lib.rs @@ -0,0 +1,28 @@ +//! # craft-mesh-ops +//! +//! Triangle mesh operations: the [`Mesh`] type with normals and MikkTSpace tangents, built-in +//! [`primitives`] (material ball, sphere, cube, …), a [`Bvh`] for ray casts and box queries, +//! the UV-space [`UvGBuffer`] that maps texels to surface points, and the [`OrbitCamera`]. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod bvh; +pub mod camera; +pub mod gbuffer; +pub mod mesh; +pub mod primitives; +pub mod unwrap; + +pub use bvh::{Bvh, Hit}; +pub use camera::{OrbitCamera, Ray}; +pub use gbuffer::{MAX_BAND_ENTRIES, MAX_SIDE, MAX_TEXELS, NO_TRI, Surface, UvGBuffer, surface_at}; +pub use glam; +pub use mesh::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh}; + +#[derive(Debug, thiserror::Error, Clone, PartialEq)] +pub enum GeomError { + #[error("invalid mesh: {0}")] + Invalid(String), +} + +pub type Result = std::result::Result; diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs new file mode 100644 index 0000000000..996b1b13fc --- /dev/null +++ b/crates/mesh-ops/src/mesh.rs @@ -0,0 +1,709 @@ +//! The internal triangle mesh. + +use glam::{Vec2, Vec3, Vec4}; + +use crate::{GeomError, Result}; + +/// An edge by the bits of its two end positions, the lower one first +type EdgePositions = ([u32; 3], [u32; 3]); + +/// A contiguous index range drawn with one material. +#[derive(Clone, Debug, PartialEq)] +pub struct SubMesh { + pub name: String, + pub material: usize, + /// First index (into [`Mesh::indices`]) and index count. + pub start: u32, + pub count: u32, +} + +/// A material's base color (what a color-map bake transfers): `factor` (linear RGBA) times an +/// optional texture sampled at the mesh UVs. +#[derive(Clone, Debug, PartialEq)] +pub struct BaseColor { + pub factor: Vec4, + pub width: u32, + pub height: u32, + /// `width × height` RGBA8 texels (color sRGB-encoded, alpha linear), rows top → bottom like + /// the UVs' v; empty without a texture. + pub texels: Vec<[u8; 4]>, +} + +/// Triangle mesh in world space. UVs use the glTF convention (origin top-left, v down). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Mesh { + pub positions: Vec, + pub normals: Vec, + /// xyz tangent, w bitangent sign. + pub tangents: Vec, + pub uvs: Vec, + /// RGBA vertex colors in 0..1 (glTF: linear; OBJ, PLY: as stored): one per vertex, or empty. + pub colors: Vec, + pub indices: Vec, + /// Index ranges per material and part (node / object); `name` is the part name. + pub submeshes: Vec, + pub materials: Vec, + /// Per triangle, bit `i` set when edge `i` (corner `i` to corner `i + 1`) is a diagonal the + /// importer added to split a polygon, which wireframes leave out. Empty: every edge is real. + pub diagonals: Vec, +} + +/// Hard cap on mesh size accepted from files (triangles). +pub const MAX_TRIANGLES: usize = 20_000_000; + +impl Mesh { + pub fn triangle_count(&self) -> usize { + self.indices.len() / 3 + } + + pub fn vertex_count(&self) -> usize { + self.positions.len() + } + + /// Axis-aligned bounds (zero box for an empty mesh). + pub fn bounds(&self) -> (Vec3, Vec3) { + if self.positions.is_empty() { + return (Vec3::ZERO, Vec3::ZERO); + } + self.positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))) + } + + /// Bounding-sphere radius around the bounds center (at least a small epsilon). + pub fn radius(&self) -> f32 { + let (lo, hi) = self.bounds(); + ((hi - lo).length() * 0.5).max(1e-4) + } + + /// Vertex indices of triangle `t`. + pub fn tri(&self, t: usize) -> Option<[usize; 3]> { + let i = self.indices.get(t * 3..t * 3 + 3)?; + Some([i[0] as usize, i[1] as usize, i[2] as usize]) + } + + /// The edges wireframes draw: each vertex pair once (smaller index first), leaving out + /// polygon diagonals ([`Mesh::diagonals`]) unless only one triangle has the edge (a UV seam + /// split it from its twin), per material in `0..materials.len().max(1)`. + pub fn wire_edges(&self) -> Vec> { + (0..self.materials.len().max(1)) + .map(|m| { + // Edge → (real in some triangle, triangles using it), in first-seen order. + let mut edges: Vec<((u32, u32), bool, u8)> = Vec::new(); + let mut at: std::collections::HashMap<(u32, u32), usize> = std::collections::HashMap::new(); + for t in self.triangles_of(m) { + let Some(v) = self.indices.get(t * 3..t * 3 + 3) else { continue }; + let hidden = self.diagonals.get(t).copied().unwrap_or(0); + for (i, (a, b)) in [(v[0], v[1]), (v[1], v[2]), (v[2], v[0])].into_iter().enumerate() { + let key = (a.min(b), a.max(b)); + let real = hidden >> i & 1 == 0; + let e = *at.entry(key).or_insert_with(|| { + edges.push((key, false, 0)); + edges.len() - 1 + }); + if let Some((_, r, n)) = edges.get_mut(e) { + *r |= real; + *n = n.saturating_add(1); + } + } + } + edges.into_iter().filter(|(_, real, n)| *real || *n == 1).map(|(k, ..)| k).collect() + }) + .collect() + } + + /// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)`. + /// An edge between two vertices at one position is not listed, and a triangle with two corners at one position + /// connects its two other edges in UV space, as the corners of a pole row do. + pub fn uv_seam_edges(&self) -> Vec> { + // Signed zero denotes the same position on either side of an imported seam + let bits = |position: Vec3| position.to_array().map(|coordinate| if coordinate == 0.0 { 0 } else { coordinate.to_bits() }); + let mut seams = vec![Vec::new(); self.materials.len().max(1)]; + // Match across materials before grouping the lines for texture-set visibility + let mut sides: std::collections::HashMap> = std::collections::HashMap::new(); + // A triangle with two corners at one position joins its two edges to the third corner in UV space + let mut joins: std::collections::HashMap> = std::collections::HashMap::new(); + let canonical = |from: u32, to: u32, from_bits: [u32; 3], to_bits: [u32; 3]| { + if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) } + }; + for material in 0..seams.len() { + for triangle in self.triangles_of(material) { + let Some(corners) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue }; + let Some(corner_bits) = + corners.iter().map(|&corner| self.positions.get(corner as usize).map(|p| bits(*p))).collect::>>() + else { + continue; + }; + + for (a, b) in [(0, 1), (1, 2), (2, 0)] { + // An edge between two vertices at one position has no length to draw + if corner_bits[a] == corner_bits[b] { + let c = 3 - a - b; + if corner_bits[c] != corner_bits[a] { + let (edge, first) = canonical(corners[a], corners[c], corner_bits[a], corner_bits[c]); + let (_, second) = canonical(corners[b], corners[c], corner_bits[b], corner_bits[c]); + joins.entry(edge).or_default().push([first, second]); + } + continue; + } + let (edge, pair) = canonical(corners[a], corners[b], corner_bits[a], corner_bits[b]); + sides.entry(edge).or_default().push((pair.0, pair.1, material)); + } + } + } + + let uv = |index: u32| self.uvs.get(index as usize).copied(); + for (edge, pairs) in sides { + // Group the UV layouts of this edge, joining the layouts a collapsed triangle connects + let mut layouts = Vec::new(); + for &(from, to, _) in &pairs { + if !layouts.contains(&(uv(from), uv(to))) { + layouts.push((uv(from), uv(to))); + } + } + let mut group: Vec = (0..layouts.len()).collect(); + for [first, second] in joins.get(&edge).into_iter().flatten() { + let find = |(from, to): (u32, u32)| layouts.iter().position(|layout| *layout == (uv(from), uv(to))); + if let (Some(first), Some(second)) = (find(*first), find(*second)) { + let (kept, merged) = (group[first], group[second]); + for g in &mut group { + if *g == merged { + *g = kept; + } + } + } + } + + if group.iter().any(|&g| g != group[0]) { + for (from, to, material) in pairs { + if let Some(edges) = seams.get_mut(material) { + edges.push((from.min(to), from.max(to))); + } + } + } + } + for edges in &mut seams { + edges.sort_unstable(); + edges.dedup(); + } + + seams + } + + /// Material of triangle `t`. + pub fn material_of(&self, t: usize) -> Option { + let idx = (t * 3) as u32; + self.submeshes.iter().find(|s| idx >= s.start && idx < s.start.saturating_add(s.count)).map(|s| s.material) + } + + /// Triangle index range belonging to material `m` (all submeshes of that material). + pub fn triangles_of(&self, m: usize) -> impl Iterator + '_ { + self.submeshes.iter().filter(move |s| s.material == m).flat_map(|s| (s.start / 3) as usize..((s.start + s.count) / 3) as usize) + } + + /// Check that attribute arrays agree and every index is in range. + pub fn validate(&self) -> Result<()> { + let n = self.positions.len(); + if self.normals.len() != n || self.uvs.len() != n || self.tangents.len() != n { + return Err(GeomError::Invalid(format!( + "attribute counts differ: {} positions, {} normals, {} uvs, {} tangents", + n, + self.normals.len(), + self.uvs.len(), + self.tangents.len() + ))); + } + if !self.colors.is_empty() && self.colors.len() != n { + return Err(GeomError::Invalid(format!("{} vertex colors for {n} vertices", self.colors.len()))); + } + if !self.indices.len().is_multiple_of(3) { + return Err(GeomError::Invalid("index count is not a multiple of 3".into())); + } + if self.triangle_count() > MAX_TRIANGLES { + return Err(GeomError::Invalid(format!("mesh has more than {MAX_TRIANGLES} triangles"))); + } + if let Some(bad) = self.indices.iter().find(|i| **i as usize >= n) { + return Err(GeomError::Invalid(format!("index {bad} out of range ({n} vertices)"))); + } + if self.positions.iter().any(|p| !p.is_finite()) { + return Err(GeomError::Invalid("mesh has non-finite positions".into())); + } + for s in &self.submeshes { + if s.start as usize + s.count as usize > self.indices.len() || s.material >= self.materials.len().max(1) { + return Err(GeomError::Invalid(format!("submesh {} is out of range", s.name))); + } + } + Ok(()) + } + + /// Area-weighted smooth normals over the index buffer. + pub fn compute_normals(&mut self) { + let mut normals = vec![Vec3::ZERO; self.positions.len()]; + for &[a, b, c] in self.indices.as_chunks::<3>().0 { + let (a, b, c) = (a as usize, b as usize, c as usize); + let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; + let face = (*pb - *pa).cross(*pc - *pa); + for v in [a, b, c] { + if let Some(x) = normals.get_mut(v) { + *x += face; + } + } + } + + self.normals = normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); + } + + /// MikkTSpace tangents (falls back to per-triangle tangents if generation fails). + pub fn compute_tangents(&mut self) { + self.tangents = vec![Vec4::new(1.0, 0.0, 0.0, 1.0); self.positions.len()]; + if self.normals.len() != self.positions.len() { + self.compute_normals(); + } + if self.uvs.len() != self.positions.len() { + self.uvs = vec![Vec2::ZERO; self.positions.len()]; + } + // mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then. + let usable = !crate::unwrap::all_triangles_degenerate(self); + let mut g = Mikk { mesh: self }; + if !usable || !mikktspace::generate_tangents(&mut g) { + self.simple_tangents(); + } + for (t, n) in self.tangents.iter_mut().zip(&self.normals) { + // Orthonormalize against the normal; repair degenerate results. + let v = t.truncate(); + let o = (v - *n * n.dot(v)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()); + *t = o.extend(if t.w < 0.0 { -1.0 } else { 1.0 }); + } + } + + fn simple_tangents(&mut self) { + let mut tangents = vec![Vec3::ZERO; self.positions.len()]; + for &[a, b, c] in self.indices.as_chunks::<3>().0 { + let (a, b, c) = (a as usize, b as usize, c as usize); + let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; + let (Some(ua), Some(ub), Some(uc)) = (self.uvs.get(a), self.uvs.get(b), self.uvs.get(c)) else { continue }; + let (e1, e2) = (*pb - *pa, *pc - *pa); + let (d1, d2) = (*ub - *ua, *uc - *ua); + let determinant = d1.x * d2.y - d2.x * d1.y; + if determinant.abs() < 1e-12 { + continue; + } + + let tangent = (e1 * d2.y - e2 * d1.y) / determinant; + for v in [a, b, c] { + if let Some(x) = tangents.get_mut(v) { + *x += tangent; + } + } + } + + self.tangents = tangents.into_iter().map(|t| t.try_normalize().unwrap_or(Vec3::X).extend(1.0)).collect(); + } + + /// The UV tiles material `m` covers: integer parts of its triangles' UV centroids (v down), + /// ascending. Non-finite UVs are skipped. + pub fn uv_tiles(&self, m: usize) -> std::collections::BTreeSet<(i32, i32)> { + self.triangles_of(m) + .filter_map(|t| { + let [a, b, c] = self.tri(t)?; + let uv = (*self.uvs.get(a)? + *self.uvs.get(b)? + *self.uvs.get(c)?) / 3.0; + uv.is_finite().then(|| (uv.x.floor() as i32, uv.y.floor() as i32)) + }) + .collect() + } + + /// Remap the UVs of material `m`'s triangles with `f`. Vertices they share with other + /// materials are duplicated first, so the other triangles keep their UVs. + pub fn map_material_uvs(&mut self, m: usize, f: impl Fn(Vec2) -> Vec2) { + self.map_material_uvs_with(m, |_, uv| f(uv)); + } + + /// [`Mesh::map_material_uvs`] where `f` also gets the UV centroid of the first of the + /// material's triangles using the vertex: piecewise maps (UV tiles of different sizes) then + /// place a vertex on a tile border with its own triangle's tile. + pub fn map_material_uvs_with(&mut self, m: usize, f: impl Fn(Vec2, Vec2) -> Vec2) { + let material_triangles: Vec = self.triangles_of(m).collect(); + let mut in_material = vec![false; self.triangle_count()]; + for t in &material_triangles { + if let Some(x) = in_material.get_mut(*t) { + *x = true; + } + } + + let mut shared = vec![false; self.positions.len()]; + for (_, tri) in self.indices.as_chunks::<3>().0.iter().enumerate().filter(|(t, _)| !in_material.get(*t).copied().unwrap_or(false)) { + for v in tri { + if let Some(s) = shared.get_mut(*v as usize) { + *s = true; + } + } + } + + let mut duplicates = std::collections::HashMap::new(); + for k in material_triangles.iter().flat_map(|t| t * 3..t * 3 + 3) { + let Some(&v) = self.indices.get(k) else { continue }; + let v = if shared.get(v as usize).copied().unwrap_or(false) { + *duplicates.entry(v).or_insert_with(|| self.duplicate_vertex(v as usize)) + } else { + v + }; + if let Some(i) = self.indices.get_mut(k) { + *i = v; + } + } + + // (vertex, centroid of its first triangle), each vertex once + let mut vertices = Vec::with_capacity(material_triangles.len() * 3); + for t in &material_triangles { + let Some(tri) = self.tri(*t) else { continue }; + let centroid = tri.iter().map(|v| self.uvs.get(*v).copied().unwrap_or_default()).sum::() / 3.0; + vertices.extend(tri.map(|v| (v, centroid))); + } + + vertices.sort_by_key(|(v, _)| *v); + vertices.dedup_by_key(|(v, _)| *v); + for (v, centroid) in vertices { + if let Some(uv) = self.uvs.get_mut(v) { + *uv = f(centroid, *uv); + } + } + } + + /// Append a copy of vertex `v`; returns its index. + fn duplicate_vertex(&mut self, v: usize) -> u32 { + let i = self.positions.len() as u32; + self.positions.push(self.positions.get(v).copied().unwrap_or_default()); + self.normals.push(self.normals.get(v).copied().unwrap_or(Vec3::Y)); + self.tangents.push(self.tangents.get(v).copied().unwrap_or(Vec4::new(1.0, 0.0, 0.0, 1.0))); + self.uvs.push(self.uvs.get(v).copied().unwrap_or_default()); + if !self.colors.is_empty() { + self.colors.push(self.colors.get(v).copied().unwrap_or(Vec4::ONE)); + } + i + } + + /// Append `other`, offsetting indices; its submeshes keep their material indices shifted by + /// this mesh's material count. + pub fn append(&mut self, other: &Mesh) { + let base = self.positions.len() as u32; + let ibase = self.indices.len() as u32; + let mbase = self.materials.len(); + self.positions.extend_from_slice(&other.positions); + self.normals.extend_from_slice(&other.normals); + self.tangents.extend_from_slice(&other.tangents); + self.uvs.extend_from_slice(&other.uvs); + if !(self.colors.is_empty() && other.colors.is_empty()) { + // Vertices of the side without colors become white. + self.colors.resize(base as usize, Vec4::ONE); + self.colors.extend(other.colors.iter().copied().chain(std::iter::repeat(Vec4::ONE)).take(other.positions.len())); + } + if !(self.diagonals.is_empty() && other.diagonals.is_empty()) { + self.diagonals.resize(ibase as usize / 3, 0); + self.diagonals.extend(other.diagonals.iter().copied().chain(std::iter::repeat(0)).take(other.triangle_count())); + } + self.indices.extend(other.indices.iter().map(|i| i + base)); + self.materials.extend(other.materials.iter().cloned()); + self.submeshes.extend(other.submeshes.iter().map(|s| SubMesh { + name: s.name.clone(), + material: s.material + mbase, + start: s.start + ibase, + count: s.count, + })); + } + + /// Each triangle split into four at its edge midpoints (shared edges share their midpoint); + /// attributes are interpolated and submesh ranges keep their triangles. + pub fn subdivided(&self) -> Mesh { + let mut m = Mesh { indices: Vec::with_capacity(self.indices.len() * 4), ..self.clone() }; + let has = |len: usize| len == self.positions.len(); + let (has_n, has_t, has_uv, has_c) = (has(self.normals.len()), has(self.tangents.len()), has(self.uvs.len()), has(self.colors.len())); + let mut mids = std::collections::HashMap::new(); + let mut mid = |m: &mut Mesh, a: u32, b: u32| -> u32 { + *mids.entry((a.min(b), a.max(b))).or_insert_with(|| { + let (i, j) = (a as usize, b as usize); + m.positions.push((self.positions[i] + self.positions[j]) * 0.5); + if has_n { + m.normals.push((self.normals[i] + self.normals[j]).normalize_or_zero()); + } + if has_t { + let (ti, tj) = (self.tangents[i], self.tangents[j]); + m.tangents.push((ti.truncate() + tj.truncate()).normalize_or_zero().extend(ti.w)); + } + if has_uv { + m.uvs.push((self.uvs[i] + self.uvs[j]) * 0.5); + } + if has_c { + m.colors.push((self.colors[i] + self.colors[j]) * 0.5); + } + (m.positions.len() - 1) as u32 + }) + }; + // Each child keeps the hidden bits of the halves of the parent's edges it has; the edges + // inside the parent are real. + let mut diagonals = Vec::with_capacity(if self.diagonals.is_empty() { 0 } else { self.diagonals.len().saturating_mul(4) }); + for (k, t) in self.indices.as_chunks::<3>().0.iter().enumerate() { + if t.iter().any(|&i| i as usize >= self.positions.len()) { + continue; + } + let (a, b, c) = (t[0], t[1], t[2]); + let (ab, bc, ca) = (mid(&mut m, a, b), mid(&mut m, b, c), mid(&mut m, c, a)); + m.indices.extend_from_slice(&[a, ab, ca, ab, b, bc, ca, bc, c, ab, bc, ca]); + if !self.diagonals.is_empty() { + let h = self.diagonals.get(k).copied().unwrap_or(0); + diagonals.extend_from_slice(&[h & 0b101, h & 0b011, h & 0b110, 0]); + } + } + m.diagonals = diagonals; + for s in &mut m.submeshes { + s.start *= 4; + s.count *= 4; + } + m + } + + /// Uniformly scale and translate so the mesh is centered with the given bounding radius. + pub fn normalize_to(&mut self, radius: f32) { + let (lo, hi) = self.bounds(); + let c = (lo + hi) * 0.5; + let s = radius / self.radius(); + for p in &mut self.positions { + *p = (*p - c) * s; + } + } + + /// A single-material mesh from raw attributes; computes missing normals and tangents. + pub fn from_parts(positions: Vec, normals: Option>, uvs: Vec, indices: Vec, material: &str) -> Result { + let count = indices.len() as u32; + let mut m = Mesh { + normals: normals.unwrap_or_default(), + uvs, + positions, + indices, + tangents: Vec::new(), + colors: Vec::new(), + submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], + materials: vec![material.into()], + diagonals: Vec::new(), + }; + if m.normals.len() != m.positions.len() { + m.compute_normals(); + } + m.compute_tangents(); + m.validate()?; + Ok(m) + } +} + +struct Mikk<'a> { + mesh: &'a mut Mesh, +} + +impl Mikk<'_> { + fn vi(&self, face: usize, vert: usize) -> usize { + self.mesh.indices.get(face * 3 + vert).copied().unwrap_or(0) as usize + } +} + +impl mikktspace::Geometry for Mikk<'_> { + fn num_faces(&self) -> usize { + self.mesh.indices.len() / 3 + } + fn num_vertices_of_face(&self, _face: usize) -> usize { + 3 + } + fn position(&self, face: usize, vert: usize) -> [f32; 3] { + self.mesh.positions.get(self.vi(face, vert)).copied().unwrap_or_default().to_array() + } + fn normal(&self, face: usize, vert: usize) -> [f32; 3] { + self.mesh.normals.get(self.vi(face, vert)).copied().unwrap_or(Vec3::Y).to_array() + } + fn tex_coord(&self, face: usize, vert: usize) -> [f32; 2] { + // MikkTSpace expects OpenGL texture coordinates (v up); our UVs are glTF (v down). With + // v flipped, the bitangent `cross(N, T) * w` points up the image, as glTF requires. + let uv = self.mesh.uvs.get(self.vi(face, vert)).copied().unwrap_or_default(); + [uv.x, 1.0 - uv.y] + } + fn set_tangent_encoded(&mut self, tangent: [f32; 4], face: usize, vert: usize) { + let i = self.vi(face, vert); + if let Some(t) = self.mesh.tangents.get_mut(i) { + *t = Vec4::from_array(tangent); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn quad() -> Mesh { + Mesh::from_parts( + vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 0.0), Vec3::new(0.0, 1.0, 0.0)], + None, + vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)], + vec![0, 1, 2, 0, 2, 3], + "Default", + ) + .unwrap() + } + + #[test] + fn normals_and_tangents_of_a_quad() { + let m = quad(); + for n in &m.normals { + assert!((*n - Vec3::Z).length() < 1e-5); + } + for t in &m.tangents { + assert!((t.truncate() - Vec3::X).length() < 1e-4, "{t:?}"); + } + assert_eq!(m.material_of(1), Some(0)); + assert_eq!(m.triangles_of(0).collect::>(), vec![0, 1]); + } + + #[test] + fn wire_edges_leave_out_polygon_diagonals() { + let mut m = quad(); + assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (0, 2), (2, 3), (0, 3)]], "triangles show every edge"); + // Edge 2 of (0, 1, 2) and edge 0 of (0, 2, 3) split the quad. + m.diagonals = vec![0b100, 0b001]; + assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (2, 3), (0, 3)]]); + // A diagonal whose twin a seam split off (vertex 4 copies vertex 0) stays. + let mut seam = m.clone(); + seam.indices[3] = 4; + assert_eq!(seam.wire_edges()[0].len(), 6); + // Appending keeps each side's diagonals on its own triangles. + let mut a = Mesh::from_parts(m.positions.clone(), None, m.uvs.clone(), vec![0, 1, 2], "A").unwrap(); + a.append(&m); + assert_eq!(a.diagonals, vec![0, 0b100, 0b001]); + assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges"); + // Subdividing hides both halves of the diagonal and nothing else: 16 edges less 2. + let sub = m.subdivided(); + assert_eq!(sub.diagonals.len(), sub.triangle_count()); + let edges = &sub.wire_edges()[0]; + assert_eq!(edges.len(), 14); + assert!(edges.iter().all(|&(a, b)| !matches!((a, b), (0, 6) | (2, 6))), "diagonal halves {edges:?}"); + } + + #[test] + fn uv_seams_are_where_the_uv_layout_splits() { + let mesh = quad(); + assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam"); + + // Vertex 4 copies vertex 0's position with another UV: the diagonal (0, 2) / (4, 2) is cut + let mut seam = mesh.clone(); + seam.positions.push(seam.positions[0]); + seam.normals.push(seam.normals[0]); + seam.tangents.push(seam.tangents[0]); + seam.uvs.push(Vec2::new(0.9, 0.9)); + seam.indices[3] = 4; + assert_eq!(seam.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); + + // The same split with the same UV is a hard edge, not a seam + let mut hard = seam.clone(); + hard.uvs[4] = hard.uvs[0]; + assert_eq!(hard.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()]); + } + + #[test] + fn uv_seams_join_positions_with_opposite_signed_zero() { + let mut mesh = quad(); + mesh.positions.push(Vec3::new(-0.0, 0.0, 0.0)); + mesh.normals.push(mesh.normals[0]); + mesh.tangents.push(mesh.tangents[0]); + mesh.uvs.push(Vec2::new(0.9, 0.9)); + mesh.indices[3] = 4; + assert_eq!(mesh.positions[0], mesh.positions[4]); + assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); + } + + #[test] + fn uv_seams_skip_edges_between_vertices_at_one_position() { + let (segments, rings) = (3, 2); + let mesh = crate::primitives::sphere(1.0, segments, rings); + let seams = mesh.uv_seam_edges(); + assert!( + seams[0].iter().all(|&(from, to)| mesh.positions[from as usize] != mesh.positions[to as usize]), + "zero-length seam edges at a pole: {seams:?}" + ); + // Only the meridian where u = 0 meets u = 1 is a seam: columns 0 and 3, with the collapsed pole triangles + assert_eq!(seams, vec![vec![(0, 4), (2, 7), (3, 7), (4, 8), (4, 9), (7, 11)]]); + } + + #[test] + fn uv_seams_between_materials_belong_to_both_materials() { + let mut mesh = quad(); + mesh.positions.push(mesh.positions[0]); + mesh.normals.push(mesh.normals[0]); + mesh.tangents.push(mesh.tangents[0]); + mesh.uvs.push(Vec2::new(0.9, 0.9)); + mesh.indices[3] = 4; + mesh.materials.push("second".into()); + mesh.submeshes[0].count = 3; + mesh.submeshes.push(SubMesh { name: "second".into(), material: 1, start: 3, count: 3 }); + + assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]); + mesh.uvs[4] = mesh.uvs[0]; + assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a UV seam"); + } + + #[test] + fn subdivision_shares_edge_midpoints() { + let m = quad().subdivided(); + // 4 corners + 5 edge midpoints (the diagonal is shared), 8 triangles. + assert_eq!((m.positions.len(), m.triangle_count()), (9, 8)); + assert_eq!(m.uvs.len(), 9); + assert_eq!((m.submeshes[0].start, m.submeshes[0].count), (0, 24)); + m.validate().unwrap(); + } + + #[test] + fn validate_catches_bad_indices() { + let mut m = quad(); + m.indices[0] = 99; + assert!(m.validate().is_err()); + let mut m = quad(); + m.uvs.pop(); + assert!(m.validate().is_err()); + } + + #[test] + fn append_offsets_indices_and_materials() { + let mut a = quad(); + let b = quad(); + a.append(&b); + assert_eq!(a.indices[6], 4); + assert_eq!(a.submeshes[1].material, 1); + assert_eq!(a.submeshes[1].start, 6); + a.validate().unwrap(); + // Colors on one side only: the other side's vertices become white. + let mut red = quad(); + red.colors = vec![Vec4::new(1.0, 0.0, 0.0, 1.0); 4]; + a.append(&red); + assert_eq!(a.colors.len(), 12); + assert_eq!((a.colors[0], a.colors[8]), (Vec4::ONE, Vec4::new(1.0, 0.0, 0.0, 1.0))); + a.append(&quad()); + assert_eq!(a.colors[15], Vec4::ONE); + a.validate().unwrap(); + a.colors.pop(); + assert!(a.validate().is_err()); + } + + #[test] + fn material_uvs_remap_and_split_shared_vertices() { + // quad(): two triangles sharing an edge; put the second in its own material. + let mut m = quad(); + m.materials = vec!["a".into(), "b".into()]; + m.submeshes = + vec![SubMesh { name: "a".into(), material: 0, start: 0, count: 3 }, SubMesh { name: "b".into(), material: 1, start: 3, count: 3 }]; + let before = m.clone(); + m.map_material_uvs(1, |uv| uv + Vec2::X); + m.validate().unwrap(); + assert_eq!(m.vertex_count(), 6, "the two shared vertices are split"); + assert_eq!(&m.indices[..3], &before.indices[..3]); + for k in 0..3 { + let (old, new) = (before.indices[k] as usize, m.indices[k] as usize); + assert_eq!(m.uvs[new], before.uvs[old], "material a keeps its UVs"); + let (old, new) = (before.indices[3 + k] as usize, m.indices[3 + k] as usize); + assert_eq!((m.uvs[new], m.positions[new]), (before.uvs[old] + Vec2::X, before.positions[old])); + } + assert_eq!(m.uv_tiles(1).into_iter().collect::>(), vec![(1, 0)]); + assert_eq!(m.uv_tiles(0).into_iter().collect::>(), vec![(0, 0)]); + } +} diff --git a/crates/mesh-ops/src/primitives.rs b/crates/mesh-ops/src/primitives.rs new file mode 100644 index 0000000000..9bfc17af1d --- /dev/null +++ b/crates/mesh-ops/src/primitives.rs @@ -0,0 +1,760 @@ +//! Built-in meshes with clean, non-overlapping UVs: material ball, sphere, (rounded) cube, +//! cylinder, torus and plane. Y is up; triangles are counter-clockwise seen from outside. + +use std::f32::consts::{PI, TAU}; + +use glam::{DVec2, Vec2, Vec3}; + +use crate::mesh::{Mesh, SubMesh}; +use crate::{GeomError, Result}; + +/// A UV-space rectangle: origin and size. +#[derive(Clone, Copy, Debug)] +struct UvRect { + o: Vec2, + s: Vec2, +} + +impl UvRect { + const FULL: UvRect = UvRect { o: Vec2::ZERO, s: Vec2::ONE }; + fn map(&self, u: f32, v: f32) -> Vec2 { + self.o + self.s * Vec2::new(u, v) + } + fn inset(&self, m: f32) -> UvRect { + UvRect { o: self.o + Vec2::splat(m), s: self.s - Vec2::splat(2.0 * m) } + } +} + +#[derive(Default)] +struct Builder { + p: Vec, + n: Vec, + uv: Vec, + idx: Vec, + /// Per triangle: its [`Mesh::diagonals`] bits. + diag: Vec, +} + +impl Builder { + fn vert(&mut self, p: Vec3, n: Vec3, uv: Vec2) -> u32 { + self.p.push(p); + self.n.push(n.try_normalize().unwrap_or(Vec3::Y)); + self.uv.push(uv); + (self.p.len() - 1) as u32 + } + + /// A grid of (rows+1)×(cols+1) vertices from `f(row, col)`, rows going "down" the texture. + fn grid(&mut self, rows: usize, cols: usize, mut f: impl FnMut(usize, usize) -> (Vec3, Vec3, Vec2)) { + let base = self.p.len() as u32; + for i in 0..=rows { + for j in 0..=cols { + let (p, n, uv) = f(i, j); + self.vert(p, n, uv); + } + } + let w = (cols + 1) as u32; + for i in 0..rows as u32 { + for j in 0..cols as u32 { + let a = base + i * w + j; + let (b, c, d) = (a + 1, a + w, a + w + 1); + self.idx.extend_from_slice(&[a, c, d, a, d, b]); + // Edge d-a of the first triangle and a-d of the second split the quad. + self.diag.extend_from_slice(&[0b100, 0b001]); + } + } + } + + /// The mesh of one material, with tangents. + fn finish(self, material: &str) -> Mesh { + let mut m = self.into_mesh(material); + m.compute_tangents(); + m + } + + /// The mesh of one material, without tangents. + fn into_mesh(self, material: &str) -> Mesh { + let count = self.idx.len() as u32; + Mesh { + positions: self.p, + normals: self.n, + uvs: self.uv, + indices: self.idx, + tangents: Vec::new(), + colors: Vec::new(), + submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], + materials: vec![material.into()], + diagonals: self.diag, + } + } +} + +/// A UV sphere of `radius` centered at the origin. The seam endpoints have identical positions +/// at each ring. Vertices at each pole share one position. +pub fn sphere(radius: f32, segments: usize, rings: usize) -> Mesh { + let mut b = Builder::default(); + sphere_into(&mut b, Vec3::ZERO, radius, segments.max(3), rings.max(2), UvRect::FULL); + b.finish("Sphere") +} + +fn sphere_into(b: &mut Builder, center: Vec3, radius: f32, segs: usize, rings: usize, r: UvRect) { + b.grid(rings, segs, |i, j| { + let (u, v) = (j as f32 / segs as f32, i as f32 / rings as f32); + let (theta, phi) = (v * PI, if j == segs { PI * 1.5 } else { u * TAU + PI * 1.5 }); + let n = if i == 0 { + Vec3::Y + } else if i == rings { + -Vec3::Y + } else { + Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin()) + }; + (center + n * radius, n, r.map(u, v)) + }); +} + +/// A box with rounded edges (`bevel` = edge radius; 0 gives a plain cube). Faces are laid out +/// in a 3×2 UV atlas. +/// Each half extent must be finite and positive, and its doubled value must be finite. +/// `bevel` must be finite and between zero and 95% of the smallest half extent. +pub fn rounded_box(half: Vec3, bevel: f32) -> Result { + if !half.is_finite() || !half.cmpgt(Vec3::ZERO).all() || !(half * 2.0).is_finite() { + return Err(GeomError::Invalid("box half extents must be positive and finite, with finite doubled extents".into())); + } + if !bevel.is_finite() || bevel < 0.0 || bevel > half.min_element() * 0.95 { + return Err(GeomError::Invalid("box bevel must be finite and between zero and 95% of the smallest half extent".into())); + } + let mut b = Builder::default(); + rounded_box_into(&mut b, Vec3::ZERO, half, bevel, UvRect::FULL); + Ok(b.finish("Box")) +} + +/// The cube primitive (sharp edges). `size` must be finite and have a finite positive half extent. +pub fn cube(size: f32) -> Result { + let mut m = rounded_box(Vec3::splat(size * 0.5), 0.0)?; + m.materials = vec!["Cube".into()]; + if let Some(s) = m.submeshes.first_mut() { + s.name = "Cube".into(); + } + Ok(m) +} + +fn rounded_box_into(b: &mut Builder, center: Vec3, half: Vec3, bevel: f32, r: UvRect) { + let bevel = bevel.clamp(0.0, half.min_element() * 0.95); + // (normal, U = right, V = down) per face, seen from outside. + let faces = [ + (Vec3::Z, Vec3::X, -Vec3::Y), + (Vec3::X, -Vec3::Z, -Vec3::Y), + (-Vec3::Z, -Vec3::X, -Vec3::Y), + (-Vec3::X, Vec3::Z, -Vec3::Y), + (Vec3::Y, Vec3::X, Vec3::Z), + (-Vec3::Y, Vec3::X, -Vec3::Z), + ]; + let (kb, kc) = if bevel > 0.0 { (6usize, 10usize) } else { (0, 12) }; + // Coordinates along one face axis from -h to h, dense in the bevels. + let coords = |h: f32| -> Vec { + let inner = h - bevel; + let mut v = Vec::new(); + for i in 0..kb { + v.push(-h + bevel * (i as f32 / kb as f32)); + } + for i in 0..=kc { + v.push(inner * (2.0 * (i as f32 / kc as f32) - 1.0)); + } + for i in 1..=kb { + v.push(if i == kb { h } else { inner + bevel * (i as f32 / kb as f32) }); + } + for i in 0..v.len() / 2 { + v[i] = -v[v.len() - 1 - i]; + } + v + }; + let inner = half - Vec3::splat(bevel); + for (f, (n, u, v)) in faces.iter().enumerate() { + let cell = UvRect { o: r.map((f % 3) as f32 / 3.0, (f / 3) as f32 / 2.0), s: r.s * Vec2::new(1.0 / 3.0, 0.5) }.inset(0.01 * r.s.x); + let (hu, hv, hn) = ((*u * half).abs().max_element(), (*v * half).abs().max_element(), (*n * half).abs().max_element()); + let (cu, cv) = (coords(hu), coords(hv)); + let (cols, rows) = (cu.len() - 1, cv.len() - 1); + b.grid(rows, cols, |i, j| { + let (a, c) = (cu[j], cv[i]); + let q = *n * hn + *u * a + *v * c; + let clamped = q.clamp(-inner, inner); + let dir = (q - clamped).as_dvec3().try_normalize().map(|v| v.as_vec3()).unwrap_or(*n); + let p = if bevel > 0.0 { clamped + dir * bevel } else { q }; + let nn = if bevel > 0.0 { dir } else { *n }; + (center + p, nn, cell.map((a + hu) / (2.0 * hu), (c + hv) / (2.0 * hv))) + }); + } +} + +/// Surface of revolution of a profile `(radius, y)` listed top → bottom, mapped into `r` +/// (u around, v down the profile by arc length). +fn lathe_into(b: &mut Builder, center: Vec3, profile: &[(f32, f32)], segs: usize, r: UvRect) { + if profile.len() < 2 { + return; + } + let mut len = vec![0.0f64]; + for w in profile.windows(2) { + let d = DVec2::new(f64::from(w[1].0) - f64::from(w[0].0), f64::from(w[1].1) - f64::from(w[0].1)).length(); + len.push(len.last().copied().unwrap_or(0.0) + d); + } + let total = len.last().copied().filter(|total| *total > 0.0).unwrap_or(1.0); + let rows = profile.len() - 1; + b.grid(rows, segs, |i, j| { + let (rad, y) = profile[i]; + // Profile tangent (downwards) → outward normal in the (r, y) plane. + let prev = profile[i.saturating_sub(1)]; + let next = profile[(i + 1).min(rows)]; + let t = DVec2::new(f64::from(next.0) - f64::from(prev.0), f64::from(next.1) - f64::from(prev.1)) + .try_normalize() + .map(|t| t.as_vec2()) + .unwrap_or(Vec2::NEG_Y); + let n2 = Vec2::new(-t.y, t.x); + let u = j as f32 / segs as f32; + let dir = circle_sample(j, segs); + let p = center + dir * rad + Vec3::Y * y; + let n = dir * n2.x + Vec3::Y * n2.y; + (p, n, r.map(u, (len[i] / total) as f32)) + }); +} + +/// [`preview_orb`]: half-size of the cube that cuts the unit sphere flat (each face rim is the +/// circle where they meet). +const ORB_CUT: f32 = 0.8; +/// [`preview_orb`] domed panels: where the valley sits, as a fraction of the face rim radius. +const ORB_PANEL_VALLEY: f32 = 0.88; + +/// The preview orb of the smart mask and smart material previews: a sphere cut flat by a cube on six sides, on a thin round base +/// Each feature gives one kind of mask something to show: sharp face rims (edges), a softly +/// blended left face (soft edges), domed panels inside the front, left and top faces whose valleys +/// hold dirt (cavities), a slot around the middle (cavity), the base (thin part, the seam where it +/// meets the body) and plain rounded corners (gradients). Faces +Z (front), -X (left) and +Y (top) +/// carry the panels, so the shape is made to be seen from the front left, slightly from above. +/// The body takes the top 79 % of the UV square, the base the bottom 19 %. +pub fn preview_orb() -> Mesh { + // Grid rows (columns: twice as many); fewer blur the panel walls, more cost bake time + const ROWS: usize = 300; + const BODY_UV_HEIGHT: f32 = 0.79; + const BASE_UV: UvRect = UvRect { o: Vec2::new(0.0, 0.81), s: Vec2::new(1.0, 0.19) }; + const BASE_RADIUS: f32 = 0.95; + const BASE_HALF_HEIGHT: f32 = 0.025; + const BASE_Y: f32 = -0.6; + const BASE_RIM_STEPS: usize = 12; + const BASE_SEGMENTS: usize = 256; + + let mut b = Builder::default(); + b.grid(ROWS, ROWS * 2, |i, j| { + let (u, v) = (j as f32 / (ROWS * 2) as f32, i as f32 / ROWS as f32); + let (theta, phi) = (v * PI, u * TAU + PI * 1.5); + let dir = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin()); + (dir * preview_orb_radius(dir), dir, Vec2::new(u, v * BODY_UV_HEIGHT)) + }); + + // Base: a thin disc with a rounded rim (a half circle from its top face to its bottom face) + let mut profile = vec![(0.0, BASE_HALF_HEIGHT)]; + for k in 0..=BASE_RIM_STEPS { + let a = k as f32 / BASE_RIM_STEPS as f32 * PI; + profile.push((BASE_RADIUS - BASE_HALF_HEIGHT + BASE_HALF_HEIGHT * a.sin(), BASE_HALF_HEIGHT * a.cos())); + } + profile.push((0.0, -BASE_HALF_HEIGHT)); + lathe_into(&mut b, Vec3::Y * BASE_Y, &profile, BASE_SEGMENTS, BASE_UV); + + let mut m = b.into_mesh("Preview"); + // Normals from the triangles: the panel walls are too steep for the sphere's directions + m.compute_normals(); + // Body and base both run U around the vertical axis, so the tangent is that direction (a + // fraction of the cost of the general tangent pass on this many triangles) + m.tangents = m + .positions + .iter() + .zip(&m.normals) + .map(|(p, n)| { + let around = Vec3::new(p.z, 0.0, -p.x).try_normalize().unwrap_or(Vec3::X); + (around - *n * n.dot(around)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()).extend(1.0) + }) + .collect(); + m +} + +/// Distance from the centre of the [`preview_orb`] body along unit direction `d`. +fn preview_orb_radius(d: Vec3) -> f32 { + // Rim blends: the sharp faces, and the softly blended left face + const SHARP_BLEND: f32 = 0.035; + const SOFT_BLEND: f32 = 0.18; + // Domed panels: valley depth below the face, dome rise past it; the left panel is smaller + const PANEL_DEPTH: f32 = 0.11; + const PANEL_BULGE: f32 = 0.04; + const LEFT_PANEL_SCALE: f32 = 0.9; + // Slot around the middle: centre height, half-width, edge rounding, depth; it fades out over + // this fraction of the left panel's rim + const SLOT_Y: f32 = -0.03; + const SLOT_HALF_WIDTH: f32 = 0.05; + const SLOT_ROUNDING: f32 = 0.015; + const SLOT_DEPTH: f32 = 0.12; + const SLOT_FADE: f32 = 0.04; + + let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT; + let smooth = |a: f32, b: f32, x: f32| { + let t = ((x - a) / (b - a)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) + }; + // Polynomial smooth minimum with blend radius k + let smin = |a: f32, b: f32, k: f32| { + let h = (0.5 + 0.5 * (b - a) / k).clamp(0.0, 1.0); + b + (a - b) * h - k * h * (1.0 - h) + }; + // Domed panel at `rho` (radius in face units) inside a face of rim `rim`: a steep wall from + // the rim into a valley, then a dome rising slightly past the face over the middle + let panel = |rho: f32, rim: f32| { + let valley = rim * ORB_PANEL_VALLEY; + if rho < valley { + PANEL_BULGE - (PANEL_BULGE + PANEL_DEPTH) * (rho / valley).powi(3) + } else { + -PANEL_DEPTH * (1.0 - ((rho - valley) / (rim - valley)).min(1.0)) + } + }; + let face_rho = |along: f32, u: f32, v: f32| (u * u + v * v).sqrt() / along.max(1e-3); + + // The cut: sharp rims except the softly blended left face + let mut radius = 1.0f32; + for (along, blend) in [(d.x, SHARP_BLEND), (-d.x, SOFT_BLEND), (d.y, SHARP_BLEND), (-d.y, SHARP_BLEND), (d.z, SHARP_BLEND), (-d.z, SHARP_BLEND)] { + // Directions facing away from a face stay on the sphere (9 = far past it) + let to_face = if along > 1e-3 { ORB_CUT / along } else { 9.0 }; + radius = smin(radius, to_face, blend); + } + + let a = d.abs(); + let left_rim = rim * LEFT_PANEL_SCALE; + let mut relief = 0.0; + if d.z > 0.0 && a.z >= a.x && a.z >= a.y { + relief += panel(face_rho(d.z, d.x, d.y), rim); + } + if d.x < 0.0 && a.x >= a.y && a.x >= a.z { + relief += panel(face_rho(-d.x, d.y, d.z), left_rim); + } + if d.y > 0.0 && a.y >= a.x && a.y >= a.z { + relief += panel(face_rho(d.y, d.x, d.z), rim); + } + + // Slot around the middle, stopping at the left panel + let in_left_panel = + if d.x < 0.0 { 1.0 - smooth(left_rim * (1.0 - SLOT_FADE), left_rim * (1.0 + SLOT_FADE), face_rho(-d.x, d.y, d.z)) } else { 0.0 }; + let slot_band = 1.0 - smooth(SLOT_HALF_WIDTH - SLOT_ROUNDING, SLOT_HALF_WIDTH + SLOT_ROUNDING, (d.y - SLOT_Y).abs()); + relief -= SLOT_DEPTH * slot_band * (1.0 - in_left_panel); + + radius + relief +} + +fn circle_sample(column: usize, segments: usize) -> Vec3 { + let angle = if column == segments { PI * 1.5 } else { column as f32 / segments as f32 * TAU + PI * 1.5 }; + Vec3::new(angle.cos(), 0.0, -angle.sin()) +} + +/// A flat disk facing up (+Y) or down, with planar UVs inside `r`. +fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, r: UvRect) { + let n = if up { Vec3::Y } else { Vec3::NEG_Y }; + let c = b.vert(center, n, r.map(0.5, 0.5)); + let first = b.p.len() as u32; + for j in 0..segs { + let sample = circle_sample(j, segs); + let (x, z) = (sample.x, sample.z); + // Top view: +X right, +Z down the texture; bottom view mirrors X. + let uv = if up { r.map(0.5 + x * 0.5, 0.5 + z * 0.5) } else { r.map(0.5 + x * 0.5, 0.5 - z * 0.5) }; + b.vert(center + Vec3::new(x, 0.0, z) * radius, n, uv); + } + for j in 0..segs as u32 { + let (a, bb) = (first + j, first + (j + 1) % segs as u32); + if up { + b.idx.extend_from_slice(&[c, a, bb]); + } else { + b.idx.extend_from_slice(&[c, bb, a]); + } + b.diag.push(0); + } +} + +/// A capped cylinder along Y. +pub fn cylinder(radius: f32, height: f32, segs: usize) -> Mesh { + let mut b = Builder::default(); + let h = height * 0.5; + lathe_into(&mut b, Vec3::ZERO, &[(radius, h), (radius, -h)], segs.max(3), UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01)); + disk_into(&mut b, Vec3::Y * h, radius, true, segs.max(3), UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); + disk_into(&mut b, -Vec3::Y * h, radius, false, segs.max(3), UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); + b.finish("Cylinder") +} + +/// A torus around Y. +pub fn torus(major: f32, minor: f32, segs: usize, sides: usize) -> Mesh { + let mut b = Builder::default(); + let (segs, sides) = (segs.max(3), sides.max(3)); + b.grid(sides, segs, |i, j| { + let (u, v) = (j as f32 / segs as f32, i as f32 / sides as f32); + let phi = if j == segs { PI * 1.5 } else { u * TAU + PI * 1.5 }; + let theta = if i == sides { 0.0 } else { v * TAU }; + let dir = Vec3::new(phi.cos(), 0.0, -phi.sin()); + let n = dir * theta.cos() - Vec3::Y * theta.sin(); + (dir * major + n * minor, n, Vec2::new(u, v)) + }); + b.finish("Torus") +} + +/// A subdivided plane facing +Y. +pub fn plane(size: f32, subdivisions: usize) -> Mesh { + let mut b = Builder::default(); + let s = subdivisions.max(1); + b.grid(s, s, |i, j| { + let (u, v) = (j as f32 / s as f32, i as f32 / s as f32); + (Vec3::new((u - 0.5) * size, 0.0, (v - 0.5) * size), Vec3::Y, Vec2::new(u, v)) + }); + b.finish("Plane") +} + +/// Two planes side by side on UV tiles 1001 and 1002 (UDIM): one material, 4 × 2 units. +pub fn udim_plane() -> Mesh { + let mut m = plane(2.0, 16); + let mut right = m.clone(); + for p in &mut m.positions { + p.x -= 1.0; + } + for p in &mut right.positions { + p.x += 1.0; + } + for uv in &mut right.uvs { + uv.x += 1.0; + } + right.materials.clear(); + right.submeshes.clear(); + m.append(&right); + let count = m.indices.len() as u32; + if let Some(s) = m.submeshes.first_mut() { + s.count = count; + } + m +} + +/// The default project mesh: a ball on a beveled pedestal, two materials ("Ball", "Base"). +pub fn material_ball() -> Mesh { + let mut ball = Builder::default(); + sphere_into(&mut ball, Vec3::new(0.0, 1.32, 0.0), 1.0, 128, 64, UvRect::FULL); + let mut ball = ball.finish("Ball"); + + let mut base = Builder::default(); + let (r, top, bot, bev) = (1.05f32, 0.32f32, 0.0f32, 0.07f32); + let mut profile = vec![(0.42, top + 0.06), (0.62, top + 0.06)]; + // Collar bevel and the ring the ball sits on, then the beveled drum. + for k in 1..=6 { + let a = k as f32 / 6.0 * PI * 0.5; + profile.push((0.62 + 0.06 * a.sin(), top + 0.06 * a.cos())); + } + profile.push((r - bev, top)); + for k in 1..=6 { + let a = k as f32 / 6.0 * PI * 0.5; + profile.push((r - bev + bev * a.sin(), top - bev + bev * a.cos())); + } + profile.push((r, bot + bev)); + for k in 1..=6 { + let a = k as f32 / 6.0 * PI * 0.5; + profile.push((r - bev + bev * a.cos(), bot + bev - bev * a.sin())); + } + lathe_into(&mut base, Vec3::ZERO, &profile, 128, UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01)); + disk_into(&mut base, Vec3::new(0.0, top + 0.06, 0.0), 0.42, true, 128, UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); + disk_into(&mut base, Vec3::new(0.0, bot, 0.0), r - bev, false, 128, UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); + let base = base.finish("Base"); + ball.append(&base); + ball +} + +/// A small showcase scene: a beveled crate with a rounded lid and a cylinder handle, in three +/// materials (used for demo projects and tests of multiple texture sets). +pub fn crate_scene() -> Mesh { + let mut body = Builder::default(); + rounded_box_into(&mut body, Vec3::new(0.0, 0.8, 0.0), Vec3::new(1.2, 0.8, 0.8), 0.12, UvRect::FULL); + let mut m = body.finish("Crate"); + let mut lid = Builder::default(); + rounded_box_into(&mut lid, Vec3::new(0.0, 1.72, 0.0), Vec3::new(1.28, 0.12, 0.88), 0.08, UvRect::FULL); + m.append(&lid.finish("Lid")); + let mut handle = torus(0.32, 0.07, 64, 24); + for p in &mut handle.positions { + *p = Vec3::new(p.x, p.z, -p.y) + Vec3::new(0.0, 1.84, 0.0); + } + for n in &mut handle.normals { + *n = Vec3::new(n.x, n.z, -n.y); + } + handle.materials = vec!["Handle".into()]; + if let Some(s) = handle.submeshes.first_mut() { + s.name = "Handle".into(); + } + handle.compute_tangents(); + m.append(&handle); + m +} + +/// Built-in mesh by id (`builtin:` in project files). +pub fn builtin(id: &str) -> Option { + Some(match id { + "material_ball" | "materialball" | "ball" => material_ball(), + "sphere" => sphere(1.0, 128, 64), + "cube" => cube(2.0).ok()?, + "rounded_cube" | "roundedcube" | "box" => rounded_box(Vec3::ONE, 0.15).ok()?, + "cylinder" => cylinder(1.0, 2.0, 96), + "torus" => torus(1.0, 0.35, 128, 48), + "plane" => plane(2.0, 16), + "crate" => crate_scene(), + "udim_plane" | "udimplane" => udim_plane(), + // Not offered for new projects (not in BUILTINS): the smart mask preview session's mesh + "preview_orb" => preview_orb(), + _ => return None, + }) +} + +/// Ids accepted by [`builtin`], in menu order. +pub const BUILTINS: [(&str, &str); 9] = [ + ("material_ball", "Material ball"), + ("sphere", "Sphere"), + ("cube", "Cube"), + ("rounded_cube", "Rounded cube"), + ("cylinder", "Cylinder"), + ("torus", "Torus"), + ("plane", "Plane"), + ("crate", "Crate"), + ("udim_plane", "UDIM plane"), +]; + +#[cfg(test)] +mod tests { + #[test] + fn lathe_profile_uvs_are_independent_of_height() { + let side_range = |mesh: &Mesh| { + mesh.uvs + .iter() + .zip(&mesh.normals) + .filter(|(_, normal)| normal.y.abs() < 0.5) + .fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), (uv, _)| (lo.min(uv.y), hi.max(uv.y))) + }; + let expected = side_range(&cylinder(1.0, 1.0, 16)); + let actual = side_range(&cylinder(1.0, 1e-20, 16)); + assert!((actual.0 - expected.0).abs() < 1e-6 && (actual.1 - expected.1).abs() < 1e-6, "{actual:?} {expected:?}"); + } + + #[test] + fn tall_cylinders_keep_finite_profile_uvs_and_unit_normals() { + let mesh = cylinder(1.0, 1e20, 16); + mesh.validate().unwrap(); + assert!(mesh.uvs.iter().all(|uv| uv.is_finite() && uv.min_element() >= 0.0 && uv.max_element() <= 1.0)); + assert!(mesh.normals.iter().all(|normal| normal.is_finite() && (normal.length_squared() - 1.0).abs() < 1e-5)); + } + + #[test] + fn accepted_small_box_dimensions_are_preserved() { + let cube = cube(1e-7).unwrap(); + let (lo, hi) = cube.bounds(); + assert_eq!(hi - lo, Vec3::splat(1e-7)); + let half = Vec3::new(5e-8, 2e-7, 3e-7); + let mesh = rounded_box(half, 0.0).unwrap(); + let (lo, hi) = mesh.bounds(); + assert_eq!((lo, hi), (-half, half)); + } + + #[test] + fn rounded_box_face_boundaries_share_exact_positions() { + for (half, bevel) in [(1.038, 0.037), (1e21, 1e20)] { + let mut builder = Builder::default(); + rounded_box_into(&mut builder, Vec3::ZERO, Vec3::splat(half), bevel, UvRect::FULL); + assert!(builder.n[0].abs().min_element() > 0.5, "rounded corner normal {:?}, half={half}", builder.n[0]); + let key = |p: Vec3| p.to_array().map(|v| if v == 0.0 { 0 } else { v.to_bits() }); + let mut counts = std::collections::HashMap::new(); + for &position in &builder.p { + *counts.entry(key(position)).or_insert(0usize) += 1; + } + let side = 23; + for face in 0..6 { + for row in 0..side { + for column in 0..side { + if row == 0 || column == 0 || row == side - 1 || column == side - 1 { + let position = builder.p[face * side * side + row * side + column]; + assert!(counts[&key(position)] >= 2, "unmatched boundary {position:?}, half={half}"); + } + } + } + } + } + } + + #[test] + fn cylinder_caps_match_the_wall_at_every_segment_count() { + for segments in [3, 6, 7, 32] { + let mesh = cylinder(1.0, 2.0, segments); + for row in 0..=1 { + let (first, last) = (row * (segments + 1), row * (segments + 1) + segments); + assert_eq!(mesh.positions[first], mesh.positions[last]); + assert_eq!(mesh.normals[first], mesh.normals[last]); + assert!(mesh.uvs[first].x < mesh.uvs[last].x); + } + for y in [-1.0, 1.0] { + let wall: Vec<_> = mesh + .positions + .iter() + .zip(&mesh.normals) + .filter_map(|(position, normal)| (position.y == y && normal.y == 0.0).then_some(*position)) + .collect(); + let rim: Vec<_> = mesh + .positions + .iter() + .zip(&mesh.normals) + .filter_map(|(position, normal)| { + (position.y == y && normal.y != 0.0 && position.x * position.x + position.z * position.z > 0.5).then_some(*position) + }) + .collect(); + assert_eq!(rim.len(), segments); + assert!(rim.iter().all(|position| wall.contains(position)), "{segments} segments at height {y}: {rim:?} vs {wall:?}"); + } + } + } + + #[test] + fn sphere_poles_use_identical_endpoint_positions() { + for segments in [3, 7, 32] { + let rings = 8; + let mesh = sphere(1.0, segments, rings); + for (row, expected) in [(0, Vec3::Y), (rings, -Vec3::Y)] { + for column in 0..=segments { + let index = row * (segments + 1) + column; + assert_eq!(mesh.positions[index], expected); + assert_eq!(mesh.normals[index], expected); + } + } + } + } + + #[test] + fn sphere_geometry_closes_its_longitudinal_uv_seam_exactly() { + for segments in [3, 7, 32] { + let rings = 8; + let mesh = sphere(1.0, segments, rings); + let width = segments + 1; + for row in 0..=rings { + let (a, b) = (row * width, row * width + segments); + assert_eq!(mesh.positions[a], mesh.positions[b], "seam row {row}"); + assert_eq!(mesh.normals[a], mesh.normals[b], "seam normal row {row}"); + assert_eq!((mesh.uvs[a].x, mesh.uvs[b].x), (0.0, 1.0)); + } + } + } + + #[test] + fn torus_geometry_closes_both_uv_seams_exactly() { + for (segs, sides) in [(3, 3), (7, 5), (32, 12)] { + let mesh = torus(1.0, 0.35, segs, sides); + let width = segs + 1; + for row in 0..=sides { + let (a, b) = (row * width, row * width + segs); + assert_eq!(mesh.positions[a], mesh.positions[b], "u seam row {row}"); + assert_eq!(mesh.normals[a], mesh.normals[b], "u seam normal row {row}"); + assert_eq!((mesh.uvs[a].x, mesh.uvs[b].x), (0.0, 1.0)); + } + for col in 0..=segs { + let (a, b) = (col, sides * width + col); + assert_eq!(mesh.positions[a], mesh.positions[b], "v seam column {col}"); + assert_eq!(mesh.normals[a], mesh.normals[b], "v seam normal column {col}"); + assert_eq!((mesh.uvs[a].y, mesh.uvs[b].y), (0.0, 1.0)); + } + } + } + + use super::*; + + #[test] + fn invalid_cube_dimensions_do_not_panic() { + for size in [-1.0, 0.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + let result = std::panic::catch_unwind(|| cube(size)); + assert!(result.is_ok(), "cube({size}) panicked"); + assert!(result.unwrap().is_err(), "cube({size}) must reject invalid dimensions"); + } + } + + #[test] + fn invalid_rounded_box_dimensions_do_not_panic() { + for axis in 0..3 { + for value in [-1.0, 0.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX] { + let mut half = Vec3::ONE; + half[axis] = value; + let result = std::panic::catch_unwind(|| rounded_box(half, 0.0)); + assert!(result.is_ok(), "rounded_box({half:?}) panicked"); + assert!(result.unwrap().is_err(), "rounded_box({half:?}) must reject invalid dimensions"); + } + } + } + + #[test] + fn invalid_box_bevels_are_rejected_instead_of_clamped() { + for bevel in [-1.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.950001] { + assert!(rounded_box(Vec3::ONE, bevel).is_err(), "{bevel}"); + } + for bevel in [0.0, 0.95] { + assert!(rounded_box(Vec3::ONE, bevel).is_ok(), "{bevel}"); + } + assert!(cube(2.0).is_ok()); + } + + #[test] + fn large_finite_box_extents_keep_generated_positions_finite() { + let mesh = rounded_box(Vec3::new(1e38, 1.0, 1.0), 0.0).unwrap(); + assert!(mesh.positions.iter().all(|p| p.is_finite())); + } + + /// Every triangle's winding agrees with its vertex normals, UVs stay in 0..1 (u in 0..max_u), + /// and the UV mapping is not mirrored (tangent handedness +1). + fn check(m: &Mesh, max_u: f32) { + m.validate().unwrap(); + let mut bad = 0; + for t in 0..m.triangle_count() { + let [a, b, c] = m.tri(t).unwrap(); + let face = (m.positions[b] - m.positions[a]).cross(m.positions[c] - m.positions[a]); + if face.length() < 1e-9 { + continue; + } + let n = m.normals[a] + m.normals[b] + m.normals[c]; + if face.dot(n) <= 0.0 { + bad += 1; + } + } + assert_eq!(bad, 0, "{} triangles wound against their normals", bad); + for uv in &m.uvs { + assert!((0.0..=max_u).contains(&uv.x) && (0.0..=1.0).contains(&uv.y), "{uv:?}"); + } + let mirrored = m.tangents.iter().filter(|t| t.w < 0.0).count(); + assert!(mirrored * 50 < m.tangents.len().max(1), "{mirrored} mirrored tangents"); + } + + #[test] + fn primitives_are_well_formed() { + for (id, _) in BUILTINS { + let m = builtin(id).unwrap(); + assert!(m.triangle_count() > 0, "{id}"); + check(&m, if id == "udim_plane" { 2.0 } else { 1.0 }); + } + assert!(builtin("nope").is_none()); + assert_eq!(udim_plane().uv_tiles(0).into_iter().collect::>(), vec![(0, 0), (1, 0)]); + } + + #[test] + fn preview_orb_is_well_formed_with_domed_panels() { + let m = preview_orb(); + check(&m, 1.0); + + // Above the middle slot, the front panel's dome rises past the cut face and its valley + // sits below it + let front_depth = |rho: f32| { + let d = Vec3::new(0.0, rho, 1.0).normalize(); + preview_orb_radius(d) * d.z + }; + let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT; + let (dome, valley) = (front_depth(0.2), front_depth(rim * ORB_PANEL_VALLEY)); + assert!(dome > ORB_CUT && valley < ORB_CUT - 0.05, "dome {dome}, valley {valley}"); + } + + #[test] + fn material_ball_has_two_materials() { + let m = material_ball(); + assert_eq!(m.materials, vec!["Ball".to_string(), "Base".to_string()]); + assert!(m.triangles_of(0).count() > 0 && m.triangles_of(1).count() > 0); + } +} diff --git a/crates/mesh-ops/src/unwrap.rs b/crates/mesh-ops/src/unwrap.rs new file mode 100644 index 0000000000..29ad58da0e --- /dev/null +++ b/crates/mesh-ops/src/unwrap.rs @@ -0,0 +1,690 @@ +//! Automatic UV unwrapping for meshes imported without texture coordinates. +//! +//! Triangles are grouped into charts by flood fill across shared (welded) edges while each face +//! normal stays within 60° of the chart's seed face. Charts are rotated to their principal axes +//! and shelf-packed per material into 0..1 with one uniform scale. Texel density is the same +//! everywhere within a material. + +use std::collections::{HashMap, VecDeque}; + +use glam::{DVec2, DVec3, Vec2, Vec3}; + +use crate::{GeomError, Mesh, Result}; + +/// Vertices an unwrap accepts, and the most it produces. +const MAX_UNWRAP_VERTICES: usize = 20_000_000; +/// Triangles an unwrap accepts, counting a triangle once for each submesh that lists it. +const MAX_UNWRAP_TRIANGLES: usize = 4_000_000; + +/// Faces of a chart stay within this angle of the seed face normal (cos 60°). +const CHART_COS: f32 = 0.5; + +/// Welded vertex id per vertex: vertices at the same position (snapped to a grid of 1e-6 of +/// the bounding diagonal) share an id. Ids are dense, in order of first appearance. +pub fn weld_ids(positions: &[Vec3]) -> Vec { + let (lo, hi) = + positions.iter().map(|p| p.as_dvec3()).fold((DVec3::splat(f64::MAX), DVec3::splat(f64::MIN)), |(lo, hi), p| (lo.min(p), hi.max(p))); + let diagonal = (hi - lo).length(); + let cell = if diagonal > 0.0 && diagonal.is_finite() { diagonal * 1e-6 } else { 1.0 }; + let mut map: HashMap<[i64; 3], u32> = HashMap::with_capacity(positions.len()); + positions + .iter() + .map(|p| { + let q = ((p.as_dvec3() - lo) / cell).round(); + let next = map.len() as u32; + *map.entry([q.x as i64, q.y as i64, q.z as i64]).or_insert(next) + }) + .collect() +} + +/// True when the mesh has triangles and every one of them has two corners at the same position. +/// MikkTSpace (and so [`Mesh::compute_tangents`]) crashes on such meshes, so callers reject them. +pub fn all_triangles_degenerate(mesh: &Mesh) -> bool { + let p = |i: &u32| mesh.positions.get(*i as usize); + !mesh.indices.is_empty() + && mesh.indices.chunks(3).all(|t| match t { + [a, b, c] => p(a) == p(b) || p(a) == p(c) || p(b) == p(c), + _ => true, + }) +} + +fn face_has_area(positions: [Vec3; 3]) -> bool { + (0..3).any(|axis| { + let next = (axis + 1) % 3; + let [a, b, c] = positions.map(|position| [f64::from(position[axis]), f64::from(position[next])]); + let products = [a[0] * b[1], b[0] * c[1], c[0] * a[1], -a[1] * b[0], -b[1] * c[0], -c[1] * a[0]]; + let (mut expansion, mut len) = ([0.0; 6], 0); + for mut value in products { + let mut kept = 0; + for index in 0..len { + let part = expansion[index]; + let sum = value + part; + let part_virtual = sum - value; + let value_virtual = sum - part_virtual; + let error = (value - value_virtual) + (part - part_virtual); + if error != 0.0 { + expansion[kept] = error; + kept += 1; + } + value = sum; + } + expansion[kept] = value; + len = kept + 1; + } + expansion[..len].iter().any(|part| *part != 0.0) + }) +} + +struct Chart { + material: usize, + /// The seed face's first corner. Projections are taken relative to it, in `f64`, so they + /// keep the chart's own detail wherever the chart lies. + origin: DVec3, + /// Projection basis (right-handed with the seed normal). + t: DVec3, + b: DVec3, + /// Rotation to the chart's principal axes (cos, sin). + rot: DVec2, + /// Bounds of the rotated chart. Charts are measured and packed in `f64`, where the extent of + /// any chart of finite `f32` positions and the scale that packs it neither overflow nor + /// round to zero. + lo: DVec2, + hi: DVec2, + /// Texel offset of the chart's packed rectangle. + offset: DVec2, +} + +impl Chart { + fn local(&self, p: Vec3) -> DVec2 { + let d = p.as_dvec3() - self.origin; + let q = DVec2::new(d.dot(self.t), d.dot(self.b)); + DVec2::new(q.x * self.rot.x - q.y * self.rot.y, q.x * self.rot.y + q.y * self.rot.x) + } + fn size(&self) -> DVec2 { + (self.hi - self.lo).max(DVec2::ZERO) + } +} + +/// Area-weighted smooth normals over the index buffer, as [`Mesh::compute_normals`] computes +/// them, returned instead of stored. +fn smooth_normals(mesh: &Mesh) -> Vec { + let mut normals = vec![DVec3::ZERO; mesh.positions.len()]; + for &[a, b, c] in mesh.indices.as_chunks::<3>().0 { + let (a, b, c) = (a as usize, b as usize, c as usize); + let (Some(pa), Some(pb), Some(pc)) = (mesh.positions.get(a), mesh.positions.get(b), mesh.positions.get(c)) else { continue }; + let face = (pb.as_dvec3() - pa.as_dvec3()).cross(pc.as_dvec3() - pa.as_dvec3()); + for v in [a, b, c] { + if let Some(x) = normals.get_mut(v) { + *x += face; + } + } + } + normals.into_iter().map(|v| v.try_normalize().map(|normal| normal.as_vec3()).unwrap_or(Vec3::Y)).collect() +} + +/// The checks [`auto_unwrap`] makes before it changes anything. The size limits come first. +fn check_input(mesh: &Mesh) -> Result<()> { + if mesh.positions.len() > MAX_UNWRAP_VERTICES { + return Err(GeomError::Invalid(format!("mesh has {} vertices; unwrapping accepts at most {MAX_UNWRAP_VERTICES}", mesh.positions.len()))); + } + if mesh.triangle_count() > MAX_UNWRAP_TRIANGLES { + return Err(GeomError::Invalid(format!("mesh has {} triangles; unwrapping accepts at most {MAX_UNWRAP_TRIANGLES}", mesh.triangle_count()))); + } + let listed = mesh.submeshes.iter().fold(0u64, |sum, s| sum.saturating_add(u64::from(s.count / 3))); + if listed > MAX_UNWRAP_TRIANGLES as u64 { + return Err(GeomError::Invalid(format!("submeshes list {listed} triangles; unwrapping accepts at most {MAX_UNWRAP_TRIANGLES}"))); + } + mesh.validate_indices()?; + for s in &mesh.submeshes { + if !s.start.is_multiple_of(3) || !s.count.is_multiple_of(3) { + return Err(GeomError::Invalid(format!("submesh {} is not triangle-aligned", s.name))); + } + if u64::from(s.start) + u64::from(s.count) > mesh.indices.len() as u64 || s.material >= mesh.materials.len().max(1) { + return Err(GeomError::Invalid(format!("submesh {} is out of range", s.name))); + } + } + if mesh.positions.iter().any(|p| !p.is_finite()) { + return Err(GeomError::Invalid("mesh has non-finite positions".into())); + } + if mesh.normals.len() == mesh.positions.len() && mesh.normals.iter().any(|v| !v.is_finite()) { + return Err(GeomError::Invalid("mesh has non-finite normals".into())); + } + if !mesh.colors.is_empty() && (mesh.colors.len() != mesh.positions.len() || mesh.colors.iter().any(|c| !c.is_finite())) { + return Err(GeomError::Invalid("mesh colors are not one finite color per vertex".into())); + } + if all_triangles_degenerate(mesh) { + return Err(GeomError::Invalid("every triangle of the mesh is degenerate".into())); + } + if !mesh.indices.is_empty() + && mesh.indices.as_chunks::<3>().0.iter().all(|vertices| !face_has_area(vertices.map(|vertex| mesh.positions[vertex as usize]))) + { + return Err(GeomError::Invalid("every triangle of the mesh is degenerate".into())); + } + Ok(()) +} + +/// The material of every triangle. Each material is packed into its own 0..1 square, so a +/// triangle that submeshes of two materials list would be laid out over another chart of one of +/// them, and is an error. Every triangle must be listed by a submesh. +fn face_materials(mesh: &Mesh) -> Result> { + let n = mesh.triangle_count(); + let mut material = vec![usize::MAX; n]; + for s in &mesh.submeshes { + let end = (u64::from(s.start) + u64::from(s.count)) / 3; + for t in (s.start / 3) as usize..(end as usize).min(n) { + if let Some(m) = material.get_mut(t) { + if *m != usize::MAX && *m != s.material { + return Err(GeomError::Invalid(format!("triangle {t} is in submeshes of materials {} and {}", *m, s.material))); + } + *m = s.material; + } + } + } + if material.contains(&usize::MAX) { + return Err(GeomError::Invalid("submeshes do not cover every triangle".into())); + } + Ok(material) +} + +/// Replace the UVs of `mesh` with an automatic non-overlapping layout: each material gets its +/// own 0..1 space with charts at least `padding_texels` (minimum 1, which a NaN counts as) away +/// from each other and the borders at `resolution`. Vertices are split at chart borders; +/// tangents are recomputed. Returns the number of charts. +/// The effective resolution is at least 16. A layout that cannot fit with the requested +/// padding returns an error without changing the mesh. +/// +/// A mesh that fails a check is returned unchanged: indices, triangle-aligned submesh ranges +/// that cover every triangle, materials, no +/// triangle listed by submeshes of two materials, finite positions, finite normals and colors +/// when it has them, at least one triangle that is not degenerate, and the size limits (20 +/// million vertices; 4 million triangles, counting a triangle once for each submesh that lists +/// it). The limits are checked before any other work. More than 20 million new vertices is an +/// error as well. +pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Result { + check_input(mesh)?; + // Kept apart from the mesh until the layout is packed, so an error leaves the mesh as it was. + let computed_normals = if mesh.normals.len() != mesh.positions.len() { Some(smooth_normals(mesh)) } else { None }; + let old_normals = computed_normals.as_deref().unwrap_or(&mesh.normals); + let n = mesh.triangle_count(); + let weld = weld_ids(&mesh.positions); + let pos = |v: usize| mesh.positions.get(v).copied().unwrap_or_default(); + let wid = |v: usize| weld.get(v).copied().unwrap_or(u32::MAX); + + // Face normals (None for degenerate faces) and materials. + let mut normal: Vec> = Vec::with_capacity(n); + let mut area = Vec::with_capacity(n); + for t in 0..n { + let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]).map(|v| pos(v).as_dvec3()); + let cr = (b - a).cross(c - a); + area.push(cr.length() * 0.5); + normal.push(cr.try_normalize().map(|n| n.as_vec3())); + } + let material = face_materials(mesh)?; + + // Manifold edge adjacency over welded vertices: edge → (face, face, count). + let mut edges: HashMap<(u32, u32), (u32, u32, u8)> = HashMap::with_capacity(n * 2); + let tri_edges = |t: usize| -> [(u32, u32); 3] { + let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]); + let key = |x: usize, y: usize| { + let (p, q) = (wid(x), wid(y)); + (p.min(q), p.max(q)) + }; + [key(a, b), key(b, c), key(c, a)] + }; + for t in 0..n { + for e in tri_edges(t) { + if e.0 == e.1 { + continue; + } + let slot = edges.entry(e).or_insert((t as u32, u32::MAX, 0)); + if slot.2 == 1 { + slot.1 = t as u32; + } + slot.2 = slot.2.saturating_add(1); + } + } + + // Grow charts from the largest unassigned faces. + let mut order: Vec = (0..n).collect(); + order.sort_by(|a, b| area[*b].total_cmp(&area[*a])); + let mut chart_of = vec![u32::MAX; n]; + let mut charts: Vec = Vec::new(); + let mut queue = VecDeque::new(); + for &seed in &order { + if chart_of[seed] != u32::MAX { + continue; + } + let id = charts.len() as u32; + let sn = normal[seed].unwrap_or(Vec3::Z); + let t = sn.any_orthonormal_vector(); + let b = sn.cross(t); + // Relative to the seed's first corner, so the rounding of a projection follows the + // chart's size rather than its distance from the origin. + let origin = pos(mesh.tri(seed).unwrap_or([0; 3])[0]).as_dvec3(); + charts.push(Chart { + material: material[seed], + origin, + t: t.as_dvec3(), + b: b.as_dvec3(), + rot: DVec2::X, + lo: DVec2::ZERO, + hi: DVec2::ZERO, + offset: DVec2::ZERO, + }); + chart_of[seed] = id; + queue.push_back(seed); + while let Some(f) = queue.pop_front() { + for e in tri_edges(f) { + let Some(&(f0, f1, 2)) = edges.get(&e) else { continue }; + let g = if f0 as usize == f { f1 } else { f0 } as usize; + let ok = normal.get(g).is_some_and(|nn| nn.is_none_or(|nn| nn.dot(sn) >= CHART_COS)); + if ok && chart_of.get(g) == Some(&u32::MAX) && material.get(g) == Some(&material[seed]) { + chart_of[g] = id; + queue.push_back(g); + } + } + } + } + + // Principal axes and bounds of every chart, in f64 from the positions as given. + let mut cov = vec![(DVec2::ZERO, [0.0f64; 3], 0usize); charts.len()]; + for (t, &c) in chart_of.iter().enumerate() { + let c = c as usize; + for v in mesh.tri(t).unwrap_or([0; 3]) { + if let (Some(ch), Some(acc)) = (charts.get(c), cov.get_mut(c)) { + let q = ch.local(pos(v)); + acc.0 += q; + acc.1[0] += q.x * q.x; + acc.1[1] += q.y * q.y; + acc.1[2] += q.x * q.y; + acc.2 += 1; + } + } + } + for (ch, (sum, m, k)) in charts.iter_mut().zip(&cov) { + let k = (*k).max(1) as f64; + let (mx, my) = (sum.x / k, sum.y / k); + let (cxx, cyy, cxy) = (m[0] / k - mx * mx, m[1] / k - my * my, m[2] / k - mx * my); + let angle = 0.5 * (2.0 * cxy).atan2(cxx - cyy); + // Rotate so the principal axis lies along x. + ch.rot = DVec2::new((-angle).cos(), (-angle).sin()); + ch.lo = DVec2::splat(f64::MAX); + ch.hi = DVec2::splat(f64::MIN); + } + for (t, &c) in chart_of.iter().enumerate() { + let c = c as usize; + for v in mesh.tri(t).unwrap_or([0; 3]) { + if let Some(ch) = charts.get_mut(c) { + let q = ch.local(pos(v)); + ch.lo = ch.lo.min(q); + ch.hi = ch.hi.max(q); + } + } + } + for ch in &mut charts { + if ch.size().y > ch.size().x { + // Quarter turn (x, y) → (y, −x) so shelves stay low. + ch.rot = DVec2::new(ch.rot.y, -ch.rot.x); + let (lo, hi) = (ch.lo, ch.hi); + ch.lo = DVec2::new(lo.y, -hi.x); + ch.hi = DVec2::new(hi.y, -lo.x); + } + } + + // Pack each material's charts into its own 0..1 square. + let pad = padding_texels.max(1.0); + let mut scale = HashMap::new(); + let mut by_material: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for (id, chart) in charts.iter().enumerate() { + by_material.entry(chart.material).or_default().push(id); + } + for (m, ids) in by_material { + let sizes: Vec = ids.iter().map(|i| charts[*i].size()).collect(); + let (s, res, offsets) = pack(&sizes, resolution.max(16) as f32, pad)?; + for (i, o) in ids.iter().zip(offsets) { + charts[*i].offset = o; + } + scale.insert(m, (s, res)); + } + + // Rebuild vertices: one per (vertex, chart). + let mut remap: HashMap<(u32, u32), u32> = HashMap::with_capacity(mesh.positions.len().saturating_mul(2).min(mesh.indices.len())); + let (mut positions, mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let mut indices = Vec::with_capacity(mesh.indices.len()); + for (t, &c) in chart_of.iter().enumerate() { + let Some(ch) = charts.get(c as usize) else { continue }; + let (s, res) = scale.get(&ch.material).copied().unwrap_or((0.0, 1.0f32)); + for v in mesh.tri(t).unwrap_or([0; 3]) { + let idx = *remap.entry((v as u32, c)).or_insert_with(|| { + let q = ch.local(pos(v)); + // Chart y points up; UV v points down the image. + let texel = ch.offset + DVec2::splat(f64::from(pad)) + DVec2::new(q.x - ch.lo.x, ch.hi.y - q.y) * s; + positions.push(pos(v)); + normals.push(old_normals.get(v).copied().unwrap_or(Vec3::Y)); + if let Some(c) = mesh.colors.get(v) { + colors.push(*c); + } + uvs.push((texel / f64::from(res)).as_vec2().clamp(Vec2::ZERO, Vec2::ONE)); + (positions.len() - 1) as u32 + }); + indices.push(idx); + } + if positions.len() > MAX_UNWRAP_VERTICES { + return Err(GeomError::Invalid(format!("unwrapping would produce more than {MAX_UNWRAP_VERTICES} vertices"))); + } + } + let charts = charts.len(); + // The new arrays replace the mesh's only once the tangents and the final check have passed. + let old = ( + std::mem::replace(&mut mesh.positions, positions), + std::mem::replace(&mut mesh.normals, normals), + std::mem::replace(&mut mesh.uvs, uvs), + std::mem::replace(&mut mesh.colors, colors), + std::mem::replace(&mut mesh.indices, indices), + std::mem::take(&mut mesh.tangents), + ); + mesh.compute_tangents(); + if let Err(e) = mesh.validate() { + (mesh.positions, mesh.normals, mesh.uvs, mesh.colors, mesh.indices, mesh.tangents) = old; + return Err(e); + } + Ok(charts) +} + +/// Shelf-pack rectangles of world `sizes` (each grown by `pad` texels per side) into a square of +/// `res` texels with the largest uniform scale that fits. Returns (texels per world unit, +/// resolution used, texel offset per rectangle). A layout without room for a positive scale +/// returns an error. The sizes and the scale are in +/// `f64`, where the scale of any chart of finite `f32` positions is finite and above zero. +fn pack(sizes: &[DVec2], res: f32, pad: f32) -> Result<(f64, f32, Vec)> { + let mut order: Vec = (0..sizes.len()).collect(); + order.sort_by(|a, b| sizes[*b].y.total_cmp(&sizes[*a].y)); + let mut out = vec![DVec2::ZERO; sizes.len()]; + let pad = f64::from(pad); + // Shelf-place every rectangle at scale `s` into `out`; false when they do not fit. + let place = |s: f64, res: f32, out: &mut [DVec2]| -> bool { + let res = f64::from(res); + let (mut x, mut y, mut shelf) = (0.0f64, 0.0f64, 0.0f64); + for &i in &order { + let r = sizes[i] * s + DVec2::splat(2.0 * pad); + if r.x > res { + return false; + } + if x + r.x > res { + y += shelf; + x = 0.0; + shelf = 0.0; + } + if y + r.y > res { + return false; + } + if let Some(o) = out.get_mut(i) { + *o = DVec2::new(x, y); + } + x += r.x; + shelf = shelf.max(r.y); + } + true + }; + let largest = sizes.iter().map(|s| s.max_element()).fold(0.0f64, f64::max); + if place(0.0, res, &mut out) { + if largest <= 0.0 { + return Ok((0.0, res, out)); + } + let (mut lo, mut hi) = (0.0f64, (f64::from(res) - 2.0 * pad).max(0.0) / largest); + // Halve the upper bound until a positive scale fits, so the refinement below starts + // from a feasible lower bound however far below the first guess the answer lies. + while hi > 0.0 { + if place(hi, res, &mut out) { + lo = hi; + break; + } + hi *= 0.5; + } + hi = if lo > 0.0 { (2.0 * lo).min((f64::from(res) - 2.0 * pad).max(0.0) / largest) } else { hi }; + for _ in 0..40 { + if hi - lo <= lo * 1e-4 { + break; + } + let mid = 0.5 * (lo + hi); + if place(mid, res, &mut out) { lo = mid } else { hi = mid } + } + if lo > 0.0 && place(lo, res, &mut out) { + return Ok((lo, res, out)); + } + } + Err(GeomError::Invalid("UV charts cannot fit with the requested padding and resolution".into())) +} + +impl Mesh { + /// Index-range checks only (attribute arrays may be incomplete before unwrapping). + fn validate_indices(&self) -> Result<()> { + let n = self.positions.len(); + if !self.indices.len().is_multiple_of(3) || self.indices.iter().any(|i| *i as usize >= n) { + return Err(GeomError::Invalid("mesh indices are out of range".into())); + } + if self.triangle_count() > crate::MAX_TRIANGLES { + return Err(GeomError::Invalid(format!("mesh has more than {} triangles", crate::MAX_TRIANGLES))); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn tiny_quads_keep_their_shared_chart_edge() { + let mut mesh = quad(); + for position in &mut mesh.positions { + *position *= 2.0_f32.powi(-42); + } + assert_eq!(auto_unwrap(&mut mesh, 4.0, 16).unwrap(), 1); + assert_eq!(weld_ids(&[Vec3::ONE; 4]), vec![0; 4]); + } + + #[test] + fn nonempty_all_collinear_meshes_are_rejected_unchanged() { + for positions in [vec![Vec3::ZERO, Vec3::X, Vec3::X * 2.0], { + let d = Vec3::new(1.0, 17.0, 0.0); + vec![Vec3::ZERO, d * (3.0 * 2.0_f32.powi(-49)), d] + }] { + let mut mesh = Mesh::from_parts(positions, Some(vec![Vec3::Z; 3]), Vec::new(), vec![0, 1, 2], "m").unwrap(); + let before = mesh.clone(); + assert!(auto_unwrap(&mut mesh, 4.0, 256).is_err()); + assert_eq!(mesh, before); + } + } + + #[test] + fn missing_normals_keep_tiny_and_large_face_directions() { + for scale in [1e-25, 1e25] { + let mesh = Mesh { positions: vec![Vec3::ZERO, Vec3::Y * scale, Vec3::Z * scale], indices: vec![0, 1, 2], ..Mesh::default() }; + assert_eq!(smooth_normals(&mesh), vec![Vec3::X; 3], "scale={scale}"); + } + } + + #[test] + fn incomplete_or_unaligned_submeshes_leave_the_layout_unchanged() { + let original = primitives::cube(1.0).unwrap(); + for variant in 0..3 { + let mut mesh = original.clone(); + match variant { + 0 => mesh.submeshes.clear(), + 1 => mesh.submeshes[0].count -= 3, + _ => { + mesh.submeshes[0].start = 1; + mesh.submeshes[0].count = 3; + } + } + let before = mesh.clone(); + assert!(auto_unwrap(&mut mesh, 4.0, 256).is_err(), "variant {variant}"); + assert_eq!(mesh, before); + } + } + + #[test] + fn packing_preserves_the_requested_resolution_and_border() { + assert!(pack(&[DVec2::ONE; 2000], 128.0, 4.0).is_err()); + assert!(pack(&[DVec2::ONE], 16.0, 8.0).is_err()); + let (_, resolution, offsets) = pack(&[DVec2::ONE; 2], 128.0, 4.0).unwrap(); + assert_eq!(resolution, 128.0); + assert_eq!((offsets[0].x + 4.0) / f64::from(resolution) * 128.0, 4.0); + } + + #[test] + fn packing_finds_a_small_scale_far_below_the_first_guess() { + let pad = 1.0 + 262_657.0 / 8_388_608.0; + let (scale, _, _) = pack(&vec![DVec2::ONE; 511 * 511], 1054.0, pad as f32).unwrap(); + assert!(scale > 0.0); + assert!(pack(&vec![DVec2::ONE; 600 * 600], 1054.0, pad as f32).is_err()); + } + + #[test] + fn weld_grid_keeps_distinct_extreme_positions() { + let positions = [Vec3::splat(-f32::MAX), Vec3::ZERO, Vec3::splat(f32::MAX)]; + assert_eq!(weld_ids(&positions), vec![0, 1, 2]); + } + + use glam::Vec4; + + use super::*; + use crate::{UvGBuffer, primitives}; + + fn check(mut m: Mesh, min_coverage: f32) { + m.uvs.clear(); + let charts = auto_unwrap(&mut m, 4.0, 512).unwrap(); + assert!(charts >= 1); + m.validate().unwrap(); + assert!(m.uvs.iter().all(|uv| (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y))); + let g = UvGBuffer::new(&m, 0, 512, 512).unwrap(); + let covered = g.covered_count() as f32; + let coverage = covered / (512.0 * 512.0); + assert!(coverage > min_coverage, "coverage {coverage} with {charts} charts"); + assert!((g.overlaps as f32) < covered * 0.005, "overlaps {} of {covered}", g.overlaps); + } + + #[test] + fn sphere_unwraps_without_overlaps() { + check(primitives::sphere(1.0, 48, 24), 0.3); + } + + #[test] + fn cube_unwraps_without_overlaps() { + check(primitives::cube(2.0).unwrap(), 0.3); + } + + #[test] + fn torus_and_material_ball_unwrap() { + check(primitives::torus(1.0, 0.3, 48, 24), 0.2); + let mut ball = primitives::material_ball(); + ball.uvs.clear(); + auto_unwrap(&mut ball, 2.0, 1024).unwrap(); + for m in 0..ball.materials.len() { + let g = UvGBuffer::new(&ball, m, 512, 512).unwrap(); + assert!((g.overlaps as f32) < g.covered_count() as f32 * 0.005 + 1.0, "material {m}: {} overlaps", g.overlaps); + } + } + + #[test] + fn many_tiny_charts_require_room_at_the_requested_resolution() { + let mut p = Vec::new(); + let mut idx = Vec::new(); + for i in 0..2000u32 { + let o = Vec3::new(i as f32 * 3.0, 0.0, 0.0); + p.extend([o, o + Vec3::X, o + Vec3::Y]); + idx.extend([i * 3, i * 3 + 1, i * 3 + 2]); + } + let mut m = Mesh::from_parts(p, None, Vec::new(), idx, "m").unwrap(); + let before = m.clone(); + assert!(auto_unwrap(&mut m, 4.0, 128).is_err()); + assert_eq!(m, before); + auto_unwrap(&mut m, 4.0, 512).unwrap(); + assert!(m.uvs.iter().all(|uv| (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y))); + } + + #[test] + fn degenerate_and_empty_meshes_do_not_fail() { + let mut empty = Mesh::default(); + assert_eq!(auto_unwrap(&mut empty, 4.0, 256).unwrap(), 0); + // A sliver (zero-area) triangle next to a real one. + let p = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::X * 2.0]; + let mut m = Mesh::from_parts(p, None, Vec::new(), vec![0, 1, 2, 0, 1, 3], "m").unwrap(); + auto_unwrap(&mut m, 4.0, 256).unwrap(); + m.validate().unwrap(); + let mut point = Mesh { positions: vec![Vec3::ONE; 3], indices: vec![0, 1, 2], ..Mesh::default() }; + assert!(all_triangles_degenerate(&point)); + assert!(auto_unwrap(&mut point, 4.0, 256).is_err()); + } + + fn quad() -> Mesh { + let p = vec![Vec3::ZERO, Vec3::X, Vec3::new(1.0, 1.0, 0.0), Vec3::Y]; + Mesh::from_parts(p, None, Vec::new(), vec![0, 1, 2, 0, 2, 3], "m").unwrap() + } + + fn submesh(material: usize, start: u32, count: u32) -> crate::SubMesh { + crate::SubMesh { name: "s".into(), material, start, count } + } + + #[test] + fn rejected_meshes_are_left_unchanged() { + let mut two_materials = quad(); + two_materials.materials = vec!["a".into(), "b".into()]; + two_materials.submeshes = vec![submesh(0, 0, 6), submesh(1, 3, 3)]; + let mut nan_normal = quad(); + nan_normal.normals = vec![Vec3::INFINITY; 4]; + let mut short_colors = quad(); + short_colors.colors = vec![Vec4::ONE; 2]; + let mut range = quad(); + range.submeshes = vec![submesh(0, 6, 3)]; + let mut nan_position = quad(); + nan_position.positions[2] = Vec3::INFINITY; + for (name, mut m) in [ + ("two materials", two_materials), + ("infinite normal", nan_normal), + ("short colors", short_colors), + ("range", range), + ("infinite position", nan_position), + ] { + m.uvs.clear(); + let before = m.clone(); + assert!(auto_unwrap(&mut m, 4.0, 256).is_err(), "{name}"); + assert_eq!(m, before, "{name}"); + } + } + + #[test] + fn size_limits_are_checked_before_anything_else() { + // Indices out of range as well: the limit is the error reported. + let mut m = quad(); + m.indices = vec![0, 1, 9]; + m.submeshes = vec![submesh(0, 0, u32::MAX)]; + let before = m.clone(); + let message = auto_unwrap(&mut m, 4.0, 256).unwrap_err().to_string(); + assert!(message.contains("accepts at most"), "{message}"); + assert_eq!(m, before); + } + + #[test] + fn small_charts_far_from_the_origin_keep_their_shape() { + // A right triangle with 16-unit legs at 1e8, where an f32 position is 8 units apart. + let o = Vec3::splat(1e8); + let p = vec![o, o + Vec3::X * 16.0, o + Vec3::Y * 16.0]; + let mut m = Mesh::from_parts(p, None, Vec::new(), vec![0, 1, 2], "m").unwrap(); + auto_unwrap(&mut m, 4.0, 256).unwrap(); + let (a, b, c) = (m.uvs[m.indices[0] as usize], m.uvs[m.indices[1] as usize], m.uvs[m.indices[2] as usize]); + let (e1, e2) = (b - a, c - a); + assert!(e1.length() > 0.1 && (e1.length() - e2.length()).abs() < 1e-3, "legs {e1} and {e2}"); + assert!(e1.dot(e2).abs() < 1e-3, "legs {e1} and {e2} are not at a right angle"); + } + + #[test] + fn padding_that_fills_the_square_does_not_replace_the_mesh() { + let mut m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y], None, Vec::new(), vec![0, 1, 2], "m").unwrap(); + let before = m.clone(); + assert!(auto_unwrap(&mut m, 128.0, 256).is_err()); + assert_eq!(m, before); + auto_unwrap(&mut m, 128.0, 512).unwrap(); + let (a, b, c) = (m.uvs[m.indices[0] as usize], m.uvs[m.indices[1] as usize], m.uvs[m.indices[2] as usize]); + assert!((b - a).length() > 1e-4 && (c - a).length() > 1e-4, "uvs {a} {b} {c}"); + } +} diff --git a/crates/mime/src/mailto.rs b/crates/mime/src/mailto.rs index 36a8f1c701..bd252ec0da 100644 --- a/crates/mime/src/mailto.rs +++ b/crates/mime/src/mailto.rs @@ -44,13 +44,13 @@ pub fn parse_mailto(link: &str) -> Option { let mut m = Mailto::default(); // Commas separate the addresses before they are decoded: an encoded comma belongs to its address. for address in path.split(',') { - add(&mut m.to, &decode(address)); + add(&mut m.to, &percent_decode(address)); } let (mut subject, mut body) = (None, None); for field in query.split('&') { let (name, value) = field.split_once('=').unwrap_or((field, "")); - let value = decode(value); - match decode(name).to_ascii_lowercase().as_str() { + let value = percent_decode(value); + match percent_decode(name).to_ascii_lowercase().as_str() { "to" => add_list(&mut m.to, &value), "cc" => add_list(&mut m.cc, &value), "bcc" => add_list(&mut m.bcc, &value), @@ -79,7 +79,7 @@ pub(crate) fn cut(text: &str, max: usize) -> &str { /// Percent-decoding. An escape that isn't one stays as it is written, a plus sign is a plus sign /// (RFC 6068 section 5), and bytes that aren't UTF-8 become the replacement character. -fn decode(text: &str) -> String { +pub(super) fn percent_decode(text: &str) -> String { let bytes = text.as_bytes(); let mut out = Vec::with_capacity(bytes.len()); let mut i = 0; diff --git a/crates/mime/src/related.rs b/crates/mime/src/related.rs index 2e252eedec..1b084028d3 100644 --- a/crates/mime/src/related.rs +++ b/crates/mime/src/related.rs @@ -48,12 +48,14 @@ impl<'a> Resources<'a> { self.by_location.get(&location.to_ascii_lowercase()).copied() } - /// The part a reference in a page names: `cid:id` by `Content-ID`; anything else by - /// `Content-Location`, as written, or resolved against `base`, the page's own location - /// ([`resolve_location`]; empty when it has none). Nothing is fetched. + /// The part a reference in a page names. A `cid:` URL is percent-decoded before the + /// `Content-ID` lookup. Other references use `Content-Location`, as written or resolved + /// against `base`, the page's own location ([`resolve_location`]). Nothing is fetched. pub fn find(&self, reference: &str, base: &str) -> Option<&'a Part> { let reference = reference.trim(); match reference.get(..4).filter(|s| s.eq_ignore_ascii_case("cid:")).and(reference.get(4..)) { + // RFC 2392 percent-decodes the URL, without form-style plus substitution. + Some(id) if id.contains('%') => self.by_content_id(&crate::mailto::percent_decode(id)).or_else(|| self.by_content_id(id)), Some(id) => self.by_content_id(id), None => self.by_location(reference).or_else(|| self.by_location(&resolve_location(base, reference))), } @@ -231,6 +233,27 @@ mod tests { assert!(start_part(&m.root).is_none()); } + #[test] + fn cid_references_decode_url_escapes_once() { + let message = parse( + b"Content-Type: multipart/related; boundary=b\n\n\ + --b\nContent-ID: \n\nplus\n\ + --b\nContent-ID: \n\npercent\n\ + --b\nContent-ID: \n\nlegacy\n--b--\n", + &Limits::default(), + ); + let resources = Resources::of(&message.root); + for (reference, expected) in [ + ("cid:part+id@example.test", "part+id@example.test"), + ("CID:part%2bid%40example.test", "part+id@example.test"), + ("cid:part%2Bid@example.test", "part+id@example.test"), + ("cid:part%252Bid@example.test", "part%2Bid@example.test"), + ("cid:legacy%41@example.test", "legacy%41@example.test"), + ] { + assert_eq!(resources.find(reference, "").and_then(Part::content_id), Some(expected), "{reference}"); + } + } + proptest::proptest! { #[test] fn any_reference_resolves(base in "[a-c:/?#.]{0,24}", reference in "[a-c:/?#.]{0,24}") { diff --git a/crates/odf/src/text/body/drawing.rs b/crates/odf/src/text/body/drawing.rs index eeb466f59c..96d1ba3881 100644 --- a/crates/odf/src/text/body/drawing.rs +++ b/crates/odf/src/text/body/drawing.rs @@ -137,7 +137,7 @@ impl Body<'_> { let path = self.shape_path.take().filter(|_| kind == craft_wordmodel::para::ShapeKind::Freeform); let (w, h) = (w.unwrap_or(72.0), h.unwrap_or(1.0)); self.note_place(kind, (w, h), &look, float.as_ref()); - Some(Inline::Shape { kind, w, h, float: float.map(Box::new), blocks, look, path }) + Some(Inline::Shape { kind, w, h, float: float.map(Box::new), blocks, look, path, link: None }) } (None, Some((linear, display))) => Some(Inline::Equation { linear, display }), (None, None) if let Some(spec) = chart => Some(Inline::Chart(model::Chart { @@ -177,7 +177,7 @@ impl Body<'_> { // A group's member goes into the group, at its place in it. if let Some(((x, y), g)) = self.member_at.take().zip(self.group.as_mut().filter(|_| self.note.is_none())) { if g.members.len() < craft_wordmodel::para::MAX_GROUP_CHILDREN { - g.members.push(model::Member { x, y, inline }); + g.members.push(model::Member { x, y, inline, link: None }); } } else { self.push_inline(inline); @@ -358,7 +358,7 @@ impl Body<'_> { float.z = g.z; let float = (float.wrap != craft_wordmodel::para::Wrap::Inline || float.z != 0).then(|| Box::new(float)); let fit = |v: f32| if v.is_finite() { v.clamp(1.0, MAX_LEN) } else { 1.0 }; - self.push_inline(Inline::Group { w: fit(x1 - x0), h: fit(y1 - y0), float, members }); + self.push_inline(Inline::Group { w: fit(x1 - x0), h: fit(y1 - y0), float, members, link: None }); } /// Begin a drawing shape (ODF 1.3 §10.3): its size, placement and look, and its text read diff --git a/crates/odf/src/text/writer.rs b/crates/odf/src/text/writer.rs index adf62a3ed5..1695725359 100644 --- a/crates/odf/src/text/writer.rs +++ b/crates/odf/src/text/writer.rs @@ -546,7 +546,7 @@ impl Writer { self.image(img, Place::Text(img.float.as_deref()), out); prev_space = false; } - Inline::Group { w, h, float, members } => { + Inline::Group { w, h, float, members, .. } => { self.group((*w, *h), float.as_deref(), members, out); prev_space = false; } @@ -571,7 +571,7 @@ impl Writer { self.comment(*id, comment, out); prev_space = false; } - Inline::Shape { kind, w, h, float, blocks, look, path } => { + Inline::Shape { kind, w, h, float, blocks, look, path, .. } => { self.drawing_shape(*kind, (*w, *h), Place::Text(float.as_deref()), (look, path.as_deref()), blocks, out); prev_space = false; } diff --git a/crates/odf/src/text/writer/drawing.rs b/crates/odf/src/text/writer/drawing.rs index 8d7576accb..6d6b2a4deb 100644 --- a/crates/odf/src/text/writer/drawing.rs +++ b/crates/odf/src/text/writer/drawing.rs @@ -383,7 +383,7 @@ impl Writer { for m in members { let (x, y) = (at.0 + m.x, at.1 + m.y); match &m.inline { - Inline::Shape { kind, w, h, float, blocks, look, path } => { + Inline::Shape { kind, w, h, float, blocks, look, path, .. } => { self.drawing_shape(*kind, (*w, *h), Place::Member(x, y, float.as_deref()), (look, path.as_deref()), blocks, out) } Inline::Image(img) => self.image(img, Place::Member(x, y, img.float.as_deref()), out), @@ -673,6 +673,7 @@ mod tests { let mut w = Writer::with_prefix("wc"); w.reserved = std::sync::Arc::new(std::iter::once("Pictures/wcimage1.png".to_string()).collect()); let img = model::Img { + link: None, data: std::sync::Arc::new(vec![1, 2, 3]), ext: "png".into(), w: 10.0, diff --git a/crates/opc/src/read.rs b/crates/opc/src/read.rs index 326f3f6288..687816e5a5 100644 --- a/crates/opc/src/read.rs +++ b/crates/opc/src/read.rs @@ -25,6 +25,20 @@ fn open_zip<'a>(bytes: &'a [u8], limits: &Limits, max_total: u64) -> Result) -> Result, Error> { + let mut out = Vec::new(); + for index in 0..zip.len() { + if let Some(name) = zip.virtual_entry_name(index).map_err(crate::zip_error)? { + out.push((index, name)); + } + } + Ok(out) +} + /// A part name as stored: `\` as `/` (code that splits paths on `/` must not meet a `\`), no /// leading `/`. fn stored_name(name: &str) -> String { @@ -59,8 +73,8 @@ impl Package { let mut files = BTreeMap::new(); let mut skipped = Vec::new(); let (mut total, mut work) = (0u64, 0u64); - let entries: Vec = zip.names().map(|n| n.into_owned()).collect(); - for (i, entry) in entries.iter().enumerate() { + let entries = entries(&mut zip)?; + for (i, (index, entry)) in entries.iter().enumerate() { if skip && work >= limits.max_work { log::warn!("opc: decompression budget spent; skipping the remaining {} entries", entries.len().saturating_sub(i)); break; @@ -69,7 +83,7 @@ impl Package { continue; } let name = stored_name(entry); - let size = zip.declared_size(entry).unwrap_or(0); + let size = zip.virtual_entry_size(*index).ok().flatten().unwrap_or(0); if size > limits.max_part { if skip { log::warn!("opc: skipping oversized part {name} ({size} bytes)"); @@ -87,7 +101,7 @@ impl Package { } return Err(Error::PackageTooLarge { limit: limits.max_total.min(limits.max_work) }); } - match zip.read(entry, room) { + match zip.read_virtual_index(*index, room) { Ok(Some(buf)) => { work = work.saturating_add(buf.len() as u64); total = total.saturating_add(buf.len() as u64); @@ -207,8 +221,8 @@ impl Package { /// reader that needs a few parts of a large file, or one part at a time. pub struct LazyPackage<'a> { zip: Zip<'a>, - /// Normalized part name → entry name (the first entry of a name). - names: HashMap, + /// Normalized part name → entry index and name (the first entry of a name). + names: HashMap, total: u64, limits: Limits, } @@ -218,10 +232,10 @@ impl<'a> LazyPackage<'a> { /// [`Limits::oversized`] are not used. pub fn open(bytes: &'a [u8], limits: &Limits) -> Result, Error> { // This reader keeps its own count, which a failed read spends (see `read_limited`). - let zip = open_zip(bytes, limits, u64::MAX)?; + let mut zip = open_zip(bytes, limits, u64::MAX)?; let mut names = HashMap::new(); - for n in zip.names() { - names.entry(normalize(&n)).or_insert_with(|| n.into_owned()); + for (index, n) in entries(&mut zip)? { + names.entry(normalize(&n)).or_insert((index, n)); } Ok(LazyPackage { zip, names, total: 0, limits: *limits }) } @@ -240,7 +254,7 @@ impl<'a> LazyPackage<'a> { /// The stored spelling of part `name` (leading `/` ignored; case-insensitive), as /// [`Package::canonical`] gives it: for a writer that keeps the package's part names. pub fn canonical(&self, name: &str) -> Option { - self.names.get(&normalize(name)).map(|n| n.trim_start_matches('/').replace('\\', "/")) + self.names.get(&normalize(name)).map(|(_, n)| n.trim_start_matches('/').replace('\\', "/")) } /// Bytes charged to [`Limits::max_total`] so far. It is the whole of it once a read has @@ -275,10 +289,10 @@ impl<'a> LazyPackage<'a> { /// pay it again and again. Every later read is then a cheap error. pub fn read_limited(&mut self, part: &str, maximum: u64) -> Result>, Error> { let maximum = maximum.min(self.limits.max_part); - let Some(entry) = self.names.get(&normalize(part)) else { + let Some(&(index, _)) = self.names.get(&normalize(part)) else { return Ok(None); }; - let size = self.zip.declared_size(entry).unwrap_or(0); + let size = self.zip.virtual_entry_size(index).ok().flatten().unwrap_or(0); if size > maximum { return Err(Error::PartTooLarge { part: part.to_string(), limit: maximum }); } @@ -287,7 +301,7 @@ impl<'a> LazyPackage<'a> { self.total = self.limits.max_total; return Err(Error::PackageTooLarge { limit: self.limits.max_total }); } - match self.zip.read(entry, maximum.min(remaining)) { + match self.zip.read_virtual_index(index, maximum.min(remaining)) { Ok(Some(out)) => { self.total = self.total.saturating_add(out.len() as u64); Ok(Some(out)) @@ -321,8 +335,10 @@ impl<'a> LazyPackage<'a> { /// the user which part made a package too large. pub fn declared_oversized(bytes: &[u8], limits: &Limits) -> Option<(String, u64)> { let mut zip = open_zip(bytes, limits, u64::MAX).ok()?; - let names: Vec = zip.names().map(|n| n.into_owned()).collect(); - names.into_iter().find_map(|n| zip.declared_size(&n).filter(|size| *size > limits.max_part).map(|size| (n, size))) + entries(&mut zip) + .ok()? + .into_iter() + .find_map(|(index, n)| zip.virtual_entry_size(index).ok().flatten().filter(|size| *size > limits.max_part).map(|size| (n, size))) } #[cfg(test)] diff --git a/crates/opc/tests/package.rs b/crates/opc/tests/package.rs index 8f3bf7f451..2ce4f5526d 100644 --- a/crates/opc/tests/package.rs +++ b/crates/opc/tests/package.rs @@ -182,10 +182,24 @@ fn skipped_parts_count_against_the_inflate_budget() { assert_eq!(Package::open(&z, &refuse).err(), Some(Error::PackageTooLarge { limit: 100 })); } +/// Renames every entry spelled `from` to `to`, a name of the same length, in its local and +/// central headers: for names the writer refuses to store. +fn rename_entries(z: &mut [u8], from: &[u8], to: &[u8]) { + assert_eq!(from.len(), to.len()); + let found: Vec = z.windows(from.len()).enumerate().filter(|(_, w)| *w == from).map(|(i, _)| i).collect(); + assert_eq!(found.len(), 2, "one local and one central header"); + for at in found { + z[at..at + to.len()].copy_from_slice(to); + } +} + #[test] fn backslash_zip_entry_names_are_found() { - let z = zip_of(&[("PPT\\Slides\\Slide1.xml", b"".to_vec()), ("/docProps/core.xml", b"".to_vec())]); + // A legacy writer's leading `/` stays a readable part: part names are never filesystem paths. + let mut z = zip_of(&[("PPT\\Slides\\Slide1.xml", b"".to_vec()), ("xdocProps/core.xml", b"".to_vec())]); + rename_entries(&mut z, b"xdocProps/core.xml", b"/docProps/core.xml"); let p = Package::open(&z, &LIMITS).unwrap(); + assert_eq!(p.get("docProps/core.xml"), Some(&b""[..])); assert!(p.get("ppt/slides/slide1.xml").is_some()); assert_eq!(p.canonical("ppt/slides/slide1.xml"), Some("PPT/Slides/Slide1.xml")); assert_eq!(p.canonical("docprops/core.xml"), Some("docProps/core.xml")); @@ -195,6 +209,34 @@ fn backslash_zip_entry_names_are_found() { assert_eq!(lazy.canonical("/DOCPROPS/core.xml").as_deref(), Some("docProps/core.xml")); assert_eq!(lazy.canonical("nothing"), None); assert_eq!(lazy.read("PPT/slides/slide1.xml").unwrap().as_deref(), Some(&b""[..])); + assert_eq!(lazy.read("docProps/core.xml").unwrap().as_deref(), Some(&b""[..])); +} + +#[test] +fn traversal_zip_entry_names_are_not_parts() { + let mut z = zip_of(&[("a.xml", b"".to_vec()), ("xx/evil.xml", b"".to_vec()), ("C_/evil2.xml", b"".to_vec())]); + rename_entries(&mut z, b"xx/evil.xml", b"../evil.xml"); + rename_entries(&mut z, b"C_/evil2.xml", b"C:/evil2.xml"); + let p = Package::open(&z, &LIMITS).unwrap(); + assert_eq!(p.names().collect::>(), ["a.xml"]); + let mut lazy = LazyPackage::open(&z, &LIMITS).unwrap(); + assert_eq!(lazy.names(), ["a.xml"]); + assert_eq!(lazy.read("../evil.xml").unwrap(), None); + assert_eq!(lazy.read("evil.xml").unwrap(), None); +} + +/// Indexing part names reads only the central directory: one part whose local header is +/// damaged leaves the others readable. +#[test] +fn a_damaged_local_header_does_not_stop_the_package_opening() { + let mut z = zip_of(&[("a.xml", b"".to_vec()), ("bad.xml", b"".to_vec())]); + let local = z.windows(7).position(|w| w == b"bad.xml").unwrap() - 30; + assert_eq!(&z[local..local + 4], b"PK\x03\x04"); + z[local] = b'X'; + let p = Package::open(&z, &LIMITS).unwrap(); + assert_eq!(p.get("a.xml"), Some(&b""[..])); + let mut lazy = LazyPackage::open(&z, &LIMITS).unwrap(); + assert_eq!(lazy.read("a.xml").unwrap().as_deref(), Some(&b""[..])); } #[test] diff --git a/crates/pages/src/ui/mod.rs b/crates/pages/src/ui/mod.rs index 6b1fbfffca..62446f4cd6 100644 --- a/crates/pages/src/ui/mod.rs +++ b/crates/pages/src/ui/mod.rs @@ -52,8 +52,8 @@ pub use reading::{ReadingNav, ReadingNavOutput, ReadingState, ReadingView, Readi pub use setup::{PageLayoutChoice, PageLayoutMenus, PageSetupDialog}; pub use sync_views::{Lead, SyncedViews, SyncedViewsOutput, SyncedViewsState}; pub use table::{ - BorderEdges, BorderPreset, CellAlign, CellSelectionOverlay, EdgeKey, EdgeLook, EdgePicker, RowHeight, SampleArea, TableChange, TableGeometry, - TableProperties, TablePropertiesOutput, TableSizePicker, TableSizePickerOutput, TableValues, TextDirection, + BorderEdges, BorderPreset, CellAlign, CellSelectionOverlay, EdgeKey, EdgeLook, EdgePicker, EdgeSize, RowHeight, SampleArea, TableChange, + TableGeometry, TableProperties, TablePropertiesOutput, TableSizePicker, TableSizePickerOutput, TableValues, TextDirection, }; pub use text_selection::{ MarkArea, MarkKind, PageTextSource, PageTexts, TextMark, TextMarks, TextSelectState, TextSelectTool, TextSelection, TextSpan, diff --git a/crates/pages/src/ui/table/edges.rs b/crates/pages/src/ui/table/edges.rs index 06d5626abc..8bf957674c 100644 --- a/crates/pages/src/ui/table/edges.rs +++ b/crates/pages/src/ui/table/edges.rs @@ -163,6 +163,8 @@ pub struct EdgePickerStyle { focus: FocusLook, /// The side of the square. side: f32, + /// The side of the square at [`EdgeSize::Sample`]. + sample_side: f32, /// How far the outer lines sit inside the square, and how near a line the pointer picks it. inset: f32, /// The area inside the lines. @@ -198,6 +200,20 @@ pub struct EdgePicker<'a> { /// How the picture is drawn: the proxy diagram, or a sample of the borders on text, a paragraph or a page. #[prop] look: EdgeLook, + /// The extent of the square: a thumbnail, or a sample-sized preview. + #[prop] + preview: EdgeSize, +} + +/// How large the picker's square is. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum EdgeSize { + /// A thumbnail (`size.thumb.lg`). + #[default] + Thumb, + /// A preview at sample size (`size.thumb.sample.lg`), for a Borders or Shading dialog's page-like preview. + Sample, } /// How the borders preview is drawn. @@ -246,7 +262,7 @@ struct ClickRun { impl<'a> EdgePicker<'a> { /// A picker named `label` editing `edges`. pub fn new(label: impl Into